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
b5a71fef615cf94bb25cbfb4e1a65b53a1495679
555ce7f1e44349316e240485dca6f7cd4496ea9c
/DirectShowFilters/TsWriter/source/ChannelLinkageParser.cpp
b3c5068d503341109aec5695e974351037d4b493
[]
no_license
Yura80/MediaPortal-1
c71ce5abf68c70852d261bed300302718ae2e0f3
5aae402f5aa19c9c3091c6d4442b457916a89053
refs/heads/master
2021-04-15T09:01:37.267793
2011-11-25T20:02:53
2011-11-25T20:11:02
2,851,405
2
0
null
null
null
null
UTF-8
C++
false
false
7,863
cpp
/* * Copyright (C) 2006-2008 Team MediaPortal * http://www.team-mediaportal.com * * 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, 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 GNU Make; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ #include <windows.h> #include <time.h> #include "ChannelLinkageParser.h" #include "..\..\shared\dvbutil.h" #pragma warning(disable : 4995) extern void LogDebug(const char *fmt, ...) ; CChannelLinkageParser::CChannelLinkageParser(void) { CEnterCriticalSection enter(m_section); m_bScanning=false; m_bScanningDone=false; sectionDecoder=new CSectionDecoder(); sectionDecoder->SetPid(PID_EPG); sectionDecoder->SetCallBack(this); } CChannelLinkageParser::~CChannelLinkageParser(void) { CEnterCriticalSection enter(m_section); delete sectionDecoder; } void CChannelLinkageParser::Start() { CEnterCriticalSection enter(m_section); m_mapChannels.clear(); m_bScanning=true; m_scanTimeout=time(NULL); m_prevChannelIndex=-1; } void CChannelLinkageParser::Reset() { CEnterCriticalSection enter(m_section); m_bScanning=false; m_bScanningDone=false; sectionDecoder->Reset(); m_mapChannels.clear(); } bool CChannelLinkageParser::IsScanningDone() { return m_bScanningDone; } bool CChannelLinkageParser::GetChannelByindex(ULONG channelIndex, PortalChannel& portalChannel) { CEnterCriticalSection lock (m_section); LinkedChannel lChannel; m_prevLinkIndex=-1; m_prevLink=lChannel; if (channelIndex>=m_mapChannels.size()) return false; ULONG count=0; imapChannels it =m_mapChannels.begin(); while (count < channelIndex) { it++; count++; } portalChannel=it->second; m_prevChannel=portalChannel; m_prevChannelIndex=channelIndex; return true; } ULONG CChannelLinkageParser::GetChannelCount() { CEnterCriticalSection lock (m_section); return (ULONG)m_mapChannels.size(); } void CChannelLinkageParser::GetChannel (ULONG channelIndex, WORD* network_id, WORD* transport_id,WORD* service_id ) { CEnterCriticalSection lock (m_section); *network_id=0; *transport_id=0; *service_id=0; if (channelIndex!=m_prevChannelIndex) { PortalChannel pChannel; if (!GetChannelByindex(channelIndex,pChannel)) return; *network_id=pChannel.original_network_id; *transport_id=pChannel.transport_id; *service_id=pChannel.service_id; } else { *network_id=m_prevChannel.original_network_id; *transport_id=m_prevChannel.transport_id; *service_id=m_prevChannel.service_id; } } ULONG CChannelLinkageParser::GetLinkedChannelsCount (ULONG channel) { CEnterCriticalSection lock (m_section); PortalChannel pChannel; if (!GetChannelByindex(channel,pChannel)) return 0; return (ULONG)pChannel.m_linkedChannels.size(); } void CChannelLinkageParser::GetLinkedChannel (ULONG channelIndex,ULONG linkIndex, WORD* network_id, WORD* transport_id,WORD* service_id, char** channelName ) { CEnterCriticalSection enter(m_section); PortalChannel pChannel; *network_id=0; *transport_id=0; *service_id=0; *channelName=(char*)""; if (channelIndex!=m_prevChannelIndex) { PortalChannel pChannel; if (!GetChannelByindex(channelIndex,pChannel)) return ; } if (linkIndex >= m_prevChannel.m_linkedChannels.size()) return; ULONG count=0; PortalChannel::ilinkedChannels itLink=m_prevChannel.m_linkedChannels.begin(); while (count < linkIndex) { itLink++; count++; } LinkedChannel& lChannel=*itLink; m_prevLinkIndex=linkIndex; m_prevLink=lChannel; *network_id=lChannel.network_id; *transport_id=lChannel.transport_id; *service_id=lChannel.service_id; *channelName=(char*)lChannel.name.c_str(); } void CChannelLinkageParser::OnTsPacket(CTsHeader& header, byte* tsPacket) { if (m_bScanning==false) return; CEnterCriticalSection enter(m_section); sectionDecoder->OnTsPacket(header,tsPacket); } void CChannelLinkageParser::OnNewSection(int pid, int tableId, CSection& section) { CEnterCriticalSection enter(m_section); try { if (section.table_id>=0x4e && section.table_id<0x70) DecodeLinkage(section.Data,section.section_length); } catch(...) { LogDebug("exception in CChannelLinkageParser::OnNewSection"); } } void CChannelLinkageParser::DecodeLinkage(byte* buf, int len) { CEnterCriticalSection lock (m_section); try { if (!m_bScanning) return; if (buf==NULL) return; time_t currentTime=time(NULL); time_t timespan=currentTime-m_scanTimeout; if (timespan>8) { m_bScanning=false; m_bScanningDone=true; return; } if (len<=14) return; int tableid = buf[0]; int service_id = (buf[3]<<8)+buf[4]; int transport_id=(buf[8]<<8)+buf[9]; int network_id=(buf[10]<<8)+buf[11]; unsigned long lNetworkId=network_id; unsigned long lTransport_id=transport_id; unsigned long lServiceId=service_id; unsigned long key=(unsigned long)(lNetworkId<<32UL); key+=(lTransport_id<<16); key+=lServiceId; imapChannels it=m_mapChannels.find(key); if (it==m_mapChannels.end()) { PortalChannel newChannel ; newChannel.original_network_id=network_id; newChannel.service_id=service_id; newChannel.transport_id=transport_id; newChannel.allSectionsReceived=false; m_mapChannels[key]=newChannel; it=m_mapChannels.find(key); } if (it==m_mapChannels.end()) return; PortalChannel& channel=it->second; //did we already receive this section ? key=crc32 ((char*)buf,len); PortalChannel::imapSectionsReceived itSec=channel.mapSectionsReceived.find(key); if (itSec!=channel.mapSectionsReceived.end()) return; //yes channel.mapSectionsReceived[key]=true; m_scanTimeout=time(NULL); int start=14; while (start+11 <= len+1) { int descriptors_len=((buf[start+10]&0xf)<<8) + buf[start+11]; start=start+12; int off=0; while (off < descriptors_len) { if (start+off+1>len) return; int descriptor_tag = buf[start+off]; int descriptor_len = buf[start+off+1]; if (start+off+descriptor_len+2>len) return; if ((descriptor_len>0) && (descriptor_tag==0x4a)) // Linkage descriptor { LinkedChannel lChannel; lChannel.transport_id=(buf[start+off+2]<<8)+buf[start+off+3]; lChannel.network_id=(buf[start+off+4]<<8)+buf[start+off+5]; lChannel.service_id=(buf[start+off+6]<<8)+buf[start+off+7]; char *cname=(char*)malloc(400); strncpy(cname,(char*)&buf[start+off+9],descriptor_len-7); cname[descriptor_len-7]=0; lChannel.name.assign(cname); free(cname); channel.m_linkedChannels.push_back(lChannel); //LogDebug("ChannelLinkageScanner: PortalChannel tsid=%d nid=%d sid=%d",channel.transport_id,channel.original_network_id,channel.service_id); //LogDebug("ChannelLinkageScanner: LinkedChannel found len=%d tsid=%d nid=%d sid=%d %s",descriptor_len,lChannel.transport_id,lChannel.network_id,lChannel.service_id,lChannel.name.c_str()); } off +=descriptor_len+2; } start +=descriptors_len; } } catch(...) { LogDebug("mpsaa: unhandled exception in Sections::DecodeChannelLinkage()"); } return; }
[ [ [ 1, 273 ] ] ]
85a285abb1983cf8dca178df90653b99077f058a
444a151706abb7bbc8abeb1f2194a768ed03f171
/trunk/ENIGMAsystem/SHELL/Universal_System/mathnc.cpp
0430a4e8dc5126f9ea4bfc318ef455e5c4f4dae2
[]
no_license
amorri40/Enigma-Game-Maker
9d01f70ab8de42f7c80af9a0f8c7a66e412d19d6
c6b701201b6037f2eb57c6938c184a5d4ba917cf
refs/heads/master
2021-01-15T11:48:39.834788
2011-11-22T04:09:28
2011-11-22T04:09:28
1,855,342
1
1
null
null
null
null
UTF-8
C++
false
false
11,050
cpp
/********************************************************************************\ ** ** ** Copyright (C) 2008-2011 Josh Ventura ** ** ** ** This file is a part of the ENIGMA Development Environment. ** ** ** ** ** ** ENIGMA 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, version 3 of the license or any later version. ** ** ** ** This application and its source code is distributed AS-IS, 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 recieved a copy of the GNU General Public License along ** ** with this code. If not, see <http://www.gnu.org/licenses/> ** ** ** ** ENIGMA is an environment designed to create games and other programs with a ** ** high-level, fully compilable language. Developers of ENIGMA or anything ** ** associated with ENIGMA are in no way responsible for its users or ** ** applications created by its users, or damages caused by the environment ** ** or programs made in the environment. ** ** ** \********************************************************************************/ #include <stdlib.h> #include <cmath> #include "var4.h" #include "dynamic_args.h" #define INCLUDED_FROM_SHELLMAIN Not really. #include "mathnc.h" double bessel_j0(double x); double bessel_j1(double x); double bessel_jn(int x, double y); double bessel_y0(double x); double bessel_y1(double x); double bessel_yn(int x, double y); double bessel_j0(double x) { return j0(x); } double bessel_j1(double x) { return j1(x); } double bessel_jn(int x, double y) { return jn(x,y); } double bessel_y0(double x) { return y0(x); } double bessel_y1(double x) { return y1(x); } double bessel_yn(int x, double y) { return yn(x,y); } //overloading double abs(const variant& x) { return fabs(double(x)); } double ceil(const variant& x) { return ceil((double)x); } double floor(const variant& x) { return floor((double)x); } double exp(const variant& x) { return exp((double)x); } double sqrt(const variant& x) { return sqrt((double)x); } double log10(const variant& x) { return log10((double)x); } double sin(const variant& x) { return sin((double)x); } double cos(const variant& x) { return cos((double)x); } double tan(const variant& x) { return tan((double)x); } double abs(const var& x) { return fabs(double(x)); } double ceil(const var& x) { return ceil((double)x); } double floor(const var& x) { return floor((double)x); } double exp(const var& x) { return exp((double)x); } double sqrt(const var& x) { return sqrt((double)x); } double log10(const var& x) { return log10((double)x); } double sin(const var& x) { return sin((double)x); } double cos(const var& x) { return cos((double)x); } double tan(const var& x) { return tan((double)x); } double round(double x) { return lrint(x); } double sqr(double x) { return x*x; } double power(double x,double p) { return pow(x,p); } double ln(double x) { return log(x); } double logn(double n,double x) { return log(x)/log(n); } double log2(double x) { return log(x)/M_LN2; }//This may already exist double arcsin(double x) { return asin(x); } double arccos(double x) { return acos(x); } double arctan(double x) { return atan(x); } double arctan2(double y,double x) { return atan2(y,x); } double sind(double x) { return sin(x * M_PI / 180.0); } double cosd(double x) { return cos(x * M_PI / 180.0); } double tand(double x) { return tan(x * M_PI / 180.0); } //double tand2(double y,double x); double asind(double x) { return asin(x) * 180.0 / M_PI; } double acosd(double x) { return acos(x) * 180.0 / M_PI; } double atand(double x) { return atan(x) * 180.0 / M_PI; } double atand2(double y,double x) { return atan2(y,x) * 180.0 / M_PI; } double arcsind(double x) { return asin(x) * 180.0 / M_PI; } double arccosd(double x) { return acos(x) * 180.0 / M_PI; } double arctand(double x) { return atan(x) * 180.0 / M_PI; } double arctand2(double y,double x) { return atan2(y,x) * 180.0 / M_PI; } int sign(double x) { return (x>0)-(x<0); } int cmp(double x,double y) { return (x>y)-(x<y); } double frac(double x) { return x-(int)x; } double degtorad(double x) { return x*(M_PI/180.0);} double radtodeg(double x) { return x*(180.0/M_PI);} double lengthdir_x(double len,double dir) { return len * cosd(dir); } double lengthdir_y(double len,double dir) { return len * -sind(dir); } double lerp(double x, double y, double a) { return x + ((y-x)*a); } double direction_difference(double dir1,double dir2) { return fmod((fmod((dir1 - dir2),360) + 540), 360) - 180; } double point_direction(double x1,double y1,double x2,double y2) { return fmod((atan2(y1-y2,x2-x1)*(180/M_PI))+360,360); } double point_distance(double x1,double y1,double x2,double y2) { return hypot(x2-x1,y2-y1); } double min(double x, double y) { return x < y ? x : y; } double max(double x, double y) { return x > y ? x : y; } double max(const enigma::varargs &t) { register double ret = t.get(0), tst; for (int i = 1; i < t.argc; i++) if ((tst = t.get(i)) > ret) ret = tst; return ret; } double min(const enigma::varargs &t) { register double ret = t.get(0), tst; for (int i = 1; i < t.argc; i++) if ((tst = t.get(i)) < ret) ret = tst; return ret; } double median(enigma::varargs t) { t.sort(); if (t.argc & 1) return t.get(t.argc/2); return (t.get(t.argc/2) + t.get(t.argc/2-1)) / 2.; } double mean(const enigma::varargs &t) { register double ret = 0; for (int i = 0; i < t.argc; i++) ret += t.get(i); return ret/t.argc; } variant choose(const enigma::varargs& args) { return args.get(rand() % args.argc); }; // For added randomness // ................................................... #define UPPER_MASK 0x80000000 // most significant w-r bits #define LOWER_MASK 0x7fffffff // least significant r bits namespace enigma { unsigned int Random_Seed; unsigned long mt[625]; } /* The code in this module was based on a download from: http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html It was modified in 2002 by Raymond Hettinger. Then I modified 2009 The following are the verbatim comments from the original code A C-program for MT19937, with initialization improved 2002/1/26. Coded by Takuji Nishimura and Makoto Matsumoto. Before using, initialize the state by using init_genrand(seed) or init_by_array(init_key, key_length). Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of its contributors may not 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 OWNER 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. Any feedback is very welcome. http://www.math.keio.ac.jp/matumoto/emt.html email: [email protected]*/ unsigned int random32() { unsigned int y; static const unsigned int mag01[2]={0,0x9908b0df}; if (enigma::mt[624] >= 624) { /* generate N words at one time */ int kk; for(kk=0;kk<227;kk++) { y = (enigma::mt[kk]&UPPER_MASK)|(enigma::mt[kk+1]&LOWER_MASK); enigma::mt[kk] = enigma::mt[kk+397] ^ (y >> 1) ^ mag01[y&1]; } for(;kk<623;kk++) { y = (enigma::mt[kk]&UPPER_MASK)|(enigma::mt[kk+1]&LOWER_MASK); enigma::mt[kk] = enigma::mt[kk-227] ^ (y >> 1) ^ mag01[y&1]; } y = (enigma::mt[623]&UPPER_MASK) | (enigma::mt[0]&LOWER_MASK); enigma::mt[623] = enigma::mt[396] ^ (y >> 1) ^ mag01[y & 1]; enigma::mt[624] = 0; } y = enigma::mt[enigma::mt[624]++]; y ^= y >> 11; y ^= (y << 7) & 0x9d2c5680UL; y ^= (y << 15) & 0xefc60000UL; return y^(y >> 18); } double mtrandom(){ return ((random32()>>5)*67108864.+(random32()>>6))/9007199254740992.; } int mtrandom_seed(int x){ enigma::mt[0]=x&0xffffffff; for(int mti=1;mti<624;mti++) enigma::mt[mti]=1812433253*(enigma::mt[mti-1]^(enigma::mt[mti-1]>>30))+mti; enigma::mt[624] = 624; return 0; } int random_integer(int x) {return x>0?random32()*(x/0xFFFFFFFF):0;} //END MERSENNE double random(double n) //Do not fix. Based off of Delphi prng { double rval=frac( 0.031379939289763571*(enigma::Random_Seed%32) +0.00000000023283064365387*(enigma::Random_Seed/32+1) +0.004158057505264878*(enigma::Random_Seed/32))*n; enigma::Random_Seed=random32(); return rval; } int random_set_seed(int seed){return enigma::Random_Seed=seed;} int random_get_seed(){return enigma::Random_Seed;} int randomize(){return enigma::Random_Seed=random32();}
[ [ [ 1, 272 ] ] ]
e33ce8630edd8cbf07f717f6f2efdb1ae0a75328
9426ad6e612863451ad7aac2ad8c8dd100a37a98
/ULLib/include/ULOther.h
ba85f9e4328a98707fbe98e5c8d5c791e209a8ce
[]
no_license
piroxiljin/ullib
61f7bd176c6088d42fd5aa38a4ba5d4825becd35
7072af667b6d91a3afd2f64310c6e1f3f6a055b1
refs/heads/master
2020-12-28T19:46:57.920199
2010-02-17T01:43:44
2010-02-17T01:43:44
57,068,293
0
0
null
2016-04-25T19:05:41
2016-04-25T19:05:41
null
WINDOWS-1251
C++
false
false
2,173
h
///\file ULOther.h ///\brief Заголовочный файл пространства имён просто для полезных функций(25.08.2007) #pragma once #ifndef __ULOTHER__H_ #define __ULOTHER__H_ #include <windows.h> #include "ULProfileReg.h" #include "ULPtr.inl" #include "ULFileVersionInfo.h" #include "ULWaitCursor.h" #include "ULRes.h" #include "ULTrayIcon.h" ///\namespace ULOther ///\brief Пространство имён просто для полезных функций(25.08.2007) namespace ULOther { ///\brief Функция для подключения длл и импортирования функций(2006) ///\param hLibrary -хендл подключенной библиотеки ///\param lpszLibrary-имя файла подключаемой библиотеки ///\param nCount-колличество импортируемых функций ///\param ... - указатель на прототип функции, имя функции ///\return TRUE в случае успеха BOOL GetProcAddresses(HINSTANCE *hLibrary, LPCTSTR lpszLibrary, INT nCount, ... ); ///\brief Функция для перевода rus текста в консольный(30.07.2007) ///\param pszIn - указатель на буфер с текстом ///\return консольный текст const char* Rus(const TCHAR* pszIn); ///\brief Функция возвращает описание ошибки(29.12.2007) ///\param nErr - номер ошибки ///\return описание последней ошибки LPTSTR ParseError(UINT nErr); ///\brief Для получения директории, в которой расположен указанный модуль ///\param hModule - хенжл модуля ///\param lpszFolderPath - возвращаемая строка с именем директории ///\param dwSize - размер буфера ///\return длина строки пути к возвращаемой директории DWORD GetModuleFolderPath(HMODULE hModule,LPTSTR lpszFolderPath,DWORD dwSize); }; #endif//__ULOTHER__H_
[ "UncleLab@a8b69a72-a546-0410-9fb4-5106a01aa11f" ]
[ [ [ 1, 40 ] ] ]
b7541139610cbb98a3e456ef39f62d190af882c2
c9599775f0da57207d0a90f88a588e054f926b04
/guano/Terrain.h
f468aee2566279ebeeed9861940414f40366f9a9
[]
no_license
isoiphone/ggjvic
7faced0e60ad4dae69131bf4b4925000f0170a86
ff8b47013152f5f0909232f00b2a514c2321a267
refs/heads/master
2020-06-01T05:09:55.790734
2011-01-30T23:04:33
2011-01-30T23:04:33
32,309,386
0
0
null
null
null
null
UTF-8
C++
false
false
580
h
#ifndef _TERRAIN_H_INCLUDED #define _TERRAIN_H_INCLUDED #include "main.h" class Gamepad; class Sprite2d; #define kMaxObstacles 10 typedef struct Obstacle { vector2f pos; float rad; bool bActive; }; extern Obstacle obstacles[kMaxObstacles]; // one-time setup crap void terrInit(); // set up the level void terrReset(); // draw a frame void terrRender(Sprite2d* sprite, Sprite2d* font); // time passes void terrUpdate(uint32_t elapsedMs, Gamepad* gamepad); // a shot collided with some active obstacle void terrHit(int index); #endif
[ "[email protected]@d29389ee-23ba-95cd-0add-1ea859d12ca3" ]
[ [ [ 1, 34 ] ] ]
3feacb6f713752c27f2c3cb9bf029bfa602f36dc
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/graph/example/edge-connectivity.cpp
4af198bfa005f30f56441d59c82bfec7d6d9b46b
[ "Artistic-2.0", "LicenseRef-scancode-public-domain", "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
6,905
cpp
//======================================================================= // Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, // // 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) //======================================================================= #include <boost/config.hpp> #include <algorithm> #include <utility> #include <boost/graph/edmonds_karp_max_flow.hpp> #include <boost/graph/push_relabel_max_flow.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/graphviz.hpp> namespace boost { template < typename Graph > std::pair < typename graph_traits < Graph >::vertex_descriptor, typename graph_traits < Graph >::degree_size_type > min_degree_vertex(Graph & g) { typename graph_traits < Graph >::vertex_descriptor p; typedef typename graph_traits < Graph >::degree_size_type size_type; size_type delta = (std::numeric_limits < size_type >::max)(); typename graph_traits < Graph >::vertex_iterator i, iend; for (tie(i, iend) = vertices(g); i != iend; ++i) if (degree(*i, g) < delta) { delta = degree(*i, g); p = *i; } return std::make_pair(p, delta); } template < typename Graph, typename OutputIterator > void neighbors(const Graph & g, typename graph_traits < Graph >::vertex_descriptor u, OutputIterator result) { typename graph_traits < Graph >::adjacency_iterator ai, aend; for (tie(ai, aend) = adjacent_vertices(u, g); ai != aend; ++ai) *result++ = *ai; } template < typename Graph, typename VertexIterator, typename OutputIterator > void neighbors(const Graph & g, VertexIterator first, VertexIterator last, OutputIterator result) { for (; first != last; ++first) neighbors(g, *first, result); } template < typename VertexListGraph, typename OutputIterator > typename graph_traits < VertexListGraph >::degree_size_type edge_connectivity(VertexListGraph & g, OutputIterator disconnecting_set) { typedef typename graph_traits < VertexListGraph >::vertex_descriptor vertex_descriptor; typedef typename graph_traits < VertexListGraph >::degree_size_type degree_size_type; typedef color_traits < default_color_type > Color; typedef typename adjacency_list_traits < vecS, vecS, directedS >::edge_descriptor edge_descriptor; typedef adjacency_list < vecS, vecS, directedS, no_property, property < edge_capacity_t, degree_size_type, property < edge_residual_capacity_t, degree_size_type, property < edge_reverse_t, edge_descriptor > > > > FlowGraph; vertex_descriptor u, v, p, k; edge_descriptor e1, e2; bool inserted; typename graph_traits < VertexListGraph >::vertex_iterator vi, vi_end; degree_size_type delta, alpha_star, alpha_S_k; std::set < vertex_descriptor > S, neighbor_S; std::vector < vertex_descriptor > S_star, nonneighbor_S; std::vector < default_color_type > color(num_vertices(g)); std::vector < edge_descriptor > pred(num_vertices(g)); FlowGraph flow_g(num_vertices(g)); typename property_map < FlowGraph, edge_capacity_t >::type cap = get(edge_capacity, flow_g); typename property_map < FlowGraph, edge_residual_capacity_t >::type res_cap = get(edge_residual_capacity, flow_g); typename property_map < FlowGraph, edge_reverse_t >::type rev_edge = get(edge_reverse, flow_g); typename graph_traits < VertexListGraph >::edge_iterator ei, ei_end; for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) { u = source(*ei, g), v = target(*ei, g); tie(e1, inserted) = add_edge(u, v, flow_g); cap[e1] = 1; tie(e2, inserted) = add_edge(v, u, flow_g); cap[e2] = 1; rev_edge[e1] = e2; rev_edge[e2] = e1; } tie(p, delta) = min_degree_vertex(g); S_star.push_back(p); alpha_star = delta; S.insert(p); neighbor_S.insert(p); neighbors(g, S.begin(), S.end(), std::inserter(neighbor_S, neighbor_S.begin())); std::set_difference(vertices(g).first, vertices(g).second, neighbor_S.begin(), neighbor_S.end(), std::back_inserter(nonneighbor_S)); while (!nonneighbor_S.empty()) { k = nonneighbor_S.front(); alpha_S_k = edmonds_karp_max_flow (flow_g, p, k, cap, res_cap, rev_edge, &color[0], &pred[0]); if (alpha_S_k < alpha_star) { alpha_star = alpha_S_k; S_star.clear(); for (tie(vi, vi_end) = vertices(flow_g); vi != vi_end; ++vi) if (color[*vi] != Color::white()) S_star.push_back(*vi); } S.insert(k); neighbor_S.insert(k); neighbors(g, k, std::inserter(neighbor_S, neighbor_S.begin())); nonneighbor_S.clear(); std::set_difference(vertices(g).first, vertices(g).second, neighbor_S.begin(), neighbor_S.end(), std::back_inserter(nonneighbor_S)); } std::vector < bool > in_S_star(num_vertices(g), false); typename std::vector < vertex_descriptor >::iterator si; for (si = S_star.begin(); si != S_star.end(); ++si) in_S_star[*si] = true; degree_size_type c = 0; for (si = S_star.begin(); si != S_star.end(); ++si) { typename graph_traits < VertexListGraph >::out_edge_iterator ei, ei_end; for (tie(ei, ei_end) = out_edges(*si, g); ei != ei_end; ++ei) if (!in_S_star[target(*ei, g)]) { *disconnecting_set++ = *ei; ++c; } } return c; } } int main() { using namespace boost; GraphvizGraph g; read_graphviz("figs/edge-connectivity.dot", g); typedef graph_traits < GraphvizGraph >::edge_descriptor edge_descriptor; typedef graph_traits < GraphvizGraph >::degree_size_type degree_size_type; std::vector < edge_descriptor > disconnecting_set; degree_size_type c = edge_connectivity(g, std::back_inserter(disconnecting_set)); std::cout << "The edge connectivity is " << c << "." << std::endl; property_map < GraphvizGraph, vertex_attribute_t >::type attr_map = get(vertex_attribute, g); std::cout << "The disconnecting set is {"; for (std::vector < edge_descriptor >::iterator i = disconnecting_set.begin(); i != disconnecting_set.end(); ++i) std:: cout << "(" << attr_map[source(*i, g)]["label"] << "," << attr_map[target(*i, g)]["label"] << ") "; std::cout << "}." << std::endl; return EXIT_SUCCESS; }
[ "metrix@Blended.(none)" ]
[ [ [ 1, 176 ] ] ]
78554cdc259702063a13f5b3ca8d8f786f7e8276
b5b57f95c6ee44fbb7d9c8ddda870c5338359e01
/miniMap.cpp
84ed4ce02161d428468645d2ad19034019a582d4
[]
no_license
Objelisks/descendinghammer
bcaa81b086da65f4207339c2348cbcdb2c765e44
2cbd67bcfba5ee1008d58bde59cfee18f01166b6
refs/heads/master
2020-04-21T17:26:35.740409
2009-04-04T06:20:01
2009-04-04T06:20:01
32,121,262
0
0
null
null
null
null
UTF-8
C++
false
false
1,767
cpp
#include "miniMap.h" #include "allegro.h" #include "gameState.h" #include "vector" MiniMap::MiniMap(BITMAP* parentScreen) { MiniMap(parentScreen,300,200); }; MiniMap::MiniMap(BITMAP* parentScreen,int w, int h) { width = w; height = h; m_subScreen = create_sub_bitmap(parentScreen,175,300,width ? width : 200,height ? height : 200); //scanline colors colors[0] = makecol(0,32,16); colors[1] = makecol(0,48,8); colors[2] = makecol(0,48,16); colors[3] = makecol(0,128,16); //bullet colors colors[4] = makecol(250,201,58); colors[5] = makecol(255,174,46); colors[6] = makecol(245,119,18); colors[7] = makecol(255,82,21); colors[8] = makecol(250,19,0); xScale = -1; yScale = -1; }; void MiniMap::draw() { if(xScale == -1) { xScale = (float)width/(float)theState()->world.x; yScale = (float)height/(float)theState()->world.y; } clear_bitmap(m_subScreen); //scanlines int col = colors[rand()%3]; for(int i=1; i<height-2; i+=2) { hline(m_subScreen,1,i,width-2,col); } //Draw awesome dude circle(m_subScreen,theState()->player.pos.x*xScale,theState()->player.pos.y*yScale,5,colors[3]); //Draw bullets and stuf for(std::list<Bullet>::iterator iter = theState()->bulletManager.bullets.begin(); iter!= theState()->bulletManager.bullets.end(); iter++) { putpixel(m_subScreen,iter->pos.x*xScale,iter->pos.y*yScale,colors[std::max<int>(8-(rand()%5),4)]); } //Draw bad dudes for(std::list<Enemy>::iterator iter = theState()->enemyManager.enemies.begin(); iter!= theState()->enemyManager.enemies.end(); iter++) { circle(m_subScreen,iter->pos.x*xScale,iter->pos.y*yScale,iter->size,colors[8]); } rect(m_subScreen,0,0,width-1,height-1,colors[2+rand()%2]); };
[ "supertyrian@ae15d362-055d-11de-a1f0-819f45317607" ]
[ [ [ 1, 68 ] ] ]
556435b95b5e6ef24227e61543c466aba7293872
7e68ef369eff945f581e22595adecb6b3faccd0e
/code/linux/minifw/reactor.cpp
8166aadbf2ef1d239bb3bae80598a9fc12b4fde9
[]
no_license
kimhmadsen/mini-framework
700bb1052227ba18eee374504ff90f41e98738d2
d1983a68c6b1d87e24ef55ca839814ed227b3956
refs/heads/master
2021-01-01T05:36:55.074091
2008-12-16T00:33:10
2008-12-16T00:33:10
32,415,758
0
0
null
null
null
null
UTF-8
C++
false
false
47
cpp
#include "stdafx.h" #include "reactor.h"
[ "mariasolercliment@77f6bdef-6155-0410-8b08-fdea0229669f" ]
[ [ [ 1, 4 ] ] ]
662c8db353850cb1206aaaa1a93cf0207117f272
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/test/src/unit_test_monitor.cpp
0b31d51860c042185b79642babf5a5509dda5d57
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
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
1,054
cpp
// (C) Copyright Gennadiy Rozental 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: unit_test_monitor.cpp,v $ // // Version : $Revision: 1.19 $ // // Description : forwarding source // *************************************************************************** #define BOOST_TEST_SOURCE #include <boost/test/impl/unit_test_monitor.ipp> // *************************************************************************** // Revision History : // // $Log: unit_test_monitor.cpp,v $ // Revision 1.19 2005/03/22 07:18:50 rogeeff // no message // // Revision 1.18 2005/01/22 19:26:37 rogeeff // implementation moved into headers section to eliminate dependency of included/minimal component on src directory // // *************************************************************************** // EOF
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 30 ] ] ]
3927ce0a8f34abcc02981098efa47ded66fe8b53
38926bfe477f933a307f51376dd3c356e7893ffc
/Source/SDKs/STLPORT/src/facets_byname.cpp
d6ae23dbc4b58317e5911fb24a4554e8f67a297c
[ "LicenseRef-scancode-stlport-4.5" ]
permissive
richmondx/dead6
b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161
955f76f35d94ed5f991871407f3d3ad83f06a530
refs/heads/master
2021-12-05T14:32:01.782047
2008-01-01T13:13:39
2008-01-01T13:13:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
41,284
cpp
/* * Copyright (c) 1999 * Silicon Graphics Computer Systems, Inc. * * Copyright (c) 1999 * Boris Fomitchev * * This material is provided "as is", with absolutely no warranty expressed * or implied. Any use is at your own risk. * * Permission to use or copy this software for any purpose is hereby granted * without fee, provided the above notices are retained on all copies. * Permission to modify the code and to distribute modified code is granted, * provided the above notices are retained, and a notice that the code was * modified is included with the above copyright notice. * */ # include "stlport_prefix.h" #include <hash_map> #include "locale_impl.h" #include "c_locale.h" //#include "locale_nonclassic.h" #include "locale_impl.h" #include <stl/_codecvt.h> #include <stl/_collate.h> #include <stl/_ctype.h> #include <stl/_monetary.h> #include <stl/_time_facets.h> #include <stl/_messages_facets.h> #include <stl/_istream.h> #include <stl/_num_get.h> #include <stl/_num_put.h> #include <algorithm> // #include <stl/_ctype.h> #include <stl/_function.h> #include "c_locale.h" _STLP_BEGIN_NAMESPACE _Locale_ctype* __acquire_ctype(const char* name); void __release_ctype(_Locale_ctype* cat); //---------------------------------------------------------------------- // ctype_byname<char> ctype_byname<char>::ctype_byname(const char* name, size_t refs) : ctype<char>( 0, false, refs), _M_ctype(__acquire_ctype(name)) { ctype<char>::_M_ctype_table = _M_byname_table; if (!_M_ctype) locale::_M_throw_runtime_error(); // We have to do this, instead of just pointer twiddling, because // ctype_base::mask isn't the same type as _Locale_mask_t. const _Locale_mask_t* p = _Locale_ctype_table(_M_ctype); if (!p) locale::_M_throw_runtime_error(); for (size_t i = 0; i < table_size; ++i) { _Locale_mask_t __m = p[i]; if (__m & (upper | lower)) __m |= alpha; _M_byname_table[i] = ctype_base::mask(__m); } } ctype_byname<char>::~ctype_byname() { __release_ctype(_M_ctype); } char ctype_byname<char>::do_toupper(char c) const { return (char)_Locale_toupper(_M_ctype, c); } char ctype_byname<char>::do_tolower(char c) const { return (char)_Locale_tolower(_M_ctype, c); } const char* ctype_byname<char>::do_toupper(char* first, const char* last) const { for ( ; first != last ; ++first) *first = (char)_Locale_toupper(_M_ctype, *first); return last; } const char* ctype_byname<char>::do_tolower(char* first, const char* last) const { for ( ; first != last ; ++first) *first = (char)_Locale_tolower(_M_ctype, *first); return last; } // Some helper functions used in ctype<>::scan_is and scan_is_not. # ifndef _STLP_NO_WCHAR_T // ctype_byname<wchar_t> struct _Ctype_byname_w_is_mask { typedef wchar_t argument_type; typedef bool result_type; /* ctype_base::mask*/ int M; _Locale_ctype* M_ctp; _Ctype_byname_w_is_mask(/* ctype_base::mask */ int m, _Locale_ctype* c) : M((int)m), M_ctp(c) {} bool operator()(wchar_t c) const { return (M & _Locale_wchar_ctype(M_ctp, c, M)) != 0; } }; ctype_byname<wchar_t>::ctype_byname(const char* name, size_t refs) : ctype<wchar_t>(refs), _M_ctype(__acquire_ctype(name)) { if (!_M_ctype) locale::_M_throw_runtime_error(); } ctype_byname<wchar_t>::~ctype_byname() { __release_ctype(_M_ctype); } bool ctype_byname<wchar_t>::do_is(ctype_base::mask m, wchar_t c) const { return (m & _Locale_wchar_ctype(_M_ctype, c, m)) != 0; } const wchar_t* ctype_byname<wchar_t>::do_is(const wchar_t* low, const wchar_t* high, ctype_base::mask * m) const { ctype_base::mask all_bits = ctype_base::mask( ctype_base::space | ctype_base::print | ctype_base::cntrl | ctype_base::upper | ctype_base::lower | ctype_base::alpha | ctype_base::digit | ctype_base::punct | ctype_base::xdigit); for ( ; low < high; ++low, ++m) *m = ctype_base::mask (_Locale_wchar_ctype(_M_ctype, *low, all_bits)); return high; } const wchar_t* ctype_byname<wchar_t> ::do_scan_is(ctype_base::mask m, const wchar_t* low, const wchar_t* high) const { return find_if(low, high, _Ctype_byname_w_is_mask(m, _M_ctype)); } const wchar_t* ctype_byname<wchar_t> ::do_scan_not(ctype_base::mask m, const wchar_t* low, const wchar_t* high) const { return find_if(low, high, not1(_Ctype_byname_w_is_mask(m, _M_ctype))); } wchar_t ctype_byname<wchar_t>::do_toupper(wchar_t c) const { return _Locale_wchar_toupper(_M_ctype, c); } const wchar_t* ctype_byname<wchar_t>::do_toupper(wchar_t* low, const wchar_t* high) const { for ( ; low < high; ++low) *low = _Locale_wchar_toupper(_M_ctype, *low); return high; } wchar_t ctype_byname<wchar_t>::do_tolower(wchar_t c) const { return _Locale_wchar_tolower(_M_ctype, c); } const wchar_t* ctype_byname<wchar_t>::do_tolower(wchar_t* low, const wchar_t* high) const { for ( ; low < high; ++low) *low = _Locale_wchar_tolower(_M_ctype, *low); return high; } # endif /* WCHAR_T */ _STLP_END_NAMESPACE // # include "collate_byname.cpp" #include "stl/_collate.h" #include "c_locale.h" #include <vector> _STLP_BEGIN_NAMESPACE // collate_byname<char> _Locale_collate* __acquire_collate(const char* name); void __release_collate(_Locale_collate* cat); collate_byname<char>::collate_byname(const char* name, size_t refs) : collate<char>(refs), _M_collate(__acquire_collate(name)) { if (!_M_collate) locale::_M_throw_runtime_error(); } collate_byname<char>::~collate_byname() { __release_collate(_M_collate); } int collate_byname<char>::do_compare(const char* __low1, const char* __high1, const char* __low2, const char* __high2) const { return _Locale_strcmp(_M_collate, __low1, __high1 - __low1, __low2, __high2 - __low2); } collate_byname<char>::string_type collate_byname<char>::do_transform(const char* low, const char* high) const { size_t n = _Locale_strxfrm(_M_collate, NULL, 0, low, high - low); vector<char, allocator<char> > buf(n); _Locale_strxfrm(_M_collate, &buf.front(), n, low, high - low); char& __c1 = *(buf.begin()); char& __c2 = (n == (size_t)-1) ? *(buf.begin() + (high-low-1)) : *(buf.begin() + n); // char& __c2 = *(buf.begin() + n); return string_type( &__c1, &__c2 ); } # ifndef _STLP_NO_WCHAR_T // collate_byname<wchar_t> collate_byname<wchar_t>::collate_byname(const char* name, size_t refs) : collate<wchar_t>(refs), _M_collate(__acquire_collate(name)) { if (!_M_collate) locale::_M_throw_runtime_error(); } collate_byname<wchar_t>::~collate_byname() { __release_collate(_M_collate); } int collate_byname<wchar_t>::do_compare(const wchar_t* low1, const wchar_t* high1, const wchar_t* low2, const wchar_t* high2) const { return _Locale_strwcmp(_M_collate, low1, high1 - low1, low2, high2 - low2); } collate_byname<wchar_t>::string_type collate_byname<wchar_t> ::do_transform(const wchar_t* low, const wchar_t* high) const { size_t n = _Locale_strwxfrm(_M_collate, NULL, 0, low, high - low); vector<wchar_t, allocator<wchar_t> > buf(high - low); _Locale_strwxfrm(_M_collate, &buf.front(), n, low, high - low); wchar_t& __c1 = *(buf.begin()); wchar_t& __c2 = (n == (size_t)-1) ? *(buf.begin() + (high-low-1)) : *(buf.begin() + n); // wchar_t& __c2 = *(buf.begin() + n); return string_type( &__c1, &__c2 ); } # endif /* _STLP_NO_WCHAR_T */ _STLP_END_NAMESPACE # ifndef _STLP_NO_MBSTATE_T #include <stl/_codecvt.h> #include <stl/_algobase.h> #include "c_locale.h" _STLP_BEGIN_NAMESPACE //---------------------------------------------------------------------- // codecvt_byname<char> codecvt_byname<char, char, mbstate_t> ::codecvt_byname(const char* /* name */, size_t refs) : codecvt<char, char, mbstate_t>(refs) {} codecvt_byname<char, char, mbstate_t>::~codecvt_byname() {} # ifndef _STLP_NO_WCHAR_T //---------------------------------------------------------------------- // codecvt_byname<wchar_t> _Locale_ctype* __acquire_ctype(const char* name); void __release_ctype(_Locale_ctype* cat); codecvt_byname<wchar_t, char, mbstate_t> ::codecvt_byname(const char* name, size_t refs) : codecvt<wchar_t, char, mbstate_t>(refs), _M_ctype(__acquire_ctype(name)) { if (!_M_ctype) locale::_M_throw_runtime_error(); } codecvt_byname<wchar_t, char, mbstate_t>::~codecvt_byname() { __release_ctype(_M_ctype); } codecvt<wchar_t, char, mbstate_t>::result codecvt_byname<wchar_t, char, mbstate_t> ::do_out(state_type& state, const wchar_t* from, const wchar_t* from_end, const wchar_t*& from_next, char* to, char* to_limit, char*& to_next) const { while (from != from_end) { size_t chars_stored = _Locale_wctomb(_M_ctype, to, to_limit - to, *from, &state); if (chars_stored == (size_t) -1) { from_next = from; to_next = to; return error; } else if (chars_stored == (size_t) -2) { from_next = from; to_next = to; return partial; } ++from; to += chars_stored; } from_next = from; to_next = to; return ok; } codecvt<wchar_t, char, mbstate_t>::result codecvt_byname<wchar_t, char, mbstate_t> ::do_in(state_type& state, const extern_type* from, const extern_type* from_end, const extern_type*& from_next, intern_type* to, intern_type* , intern_type*& to_next) const { while (from != from_end) { size_t chars_read = _Locale_mbtowc(_M_ctype, to, from, from_end - from, &state); if (chars_read == (size_t) -1) { from_next = from; to_next = to; return error; } if (chars_read == (size_t) -2) { from_next = from; to_next = to; return partial; } from += chars_read; to++; } from_next = from; to_next = to; return ok; } codecvt<wchar_t, char, mbstate_t>::result codecvt_byname<wchar_t, char, mbstate_t> ::do_unshift(state_type& state, extern_type* to, extern_type* to_limit, extern_type*& to_next) const { to_next = to; size_t result = _Locale_unshift(_M_ctype, &state, to, to_limit - to, &to_next); if (result == (size_t) -1) return error; else if (result == (size_t) -2) return partial; else #ifdef __ISCPP__ return /*to_next == to ? noconv :*/ ok; #else return to_next == to ? noconv : ok; #endif } int codecvt_byname<wchar_t, char, mbstate_t>::do_encoding() const _STLP_NOTHROW { if (_Locale_is_stateless(_M_ctype)) { int max_width = _Locale_mb_cur_max(_M_ctype); int min_width = _Locale_mb_cur_min(_M_ctype); return min_width == max_width ? min_width : 0; } else return -1; } bool codecvt_byname<wchar_t, char, mbstate_t> ::do_always_noconv() const _STLP_NOTHROW { return false; } int codecvt_byname<wchar_t, char, mbstate_t>::do_length(const state_type&, const extern_type* from, const extern_type* end, size_t mx) const { return (int)(min) ((size_t) (end - from), mx); } int codecvt_byname<wchar_t, char, mbstate_t>::do_max_length() const _STLP_NOTHROW { return _Locale_mb_cur_max(_M_ctype); } # endif /* WCHAR_T */ _STLP_END_NAMESPACE # endif /* MBSTATE_T */ #include "locale_impl.h" # include <stl/_numpunct.h> _STLP_BEGIN_NAMESPACE _Locale_numeric* _STLP_CALL __acquire_numeric(const char* name); void _STLP_CALL __release_numeric(_Locale_numeric* cat); // numpunct_byname<char> numpunct_byname<char>::numpunct_byname(const char* name, size_t refs) : numpunct<char>(refs), _M_numeric(__acquire_numeric(name)) { if (!_M_numeric) locale::_M_throw_runtime_error(); _M_truename = _Locale_true(_M_numeric); _M_falsename = _Locale_false(_M_numeric); } numpunct_byname<char>::~numpunct_byname() { __release_numeric(_M_numeric); } char numpunct_byname<char>::do_decimal_point() const { return _Locale_decimal_point(_M_numeric); } char numpunct_byname<char>::do_thousands_sep() const { return _Locale_thousands_sep(_M_numeric); } string numpunct_byname<char>::do_grouping() const { const char * __grouping = _Locale_grouping(_M_numeric); if (__grouping != NULL && __grouping[0] == CHAR_MAX) __grouping = ""; return __grouping; } //---------------------------------------------------------------------- // numpunct<wchar_t> # ifndef _STLP_NO_WCHAR_T // numpunct_byname<wchar_t> numpunct_byname<wchar_t>::numpunct_byname(const char* name, size_t refs) : numpunct<wchar_t>(refs), _M_numeric(__acquire_numeric(name)) { if (!_M_numeric) locale::_M_throw_runtime_error(); const char* truename = _Locale_true(_M_numeric); const char* falsename = _Locale_false(_M_numeric); _M_truename.resize(strlen(truename)); _M_falsename.resize(strlen(falsename)); copy(truename, truename + strlen(truename), _M_truename.begin()); copy(falsename, falsename + strlen(falsename), _M_falsename.begin()); } numpunct_byname<wchar_t>::~numpunct_byname() { __release_numeric(_M_numeric); } wchar_t numpunct_byname<wchar_t>::do_decimal_point() const { return (wchar_t) _Locale_decimal_point(_M_numeric); } wchar_t numpunct_byname<wchar_t>::do_thousands_sep() const { return (wchar_t) _Locale_thousands_sep(_M_numeric); } string numpunct_byname<wchar_t>::do_grouping() const { const char * __grouping = _Locale_grouping(_M_numeric); if (__grouping != NULL && __grouping[0] == CHAR_MAX) __grouping = ""; return __grouping; } # endif _STLP_END_NAMESPACE #include <stl/_monetary.h> // #include <stl/_ostream.h> // #include <stl/_istream.h> #include "c_locale.h" _STLP_BEGIN_NAMESPACE static void _Init_monetary_formats(money_base::pattern& pos_format, money_base::pattern& neg_format, _Locale_monetary * monetary) { switch (_Locale_p_sign_posn(monetary)) { case 0: // Parentheses surround the quantity and currency_symbol case 1: // The sign string precedes the quantity and currency_symbol pos_format.field[0] = (char) money_base::sign; if (_Locale_p_cs_precedes(monetary)) { // 1 if currency_symbol precedes a positive value pos_format.field[1] = (char) money_base::symbol; if (_Locale_p_sep_by_space(monetary)) { // a space separates currency_symbol from a positive value. pos_format.field[2] = (char) money_base::space; pos_format.field[3] = (char) money_base::value; } else { // a space not separates currency_symbol from a positive value. pos_format.field[2] = (char) money_base::value; pos_format.field[3] = (char) money_base::none; } } else { // 0 if currency_symbol succeeds a positive value pos_format.field[1] = (char) money_base::value; if (_Locale_p_sep_by_space(monetary)) { // a space separates currency_symbol from a positive value. pos_format.field[2] = (char) money_base::space; pos_format.field[3] = (char) money_base::symbol; } else { // a space not separates currency_symbol from a positive value. pos_format.field[2] = (char) money_base::symbol; pos_format.field[3] = (char) money_base::none; } } break; case 2: // The sign string succeeds the quantity and currency_symbol. if (_Locale_p_cs_precedes(monetary)) { // 1 if currency_symbol precedes a positive value pos_format.field[0] = (char) money_base::symbol; if (_Locale_p_sep_by_space(monetary)) { // a space separates currency_symbol from a positive value. pos_format.field[1] = (char) money_base::space; pos_format.field[2] = (char) money_base::value; pos_format.field[3] = (char) money_base::sign; } else { // a space not separates currency_symbol from a positive value. pos_format.field[1] = (char) money_base::value; pos_format.field[2] = (char) money_base::sign; pos_format.field[3] = (char) money_base::none; } } else { // 0 if currency_symbol succeeds a positive value pos_format.field[0] = (char) money_base::value; if (_Locale_p_sep_by_space(monetary)) { // a space separates currency_symbol from a positive value. pos_format.field[1] = (char) money_base::space; pos_format.field[2] = (char) money_base::symbol; pos_format.field[3] = (char) money_base::sign; } else { // a space not separates currency_symbol from a positive value. pos_format.field[1] = (char) money_base::symbol; pos_format.field[2] = (char) money_base::sign; pos_format.field[3] = (char) money_base::none; } } break; case 3: // The sign string immediately precedes the currency_symbol. if (_Locale_p_cs_precedes(monetary)) { // 1 if currency_symbol precedes a positive value pos_format.field[0] = (char) money_base::sign; pos_format.field[1] = (char) money_base::symbol; if (_Locale_p_sep_by_space(monetary)) { // a space separates currency_symbol from a positive value. pos_format.field[2] = (char) money_base::space; pos_format.field[3] = (char) money_base::value; } else { // a space not separates currency_symbol from a positive value. pos_format.field[2] = (char) money_base::value; pos_format.field[3] = (char) money_base::none; } } else { // 0 if currency_symbol succeeds a positive value pos_format.field[0] = (char) money_base::value; pos_format.field[1] = (char) money_base::sign; pos_format.field[2] = (char) money_base::symbol; pos_format.field[3] = (char) money_base::none; } break; case 4: // The sign string immediately succeeds the currency_symbol. default: if (_Locale_p_cs_precedes(monetary)) { // 1 if currency_symbol precedes a positive value pos_format.field[0] = (char) money_base::symbol; pos_format.field[1] = (char) money_base::sign; pos_format.field[2] = (char) money_base::value; pos_format.field[3] = (char) money_base::none; } else { // 0 if currency_symbol succeeds a positive value pos_format.field[0] = (char) money_base::value; if (_Locale_p_sep_by_space(monetary)) { // a space separates currency_symbol from a positive value. pos_format.field[1] = (char) money_base::space; pos_format.field[2] = (char) money_base::symbol; pos_format.field[3] = (char) money_base::sign; } else { // a space not separates currency_symbol from a positive value. pos_format.field[1] = (char) money_base::symbol; pos_format.field[2] = (char) money_base::sign; pos_format.field[3] = (char) money_base::none; } } break; } switch (_Locale_n_sign_posn(monetary)) { case 0: // Parentheses surround the quantity and currency_symbol case 1: // The sign string precedes the quantity and currency_symbol neg_format.field[0] = (char) money_base::sign; if (_Locale_n_cs_precedes(monetary)) { // 1 if currency_symbol precedes a negative value neg_format.field[1] = (char) money_base::symbol; if (_Locale_n_sep_by_space(monetary)) { // a space separates currency_symbol from a negative value. neg_format.field[2] = (char) money_base::space; neg_format.field[3] = (char) money_base::value; } else { // a space not separates currency_symbol from a negative value. neg_format.field[2] = (char) money_base::value; neg_format.field[3] = (char) money_base::none; } } else { // 0 if currency_symbol succeeds a negative value neg_format.field[1] = (char) money_base::value; if (_Locale_n_sep_by_space(monetary)) { // a space separates currency_symbol from a negative value. neg_format.field[2] = (char) money_base::space; neg_format.field[3] = (char) money_base::symbol; } else { // a space not separates currency_symbol from a negative value. neg_format.field[2] = (char) money_base::symbol; neg_format.field[3] = (char) money_base::none; } } break; case 2: // The sign string succeeds the quantity and currency_symbol. if (_Locale_n_cs_precedes(monetary)) { // 1 if currency_symbol precedes a negative value neg_format.field[0] = (char) money_base::symbol; if (_Locale_n_sep_by_space(monetary)) { // a space separates currency_symbol from a negative value. neg_format.field[1] = (char) money_base::space; neg_format.field[2] = (char) money_base::value; neg_format.field[3] = (char) money_base::sign; } else { // a space not separates currency_symbol from a negative value. neg_format.field[1] = (char) money_base::value; neg_format.field[2] = (char) money_base::sign; neg_format.field[3] = (char) money_base::none; } } else { // 0 if currency_symbol succeeds a negative value neg_format.field[0] = (char) money_base::value; if (_Locale_n_sep_by_space(monetary)) { // a space separates currency_symbol from a negative value. neg_format.field[1] = (char) money_base::space; neg_format.field[2] = (char) money_base::symbol; neg_format.field[3] = (char) money_base::sign; } else { // a space not separates currency_symbol from a negative value. neg_format.field[1] = (char) money_base::symbol; neg_format.field[2] = (char) money_base::sign; neg_format.field[3] = (char) money_base::none; } } break; case 3: // The sign string immediately precedes the currency_symbol. if (_Locale_n_cs_precedes(monetary)) { // 1 if currency_symbol precedes a negative value neg_format.field[0] = (char) money_base::sign; neg_format.field[1] = (char) money_base::symbol; if (_Locale_n_sep_by_space(monetary)) { // a space separates currency_symbol from a negative value. neg_format.field[2] = (char) money_base::space; neg_format.field[3] = (char) money_base::value; } else { // a space not separates currency_symbol from a negative value. neg_format.field[2] = (char) money_base::value; neg_format.field[3] = (char) money_base::none; } } else { // 0 if currency_symbol succeeds a negative value neg_format.field[0] = (char) money_base::value; neg_format.field[1] = (char) money_base::sign; neg_format.field[2] = (char) money_base::symbol; neg_format.field[3] = (char) money_base::none; } break; case 4: // The sign string immediately succeeds the currency_symbol. default: if (_Locale_n_cs_precedes(monetary)) { // 1 if currency_symbol precedes a negative value neg_format.field[0] = (char) money_base::symbol; neg_format.field[1] = (char) money_base::sign; neg_format.field[2] = (char) money_base::value; neg_format.field[3] = (char) money_base::none; } else { // 0 if currency_symbol succeeds a negative value neg_format.field[0] = (char) money_base::value; if (_Locale_n_sep_by_space(monetary)) { // a space separates currency_symbol from a negative value. neg_format.field[1] = (char) money_base::space; neg_format.field[2] = (char) money_base::symbol; neg_format.field[3] = (char) money_base::sign; } else { // a space not separates currency_symbol from a negative value. neg_format.field[1] = (char) money_base::symbol; neg_format.field[2] = (char) money_base::sign; neg_format.field[3] = (char) money_base::none; } } break; } } // international variant of monetary /* * int_curr_symbol * * The international currency symbol. The operand is a four-character * string, with the first three characters containing the alphabetic * international currency symbol in accordance with those specified * in the ISO 4217 specification. The fourth character is the character used * to separate the international currency symbol from the monetary quantity. * * (http://www.opengroup.org/onlinepubs/7990989775/xbd/locale.html) */ /* * Standards are unclear in the usage of international currency * and monetary formats. * But I am expect that international currency symbol should be the first * (not depends upon where currency symbol situated in the national * format). * * If this isn't so, let's see: * 1 234.56 RUR * GBP 1,234.56 * USD 1,234.56 * The situation really is worse than you see above: * RUR typed wrong here---it prints '1 234.56 RUR ' (see space after RUR). * This is due to intl_fmp.curr_symbol() == "RUR ". (see reference in comments * above). * */ static void _Init_monetary_formats_int(money_base::pattern& pos_format, money_base::pattern& neg_format, _Locale_monetary * monetary) { pos_format.field[0] = (char) money_base::symbol; // pos_format.field[1] = (char) money_base::space; switch (_Locale_p_sign_posn(monetary)) { case 0: // Parentheses surround the quantity and currency_symbol case 1: // The sign string precedes the quantity and currency_symbol pos_format.field[1] = (char) money_base::sign; pos_format.field[2] = (char) money_base::value; break; case 2: // The sign string succeeds the quantity and currency_symbol. pos_format.field[1] = (char) money_base::value; pos_format.field[2] = (char) money_base::sign; break; case 3: // The sign string immediately precedes the currency_symbol. case 4: // The sign string immediately succeeds the currency_symbol. default: if (_Locale_p_cs_precedes(monetary)) { // 1 if currency_symbol precedes a positive value pos_format.field[1] = (char) money_base::sign; pos_format.field[2] = (char) money_base::value; } else { // 0 if currency_symbol succeeds a positive value pos_format.field[1] = (char) money_base::value; pos_format.field[2] = (char) money_base::sign; } break; } pos_format.field[3] = (char) money_base::none; neg_format.field[0] = (char) money_base::symbol; // neg_format.field[1] = (char) money_base::space; switch (_Locale_n_sign_posn(monetary)) { case 0: // Parentheses surround the quantity and currency_symbol case 1: // The sign string precedes the quantity and currency_symbol neg_format.field[1] = (char) money_base::sign; neg_format.field[2] = (char) money_base::value; break; case 2: // The sign string succeeds the quantity and currency_symbol. neg_format.field[1] = (char) money_base::value; neg_format.field[2] = (char) money_base::sign; break; case 3: // The sign string immediately precedes the currency_symbol. case 4: // The sign string immediately succeeds the currency_symbol. default: if (_Locale_n_cs_precedes(monetary)) { // 1 if currency_symbol precedes a negative value neg_format.field[1] = (char) money_base::sign; neg_format.field[2] = (char) money_base::value; } else { // 0 if currency_symbol succeeds a negative value neg_format.field[1] = (char) money_base::value; neg_format.field[2] = (char) money_base::sign; } break; } neg_format.field[3] = (char) money_base::none; } // // moneypunct_byname<> // _Locale_monetary* __acquire_monetary(const char* name); void __release_monetary(_Locale_monetary* mon); moneypunct_byname<char, true>::moneypunct_byname(const char * name, size_t refs): moneypunct<char, true>(refs), _M_monetary(__acquire_monetary(name)) { if (!_M_monetary) locale::_M_throw_runtime_error(); _Init_monetary_formats_int(_M_pos_format, _M_neg_format, _M_monetary); } moneypunct_byname<char, true>::~moneypunct_byname() { __release_monetary(_M_monetary); } char moneypunct_byname<char, true>::do_decimal_point() const {return _Locale_mon_decimal_point(_M_monetary);} char moneypunct_byname<char, true>::do_thousands_sep() const {return _Locale_mon_thousands_sep(_M_monetary);} string moneypunct_byname<char, true>::do_grouping() const {return _Locale_mon_grouping(_M_monetary);} string moneypunct_byname<char, true>::do_curr_symbol() const {return _Locale_int_curr_symbol(_M_monetary);} string moneypunct_byname<char, true>::do_positive_sign() const {return _Locale_positive_sign(_M_monetary);} string moneypunct_byname<char, true>::do_negative_sign() const {return _Locale_negative_sign(_M_monetary);} int moneypunct_byname<char, true>::do_frac_digits() const {return _Locale_int_frac_digits(_M_monetary);} moneypunct_byname<char, false>::moneypunct_byname(const char * name, size_t refs): moneypunct<char, false>(refs), _M_monetary(__acquire_monetary(name)) { if (!_M_monetary) locale::_M_throw_runtime_error(); _Init_monetary_formats(_M_pos_format, _M_neg_format, _M_monetary); } moneypunct_byname<char, false>::~moneypunct_byname() { __release_monetary(_M_monetary); } char moneypunct_byname<char, false>::do_decimal_point() const {return _Locale_mon_decimal_point(_M_monetary);} char moneypunct_byname<char, false>::do_thousands_sep() const {return _Locale_mon_thousands_sep(_M_monetary);} string moneypunct_byname<char, false>::do_grouping() const {return _Locale_mon_grouping(_M_monetary);} string moneypunct_byname<char, false>::do_curr_symbol() const {return _Locale_currency_symbol(_M_monetary);} string moneypunct_byname<char, false>::do_positive_sign() const {return _Locale_positive_sign(_M_monetary);} string moneypunct_byname<char, false>::do_negative_sign() const {return _Locale_negative_sign(_M_monetary);} int moneypunct_byname<char, false>::do_frac_digits() const {return _Locale_frac_digits(_M_monetary);} // // moneypunct_byname<wchar_t> // # ifndef _STLP_NO_WCHAR_T moneypunct_byname<wchar_t, true>::moneypunct_byname(const char * name, size_t refs): moneypunct<wchar_t, true>(refs), _M_monetary(__acquire_monetary(name)) { if (!_M_monetary) locale::_M_throw_runtime_error(); _Init_monetary_formats_int(_M_pos_format, _M_neg_format, _M_monetary); } moneypunct_byname<wchar_t, true>::~moneypunct_byname() { __release_monetary(_M_monetary); } wchar_t moneypunct_byname<wchar_t, true>::do_decimal_point() const {return _Locale_mon_decimal_point(_M_monetary);} wchar_t moneypunct_byname<wchar_t, true>::do_thousands_sep() const {return _Locale_mon_thousands_sep(_M_monetary);} string moneypunct_byname<wchar_t, true>::do_grouping() const {return _Locale_mon_grouping(_M_monetary);} inline wstring __do_widen (string const& str) { # if defined (_STLP_NO_MEMBER_TEMPLATES) || defined (_STLP_MSVC) || defined(__MRC__) || defined(__SC__) //*ty 05/26/2001 - added workaround for mpw wstring::_Reserve_t __Reserve; size_t __size = str.size(); wstring result(__Reserve, __size); copy(str.begin(), str.end(), result.begin()); # else wstring result(str.begin(), str.end()); # endif return result; } wstring moneypunct_byname<wchar_t, true>::do_curr_symbol() const {return __do_widen(_Locale_int_curr_symbol(_M_monetary));} wstring moneypunct_byname<wchar_t, true>::do_positive_sign() const {return __do_widen(_Locale_positive_sign(_M_monetary));} wstring moneypunct_byname<wchar_t, true>::do_negative_sign() const {return __do_widen(_Locale_negative_sign(_M_monetary));} int moneypunct_byname<wchar_t, true>::do_frac_digits() const {return _Locale_int_frac_digits(_M_monetary);} moneypunct_byname<wchar_t, false>::moneypunct_byname(const char * name, size_t refs): moneypunct<wchar_t, false>(refs), _M_monetary(__acquire_monetary(name)) { if (!_M_monetary) locale::_M_throw_runtime_error() ; _Init_monetary_formats(_M_pos_format, _M_neg_format, _M_monetary); } moneypunct_byname<wchar_t, false>::~moneypunct_byname() {__release_monetary(_M_monetary);} wchar_t moneypunct_byname<wchar_t, false>::do_decimal_point() const {return _Locale_mon_decimal_point(_M_monetary);} wchar_t moneypunct_byname<wchar_t, false>::do_thousands_sep() const {return _Locale_mon_thousands_sep(_M_monetary);} string moneypunct_byname<wchar_t, false>::do_grouping() const {return _Locale_mon_grouping(_M_monetary);} wstring moneypunct_byname<wchar_t, false>::do_curr_symbol() const {return __do_widen(_Locale_currency_symbol(_M_monetary));} wstring moneypunct_byname<wchar_t, false>::do_positive_sign() const {return __do_widen(_Locale_positive_sign(_M_monetary));} wstring moneypunct_byname<wchar_t, false>::do_negative_sign() const {return __do_widen(_Locale_negative_sign(_M_monetary));} int moneypunct_byname<wchar_t, false>::do_frac_digits() const {return _Locale_frac_digits(_M_monetary);} # endif _STLP_END_NAMESPACE #include <stl/_messages_facets.h> #include "message_facets.h" #ifndef _STLP_NO_RTTI # include <typeinfo> #endif /*_STLP_NO_RTTI*/ _STLP_BEGIN_NAMESPACE void _Catalog_locale_map::insert(nl_catd_type key, const locale& L) { _STLP_TRY { #if !defined(_STLP_NO_TYPEINFO) && !defined(_STLP_NO_RTTI) // Don't bother to do anything unless we're using a non-default ctype facet # ifdef _STLP_NO_WCHAR_T typedef char _Char; # else typedef wchar_t _Char; # endif typedef ctype<_Char> wctype; wctype const& wct = use_facet<wctype>(L); if (typeid(wct) != typeid(wctype)) { # endif /* _STLP_NO_TYPEINFO */ if (!M) M = new map_type; #if defined(__SC__) if (!M) delete M; #endif M->insert(map_type::value_type(key, L)); #if !defined(_STLP_NO_TYPEINFO) && !defined(_STLP_NO_RTTI) } # endif /* _STLP_NO_TYPEINFO */ } _STLP_CATCH_ALL {} } void _Catalog_locale_map::erase(nl_catd_type key) { if (M) M->erase(key); } locale _Catalog_locale_map::lookup(nl_catd_type key) const { if (M) { map_type::const_iterator i = M->find(key); return i != M->end() ? (*i).second : locale::classic(); } else return locale::classic(); } #if defined (_STLP_USE_NL_CATD_MAPPING) int _Catalog_nl_catd_map::_count = 0; messages_base::catalog _Catalog_nl_catd_map::insert(nl_catd_type cat) { messages_base::catalog &res = Mr[cat]; if ( res == 0 ) { #if defined (_STLP_ATOMIC_INCREMENT) res = _STLP_ATOMIC_INCREMENT(&_count); #else static _STLP_STATIC_MUTEX _Count_lock _STLP_MUTEX_INITIALIZER; { _STLP_auto_lock sentry(_Count_lock); res = ++_count; } #endif M[res] = cat; } return res; } void _Catalog_nl_catd_map::erase(messages_base::catalog cat) { map_type::iterator mit(M.find(cat)); if (mit != M.end()) { Mr.erase((*mit).second); M.erase(mit); } } #endif //---------------------------------------------------------------------- // // _Messages_impl::_Messages_impl(bool is_wide) : _M_message_obj(0), _M_map(0) { _M_delete = true; if (is_wide) _M_map = new _Catalog_locale_map; _M_message_obj = __acquire_messages("C"); } _Messages_impl::_Messages_impl(bool is_wide, _Locale_messages* msg_obj ) : _M_message_obj(msg_obj), _M_map(0) { _M_delete = true; if (is_wide) _M_map = new _Catalog_locale_map; } _Messages_impl::~_Messages_impl() { __release_messages(_M_message_obj); if (_M_map) delete _M_map; } _Messages::catalog _Messages_impl::do_open(const string& filename, const locale& L) const { nl_catd_type result = _M_message_obj ? _Locale_catopen(_M_message_obj, filename.c_str()) : (nl_catd_type)(-1); if ( result != (nl_catd_type)(-1) ) { if ( _M_map != 0 ) { _M_map->insert(result, L); } return _M_cat.insert( result ); } return -1; } string _Messages_impl::do_get(catalog cat, int set, int p_id, const string& dfault) const { return _M_message_obj != 0 && cat >= 0 ? string(_Locale_catgets(_M_message_obj, _M_cat[cat], set, p_id, dfault.c_str())) : dfault; } # ifndef _STLP_NO_WCHAR_T wstring _Messages_impl::do_get(catalog thecat, int set, int p_id, const wstring& dfault) const { typedef ctype<wchar_t> wctype; const wctype& ct = use_facet<wctype>(_M_map->lookup( _M_cat[thecat] ) ); const char* str = _Locale_catgets(_M_message_obj, _M_cat[thecat], set, p_id, ""); // Verify that the lookup failed; an empty string might represent success. if (!str) return dfault; else if (str[0] == '\0') { const char* str2 = _Locale_catgets(_M_message_obj, _M_cat[thecat], set, p_id, "*"); if (!str2 || ((str2[0] == '*') && (str2[1] == '\0'))) return dfault; } // str is correct. Now we must widen it to get a wstring. size_t n = strlen(str); // NOT PORTABLE. What we're doing relies on internal details of the // string implementation. (Contiguity of string elements.) wstring result(n, wchar_t(0)); ct.widen(str, str + n, &*result.begin()); return result; } # endif void _Messages_impl::do_close(catalog thecat) const { if (_M_message_obj) _Locale_catclose(_M_message_obj, _M_cat[thecat]); if (_M_map) _M_map->erase(_M_cat[thecat]); _M_cat.erase( thecat ); } //---------------------------------------------------------------------- // messages<char> messages<char>::messages(size_t refs) : locale::facet(refs), _M_impl(new _Messages_impl(false)) {} messages<char>::messages(size_t refs, _Locale_messages* msg_obj) : locale::facet(refs), _M_impl(new _Messages_impl(false, msg_obj)) {} //---------------------------------------------------------------------- // messages_byname<char> messages_byname<char>::messages_byname(const char* name, size_t refs) : messages<char>(refs, name ? __acquire_messages(name) : 0) {} messages_byname<char>::~messages_byname() {} # ifndef _STLP_NO_WCHAR_T //---------------------------------------------------------------------- // messages<wchar_t> messages<wchar_t>::messages(size_t refs) : locale::facet(refs), _M_impl(new _Messages_impl(true)) {} messages<wchar_t>::messages(size_t refs, _Locale_messages* msg_obj) : locale::facet(refs), _M_impl(new _Messages_impl(true, msg_obj)) {} //---------------------------------------------------------------------- // messages_byname<wchar_t> messages_byname<wchar_t>::messages_byname(const char* name, size_t refs) : messages<wchar_t>(refs, name ? __acquire_messages(name) : 0) {} messages_byname<wchar_t>::~messages_byname() {} # endif _STLP_END_NAMESPACE
[ [ [ 1, 1222 ] ] ]
4c27a9698657fe920b81795a1a4eef98635d0895
52ee98d8e00d66f71139a2e86f1464244eb1616b
/left_rotate.cpp
04f802595d2f055dff7c3cc581edbd126f144783
[]
no_license
shaoyang/algorithm
ea0784e2b92465e54517016a7a8623c109ac9fc1
571b6423f5cf7c4bee21ff99b69b972d491c970d
refs/heads/master
2016-09-05T12:37:14.878376
2011-03-22T16:21:58
2011-03-22T16:21:58
1,502,765
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
658
cpp
#include<iostream> using namespace std; typedef struct Node{ int key; int color; struct Node* parent; struct Node* left; struct Node* right; }*BRNode; BRNode NIL = new Node(); NIL->key = -1; NIL->color = -1; NIL->parent = NULL; NIL->left = NULL; NIL->right = NULL; //×óÐý void left_rotate(BRNode head,BRNode x){ BRNode y,p; y = x->right; x->right = y->left; p = x->parent; y->parent = p; if(p == NULL) head = y; else if(x == p->left) x->left = y; else x->right = y; y->left = x; x->parent = y; } int main(){ int A[] = {10,8,23,15,16,2,9,4,29}; int len = 9; BRNode head = new Node(); }
[ [ [ 1, 40 ] ] ]
028de226e462800805d54ecc30ea924da348d537
6a925ad6f969afc636a340b1820feb8983fc049b
/librtsp/librtsp/src/ServerMediasession.cpp
b0cb24e79a7528c59944bd659f150c5437439968
[]
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
6,237
cpp
/*!@file ServerMediasession.cpp @brief Copyright (c) 2009 HUST ITEC VoIP Lab. All rights reserved. @author Wentao Tang @date 2009.3.21 @version 1.0 */ #include "rtspCommon.h" #include "util.h" #include "jrtplib/rtpsession.h" #include <sys/time.h> #include "ServerMediaSubsession.h" #include "ServerMediasession.h" #include <cmath> ServerMediaSession::ServerMediaSession( string streamName /*= "VoIP_Stream"*/, string InfoString /*= "VoIP Live"*/, string DesString /*= "Streaming By VoIP Live System"*/, string micsString /*= ""*/ ) { streamName_ = streamName; SDPInfoString_ = InfoString; SDPDescriptionString_ = DesString; SDPmicsString_ = micsString; streamingStatus_ = STREAM_READY; } ServerMediaSession::~ServerMediaSession(void) { SubsessionIterator begin = subSessions_.begin(); SubsessionIterator end = subSessions_.end(); SubsessionIterator Itor = begin; for ( ; Itor != end; ++Itor ) { if ( *Itor ) { delete *Itor; *Itor = NULL; } } } string ServerMediaSession::GenerateSDPDescription() { //To support SSM source in the future float dur = Duration(); string rangeLine; if (dur == 0.0) ///FIXME { rangeLine = string("a=range:npt=0-"); } else if (dur > 0.0) { char buf[100]; sprintf(buf, "a=range:npt=0-%.3f", dur); rangeLine = string(buf); } else { // subSessions have differing durations, so "a=range:" lines go there rangeLine = ""; } string sdpinfo; sdpinfo += "v=0\r\n"; // Version 0 struct timeval generatetime; gettimeofday(&generatetime, NULL); char buf[100]; sprintf(buf, "o=- %ld%06ld %d IN IP4 %s\r\n", generatetime.tv_sec, generatetime.tv_usec, 1, localIPAddr_.data()); sdpinfo += buf; // Version 0 sdpinfo += "s=" + SDPDescriptionString_ + RTSP::CRLF; sdpinfo += "i=" + SDPInfoString_ + RTSP::CRLF; //sdpinfo += "a=tool:" + "" sdpinfo += "t=0 0\r\n"; sdpinfo += "a=type:broadcast\r\n"; sdpinfo += "a=control:*\r\n"; sdpinfo += rangeLine + RTSP::CRLF; sdpinfo += "a=x-qt-text-nam:" + SDPDescriptionString_ + RTSP::CRLF; sdpinfo += "a=x-qt-text-inf:" + SDPInfoString_ + RTSP::CRLF; SubsessionIterator begin = subSessions_.begin(); SubsessionIterator end = subSessions_.end(); SubsessionIterator Itor = begin; for ( ; Itor != end; ++Itor ) { sdpinfo += (*Itor)->SDPLines(); } return sdpinfo; } bool ServerMediaSession::AddSubsession( ServerMediaSubSession * subsession) { if ( subsession->IsAlreadyUsed() ) { return false; } else { subSessions_.push_back(subsession); subsession->IncreUseCount(); subsession->SetTrackID(subSessions_.size()); } return true; } float ServerMediaSession::Duration() const { float result = 0.0; float maxduration = 0; float minduration = 0; const_SubsessionIterator begin = subSessions_.begin(); const_SubsessionIterator end = subSessions_.end(); const_SubsessionIterator Itor = begin; for ( ; Itor != end; ++Itor ) { float dur = (*Itor)->Duration(); if ( dur > maxduration ) { maxduration = dur; } if ( dur < minduration ) { minduration = dur; } } // subSession durations differ // fabs( maxduration - minduration ) < 1e-6 if ( maxduration - minduration < 1e-6 || - ( maxduration - minduration ) < 1e-6) { result = - maxduration; } else // all subSession durations are the same { result = maxduration; } return result; } int ServerMediaSession::StartStream() { if ( STREAMING == streamingStatus_ ) { return 0; } SubsessionIterator begin = subSessions_.begin(); SubsessionIterator end = subSessions_.end(); SubsessionIterator Itor = begin; for ( ; Itor != end; ++Itor ) { (*Itor)->Start(); } streamingStatus_ = STREAMING; return -1; } void ServerMediaSession::TestScaleFactor( float& scale ) { scale = 1; } void ServerMediaSession::AddDestinationAddr( string dstaddr ) { SubsessionIterator begin = subSessions_.begin(); SubsessionIterator end = subSessions_.end(); SubsessionIterator Itor = begin; destinationAddr_ = dstaddr; for ( ; Itor != end; ++Itor ) { (*Itor)->AddDestination(dstaddr); } } ServerMediaSubSession * ServerMediaSession::FindSubSessionByTrackName( string trackname ) { SubsessionIterator begin = subSessions_.begin(); SubsessionIterator end = subSessions_.end(); SubsessionIterator Itor = begin; for ( ; Itor != end; ++Itor ) { string tname = (*Itor)->TrackName(); if (tname == trackname ) { return *Itor; } } return NULL; } string ServerMediaSession::GetRTPInfo( string requestURI ) { SubsessionIterator begin = subSessions_.begin(); SubsessionIterator end = subSessions_.end(); SubsessionIterator Itor = begin; string rtpInfo; for ( ; Itor != end; ++Itor ) { if (Itor != begin ) { rtpInfo += ","; } rtpInfo += "url=" + requestURI + "/" +(*Itor)->RTPInfo(); } return rtpInfo; } int ServerMediaSession::StopStream() { if ( STREAM_STOP == streamingStatus_ ) { return 0; } SubsessionIterator begin = subSessions_.begin(); SubsessionIterator end = subSessions_.end(); SubsessionIterator Itor = begin; for ( ; Itor != end; ++Itor ) { (*Itor)->Stop(); } streamingStatus_ = STREAM_STOP; return 0; } void ServerMediaSession::SetLoaclAddr( string addr ) { localIPAddr_ = addr; }
[ "TangWentaoHust@95ff1050-1aa1-11de-b6aa-3535bc3264a2" ]
[ [ [ 1, 244 ] ] ]
324d5812f04b215bd9fd76df269e55a7df7cd003
0b1111e870b496aae0d6210806eebf1c942c9d3a
/LinearAlgebra/TBLAS/tblas_defs.hpp
9fc0e1592a1237224998627884669e70bdf4a2e0
[ "WTFPL" ]
permissive
victorliu/Templated-Numerics
8ca3fabd79435fa40e95e9c8c944ecba42a0d8db
35ca6bb719615d5498a450a2d58e2aa2bb7ef5f9
refs/heads/master
2016-09-05T16:32:22.250276
2009-12-30T07:48:03
2009-12-30T07:48:03
318,857
3
1
null
null
null
null
UTF-8
C++
false
false
956
hpp
#ifndef _TBLAS_DEFS_H_ #define _TBLAS_DEFS_H_ #define TBLAS_UINT unsigned int #define TBLAS_INT int #define TBLAS_EXTENSIONS // want to use the extra functions #define TBLAS_OVERFLOW_PROTECTION // want to go prevent against over/underflow #define TBLAS_NAME(lower,upper) lower #define TBLAS_ASSERT(COND, DESC) do{ if(!(COND)){ TBLAS_ERROR(DESC); } }while(0) #define TBLAS_ERROR(DESC) fprintf(stderr, "Error in %s: %s", __FUNCTION__, DESC) #define TBLAS_STARTING_OFFSET(N, INC) ((INC)>0 ? 0 : ((N) - 1) * (-(INC))) #define GB(KU,KL,lda,i,j) ((KU+1+(i-j))*lda + j) #define TRCOUNT(N,i) ((((i)+1)*(2*(N)-(i)))/2) /* #define TBUP(N,i,j) */ /* #define TBLO(N,i,j) */ #define TPUP(N,i,j) (TRCOUNT(N,(i)-1)+(j)-(i)) #define TPLO(N,i,j) (((i)*((i)+1))/2 + (j)) #define TBLAS_ABS(arg) std::abs(arg) #define TBLAS_SQRT(arg) std::sqrt(arg) #define TBLAS_CONJ(arg) std::conj(arg) #define TBLAS_TRAITS(type) TypeTraits<type> #endif
[ "victor@onyx.(none)", "[email protected]" ]
[ [ [ 1, 3 ], [ 7, 26 ], [ 28, 29 ] ], [ [ 4, 6 ], [ 27, 27 ] ] ]
c5691435a3467ee837b3e93922f2647ed01e7897
7eb81dd252c71766e047eaf6c0a78549b3eeee20
/trunk/src/egmg/Function/Function.cpp
f7510bbb70d3f239f2fc0f63e4493699b2e6ccf8
[]
no_license
BackupTheBerlios/egmg-svn
1325afce712567c99bd7601e24c6cac44a032905
71d770fc123611de8a62d2cabf4134e783dbae49
refs/heads/master
2021-01-01T15:18:37.469550
2007-04-30T11:31:27
2007-04-30T11:31:27
40,614,587
0
0
null
null
null
null
UTF-8
C++
false
false
171
cpp
#include "Function.h" namespace mg { Precision Function::operator() (Precision x, Precision y) const { return apply(x, y); } Function::~Function() {} }
[ "jirikraus@c8ad9165-030d-0410-b95e-c1df97c73749", "tragetaschen@c8ad9165-030d-0410-b95e-c1df97c73749" ]
[ [ [ 1, 10 ], [ 14, 14 ] ], [ [ 11, 13 ] ] ]
14bf41ec75823352f5e02c5788b3fd90bfff3fb4
e8fab7f64d01d63f439ec6a98aff2a1d30b648b4
/process/datastore/direct/tm_q_4.cpp
abb4bada3b5219b4eb56356610fb055758b84111
[]
no_license
robbywalker/phftables
387452301aace677cb345909704967e8390d1be9
e00afc683025cfb3abced5721f3449783e4a9023
refs/heads/master
2021-01-21T00:52:09.945550
2011-04-24T18:20:38
2011-04-24T18:20:38
1,657,308
0
0
null
null
null
null
UTF-8
C++
false
false
904
cpp
#include "direct.h" #include "../datastore.h" #include "../util/math.h" class direct_tm_q_4 : public directConstruction { public: direct_tm_q_4() : directConstruction( "tm_q_4", 11 ) { } void process() { intSet::const_iterator it; for ( it = prime_powers.begin(); it != prime_powers.end(); it++ ) { int v = *it; if ( v < 7 ) continue; if ( v > MAXV ) break; int i = 1; bool toobig = false; while ( ! toobig ) { array * arr = new array(); arr->N = ((2 * i * i * i + 3 * i * i + i)/6)*5 + i + 1; arr->k = ipow( v, i + 1 ); arr->v = v; arr->t = 4; if ( arr->k > MAXK ) { toobig = true; } arr->type = 'D'; arr->source = id; printArray( arr ); insertArray( arr ); i++; } } } }; // declare the construction object directConstruction * tm_q_4 = new direct_tm_q_4();
[ [ [ 1, 45 ] ] ]
cc65fa5002123a669d3784d16368fb02ca048c3b
3a8f285d73216552b351cf471a08bcc2ad929c7f
/ghost/map.cpp
41d8862ce4689a365893b027033aa2a175405f42
[ "Apache-2.0" ]
permissive
LAPIZTOLITA/Ghost-C--
614adf84aaa908b61e0f00085e41718d5c54391f
ea5ab65de6d60ed4a95038e09657cf331520c077
refs/heads/master
2021-01-25T05:28:06.178821
2011-05-09T13:53:32
2011-05-09T13:53:32
1,884,328
0
0
null
null
null
null
UTF-8
C++
false
false
34,660
cpp
/* Copyright [2008] [Trevor Hogan] 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. CODE PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/ */ #include "ghost.h" #include "util.h" #include "crc32.h" #include "sha1.h" #include "config.h" #include "map.h" #define __STORMLIB_SELF__ #include <stormlib/StormLib.h> #define ROTL(x,n) ((x)<<(n))|((x)>>(32-(n))) // this won't work with signed types #define ROTR(x,n) ((x)>>(n))|((x)<<(32-(n))) // this won't work with signed types // // CMap // CMap :: CMap( CGHost *nGHost ) : m_GHost( nGHost ), m_Valid( true ), m_MapPath( "Maps\\FrozenThrone\\(12)EmeraldGardens.w3x" ), m_MapSize( UTIL_ExtractNumbers( "174 221 4 0", 4 ) ), m_MapInfo( UTIL_ExtractNumbers( "251 57 68 98", 4 ) ), m_MapCRC( UTIL_ExtractNumbers( "108 250 204 59", 4 ) ), m_MapSHA1( UTIL_ExtractNumbers( "35 81 104 182 223 63 204 215 1 17 87 234 220 66 3 185 82 99 6 13", 20 ) ), m_MapSpeed( MAPSPEED_FAST ), m_MapVisibility( MAPVIS_DEFAULT ), m_MapObservers( MAPOBS_NONE ), m_MapFlags( MAPFLAG_TEAMSTOGETHER | MAPFLAG_FIXEDTEAMS ), m_MapFilterMaker( MAPFILTER_MAKER_BLIZZARD ), m_MapFilterType( MAPFILTER_TYPE_MELEE ), m_MapFilterSize( MAPFILTER_SIZE_LARGE ), m_MapFilterObs( MAPFILTER_OBS_NONE ), m_MapOptions( MAPOPT_MELEE ), m_MapWidth( UTIL_ExtractNumbers( "172 0", 2 ) ), m_MapHeight( UTIL_ExtractNumbers( "172 0", 2 ) ), m_MapLoadInGame( false ), m_MapNumPlayers( 12 ), m_MapNumTeams( 12 ) { CONSOLE_Print( "[MAP] using hardcoded Emerald Gardens map data for Warcraft 3 version 1.24 & 1.24b" ); m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 0, 0, SLOTRACE_RANDOM | SLOTRACE_SELECTABLE ) ); m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 1, 1, SLOTRACE_RANDOM | SLOTRACE_SELECTABLE ) ); m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 2, 2, SLOTRACE_RANDOM | SLOTRACE_SELECTABLE ) ); m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 3, 3, SLOTRACE_RANDOM | SLOTRACE_SELECTABLE ) ); m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 4, 4, SLOTRACE_RANDOM | SLOTRACE_SELECTABLE ) ); m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 5, 5, SLOTRACE_RANDOM | SLOTRACE_SELECTABLE ) ); m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 6, 6, SLOTRACE_RANDOM | SLOTRACE_SELECTABLE ) ); m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 7, 7, SLOTRACE_RANDOM | SLOTRACE_SELECTABLE ) ); m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 8, 8, SLOTRACE_RANDOM | SLOTRACE_SELECTABLE ) ); m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 9, 9, SLOTRACE_RANDOM | SLOTRACE_SELECTABLE ) ); m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 10, 10, SLOTRACE_RANDOM | SLOTRACE_SELECTABLE ) ); m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 11, 11, SLOTRACE_RANDOM | SLOTRACE_SELECTABLE ) ); } CMap :: CMap( CGHost *nGHost, CConfig *CFG, string nCFGFile ) : m_GHost( nGHost ) { Load( CFG, nCFGFile ); } CMap :: ~CMap( ) { } BYTEARRAY CMap :: GetMapGameFlags( ) { /* Speed: (mask 0x00000003) cannot be combined 0x00000000 - Slow game speed 0x00000001 - Normal game speed 0x00000002 - Fast game speed Visibility: (mask 0x00000F00) cannot be combined 0x00000100 - Hide terrain 0x00000200 - Map explored 0x00000400 - Always visible (no fog of war) 0x00000800 - Default Observers/Referees: (mask 0x40003000) cannot be combined 0x00000000 - No Observers 0x00002000 - Observers on Defeat 0x00003000 - Additional players as observer allowed 0x40000000 - Referees Teams/Units/Hero/Race: (mask 0x07064000) can be combined 0x00004000 - Teams Together (team members are placed at neighbored starting locations) 0x00060000 - Fixed teams 0x01000000 - Unit share 0x02000000 - Random hero 0x04000000 - Random races */ uint32_t GameFlags = 0; // speed if( m_MapSpeed == MAPSPEED_SLOW ) GameFlags = 0x00000000; else if( m_MapSpeed == MAPSPEED_NORMAL ) GameFlags = 0x00000001; else GameFlags = 0x00000002; // visibility if( m_MapVisibility == MAPVIS_HIDETERRAIN ) GameFlags |= 0x00000100; else if( m_MapVisibility == MAPVIS_EXPLORED ) GameFlags |= 0x00000200; else if( m_MapVisibility == MAPVIS_ALWAYSVISIBLE ) GameFlags |= 0x00000400; else GameFlags |= 0x00000800; // observers if( m_MapObservers == MAPOBS_ONDEFEAT ) GameFlags |= 0x00002000; else if( m_MapObservers == MAPOBS_ALLOWED ) GameFlags |= 0x00003000; else if( m_MapObservers == MAPOBS_REFEREES ) GameFlags |= 0x40000000; // teams/units/hero/race if( m_MapFlags & MAPFLAG_TEAMSTOGETHER ) GameFlags |= 0x00004000; if( m_MapFlags & MAPFLAG_FIXEDTEAMS ) GameFlags |= 0x00060000; if( m_MapFlags & MAPFLAG_UNITSHARE ) GameFlags |= 0x01000000; if( m_MapFlags & MAPFLAG_RANDOMHERO ) GameFlags |= 0x02000000; if( m_MapFlags & MAPFLAG_RANDOMRACES ) GameFlags |= 0x04000000; return UTIL_CreateByteArray( GameFlags, false ); } uint32_t CMap :: GetMapGameType( ) { /* spec stolen from Strilanc as follows: Public Enum GameTypes As UInteger None = 0 Unknown0 = 1 << 0 '[always seems to be set?] '''<summary>Setting this bit causes wc3 to check the map and disc if it is not signed by Blizzard</summary> AuthenticatedMakerBlizzard = 1 << 3 OfficialMeleeGame = 1 << 5 SavedGame = 1 << 9 PrivateGame = 1 << 11 MakerUser = 1 << 13 MakerBlizzard = 1 << 14 TypeMelee = 1 << 15 TypeScenario = 1 << 16 SizeSmall = 1 << 17 SizeMedium = 1 << 18 SizeLarge = 1 << 19 ObsFull = 1 << 20 ObsOnDeath = 1 << 21 ObsNone = 1 << 22 MaskObs = ObsFull Or ObsOnDeath Or ObsNone MaskMaker = MakerBlizzard Or MakerUser MaskType = TypeMelee Or TypeScenario MaskSize = SizeLarge Or SizeMedium Or SizeSmall MaskFilterable = MaskObs Or MaskMaker Or MaskType Or MaskSize End Enum */ // note: we allow "conflicting" flags to be set at the same time (who knows if this is a good idea) // we also don't set any flags this class is unaware of such as Unknown0, SavedGame, and PrivateGame uint32_t GameType = 0; // maker if( m_MapFilterMaker & MAPFILTER_MAKER_USER ) GameType |= MAPGAMETYPE_MAKERUSER; if( m_MapFilterMaker & MAPFILTER_MAKER_BLIZZARD ) GameType |= MAPGAMETYPE_MAKERBLIZZARD; // type if( m_MapFilterType & MAPFILTER_TYPE_MELEE ) GameType |= MAPGAMETYPE_TYPEMELEE; if( m_MapFilterType & MAPFILTER_TYPE_SCENARIO ) GameType |= MAPGAMETYPE_TYPESCENARIO; // size if( m_MapFilterSize & MAPFILTER_SIZE_SMALL ) GameType |= MAPGAMETYPE_SIZESMALL; if( m_MapFilterSize & MAPFILTER_SIZE_MEDIUM ) GameType |= MAPGAMETYPE_SIZEMEDIUM; if( m_MapFilterSize & MAPFILTER_SIZE_LARGE ) GameType |= MAPGAMETYPE_SIZELARGE; // obs if( m_MapFilterObs & MAPFILTER_OBS_FULL ) GameType |= MAPGAMETYPE_OBSFULL; if( m_MapFilterObs & MAPFILTER_OBS_ONDEATH ) GameType |= MAPGAMETYPE_OBSONDEATH; if( m_MapFilterObs & MAPFILTER_OBS_NONE ) GameType |= MAPGAMETYPE_OBSNONE; return GameType; } unsigned char CMap :: GetMapLayoutStyle( ) { // 0 = melee // 1 = custom forces // 2 = fixed player settings (not possible with the Warcraft III map editor) // 3 = custom forces + fixed player settings if( !( m_MapOptions & MAPOPT_CUSTOMFORCES ) ) return 0; if( !( m_MapOptions & MAPOPT_FIXEDPLAYERSETTINGS ) ) return 1; return 3; } void CMap :: Load( CConfig *CFG, string nCFGFile ) { m_Valid = true; m_CFGFile = nCFGFile; // load the map data m_MapLocalPath = CFG->GetString( "map_localpath", string( ) ); m_MapData.clear( ); if( !m_MapLocalPath.empty( ) ) m_MapData = UTIL_FileRead( m_GHost->m_MapPath + m_MapLocalPath ); // load the map MPQ string MapMPQFileName = m_GHost->m_MapPath + m_MapLocalPath; HANDLE MapMPQ; bool MapMPQReady = false; if( SFileOpenArchive( MapMPQFileName.c_str( ), 0, MPQ_OPEN_FORCE_MPQ_V1, &MapMPQ ) ) { CONSOLE_Print( "[MAP] loading MPQ file [" + MapMPQFileName + "]" ); MapMPQReady = true; } else CONSOLE_Print( "[MAP] warning - unable to load MPQ file [" + MapMPQFileName + "]" ); // try to calculate map_size, map_info, map_crc, map_sha1 BYTEARRAY MapSize; BYTEARRAY MapInfo; BYTEARRAY MapCRC; BYTEARRAY MapSHA1; if( !m_MapData.empty( ) ) { m_GHost->m_SHA->Reset( ); // calculate map_size MapSize = UTIL_CreateByteArray( (uint32_t)m_MapData.size( ), false ); CONSOLE_Print( "[MAP] calculated map_size = " + UTIL_ByteArrayToDecString( MapSize ) ); // calculate map_info (this is actually the CRC) MapInfo = UTIL_CreateByteArray( (uint32_t)m_GHost->m_CRC->FullCRC( (unsigned char *)m_MapData.c_str( ), m_MapData.size( ) ), false ); CONSOLE_Print( "[MAP] calculated map_info = " + UTIL_ByteArrayToDecString( MapInfo ) ); // calculate map_crc (this is not the CRC) and map_sha1 // a big thank you to Strilanc for figuring the map_crc algorithm out string CommonJ = UTIL_FileRead( m_GHost->m_MapCFGPath + "common.j" ); if( CommonJ.empty( ) ) CONSOLE_Print( "[MAP] unable to calculate map_crc/sha1 - unable to read file [" + m_GHost->m_MapCFGPath + "common.j]" ); else { string BlizzardJ = UTIL_FileRead( m_GHost->m_MapCFGPath + "blizzard.j" ); if( BlizzardJ.empty( ) ) CONSOLE_Print( "[MAP] unable to calculate map_crc/sha1 - unable to read file [" + m_GHost->m_MapCFGPath + "blizzard.j]" ); else { uint32_t Val = 0; // update: it's possible for maps to include their own copies of common.j and/or blizzard.j // this code now overrides the default copies if required bool OverrodeCommonJ = false; bool OverrodeBlizzardJ = false; if( MapMPQReady ) { HANDLE SubFile; // override common.j if( SFileOpenFileEx( MapMPQ, "Scripts\\common.j", 0, &SubFile ) ) { uint32_t FileLength = SFileGetFileSize( SubFile, NULL ); if( FileLength > 0 && FileLength != 0xFFFFFFFF ) { char *SubFileData = new char[FileLength]; DWORD BytesRead = 0; if( SFileReadFile( SubFile, SubFileData, FileLength, &BytesRead ) ) { CONSOLE_Print( "[MAP] overriding default common.j with map copy while calculating map_crc/sha1" ); OverrodeCommonJ = true; Val = Val ^ XORRotateLeft( (unsigned char *)SubFileData, BytesRead ); m_GHost->m_SHA->Update( (unsigned char *)SubFileData, BytesRead ); } delete [] SubFileData; } SFileCloseFile( SubFile ); } } if( !OverrodeCommonJ ) { Val = Val ^ XORRotateLeft( (unsigned char *)CommonJ.c_str( ), CommonJ.size( ) ); m_GHost->m_SHA->Update( (unsigned char *)CommonJ.c_str( ), CommonJ.size( ) ); } if( MapMPQReady ) { HANDLE SubFile; // override blizzard.j if( SFileOpenFileEx( MapMPQ, "Scripts\\blizzard.j", 0, &SubFile ) ) { uint32_t FileLength = SFileGetFileSize( SubFile, NULL ); if( FileLength > 0 && FileLength != 0xFFFFFFFF ) { char *SubFileData = new char[FileLength]; DWORD BytesRead = 0; if( SFileReadFile( SubFile, SubFileData, FileLength, &BytesRead ) ) { CONSOLE_Print( "[MAP] overriding default blizzard.j with map copy while calculating map_crc/sha1" ); OverrodeBlizzardJ = true; Val = Val ^ XORRotateLeft( (unsigned char *)SubFileData, BytesRead ); m_GHost->m_SHA->Update( (unsigned char *)SubFileData, BytesRead ); } delete [] SubFileData; } SFileCloseFile( SubFile ); } } if( !OverrodeBlizzardJ ) { Val = Val ^ XORRotateLeft( (unsigned char *)BlizzardJ.c_str( ), BlizzardJ.size( ) ); m_GHost->m_SHA->Update( (unsigned char *)BlizzardJ.c_str( ), BlizzardJ.size( ) ); } Val = ROTL( Val, 3 ); Val = ROTL( Val ^ 0x03F1379E, 3 ); m_GHost->m_SHA->Update( (unsigned char *)"\x9E\x37\xF1\x03", 4 ); if( MapMPQReady ) { vector<string> FileList; FileList.push_back( "war3map.j" ); FileList.push_back( "scripts\\war3map.j" ); FileList.push_back( "war3map.w3e" ); FileList.push_back( "war3map.wpm" ); FileList.push_back( "war3map.doo" ); FileList.push_back( "war3map.w3u" ); FileList.push_back( "war3map.w3b" ); FileList.push_back( "war3map.w3d" ); FileList.push_back( "war3map.w3a" ); FileList.push_back( "war3map.w3q" ); bool FoundScript = false; for( vector<string> :: iterator i = FileList.begin( ); i != FileList.end( ); ++i ) { // don't use scripts\war3map.j if we've already used war3map.j (yes, some maps have both but only war3map.j is used) if( FoundScript && *i == "scripts\\war3map.j" ) continue; HANDLE SubFile; if( SFileOpenFileEx( MapMPQ, (*i).c_str( ), 0, &SubFile ) ) { uint32_t FileLength = SFileGetFileSize( SubFile, NULL ); if( FileLength > 0 && FileLength != 0xFFFFFFFF ) { char *SubFileData = new char[FileLength]; DWORD BytesRead = 0; if( SFileReadFile( SubFile, SubFileData, FileLength, &BytesRead ) ) { if( *i == "war3map.j" || *i == "scripts\\war3map.j" ) FoundScript = true; Val = ROTL( Val ^ XORRotateLeft( (unsigned char *)SubFileData, BytesRead ), 3 ); m_GHost->m_SHA->Update( (unsigned char *)SubFileData, BytesRead ); // DEBUG_Print( "*** found: " + *i ); } delete [] SubFileData; } SFileCloseFile( SubFile ); } else { // DEBUG_Print( "*** not found: " + *i ); } } if( !FoundScript ) CONSOLE_Print( "[MAP] couldn't find war3map.j or scripts\\war3map.j in MPQ file, calculated map_crc/sha1 is probably wrong" ); MapCRC = UTIL_CreateByteArray( Val, false ); CONSOLE_Print( "[MAP] calculated map_crc = " + UTIL_ByteArrayToDecString( MapCRC ) ); m_GHost->m_SHA->Final( ); unsigned char SHA1[20]; memset( SHA1, 0, sizeof( unsigned char ) * 20 ); m_GHost->m_SHA->GetHash( SHA1 ); MapSHA1 = UTIL_CreateByteArray( SHA1, 20 ); CONSOLE_Print( "[MAP] calculated map_sha1 = " + UTIL_ByteArrayToDecString( MapSHA1 ) ); } else CONSOLE_Print( "[MAP] unable to calculate map_crc/sha1 - map MPQ file not loaded" ); } } } else CONSOLE_Print( "[MAP] no map data available, using config file for map_size, map_info, map_crc, map_sha1" ); // try to calculate map_width, map_height, map_slot<x>, map_numplayers, map_numteams uint32_t MapOptions = 0; BYTEARRAY MapWidth; BYTEARRAY MapHeight; uint32_t MapNumPlayers = 0; uint32_t MapNumTeams = 0; vector<CGameSlot> Slots; if( !m_MapData.empty( ) ) { if( MapMPQReady ) { HANDLE SubFile; if( SFileOpenFileEx( MapMPQ, "war3map.w3i", 0, &SubFile ) ) { uint32_t FileLength = SFileGetFileSize( SubFile, NULL ); if( FileLength > 0 && FileLength != 0xFFFFFFFF ) { char *SubFileData = new char[FileLength]; DWORD BytesRead = 0; if( SFileReadFile( SubFile, SubFileData, FileLength, &BytesRead ) ) { istringstream ISS( string( SubFileData, BytesRead ) ); // war3map.w3i format found at http://www.wc3campaigns.net/tools/specs/index.html by Zepir/PitzerMike string GarbageString; uint32_t FileFormat; uint32_t RawMapWidth; uint32_t RawMapHeight; uint32_t RawMapFlags; uint32_t RawMapNumPlayers; uint32_t RawMapNumTeams; ISS.read( (char *)&FileFormat, 4 ); // file format (18 = ROC, 25 = TFT) if( FileFormat == 18 || FileFormat == 25 ) { ISS.seekg( 4, ios :: cur ); // number of saves ISS.seekg( 4, ios :: cur ); // editor version getline( ISS, GarbageString, '\0' ); // map name getline( ISS, GarbageString, '\0' ); // map author getline( ISS, GarbageString, '\0' ); // map description getline( ISS, GarbageString, '\0' ); // players recommended ISS.seekg( 32, ios :: cur ); // camera bounds ISS.seekg( 16, ios :: cur ); // camera bounds complements ISS.read( (char *)&RawMapWidth, 4 ); // map width ISS.read( (char *)&RawMapHeight, 4 ); // map height ISS.read( (char *)&RawMapFlags, 4 ); // flags ISS.seekg( 1, ios :: cur ); // map main ground type if( FileFormat == 18 ) ISS.seekg( 4, ios :: cur ); // campaign background number else if( FileFormat == 25 ) { ISS.seekg( 4, ios :: cur ); // loading screen background number getline( ISS, GarbageString, '\0' ); // path of custom loading screen model } getline( ISS, GarbageString, '\0' ); // map loading screen text getline( ISS, GarbageString, '\0' ); // map loading screen title getline( ISS, GarbageString, '\0' ); // map loading screen subtitle if( FileFormat == 18 ) ISS.seekg( 4, ios :: cur ); // map loading screen number else if( FileFormat == 25 ) { ISS.seekg( 4, ios :: cur ); // used game data set getline( ISS, GarbageString, '\0' ); // prologue screen path } getline( ISS, GarbageString, '\0' ); // prologue screen text getline( ISS, GarbageString, '\0' ); // prologue screen title getline( ISS, GarbageString, '\0' ); // prologue screen subtitle if( FileFormat == 25 ) { ISS.seekg( 4, ios :: cur ); // uses terrain fog ISS.seekg( 4, ios :: cur ); // fog start z height ISS.seekg( 4, ios :: cur ); // fog end z height ISS.seekg( 4, ios :: cur ); // fog density ISS.seekg( 1, ios :: cur ); // fog red value ISS.seekg( 1, ios :: cur ); // fog green value ISS.seekg( 1, ios :: cur ); // fog blue value ISS.seekg( 1, ios :: cur ); // fog alpha value ISS.seekg( 4, ios :: cur ); // global weather id getline( ISS, GarbageString, '\0' ); // custom sound environment ISS.seekg( 1, ios :: cur ); // tileset id of the used custom light environment ISS.seekg( 1, ios :: cur ); // custom water tinting red value ISS.seekg( 1, ios :: cur ); // custom water tinting green value ISS.seekg( 1, ios :: cur ); // custom water tinting blue value ISS.seekg( 1, ios :: cur ); // custom water tinting alpha value } ISS.read( (char *)&RawMapNumPlayers, 4 ); // number of players uint32_t ClosedSlots = 0; for( uint32_t i = 0; i < RawMapNumPlayers; ++i ) { CGameSlot Slot( 0, 255, SLOTSTATUS_OPEN, 0, 0, 1, SLOTRACE_RANDOM ); uint32_t Colour; uint32_t Status; uint32_t Race; ISS.read( (char *)&Colour, 4 ); // colour Slot.SetColour( Colour ); ISS.read( (char *)&Status, 4 ); // status if( Status == 1 ) Slot.SetSlotStatus( SLOTSTATUS_OPEN ); else if( Status == 2 ) { Slot.SetSlotStatus( SLOTSTATUS_OCCUPIED ); Slot.SetComputer( 1 ); Slot.SetComputerType( SLOTCOMP_NORMAL ); } else { Slot.SetSlotStatus( SLOTSTATUS_CLOSED ); ++ClosedSlots; } ISS.read( (char *)&Race, 4 ); // race if( Race == 1 ) Slot.SetRace( SLOTRACE_HUMAN ); else if( Race == 2 ) Slot.SetRace( SLOTRACE_ORC ); else if( Race == 3 ) Slot.SetRace( SLOTRACE_UNDEAD ); else if( Race == 4 ) Slot.SetRace( SLOTRACE_NIGHTELF ); else Slot.SetRace( SLOTRACE_RANDOM ); ISS.seekg( 4, ios :: cur ); // fixed start position getline( ISS, GarbageString, '\0' ); // player name ISS.seekg( 4, ios :: cur ); // start position x ISS.seekg( 4, ios :: cur ); // start position y ISS.seekg( 4, ios :: cur ); // ally low priorities ISS.seekg( 4, ios :: cur ); // ally high priorities if( Slot.GetSlotStatus( ) != SLOTSTATUS_CLOSED ) Slots.push_back( Slot ); } ISS.read( (char *)&RawMapNumTeams, 4 ); // number of teams for( uint32_t i = 0; i < RawMapNumTeams; ++i ) { uint32_t Flags; uint32_t PlayerMask; ISS.read( (char *)&Flags, 4 ); // flags ISS.read( (char *)&PlayerMask, 4 ); // player mask for( unsigned char j = 0; j < 12; ++j ) { if( PlayerMask & 1 ) { for( vector<CGameSlot> :: iterator k = Slots.begin( ); k != Slots.end( ); ++k ) { if( (*k).GetColour( ) == j ) (*k).SetTeam( i ); } } PlayerMask >>= 1; } getline( ISS, GarbageString, '\0' ); // team name } // the bot only cares about the following options: melee, fixed player settings, custom forces // let's not confuse the user by displaying erroneous map options so zero them out now MapOptions = RawMapFlags & ( MAPOPT_MELEE | MAPOPT_FIXEDPLAYERSETTINGS | MAPOPT_CUSTOMFORCES ); CONSOLE_Print( "[MAP] calculated map_options = " + UTIL_ToString( MapOptions ) ); MapWidth = UTIL_CreateByteArray( (uint16_t)RawMapWidth, false ); CONSOLE_Print( "[MAP] calculated map_width = " + UTIL_ByteArrayToDecString( MapWidth ) ); MapHeight = UTIL_CreateByteArray( (uint16_t)RawMapHeight, false ); CONSOLE_Print( "[MAP] calculated map_height = " + UTIL_ByteArrayToDecString( MapHeight ) ); MapNumPlayers = RawMapNumPlayers - ClosedSlots; CONSOLE_Print( "[MAP] calculated map_numplayers = " + UTIL_ToString( MapNumPlayers ) ); MapNumTeams = RawMapNumTeams; CONSOLE_Print( "[MAP] calculated map_numteams = " + UTIL_ToString( MapNumTeams ) ); uint32_t SlotNum = 1; for( vector<CGameSlot> :: iterator i = Slots.begin( ); i != Slots.end( ); ++i ) { CONSOLE_Print( "[MAP] calculated map_slot" + UTIL_ToString( SlotNum ) + " = " + UTIL_ByteArrayToDecString( (*i).GetByteArray( ) ) ); ++SlotNum; } if( MapOptions & MAPOPT_MELEE ) { CONSOLE_Print( "[MAP] found melee map, initializing slots" ); // give each slot a different team and set the race to random unsigned char Team = 0; for( vector<CGameSlot> :: iterator i = Slots.begin( ); i != Slots.end( ); ++i ) { (*i).SetTeam( Team++ ); (*i).SetRace( SLOTRACE_RANDOM ); } } if( !( MapOptions & MAPOPT_FIXEDPLAYERSETTINGS ) ) { // make races selectable for( vector<CGameSlot> :: iterator i = Slots.begin( ); i != Slots.end( ); ++i ) (*i).SetRace( (*i).GetRace( ) | SLOTRACE_SELECTABLE ); } } } else CONSOLE_Print( "[MAP] unable to calculate map_options, map_width, map_height, map_slot<x>, map_numplayers, map_numteams - unable to extract war3map.w3i from MPQ file" ); delete [] SubFileData; } SFileCloseFile( SubFile ); } else CONSOLE_Print( "[MAP] unable to calculate map_options, map_width, map_height, map_slot<x>, map_numplayers, map_numteams - couldn't find war3map.w3i in MPQ file" ); } else CONSOLE_Print( "[MAP] unable to calculate map_options, map_width, map_height, map_slot<x>, map_numplayers, map_numteams - map MPQ file not loaded" ); } else CONSOLE_Print( "[MAP] no map data available, using config file for map_options, map_width, map_height, map_slot<x>, map_numplayers, map_numteams" ); // close the map MPQ if( MapMPQReady ) SFileCloseArchive( MapMPQ ); m_MapPath = CFG->GetString( "map_path", string( ) ); if( MapSize.empty( ) ) MapSize = UTIL_ExtractNumbers( CFG->GetString( "map_size", string( ) ), 4 ); else if( CFG->Exists( "map_size" ) ) { CONSOLE_Print( "[MAP] overriding calculated map_size with config value map_size = " + CFG->GetString( "map_size", string( ) ) ); MapSize = UTIL_ExtractNumbers( CFG->GetString( "map_size", string( ) ), 4 ); } m_MapSize = MapSize; if( MapInfo.empty( ) ) MapInfo = UTIL_ExtractNumbers( CFG->GetString( "map_info", string( ) ), 4 ); else if( CFG->Exists( "map_info" ) ) { CONSOLE_Print( "[MAP] overriding calculated map_info with config value map_info = " + CFG->GetString( "map_info", string( ) ) ); MapInfo = UTIL_ExtractNumbers( CFG->GetString( "map_info", string( ) ), 4 ); } m_MapInfo = MapInfo; if( MapCRC.empty( ) ) MapCRC = UTIL_ExtractNumbers( CFG->GetString( "map_crc", string( ) ), 4 ); else if( CFG->Exists( "map_crc" ) ) { CONSOLE_Print( "[MAP] overriding calculated map_crc with config value map_crc = " + CFG->GetString( "map_crc", string( ) ) ); MapCRC = UTIL_ExtractNumbers( CFG->GetString( "map_crc", string( ) ), 4 ); } m_MapCRC = MapCRC; if( MapSHA1.empty( ) ) MapSHA1 = UTIL_ExtractNumbers( CFG->GetString( "map_sha1", string( ) ), 20 ); else if( CFG->Exists( "map_sha1" ) ) { CONSOLE_Print( "[MAP] overriding calculated map_sha1 with config value map_sha1 = " + CFG->GetString( "map_sha1", string( ) ) ); MapSHA1 = UTIL_ExtractNumbers( CFG->GetString( "map_sha1", string( ) ), 20 ); } m_MapSHA1 = MapSHA1; m_MapSpeed = CFG->GetInt( "map_speed", MAPSPEED_FAST ); m_MapVisibility = CFG->GetInt( "map_visibility", MAPVIS_DEFAULT ); m_MapObservers = CFG->GetInt( "map_observers", MAPOBS_NONE ); m_MapFlags = CFG->GetInt( "map_flags", MAPFLAG_TEAMSTOGETHER | MAPFLAG_FIXEDTEAMS ); m_MapFilterMaker = CFG->GetInt( "map_filter_maker", MAPFILTER_MAKER_USER ); m_MapFilterType = CFG->GetInt( "map_filter_type", 0 ); m_MapFilterSize = CFG->GetInt( "map_filter_size", MAPFILTER_SIZE_LARGE ); m_MapFilterObs = CFG->GetInt( "map_filter_obs", MAPFILTER_OBS_NONE ); // todotodo: it might be possible for MapOptions to legitimately be zero so this is not a valid way of checking if it wasn't parsed out earlier if( MapOptions == 0 ) MapOptions = CFG->GetInt( "map_options", 0 ); else if( CFG->Exists( "map_options" ) ) { CONSOLE_Print( "[MAP] overriding calculated map_options with config value map_options = " + CFG->GetString( "map_options", string( ) ) ); MapOptions = CFG->GetInt( "map_options", 0 ); } m_MapOptions = MapOptions; if( MapWidth.empty( ) ) MapWidth = UTIL_ExtractNumbers( CFG->GetString( "map_width", string( ) ), 2 ); else if( CFG->Exists( "map_width" ) ) { CONSOLE_Print( "[MAP] overriding calculated map_width with config value map_width = " + CFG->GetString( "map_width", string( ) ) ); MapWidth = UTIL_ExtractNumbers( CFG->GetString( "map_width", string( ) ), 2 ); } m_MapWidth = MapWidth; if( MapHeight.empty( ) ) MapHeight = UTIL_ExtractNumbers( CFG->GetString( "map_height", string( ) ), 2 ); else if( CFG->Exists( "map_height" ) ) { CONSOLE_Print( "[MAP] overriding calculated map_height with config value map_height = " + CFG->GetString( "map_height", string( ) ) ); MapHeight = UTIL_ExtractNumbers( CFG->GetString( "map_height", string( ) ), 2 ); } m_MapHeight = MapHeight; m_MapType = CFG->GetString( "map_type", string( ) ); m_MapMatchMakingCategory = CFG->GetString( "map_matchmakingcategory", string( ) ); m_MapStatsW3MMDCategory = CFG->GetString( "map_statsw3mmdcategory", string( ) ); m_MapDefaultHCL = CFG->GetString( "map_defaulthcl", string( ) ); m_MapDefaultPlayerScore = CFG->GetInt( "map_defaultplayerscore", 1000 ); m_MapLoadInGame = CFG->GetInt( "map_loadingame", 0 ) == 0 ? false : true; if( MapNumPlayers == 0 ) MapNumPlayers = CFG->GetInt( "map_numplayers", 0 ); else if( CFG->Exists( "map_numplayers" ) ) { CONSOLE_Print( "[MAP] overriding calculated map_numplayers with config value map_numplayers = " + CFG->GetString( "map_numplayers", string( ) ) ); MapNumPlayers = CFG->GetInt( "map_numplayers", 0 ); } m_MapNumPlayers = MapNumPlayers; if( MapNumTeams == 0 ) MapNumTeams = CFG->GetInt( "map_numteams", 0 ); else if( CFG->Exists( "map_numteams" ) ) { CONSOLE_Print( "[MAP] overriding calculated map_numteams with config value map_numteams = " + CFG->GetString( "map_numteams", string( ) ) ); MapNumTeams = CFG->GetInt( "map_numteams", 0 ); } m_MapNumTeams = MapNumTeams; if( Slots.empty( ) ) { for( uint32_t Slot = 1; Slot <= 12; ++Slot ) { string SlotString = CFG->GetString( "map_slot" + UTIL_ToString( Slot ), string( ) ); if( SlotString.empty( ) ) break; BYTEARRAY SlotData = UTIL_ExtractNumbers( SlotString, 9 ); Slots.push_back( CGameSlot( SlotData ) ); } } else if( CFG->Exists( "map_slot1" ) ) { CONSOLE_Print( "[MAP] overriding slots" ); Slots.clear( ); for( uint32_t Slot = 1; Slot <= 12; ++Slot ) { string SlotString = CFG->GetString( "map_slot" + UTIL_ToString( Slot ), string( ) ); if( SlotString.empty( ) ) break; BYTEARRAY SlotData = UTIL_ExtractNumbers( SlotString, 9 ); Slots.push_back( CGameSlot( SlotData ) ); } } m_Slots = Slots; // if random races is set force every slot's race to random if( m_MapFlags & MAPFLAG_RANDOMRACES ) { CONSOLE_Print( "[MAP] forcing races to random" ); for( vector<CGameSlot> :: iterator i = m_Slots.begin( ); i != m_Slots.end( ); ++i ) (*i).SetRace( SLOTRACE_RANDOM ); } // add observer slots if( m_MapObservers == MAPOBS_ALLOWED || m_MapObservers == MAPOBS_REFEREES ) { CONSOLE_Print( "[MAP] adding " + UTIL_ToString( 12 - m_Slots.size( ) ) + " observer slots" ); while( m_Slots.size( ) < 12 ) m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 12, 12, SLOTRACE_RANDOM ) ); } CheckValid( ); } void CMap :: CheckValid( ) { // todotodo: should this code fix any errors it sees rather than just warning the user? if( m_MapPath.empty( ) || m_MapPath.length( ) > 53 ) { m_Valid = false; CONSOLE_Print( "[MAP] invalid map_path detected" ); } else if( m_MapPath[0] == '\\' ) CONSOLE_Print( "[MAP] warning - map_path starts with '\\', any replays saved by GHost++ will not be playable in Warcraft III" ); if( m_MapPath.find( '/' ) != string :: npos ) CONSOLE_Print( "[MAP] warning - map_path contains forward slashes '/' but it must use Windows style back slashes '\\'" ); if( m_MapSize.size( ) != 4 ) { m_Valid = false; CONSOLE_Print( "[MAP] invalid map_size detected" ); } else if( !m_MapData.empty( ) && m_MapData.size( ) != UTIL_ByteArrayToUInt32( m_MapSize, false ) ) { m_Valid = false; CONSOLE_Print( "[MAP] invalid map_size detected - size mismatch with actual map data" ); } if( m_MapInfo.size( ) != 4 ) { m_Valid = false; CONSOLE_Print( "[MAP] invalid map_info detected" ); } if( m_MapCRC.size( ) != 4 ) { m_Valid = false; CONSOLE_Print( "[MAP] invalid map_crc detected" ); } if( m_MapSHA1.size( ) != 20 ) { m_Valid = false; CONSOLE_Print( "[MAP] invalid map_sha1 detected" ); } if( m_MapSpeed != MAPSPEED_SLOW && m_MapSpeed != MAPSPEED_NORMAL && m_MapSpeed != MAPSPEED_FAST ) { m_Valid = false; CONSOLE_Print( "[MAP] invalid map_speed detected" ); } if( m_MapVisibility != MAPVIS_HIDETERRAIN && m_MapVisibility != MAPVIS_EXPLORED && m_MapVisibility != MAPVIS_ALWAYSVISIBLE && m_MapVisibility != MAPVIS_DEFAULT ) { m_Valid = false; CONSOLE_Print( "[MAP] invalid map_visibility detected" ); } if( m_MapObservers != MAPOBS_NONE && m_MapObservers != MAPOBS_ONDEFEAT && m_MapObservers != MAPOBS_ALLOWED && m_MapObservers != MAPOBS_REFEREES ) { m_Valid = false; CONSOLE_Print( "[MAP] invalid map_observers detected" ); } // todotodo: m_MapFlags // todotodo: m_MapFilterMaker, m_MapFilterType, m_MapFilterSize, m_MapFilterObs if( m_MapWidth.size( ) != 2 ) { m_Valid = false; CONSOLE_Print( "[MAP] invalid map_width detected" ); } if( m_MapHeight.size( ) != 2 ) { m_Valid = false; CONSOLE_Print( "[MAP] invalid map_height detected" ); } if( m_MapNumPlayers == 0 || m_MapNumPlayers > 12 ) { m_Valid = false; CONSOLE_Print( "[MAP] invalid map_numplayers detected" ); } if( m_MapNumTeams == 0 || m_MapNumTeams > 12 ) { m_Valid = false; CONSOLE_Print( "[MAP] invalid map_numteams detected" ); } if( m_Slots.empty( ) || m_Slots.size( ) > 12 ) { m_Valid = false; CONSOLE_Print( "[MAP] invalid map_slot<x> detected" ); } } uint32_t CMap :: XORRotateLeft( unsigned char *data, uint32_t length ) { // a big thank you to Strilanc for figuring this out uint32_t i = 0; uint32_t Val = 0; if( length > 3 ) { while( i < length - 3 ) { Val = ROTL( Val ^ ( (uint32_t)data[i] + (uint32_t)( data[i + 1] << 8 ) + (uint32_t)( data[i + 2] << 16 ) + (uint32_t)( data[i + 3] << 24 ) ), 3 ); i += 4; } } while( i < length ) { Val = ROTL( Val ^ data[i], 3 ); ++i; } return Val; }
[ "hogantp@a7494f72-a4b0-11dd-a887-7ffe1a420f8d", "[email protected]@a7494f72-a4b0-11dd-a887-7ffe1a420f8d", "[email protected]@a7494f72-a4b0-11dd-a887-7ffe1a420f8d" ]
[ [ [ 1, 37 ], [ 39, 54 ], [ 56, 391 ], [ 393, 552 ], [ 554, 574 ], [ 576, 603 ], [ 605, 611 ], [ 613, 615 ], [ 617, 644 ], [ 646, 647 ], [ 649, 658 ], [ 660, 669 ], [ 671, 806 ], [ 808, 822 ], [ 824, 842 ], [ 844, 863 ], [ 865, 974 ], [ 976, 979 ] ], [ [ 38, 38 ], [ 55, 55 ], [ 392, 392 ], [ 553, 553 ], [ 575, 575 ], [ 604, 604 ], [ 612, 612 ], [ 616, 616 ], [ 645, 645 ], [ 648, 648 ], [ 659, 659 ], [ 670, 670 ], [ 807, 807 ], [ 823, 823 ], [ 843, 843 ], [ 975, 975 ] ], [ [ 864, 864 ] ] ]
b86849a9d7c3c09f1ab0b5bf0854b7b10ea9794e
de0881d85df3a3a01924510134feba2fbff5b7c3
/apps/dev/neuralNetworkDemo/src/ofxProcessing/src/ofxProcessing.h
9ba2bf7277b640d3b4744169e5589250b8c41f5e
[]
no_license
peterkrenn/ofx-dev
6091def69a1148c05354e55636887d11e29d6073
e08e08a06be6ea080ecd252bc89c1662cf3e37f0
refs/heads/master
2021-01-21T00:32:49.065810
2009-06-26T19:13:29
2009-06-26T19:13:29
146,543
1
1
null
null
null
null
UTF-8
C++
false
false
2,401
h
#ifndef OFXPROCESSING_H_INCLUDED #define OFXPROCESSING_H_INCLUDED /* ofxProcessing.h, r2 Replicating some functions from Processing left out of Open Frameworks. Some functions from r1 were included in 006 and had to be removed in r2 to be compatible. */ // Output: Text Area: print() and println() void ofPrint(const char* str) { printf("%s", str); } void ofPrint(string &str) { printf("%s", str.c_str()); } void ofPrint(int i) { printf("%i", i); } void ofPrint(float f) { printf("%f", f); } void ofPrint(bool b) { printf("%s", b ? "true" : "false"); } void ofPrint(char c) { printf("%c", c); } template <class T> void ofPrint(vector<T> &vec) { ofPrint("{ "); for(int i = 0; i < vec.size(); i++) { ofPrint(vec.at(i)); ofPrint(", "); } ofPrint("}"); } void ofPrintln() { ofPrint("\n"); } template <typename T> void ofPrintln(T &obj) { ofPrint(obj); ofPrintln(); } template <typename T> void ofPrintln(T* obj) { ofPrint(obj); ofPrintln(); } // Output: Image: save(), saveFrame() void ofSave(char* filename) { ofImage screen; screen.allocate(ofGetWidth(), ofGetHeight(), OF_IMAGE_COLOR); screen.grabScreen(0, 0, ofGetWidth(), ofGetHeight()); screen.saveImage(filename); } // Shapes: ellipse() with strokeWeight and CENTER/CORNER #define OF_ELLIPSE_CENTER 0 #define OF_ELLIPSE_CORNER 1 float ofEllipse(float x, float y, float w, float h, int mode) { switch(mode) { case OF_ELLIPSE_CENTER: ofEllipse(x, y, w, h); break; case OF_ELLIPSE_CORNER: ofEllipse(x + w, y + h, w, h); break; } } float ofEllipse(float x, float y, float w, float h, int mode, int strokeWeight) { for(int i = 0; i < strokeWeight; i++) { ofEllipse(x, y, w - i, h - i, mode); if(i != 0) ofEllipse(x, y, w + i, h + i, mode); } } // Transform: radians(), degrees(), rotate() float ofRadians(float d) { return d * DEG_TO_RAD; } float ofDegrees(float r) { return r * RAD_TO_DEG; } // Math: Calculation: map(), sq(), constrain(), dist(), mag() float ofSq(float x) { return x * x; } float ofConstrain(float x, float low, float high) { return x < low ? low : x > high ? high : x; } float ofMag(float x, float y) { return ofDist(0, 0, x, y); } float ofRandom(float max) { return ofRandom(0, max); } #endif // OFXPROCESSING_H_INCLUDED
[ [ [ 1, 125 ] ] ]
4b095231aa23d3bf70ac8fc820fc9a261f1e253b
61bcb936a14064e2a819269d25b5c09b92dad45f
/Reference/EDK_project/code/GUI/HIO/MainFrm.h
a957db3703b806f69d4ac1c5a0138c231d9a2d39
[]
no_license
lanxinwoaini/robotic-vision-631
47fe73588a5b51296b9ac7fbacd4a553e4fd8e34
fdb160a8498ec668a32116c655368d068110aba7
refs/heads/master
2021-01-10T08:06:58.829618
2011-04-20T15:19:06
2011-04-20T15:19:06
47,861,917
1
0
null
null
null
null
UTF-8
C++
false
false
1,014
h
// MainFrm.h : interface of the CMainFrame class // #pragma once class CMainFrame : public CFrameWnd { protected: // create from serialization only CMainFrame(); DECLARE_DYNCREATE(CMainFrame) // Attributes public: // Operations public: // Overrides public: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); // Implementation public: virtual ~CMainFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // control bar embedded members CStatusBar m_wndStatusBar; CToolBar m_wndToolBar; // Generated message map functions protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); DECLARE_MESSAGE_MAP() public: afx_msg void OnHeliosStart(); public: afx_msg void OnHeliosStop(); public: afx_msg void OnClose(); public: virtual void ActivateFrame(int nCmdShow = -1); BOOL ReadWindowPlacement(WINDOWPLACEMENT *pwp); void WriteWindowPlacement(WINDOWPLACEMENT *pwp); };
[ [ [ 1, 52 ] ] ]
0424aa7d0648bc5377e8f5f2d0e7854a3ae622aa
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKitTools/DumpRenderTree/chromium/MockSpellCheck.cpp
37ffbf7dcae657aa124c66cf5bb7b47f24028a82
[]
no_license
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
5,659
cpp
/* * Copyright (C) 2010 Google Inc. 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 Google Inc. 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 * OWNER 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 "config.h" #include "MockSpellCheck.h" #include <wtf/ASCIICType.h> #include <wtf/Assertions.h> #include <wtf/text/WTFString.h> #include "public/WebString.h" using namespace WebKit; MockSpellCheck::MockSpellCheck() : m_initialized(false) {} MockSpellCheck::~MockSpellCheck() {} static bool isNotASCIIAlpha(UChar ch) { return !isASCIIAlpha(ch); } bool MockSpellCheck::spellCheckWord(const WebString& text, int* misspelledOffset, int* misspelledLength) { ASSERT(misspelledOffset); ASSERT(misspelledLength); // Initialize this spellchecker. initializeIfNeeded(); // Reset the result values as our spellchecker does. *misspelledOffset = 0; *misspelledLength = 0; // Convert to a String because we store String instances in // m_misspelledWords and WebString has no find(). const WTF::String stringText(text.data(), text.length()); // Extract the first possible English word from the given string. // The given string may include non-ASCII characters or numbers. So, we // should filter out such characters before start looking up our // misspelled-word table. // (This is a simple version of our SpellCheckWordIterator class.) // If the given string doesn't include any ASCII characters, we can treat the // string as valid one. // Unfortunately, This implementation splits a contraction, i.e. "isn't" is // split into two pieces "isn" and "t". This is OK because webkit tests // don't have misspelled contractions. int wordOffset = stringText.find(isASCIIAlpha); if (wordOffset == -1) return true; int wordEnd = stringText.find(isNotASCIIAlpha, wordOffset); int wordLength = wordEnd == -1 ? stringText.length() - wordOffset : wordEnd - wordOffset; // Look up our misspelled-word table to check if the extracted word is a // known misspelled word, and return the offset and the length of the // extracted word if this word is a known misspelled word. // (See the comment in MockSpellCheck::initializeIfNeeded() why we use a // misspelled-word table.) WTF::String word = stringText.substring(wordOffset, wordLength); if (!m_misspelledWords.contains(word)) return true; *misspelledOffset = wordOffset; *misspelledLength = wordLength; return false; } bool MockSpellCheck::initializeIfNeeded() { // Exit if we have already initialized this object. if (m_initialized) return false; // Create a table that consists of misspelled words used in WebKit layout // tests. // Since WebKit layout tests don't have so many misspelled words as // well-spelled words, it is easier to compare the given word with misspelled // ones than to compare with well-spelled ones. static const char* misspelledWords[] = { // These words are known misspelled words in webkit tests. // If there are other misspelled words in webkit tests, please add them in // this array. "foo", "Foo", "baz", "fo", "LibertyF", "chello", "xxxtestxxx", "XXxxx", "Textx", "blockquoted", "asd", "Lorem", "Nunc", "Curabitur", "eu", "adlj", "adaasj", "sdklj", "jlkds", "jsaada", "jlda", "zz", "contentEditable", // The following words are used by unit tests. "ifmmp", "qwertyuiopasd", "qwertyuiopasdf", }; m_misspelledWords.clear(); for (size_t i = 0; i < arraysize(misspelledWords); ++i) m_misspelledWords.add(WTF::String::fromUTF8(misspelledWords[i]), false); // Mark as initialized to prevent this object from being initialized twice // or more. m_initialized = true; // Since this MockSpellCheck class doesn't download dictionaries, this // function always returns false. return false; }
[ [ [ 1, 150 ] ] ]
d504cc5c99da6d987553b9815aef4cc05da5bf3c
a4b33f717a0ab43f9d4af566ee20996dafa58e2e
/dsp/fir.h
3096c4d9bdd2e0d7d862143792571ba7e6dd3475
[ "BSD-2-Clause" ]
permissive
luwangg/cutesdr
c11af720ea31ba7334da3fdaae1a64ae526606c4
f2b8ec7c2edad6467f209636a8a9c1fc3224af06
refs/heads/master
2020-03-30T04:54:33.058259
2011-06-07T21:41:28
2011-06-07T21:41:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,361
h
////////////////////////////////////////////////////////////////////// // fir.h: interface for the CFir class. // // This class implements a FIR filter using a double flat coefficient //array to eliminate testing for buffer wrap around. // // History: // 2011-01-29 Initial creation MSW // 2011-03-27 Initial release ////////////////////////////////////////////////////////////////////// #ifndef FIR_H #define FIR_H #include "dsp/datatypes.h" #define MAX_NUMCOEF 75 #include <QMutex> class CFir { public: CFir(); void InitConstFir( int NumTaps, const double* pCoef); int InitLPFilter(TYPEREAL Scale, TYPEREAL Astop, TYPEREAL Fpass, TYPEREAL Fstop, TYPEREAL Fsamprate); int InitHPFilter(TYPEREAL Scale, TYPEREAL Astop, TYPEREAL Fpass, TYPEREAL Fstop, TYPEREAL Fsamprate); void GenerateHBFilter( TYPEREAL FreqOffset); void ProcessFilter(int InLength, TYPEREAL* InBuf, TYPEREAL* OutBuf); void ProcessFilter(int InLength, TYPECPX* InBuf, TYPECPX* OutBuf); private: TYPEREAL Izero(TYPEREAL x); TYPEREAL m_SampleRate; int m_NumTaps; int m_State; TYPEREAL m_Coef[MAX_NUMCOEF*2]; TYPEREAL m_ICoef[MAX_NUMCOEF*2]; TYPEREAL m_QCoef[MAX_NUMCOEF*2]; TYPEREAL m_rZBuf[MAX_NUMCOEF]; TYPECPX m_cZBuf[MAX_NUMCOEF]; QMutex m_Mutex; //for keeping threads from stomping on each other }; #endif // FIR_H
[ "mwheatley@2b4ecd61-fcff-4479-bce5-acad07480135" ]
[ [ [ 1, 45 ] ] ]
66e5b81daf73afd48659f3c325a6ce08406acfaa
9152cb31fbe4e82c22092bb3071b2ec8c6ae86ab
/demos/rtc/AVDConf2/MessageDlg.cpp
c496810f67588e5fa7b558153f26e2a341e9a330
[]
no_license
zzjs2001702/sfsipua-svn
ca3051b53549066494f6264e8f3bf300b8090d17
e8768338340254aa287bf37cf620e2c68e4ff844
refs/heads/master
2022-01-09T20:02:20.777586
2006-03-29T13:24:02
2006-03-29T13:24:02
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
8,599
cpp
// ------------------------------------------------------------------------------------ // Copyright ©2002 Intel Corporation // All Rights Reserved // // Permission is granted to use, copy, distribute and prepare derivative works of this // software for any purpose and without fee, provided, that the above copyright notice // and this statement appear in all copies. Intel makes no representations about the // suitability of this software for any purpose. This software is provided "AS IS." // // Intel specifically disclaims all warranties, express or implied, and all liability, // including consequential and other indirect damages, for the use of this software, // including liability for infringement of any proprietary rights, and including the // warranties of merchantability and fitness for a particular purpose. Intel does not // assume any responsibility for any errors which may appear in this software nor any // responsibility to update it. // ------------------------------------------------------------------------------------ // // MessageDlg.cpp : implementation file // #include "stdafx.h" #include "rtccore.h" #include "AVDConf.h" #include "MessageDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CMessageDlg dialog CMessageDlg::CMessageDlg(CWnd* pParent /*=NULL*/) : CDialog(CMessageDlg::IDD, pParent) { //{{AFX_DATA_INIT(CMessageDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void CMessageDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CMessageDlg) DDX_Control(pDX, IDC_MESSAGE, m_cMessage); DDX_Control(pDX, IDC_TEXT, m_cText); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CMessageDlg, CDialog) //{{AFX_MSG_MAP(CMessageDlg) ON_BN_CLICKED(IDC_SENDTEXT, OnSendtext) ON_BN_CLICKED(IDC_CLEAR, OnClear) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMessageDlg message handlers ////////////////////////////////////////////////////////////////////////////// // Method: DeliverMessage() // Parameter: pParticipant Participant interface handle // bstrContentType Type of content (not used in this demo version) // bstrMessage Message to display // Return Value: S_OK if successful. // Purpose: Display the message from local and remote. ////////////////////////////////////////////////////////////////////////////// HRESULT CMessageDlg::DeliverMessage(IRTCParticipant *pParticipant, BSTR bstrContentType, BSTR bstrMessage) { HRESULT hr; BSTR bstrURI = NULL; // Get the URI of the incoming user hr = pParticipant->get_UserURI(&bstrURI); if (FAILED(hr)) { // get_UserURI failed return hr; } // Display the incoming message char szBuf[256], szText[265]; wcstombs ( szBuf, bstrURI, 256); SendDlgItemMessage (IDC_MESSAGE, LB_INSERTSTRING, (WPARAM)-1, (LPARAM)szBuf); wcstombs ( szBuf, bstrMessage, 256 ); sprintf ( szText, " %s", szBuf ); SendDlgItemMessage (IDC_MESSAGE, LB_INSERTSTRING, (WPARAM)-1, (LPARAM)szText); if (FAILED(hr)) { // DoDisplayMessage failed return hr; } if (FAILED(hr)) { // DoDisplayTyping failed return hr; } return S_OK; } ////////////////////////////////////////////////////////////////////////////// // Method: DeliverUserStatus() // Parameter: pParticipant Participant interface handle // enStatus Displays the status of the remote user (Typing or not). // Return Value: None // Purpose: Shows the remote users activitiy status. ////////////////////////////////////////////////////////////////////////////// HRESULT CMessageDlg::DeliverUserStatus(IRTCParticipant *pParticipant, RTC_MESSAGING_USER_STATUS enStatus) { HRESULT hr; BSTR bstrURI = NULL; // Get the URI of the incoming user hr = pParticipant->get_UserURI(&bstrURI); if (FAILED(hr)) { // get_UserURI failed return hr; } // Display the typing status of the incoming user if (enStatus) { char szTyping[256], szBuf[256]; wcstombs ( szBuf, bstrURI, 256 ); wsprintf(szTyping, "%s is typing.", szBuf); SetDlgItemText ( IDC_STATUSTEXT, szTyping ); } if (FAILED(hr)) { // DoDisplayTyping failed return hr; } return S_OK; } ////////////////////////////////////////////////////////////////////////////// // Method: OnSendtext() // Parameter: None // Return Value: None // Purpose: Sends a message to the remote user. ////////////////////////////////////////////////////////////////////////////// void CMessageDlg::OnSendtext() { LONG lLength; BSTR bstrMessage; WCHAR szBuf[256]; GetDlgItemTextW (m_hWnd, IDC_TEXT, szBuf, 256); if ((lLength = lstrlenW(szBuf)) > 0) { bstrMessage = SysAllocString ( szBuf ); if (bstrMessage == NULL) { // Error allocating memory for string return; } DoDisplayMessage(); //Send the message to participant m_pParentSession->SendMessage ( NULL, bstrMessage, 0 ); SAFE_FREE_STRING (bstrMessage); } } ////////////////////////////////////////////////////////////////////////////// // Method: OnClear() // Parameter: None // Return Value: None // Purpose: Clear the text screen. ////////////////////////////////////////////////////////////////////////////// void CMessageDlg::OnClear() { m_cMessage.ResetContent (); } ////////////////////////////////////////////////////////////////////////////// // Method: OnInitDialog() // Parameter: None // Return Value: None // Purpose: Initialize the Messaging dialog (WM_INITDIALOG). ////////////////////////////////////////////////////////////////////////////// BOOL CMessageDlg::OnInitDialog() { CDialog::OnInitDialog(); m_cText.LimitText ( 256 ); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } ////////////////////////////////////////////////////////////////////////////// // Method: SetParentClient() // Parameter: pClient Parent client handle // Return Value: None // Purpose: Get the parent client handle ////////////////////////////////////////////////////////////////////////////// void CMessageDlg::SetParentClient(IRTCClient *pClient) { m_pParentClient = pClient; } ////////////////////////////////////////////////////////////////////////////// // Method: SetSession() // Parameter: pSession Parent session handle // Return Value: None // Purpose: Get the parent session handle ////////////////////////////////////////////////////////////////////////////// void CMessageDlg::SetSession(IRTCSession *pSession) { m_pParentSession = pSession; } ////////////////////////////////////////////////////////////////////////////// // Method: OnOK() // Parameter: None // Return Value: None // Purpose: Terminate the Messaging session ////////////////////////////////////////////////////////////////////////////// void CMessageDlg::OnOK() { HRESULT hr = m_pParentSession->Terminate(RTCTR_NORMAL); SAFE_RELEASE (m_pParentSession); DestroyWindow(); } ////////////////////////////////////////////////////////////////////////////// // Method: DoDisplayMessage() // Parameter: None // Return Value: None // Purpose: Displays the Message from local user in the Message window ////////////////////////////////////////////////////////////////////////////// void CMessageDlg::DoDisplayMessage() { BSTR bstrURI = NULL; char szBuf[256], LBBuf[265]; HRESULT hr = m_pParentClient->get_LocalUserURI (&bstrURI); wcstombs(szBuf, bstrURI, 256); SendDlgItemMessage (IDC_MESSAGE, LB_INSERTSTRING, (WPARAM)-1, (LPARAM)szBuf ); GetDlgItemText (IDC_TEXT, szBuf, 256); wsprintf ( LBBuf, " %s", szBuf ); SendDlgItemMessage (IDC_MESSAGE, LB_INSERTSTRING, (WPARAM)-1, (LPARAM)LBBuf); m_cText.SetSel (0, -1); m_cText.ReplaceSel (""); } ////////////////////////////////////////////////////////////////////////////// // Method: OnCancel() // Parameter: None // Return Value: None // Purpose: Just trapping this message. ////////////////////////////////////////////////////////////////////////////// void CMessageDlg::OnCancel() { return; }
[ "yippeesoft@5dda88da-d10c-0410-ac74-cc18da35fedd" ]
[ [ [ 1, 283 ] ] ]
afc86f1e109ed0893a7b770c3542e5ee7b5c486d
db0d644f1992e5a82e22579e6287f45a8f8d357a
/Caster/Ntrip/SendClientData.h
ee48f8a528308621f2425c469ad1802a8f4d7e35
[]
no_license
arnout/nano-cast
841a6dc394bfb30864134bce70e11d29b77c2411
5d11094da4dbb5027ce0a3c870b6a6cc9fcc0179
refs/heads/master
2021-01-01T05:14:29.996348
2011-01-15T17:27:48
2011-01-15T17:27:48
58,049,740
1
0
null
null
null
null
UTF-8
C++
false
false
591
h
#ifndef SendClientDataIncluded #define SendClientDataIncluded #include "CallBack.h" #include "MountTable.h" #include "Connection.h" class SendClientData : public CallBack { public: SendClientData(Connection_ptr& c, MountPoint* mnt); ~SendClientData(); bool Call(bool status); protected: Connection_ptr conn; MountPoint* Mnt; DataBuffer& buf; uint64 count; // total bytes sent on this connection. static const size_t TooFarBehind = DataBuffer::BufSize / 2; private: bool WaitForBuf(); }; #endif // SendClientDataIncluded
[ [ [ 1, 30 ] ] ]
03782fb219f577287f54e255e7f00d67184e71e2
fd3f2268460656e395652b11ae1a5b358bfe0a59
/srchybrid/MuleSystrayDlg.cpp
83f5169f575819b9982c18f725cd4ca60906bb2a
[]
no_license
mikezhoubill/emule-gifc
e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60
46979cf32a313ad6d58603b275ec0b2150562166
refs/heads/master
2021-01-10T20:37:07.581465
2011-08-13T13:58:37
2011-08-13T13:58:37
32,465,033
4
2
null
null
null
null
UTF-8
C++
false
false
19,427
cpp
// MuleSystrayDlg.cpp : implementation file // #include "stdafx.h" #include "MuleSystrayDlg.h" #include "emule.h" #include "preferences.h" #include "opcodes.h" #include "otherfunctions.h" #include "Scheduler.h" // Don't reset Connection Settings for Webserver/CML/MM [Stulle] - Stulle #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //Cax2 - new class without context menu BEGIN_MESSAGE_MAP(CInputBox, CEdit) ON_WM_CONTEXTMENU() END_MESSAGE_MAP() void CInputBox::OnContextMenu(CWnd* /*pWnd*/, CPoint /*point*/) { //Cax2 - nothing to see here! } ///////////////////////////////////////////////////////////////////////////// // CMuleSystrayDlg dialog //Xman /* CMuleSystrayDlg::CMuleSystrayDlg(CWnd* pParent, CPoint pt, int iMaxUp, int iMaxDown, int iCurUp, int iCurDown) */ CMuleSystrayDlg::CMuleSystrayDlg(CWnd* pParent, CPoint pt, float iMaxUp, float iMaxDown, float iCurUp, float iCurDown) //Xman end : CDialog(CMuleSystrayDlg::IDD, pParent) { if(iCurDown == UNLIMITED) iCurDown = 0; //Xman /* if(iCurUp == UNLIMITED) iCurUp = 0; */ //Xman end //{{AFX_DATA_INIT(CMuleSystrayDlg) m_nDownSpeedTxt = iMaxDown < iCurDown ? iMaxDown : iCurDown; m_nUpSpeedTxt = iMaxUp < iCurUp ? iMaxUp : iCurUp; //}}AFX_DATA_INIT m_iMaxUp = iMaxUp; m_iMaxDown = iMaxDown; m_ptInitialPosition = pt; m_hUpArrow = NULL; m_hDownArrow = NULL; m_nExitCode = 0; m_bClosingDown = false; } CMuleSystrayDlg::~CMuleSystrayDlg() { if(m_hUpArrow) DestroyIcon(m_hUpArrow); if(m_hDownArrow) DestroyIcon(m_hDownArrow); } void CMuleSystrayDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CMuleSystrayDlg) DDX_Control(pDX, IDC_TRAYUP, m_ctrlUpArrow); DDX_Control(pDX, IDC_TRAYDOWN, m_ctrlDownArrow); DDX_Control(pDX, IDC_SIDEBAR, m_ctrlSidebar); DDX_Control(pDX, IDC_UPSLD, m_ctrlUpSpeedSld); DDX_Control(pDX, IDC_DOWNSLD, m_ctrlDownSpeedSld); //Xman /* DDX_Control(pDX, IDC_DOWNTXT, m_DownSpeedInput); DDX_Control(pDX, IDC_UPTXT, m_UpSpeedInput); DDX_Text(pDX, IDC_DOWNTXT, m_nDownSpeedTxt); DDX_Text(pDX, IDC_UPTXT, m_nUpSpeedTxt); */ DDX_Control(pDX, IDC_DOWNTXT, m_DownSpeedInput); DDX_Control(pDX, IDC_UPTXT, m_UpSpeedInput); //Xman end //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CMuleSystrayDlg, CDialog) //{{AFX_MSG_MAP(CMuleSystrayDlg) ON_WM_MOUSEMOVE() ON_EN_CHANGE(IDC_DOWNTXT, OnChangeDowntxt) ON_EN_CHANGE(IDC_UPTXT, OnChangeUptxt) ON_WM_HSCROLL() ON_WM_LBUTTONUP() ON_WM_RBUTTONDOWN() ON_WM_KILLFOCUS() ON_WM_SHOWWINDOW() ON_WM_CAPTURECHANGED() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMuleSystrayDlg message handlers void CMuleSystrayDlg::OnMouseMove(UINT nFlags, CPoint point) { CWnd *pWnd = ChildWindowFromPoint(point, CWP_SKIPINVISIBLE|CWP_SKIPDISABLED); if(pWnd) { if(pWnd == this || pWnd == &m_ctrlSidebar) SetCapture(); // me, myself and i else ReleaseCapture(); // sweet child of mine } else SetCapture(); // i'm on the outside, i'm looking in ... CDialog::OnMouseMove(nFlags, point); } BOOL CMuleSystrayDlg::OnInitDialog() { CDialog::OnInitDialog(); m_bClosingDown = false; CRect r; CWnd *p; m_hUpArrow = theApp.LoadIcon(_T("UPLOAD")); m_hDownArrow = theApp.LoadIcon(_T("DOWNLOAD")); m_ctrlUpArrow.SetIcon(m_hUpArrow); m_ctrlDownArrow.SetIcon(m_hDownArrow); bool bValidFont = false; LOGFONT lfStaticFont = {0}; p = GetDlgItem(IDC_SPEED); if(p) { p->GetFont()->GetLogFont(&lfStaticFont); bValidFont = true; } p = GetDlgItem(IDC_SPEED); if(p) { p->GetWindowRect(r); ScreenToClient(r); m_ctrlSpeed.Create(NULL, NULL, WS_CHILD|WS_VISIBLE, r, this, IDC_SPEED); m_ctrlSpeed.m_nBtnID = IDC_SPEED; //p->GetWindowText(m_ctrlSpeed.m_strText); m_ctrlSpeed.m_strText = GetResString(IDS_TRAYDLG_SPEED); m_ctrlSpeed.m_strText.Remove(_T('&')); m_ctrlSpeed.m_bUseIcon = true; m_ctrlSpeed.m_sIcon.cx = 16; m_ctrlSpeed.m_sIcon.cy = 16; m_ctrlSpeed.m_hIcon = theApp.LoadIcon(_T("SPEED"), m_ctrlSpeed.m_sIcon.cx, m_ctrlSpeed.m_sIcon.cy); m_ctrlSpeed.m_bParentCapture = true; if(bValidFont) { LOGFONT lfFont = lfStaticFont; lfFont.lfWeight += 200; // make it bold m_ctrlSpeed.m_cfFont.CreateFontIndirect(&lfFont); } m_ctrlSpeed.m_bNoHover = true; } p = GetDlgItem(IDC_TOMAX); //zz_fly :: make font not bold for chinese :: start if(p) { p->GetFont()->GetLogFont(&lfStaticFont); bValidFont = true; } if(bValidFont && (thePrefs.m_wLanguageID != 2052) && (thePrefs.m_wLanguageID != 1028)) lfStaticFont.lfWeight += 200; // make it bold //zz_fly :: make font not bold for chinese :: end if(p) { p->GetWindowRect(r); ScreenToClient(r); m_ctrlAllToMax.Create(NULL, NULL, WS_CHILD|WS_VISIBLE, r, this, IDC_TOMAX); m_ctrlAllToMax.m_nBtnID = IDC_TOMAX; //p->GetWindowText(m_ctrlAllToMax.m_strText); m_ctrlAllToMax.m_strText = GetResString(IDS_PW_UA); m_ctrlAllToMax.m_strText.Remove(_T('&')); m_ctrlAllToMax.m_bUseIcon = true; m_ctrlAllToMax.m_sIcon.cx = 16; m_ctrlAllToMax.m_sIcon.cy = 16; m_ctrlAllToMax.m_hIcon = theApp.LoadIcon(_T("SPEEDMAX"), m_ctrlAllToMax.m_sIcon.cx, m_ctrlAllToMax.m_sIcon.cy); m_ctrlAllToMax.m_bParentCapture = true; if(bValidFont) m_ctrlAllToMax.m_cfFont.CreateFontIndirect(&lfStaticFont); } p = GetDlgItem(IDC_TOMIN); if(p) { p->GetWindowRect(r); ScreenToClient(r); m_ctrlAllToMin.Create(NULL, NULL, WS_CHILD|WS_VISIBLE, r, this, IDC_TOMIN); m_ctrlAllToMin.m_nBtnID = IDC_TOMIN; //p->GetWindowText(m_ctrlAllToMin.m_strText); m_ctrlAllToMin.m_strText = GetResString(IDS_PW_PA); m_ctrlAllToMin.m_strText.Remove(_T('&')); m_ctrlAllToMin.m_bUseIcon = true; m_ctrlAllToMin.m_sIcon.cx = 16; m_ctrlAllToMin.m_sIcon.cy = 16; m_ctrlAllToMin.m_hIcon = theApp.LoadIcon(_T("SPEEDMIN"), m_ctrlAllToMin.m_sIcon.cx, m_ctrlAllToMin.m_sIcon.cy); m_ctrlAllToMin.m_bParentCapture = true; if(bValidFont) m_ctrlAllToMin.m_cfFont.CreateFontIndirect(&lfStaticFont); } p = GetDlgItem(IDC_RESTORE); if(p) { p->GetWindowRect(r); ScreenToClient(r); m_ctrlRestore.Create(NULL, NULL, WS_CHILD|WS_VISIBLE, r, this, IDC_RESTORE); m_ctrlRestore.m_nBtnID = IDC_RESTORE; //p->GetWindowText(m_ctrlRestore.m_strText); m_ctrlRestore.m_strText = GetResString(IDS_MAIN_POPUP_RESTORE); m_ctrlRestore.m_strText.Remove(_T('&')); m_ctrlRestore.m_bUseIcon = true; m_ctrlRestore.m_sIcon.cx = 16; m_ctrlRestore.m_sIcon.cy = 16; m_ctrlRestore.m_hIcon = theApp.LoadIcon(_T("RESTOREWINDOW"), m_ctrlRestore.m_sIcon.cx, m_ctrlRestore.m_sIcon.cy); m_ctrlRestore.m_bParentCapture = true; if(bValidFont) { //zz_fly :: make font not bold for chinese :: start /* LOGFONT lfFont = lfStaticFont; lfFont.lfWeight += 200; // make it bold m_ctrlRestore.m_cfFont.CreateFontIndirect(&lfFont); */ m_ctrlRestore.m_cfFont.CreateFontIndirect(&lfStaticFont); //zz_fly :: make font not bold for chinese :: end } } p = GetDlgItem(IDC_CONNECT); if(p) { p->GetWindowRect(r); ScreenToClient(r); m_ctrlConnect.Create(NULL, NULL, WS_CHILD|WS_VISIBLE, r, this, IDC_CONNECT); m_ctrlConnect.m_nBtnID = IDC_CONNECT; //p->GetWindowText(m_ctrlConnect.m_strText); m_ctrlConnect.m_strText = GetResString(IDS_MAIN_BTN_CONNECT); m_ctrlConnect.m_strText.Remove(_T('&')); m_ctrlConnect.m_bUseIcon = true; m_ctrlConnect.m_sIcon.cx = 16; m_ctrlConnect.m_sIcon.cy = 16; m_ctrlConnect.m_hIcon = theApp.LoadIcon(_T("CONNECT"), m_ctrlConnect.m_sIcon.cx, m_ctrlConnect.m_sIcon.cy); m_ctrlConnect.m_bParentCapture = true; if(bValidFont) m_ctrlConnect.m_cfFont.CreateFontIndirect(&lfStaticFont); } p = GetDlgItem(IDC_DISCONNECT); if(p) { p->GetWindowRect(r); ScreenToClient(r); m_ctrlDisconnect.Create(NULL, NULL, WS_CHILD|WS_VISIBLE, r, this, IDC_DISCONNECT); m_ctrlDisconnect.m_nBtnID = IDC_DISCONNECT; //p->GetWindowText(m_ctrlDisconnect.m_strText); m_ctrlDisconnect.m_strText = GetResString(IDS_MAIN_BTN_DISCONNECT); m_ctrlDisconnect.m_strText.Remove(_T('&')); m_ctrlDisconnect.m_bUseIcon = true; m_ctrlDisconnect.m_sIcon.cx = 16; m_ctrlDisconnect.m_sIcon.cy = 16; m_ctrlDisconnect.m_hIcon = theApp.LoadIcon(_T("DISCONNECT"), m_ctrlDisconnect.m_sIcon.cx, m_ctrlDisconnect.m_sIcon.cy); m_ctrlDisconnect.m_bParentCapture = true; if(bValidFont) m_ctrlDisconnect.m_cfFont.CreateFontIndirect(&lfStaticFont); } p = GetDlgItem(IDC_PREFERENCES); if(p) { p->GetWindowRect(r); ScreenToClient(r); m_ctrlPreferences.Create(NULL, NULL, WS_CHILD|WS_VISIBLE, r, this, IDC_PREFERENCES); m_ctrlPreferences.m_nBtnID = IDC_PREFERENCES; //p->GetWindowText(m_ctrlPreferences.m_strText); m_ctrlPreferences.m_strText = GetResString(IDS_EM_PREFS); m_ctrlPreferences.m_strText.Remove(_T('&')); m_ctrlPreferences.m_bUseIcon = true; m_ctrlPreferences.m_sIcon.cx = 16; m_ctrlPreferences.m_sIcon.cy = 16; m_ctrlPreferences.m_hIcon = theApp.LoadIcon(_T("Preferences"), m_ctrlPreferences.m_sIcon.cx, m_ctrlPreferences.m_sIcon.cy); m_ctrlPreferences.m_bParentCapture = true; if(bValidFont) m_ctrlPreferences.m_cfFont.CreateFontIndirect(&lfStaticFont); } p = GetDlgItem(IDC_TRAY_EXIT); if(p) { p->GetWindowRect(r); ScreenToClient(r); m_ctrlExit.Create(NULL, NULL, WS_CHILD|WS_VISIBLE, r, this, IDC_EXIT); m_ctrlExit.m_nBtnID = IDC_EXIT; //p->GetWindowText(m_ctrlExit.m_strText); m_ctrlExit.m_strText = GetResString(IDS_EXIT); m_ctrlExit.m_strText.Remove(_T('&')); m_ctrlExit.m_bUseIcon = true; m_ctrlExit.m_sIcon.cx = 16; m_ctrlExit.m_sIcon.cy = 16; m_ctrlExit.m_hIcon = theApp.LoadIcon(_T("EXIT"), m_ctrlExit.m_sIcon.cx, m_ctrlExit.m_sIcon.cy); m_ctrlExit.m_bParentCapture = true; if(bValidFont) m_ctrlExit.m_cfFont.CreateFontIndirect(&lfStaticFont); } if((p = GetDlgItem(IDC_DOWNLBL)) != NULL) p->SetWindowText(GetResString(IDS_PW_CON_DOWNLBL)); if((p = GetDlgItem(IDC_UPLBL)) != NULL) p->SetWindowText(GetResString(IDS_PW_CON_UPLBL)); if((p = GetDlgItem(IDC_DOWNKB)) != NULL) p->SetWindowText(GetResString(IDS_KBYTESPERSEC)); if((p = GetDlgItem(IDC_UPKB)) != NULL) p->SetWindowText(GetResString(IDS_KBYTESPERSEC)); //Xman /* m_ctrlDownSpeedSld.SetRange(0,m_iMaxDown); m_ctrlDownSpeedSld.SetPos(m_nDownSpeedTxt); m_ctrlUpSpeedSld.SetRange(0,m_iMaxUp); m_ctrlUpSpeedSld.SetPos(m_nUpSpeedTxt); m_DownSpeedInput.EnableWindow(m_nDownSpeedTxt >0); m_UpSpeedInput.EnableWindow(m_nUpSpeedTxt >0); */ CString strBuffer; strBuffer.Format(_T("%.1f"), m_nDownSpeedTxt); GetDlgItem(IDC_DOWNTXT)->SetWindowText(strBuffer); strBuffer.Format(_T("%.1f"), m_nUpSpeedTxt); GetDlgItem(IDC_UPTXT)->SetWindowText(strBuffer); m_ctrlDownSpeedSld.SetRange(0,int(m_iMaxDown*10.0f)); m_ctrlDownSpeedSld.SetPos(int(m_nDownSpeedTxt*10.0f)); m_ctrlUpSpeedSld.SetRange(1,int(m_iMaxUp*10.0f)); m_ctrlUpSpeedSld.SetPos(int(m_nUpSpeedTxt*10.0f)); m_DownSpeedInput.EnableWindow(m_nDownSpeedTxt > 0.0f); //Xman end CFont Font; Font.CreateFont(-16,0,900,0,700,0,0,0,0,3,2,1,34,_T("Tahoma")); UINT winver = thePrefs.GetWindowsVersion(); if (winver == _WINVER_95_ || winver == _WINVER_NT4_ || g_bLowColorDesktop) { m_ctrlSidebar.SetColors(GetSysColor(COLOR_CAPTIONTEXT), GetSysColor(COLOR_ACTIVECAPTION), GetSysColor(COLOR_ACTIVECAPTION)); } else { m_ctrlSidebar.SetColors(GetSysColor(COLOR_CAPTIONTEXT), GetSysColor(COLOR_ACTIVECAPTION), GetSysColor(COLOR_GRADIENTACTIVECAPTION)); } m_ctrlSidebar.SetHorizontal(false); m_ctrlSidebar.SetFont(&Font); // ==> Show ModID in systray dialog sidebar [Stulle] - Stulle /* m_ctrlSidebar.SetWindowText(_T("eMule ") + theApp.m_strCurVersionLong); */ m_ctrlSidebar.SetWindowText(_T("eMule ") + theApp.m_strCurVersionLong + _T(" [") + theApp.m_strModLongVersion + _T("]")); // <== Show ModID in systray dialog sidebar [Stulle] - Stulle CRect rDesktop; CWnd *pDesktopWnd = GetDesktopWindow(); pDesktopWnd->GetClientRect(rDesktop); CPoint pt = m_ptInitialPosition; pDesktopWnd->ScreenToClient(&pt); int xpos, ypos; GetWindowRect(r); if(m_ptInitialPosition.x + r.Width() < rDesktop.right) xpos = pt.x; else xpos = pt.x - r.Width(); if(m_ptInitialPosition.y - r.Height() < rDesktop.top) ypos = pt.y; else ypos = pt.y - r.Height(); MoveWindow(xpos, ypos, r.Width(), r.Height()); SetCapture(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CMuleSystrayDlg::OnChangeDowntxt() { UpdateData(); //Xman CString strBuffer; if(GetDlgItem(IDC_DOWNTXT)->GetWindowTextLength()) { GetDlgItem(IDC_DOWNTXT)->GetWindowText(strBuffer); m_nDownSpeedTxt = (float)_tstof(strBuffer); // fix non-numeric input /* if(strBuffer.GetAt(0) < '0' || strBuffer.GetAt(0) > '9') { strBuffer.Format(_T("%.1f"),0.0f); GetDlgItem(IDC_DOWNTXT)->SetWindowText(strBuffer); } */ // auto complete to float (removed) /* else if(strBuffer.FindOneOf(_T(".,")) == -1) { strBuffer.Format(_T("%.1f"),m_nDownSpeedTxt); GetDlgItem(IDC_DOWNTXT)->SetWindowText(strBuffer); } */ } float m_nDownSpeedTxtOld = m_nDownSpeedTxt; //Xman end if(thePrefs.GetMaxGraphDownloadRate() == UNLIMITED) //Cax2 - shouldn't be anymore... { if(m_nDownSpeedTxt > 64) //Cax2 - why 64 ??? m_nDownSpeedTxt = 64; } else { if(m_nDownSpeedTxt > thePrefs.GetMaxGraphDownloadRate()) m_nDownSpeedTxt = thePrefs.GetMaxGraphDownloadRate(); } //Xman /* m_ctrlDownSpeedSld.SetPos(m_nDownSpeedTxt); if(m_nDownSpeedTxt < 1){ m_nDownSpeedTxt = 0; m_DownSpeedInput.EnableWindow(false); } */ m_ctrlDownSpeedSld.SetPos(int(m_nDownSpeedTxt*10.0f)); if(m_nDownSpeedTxt < 0.1f){ m_nDownSpeedTxt = 0.0f; m_DownSpeedInput.EnableWindow(false); } if(m_nDownSpeedTxt != m_nDownSpeedTxtOld) { strBuffer.Format(_T("%.1f"),m_nDownSpeedTxt); GetDlgItem(IDC_DOWNTXT)->SetWindowText(strBuffer); } //Xman end thePrefs.SetMaxDownload((m_nDownSpeedTxt == 0) ? UNLIMITED : m_nDownSpeedTxt); theApp.scheduler->SaveOriginals(); // Don't reset Connection Settings for Webserver/CML/MM [Stulle] - Stulle UpdateData(FALSE); } void CMuleSystrayDlg::OnChangeUptxt() { UpdateData(); //Xman /* if(thePrefs.GetMaxGraphUploadRate(true) == UNLIMITED) { if(m_nUpSpeedTxt > 16) m_nUpSpeedTxt = 16; } else { if(m_nUpSpeedTxt > thePrefs.GetMaxGraphUploadRate(true)) m_nUpSpeedTxt = thePrefs.GetMaxGraphUploadRate(true); } m_ctrlUpSpeedSld.SetPos(m_nUpSpeedTxt); if(m_nUpSpeedTxt < 1){ m_nUpSpeedTxt = 0; m_UpSpeedInput.EnableWindow(false); } thePrefs.SetMaxUpload((m_nUpSpeedTxt == 0) ? UNLIMITED : m_nUpSpeedTxt); */ if(GetDlgItem(IDC_UPTXT)->GetWindowTextLength()) { CString strBuffer; GetDlgItem(IDC_UPTXT)->GetWindowText(strBuffer); m_nUpSpeedTxt = (float)_tstof(strBuffer); // auto complete to float (removed) /* if(strBuffer.FindOneOf(_T(".,")) == -1) { strBuffer.Format(_T("%.1f"),m_nUpSpeedTxt); GetDlgItem(IDC_DOWNTXT)->SetWindowText(strBuffer); } */ } if(m_nUpSpeedTxt > thePrefs.GetMaxGraphUploadRate()) { m_nUpSpeedTxt = thePrefs.GetMaxGraphUploadRate(); CString strBuffer; strBuffer.Format(_T("%.1f"), m_nUpSpeedTxt); GetDlgItem(IDC_UPTXT)->SetWindowText(strBuffer); } if(m_nUpSpeedTxt < 0.1f) { m_nUpSpeedTxt = 0.1f; CString strBuffer; strBuffer.Format(_T("%.1f"), m_nUpSpeedTxt); GetDlgItem(IDC_UPTXT)->SetWindowText(strBuffer); } m_ctrlUpSpeedSld.SetPos(int(m_nUpSpeedTxt*10.0f)); thePrefs.SetMaxUpload(m_nUpSpeedTxt); theApp.scheduler->SaveOriginals(); // Don't reset Connection Settings for Webserver/CML/MM [Stulle] - Stulle //Xman end UpdateData(FALSE); } void CMuleSystrayDlg::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { if(pScrollBar == (CScrollBar*)&m_ctrlDownSpeedSld) { //Xman /* m_nDownSpeedTxt = m_ctrlDownSpeedSld.GetPos(); if(m_nDownSpeedTxt < 1){ m_nDownSpeedTxt = 0; */ m_nDownSpeedTxt = m_ctrlDownSpeedSld.GetPos()/10.0f; if(m_nDownSpeedTxt < 0.1f){ m_nDownSpeedTxt = 0.0f; //Xman end m_DownSpeedInput.EnableWindow(false); } else{ m_DownSpeedInput.EnableWindow(true); } //Xman CString strBuffer; strBuffer.Format(_T("%.1f"), m_nDownSpeedTxt); GetDlgItem(IDC_DOWNTXT)->SetWindowText(strBuffer); //Xman end UpdateData(FALSE); thePrefs.SetMaxDownload((m_nDownSpeedTxt == 0) ? UNLIMITED : m_nDownSpeedTxt); } else if(pScrollBar == (CScrollBar*)&m_ctrlUpSpeedSld) { //Xman /* m_nUpSpeedTxt = m_ctrlUpSpeedSld.GetPos(); if(m_nUpSpeedTxt < 1){ m_nUpSpeedTxt = 0; m_UpSpeedInput.EnableWindow(false); } else{ m_UpSpeedInput.EnableWindow(true); } UpdateData(FALSE); thePrefs.SetMaxUpload((m_nUpSpeedTxt == 0) ? UNLIMITED : m_nUpSpeedTxt); */ m_nUpSpeedTxt = m_ctrlUpSpeedSld.GetPos()/10.0f; if(m_nUpSpeedTxt < 0.1f) m_nUpSpeedTxt = 0.1f; CString strBuffer; strBuffer.Format(_T("%.1f"), m_nUpSpeedTxt); GetDlgItem(IDC_UPTXT)->SetWindowText(strBuffer); UpdateData(FALSE); thePrefs.SetMaxUpload(m_nUpSpeedTxt); //Xman end } theApp.scheduler->SaveOriginals(); // Don't reset Connection Settings for Webserver/CML/MM [Stulle] - Stulle CDialog::OnHScroll(nSBCode, nPos, pScrollBar); } void CMuleSystrayDlg::OnLButtonUp(UINT nFlags, CPoint point) { ReleaseCapture(); EndDialog(m_nExitCode); m_bClosingDown = true; CDialog::OnLButtonUp(nFlags, point); } //bond006: systray menu gets stuck (bugfix) void CMuleSystrayDlg::OnRButtonDown(UINT nFlags, CPoint point) { CRect systrayRect; GetClientRect(&systrayRect); if(point.x<=systrayRect.left || point.x>=systrayRect.right || point.y<=systrayRect.top || point.y>=systrayRect.bottom) { ReleaseCapture(); EndDialog(m_nExitCode); m_bClosingDown = true; } CDialog::OnRButtonDown(nFlags,point); } void CMuleSystrayDlg::OnKillFocus(CWnd* pNewWnd) { CDialog::OnKillFocus(pNewWnd); if(!m_bClosingDown) { ReleaseCapture(); EndDialog(m_nExitCode); m_bClosingDown = true; } } void CMuleSystrayDlg::OnShowWindow(BOOL bShow, UINT nStatus) { if(!bShow && !m_bClosingDown) { ReleaseCapture(); EndDialog(m_nExitCode); m_bClosingDown = true; } CDialog::OnShowWindow(bShow, nStatus); } void CMuleSystrayDlg::OnCaptureChanged(CWnd *pWnd) { if(pWnd && pWnd != this && !IsChild(pWnd)) { EndDialog(m_nExitCode); m_bClosingDown = true; } CDialog::OnCaptureChanged(pWnd); } BOOL CMuleSystrayDlg::OnCommand(WPARAM wParam, LPARAM lParam) { if(HIWORD(wParam) == BN_CLICKED) { ReleaseCapture(); m_nExitCode = LOWORD(wParam); EndDialog(m_nExitCode); m_bClosingDown = true; } return CDialog::OnCommand(wParam, lParam); }
[ "Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b", "[email protected]@dd569cc8-ff36-11de-bbca-1111db1fd05b" ]
[ [ [ 1, 9 ], [ 11, 393 ], [ 396, 396 ], [ 400, 485 ], [ 487, 544 ], [ 546, 602 ], [ 604, 678 ] ], [ [ 10, 10 ], [ 394, 395 ], [ 397, 399 ], [ 486, 486 ], [ 545, 545 ], [ 603, 603 ] ] ]
d9038e9f38eec868bdac09b7e2d755ea10667d5e
60365cfb5278ec1dfcc07a5b3e07f3c9d680fa2a
/xlview/Registry.h
321f8d35518466011b3292cda0ec6781a25b13b2
[]
no_license
cyberscorpio/xlview
6c01e96dbf225cfbc2be1cc15a8b70c61976eb46
a4b5088ce049695de2ed7ed191162e6034326381
refs/heads/master
2021-01-01T16:34:47.787022
2011-04-28T13:34:25
2011-04-28T13:34:25
38,444,399
0
0
null
null
null
null
UTF-8
C++
false
false
1,681
h
#ifndef XL_VIEW_REGISTRY_H #define XL_VIEW_REGISTRY_H #include <memory> #include <vector> #include "libxl/include/common.h" #include "libxl/include/string.h" class CRegNodeItem; typedef std::tr1::shared_ptr<CRegNodeItem> CRegNodeItemPtr; typedef std::vector<CRegNodeItemPtr> CRegNodeItems; class CRegNodeItem { xl::tstring m_name; DWORD m_type; xl::tstring m_data; public: CRegNodeItem (const xl::tstring &name, DWORD type, const xl::tstring &data); bool write (HKEY hParent); }; class CRegNode; typedef std::tr1::shared_ptr<CRegNode> CRegNodePtr; typedef std::vector<CRegNodePtr> CRegNodes; class CRegNode { xl::tstring m_name; CRegNodeItems m_items; CRegNodes m_subKeys; public: CRegNode (const xl::tstring &name); bool write (HKEY hParent); void addItem (const xl::tstring &name, DWORD type, const xl::tstring &data); void addKey (CRegNodePtr key); }; enum REGISTRYSTATUS { RS_OK, // the registry item is OK RS_NONE, // the registry item does not exist RS_PARTIAL // the registry item exists, but not complete }; /** * test whether @appkey is in HKCU\Software\Classes\ * and whether it has shell & shell\open key */ REGISTRYSTATUS isAppRegistered (const xl::tstring &app); bool registerApp (const xl::tstring &app, const xl::tstring &shellName); void unregisterApp (const xl::tstring &app); bool registerExt (const xl::tstring &ext, const xl::tstring &app); bool registerExtAsDefault (const xl::tstring &ext, const xl::tstring &app); #endif
[ [ [ 1, 59 ] ] ]
8dfd277aa62e735d09c257587b7278d41099c408
bbc02822aeffdfaa8050907c1d9bd41ff4e9f3f3
/MinecraftPSP/MinecraftPSP/World.h
9b3e383afa0eec2a03f58a77c179615b6170cb59
[]
no_license
DragonNeos/minecraft-psp
5184361c0beab2a4a25d789ba24a5cf185ef18cf
fde4e012c8ecc94f52bf222738f29e5efac47d0e
refs/heads/master
2020-03-26T15:06:44.654834
2011-03-01T09:38:49
2011-03-01T09:38:49
40,795,370
0
0
null
null
null
null
UTF-8
C++
false
false
1,084
h
//Author: Mouhamad Abdallah //Date: Tuesday 8th February 2011 //Description: Header file for the actual 'World' #ifndef WORLD_H #define WORLD_H #include <stdlib.h> //Header File for standard library #include "Cube.h" //Header File for the 'Cube' class class World { public: int worldSize, blockSize; //World information for later use Cube ***world; //3D Array of blocks/cubes World(); //Default Constructor void initialiseWorld(int worldLimit, int blockSide, short *&blockID); //Initialise the world with various limits and reference to block information short returnBlock(int x, int y, int z); //Returns the block type at the indicated position(For collision detection purposes) void changeBlock(int x, int y, int z, short blockType); //Used to change the blocks selected(Either for destruction of/creation of blocks) void draw(GLbyte* indices); //Draw the world without any rotations on the individual blocks void draw(float rotation, float xR, float yR, float zR); //Draw the world with individual rotations on blocks }; #endif
[ [ [ 1, 25 ] ] ]
4242e07a23f750f5f6df4ba040193f00d41d33f8
62fc6c4a891ffd5f4b0b98fe625a09e0932cb00c
/src/CameraCapturePreviewForm.cpp
7befb5781687cb0193ff539b7ced0b83b8f69fd3
[]
no_license
luiztiago/bada-photoclown
46837cd5500089bebdeebb76a02a95add5dc0f9f
817c8631f763c8cde3df542baf18e9f3391a5422
refs/heads/master
2021-01-23T13:48:05.278210
2011-11-23T08:26:21
2011-11-23T08:26:21
2,806,607
0
0
null
null
null
null
UTF-8
C++
false
false
38,887
cpp
#include "CameraCaptureMainForm.h" #include "CameraCapturePreview.h" #include "CameraCapturePreviewForm.h" using namespace Osp::Base; using namespace Osp::Base::Collection; using namespace Osp::Ui; using namespace Osp::Ui::Controls; using namespace Osp::Uix; using namespace Osp::Graphics; using namespace Osp::Io; using namespace Osp::Media; using namespace Osp::App; #define ACCERERATION_INTERVAL 100 #define ACCELERATION_THRESHOLD 0.2 #define IS_UPLIGHT(X) ((-ACCELERATION_THRESHOLD<1.0-X)&&(1.0-X<ACCELERATION_THRESHOLD) ? true:false) #define IS_UPSIDE_DOWN(X) ((-ACCELERATION_THRESHOLD<1.0+X)&&(1.0+X<ACCELERATION_THRESHOLD) ? true:false) #define DEVICE_PORTRAIT 0 #define DEVICE_PORTRAIT_REVERSE 1 #define DEVICE_LANDSCAPE 2 #define DEVICE_LANDSCAPE_REVERSE 3 class MyFacebookClass : public Osp::Social::Services::ISnsAuthenticatorListener, public Osp::Social::Services::ISnsGatewayListener, public Osp::Social::Services::ISnsContentListener{ Osp::Social::Services::SnsGateway* pSnsGateway; Osp::Social::Services::SnsAuthenticator* pSNSAuthenticator; Osp::Social::Services::SnsAuthResult* pSNSAuthResult; result Construct(void); result Authenticate(void); void OnSnsAuthenticated(Osp::Social::Services::SnsAuthResult&snsAuthResult, result r,const String& errorCode, const String&errorMsg); void OnSnsLoggedInStatusReceived(RequestId reqId,Osp::Base::String& serviceProvider, bool isLoggedIn, result r, const Osp::Base::String& errorCode, const Osp::Base::String& errorMsg); result UploadPhoto(void); void OnSnsPhotoReceived(RequestId reqId,Osp::Social::Services::SnsPhotoInfo *pPhoto, result r,const Osp::Base::String &errorCode, const Osp::Base::String &errorMsg); void OnSnsPhotosByUserReceivedN(RequestId reqId, Osp::Base::Collection::IList *pPhotoList, bool hasNext,Osp::Social::Services::SnsPagingParam& pagingParam,result r, const Osp::Base::String &errorCode, const Osp::Base::String &errorMsg); void OnSnsPhotosInAlbumReceivedN(RequestId reqId, Osp::Base::Collection::IList *pPhotoList, bool hasNext,Osp::Social::Services::SnsPagingParam& pagingParam, result r,const Osp::Base::String &errorCode, const Osp::Base::String &errorMsg); void OnSnsPhotoUploaded(RequestId reqId, Osp::Base::String &serviceProvider,Osp::Base::String *pPhotoId,result r, const Osp::Base::String &errorCode, const Osp::Base::String &errorMsg); }; result MyFacebookClass::configure(void) { result r = E_SUCCESS; String serviceProvider = "facebook"; r = pSNSAuthenticator->Authenticate(serviceProvider, appID, appSecret); if(IsFailed(r)) { AppLogException( "Facebook fulerou"); return r; } } result MyFacebookClass::uploadPhoto(void) { pSnsGateway->Construct(*this, this, null, null); r = pSnsGateway->UploadPhoto(serviceProvider, null, *pContentInfo, reqId); RequestId reqId = INVALID_REQUEST_ID; result r = E_SUCCESS; String filepath = "/res/bada.png"; String serviceProvider = pSNSAuthResult->GetServiceProvider(); SnsUploadContentInfo* pContentInfo = newSnsUploadContentInfo(SNS_UPLOAD_CONTENT_PHOTO, filepath); r = pSnsGateway->UploadPhoto(serviceProvider, null, *pContentInfo,reqId); delete pContentInfo;p ContentInfo = null; } void MyFacebookClass::OnSnsPhotoUploaded(RequestId reqId, Osp::Base::String&serviceProvider, Osp::Base::String *pPhotoId, result r, const Osp::Base::String &errorCode, const Osp::Base::String &errorMsg) { if (!isFailed(r)) { AppLog("Successfully uploaded the photo with photoId as%ls",pPhotoId->GetPointer()); } } CameraForm::CameraForm(void) { __pCameraPreview = null; __pOverlayCanvas = null; __pOverlayRegion = null; __pBackButton = null; __pCaptureButton = null; __startType = CAMERA_START_NONE; __orientation = ORIENTATION_NONE; __isStarted = false; __pFrame = null; __pMainForm = null; __previewWidth = 0; __previewHeight = 0; __previewPixelFormat = PIXEL_FORMAT_YCbCr420_PLANAR; __pOutByteBuffer = null; __pSensorManager = null; __deviceOrientation = DEVICE_LANDSCAPE; __skipFrame = 0; } CameraForm::~CameraForm(void) { if ( __pCameraPreview ) { delete __pCameraPreview; __pCameraPreview = null; } if ( __pOverlayRegion ) { delete __pOverlayRegion; __pOverlayRegion = null; } if ( __pOverlayCanvas ) { delete __pOverlayCanvas; __pOverlayCanvas = null; } } result CameraForm::Construct( Frame *pFrame, Form *pMainForm, Orientation orientation, CameraStartType cameraStartType ) { result r = E_SUCCESS; r = Form::Construct(FORM_STYLE_NORMAL); if(IsFailed(r)) { AppLogException( "Constructing form failed."); return r; } __pFrame = pFrame; __pMainForm = pMainForm; __startType = cameraStartType; __orientation = orientation; return E_SUCCESS; } result CameraForm::OnInitializing(void) { result r = E_SUCCESS; AppLog("Orientation : %d", __orientation); r = __InitCamera(); if ( r != E_SUCCESS ) { return r; } SetOrientation(__orientation); r = __InitOverlayRegion(__orientation); if ( r != E_SUCCESS ) { return r; } r = __InitSensor(); if ( r != E_SUCCESS ) { return r; } r = CameraForm::Start(); if ( r != E_SUCCESS ) { return r; } AddKeyEventListener(*this); return E_SUCCESS; } result CameraForm::OnTerminating(void) { __TerminateCamera(); __TerminateSensor(); return E_SUCCESS; } void CameraForm::OnActionPerformed(const Control& source, int actionId) { result r = E_SUCCESS; if( actionId == IDC_CAMERA_CAPTURE ) { AppLog("__deviceOrientation:%d", __deviceOrientation); switch ( __deviceOrientation) { case DEVICE_PORTRAIT: r=__pCameraPreview->SetExifOrientation(CAMERA_EXIF_ORIENTATION_RIGHT_TOP ); break; case DEVICE_PORTRAIT_REVERSE: r=__pCameraPreview->SetExifOrientation(CAMERA_EXIF_ORIENTATION_LEFT_BOTTOM ); break; case DEVICE_LANDSCAPE: r=__pCameraPreview->SetExifOrientation(CAMERA_EXIF_ORIENTATION_TOP_LEFT); break; case DEVICE_LANDSCAPE_REVERSE: r=__pCameraPreview->SetExifOrientation(CAMERA_EXIF_ORIENTATION_BOTTOM_RIGHT); break; default: break; } _SetButtonEnabled(__pBackButton, false); _SetButtonEnabled(__pCaptureButton, false); r = __pCameraPreview->StartCapture(); if ( r != E_SUCCESS ) { _SetButtonEnabled(__pBackButton, true); _SetButtonEnabled(__pCaptureButton, true); } } else if( actionId == IDC_GOTO_MAIN ) { r = Cancel(); _GotoMainForm(); } } Orientation CameraForm::GetOrientation (void) { return __orientation; } OverlayRegion* CameraForm::GetOverlayRegion(void) { return __pOverlayRegion; } Canvas* CameraForm::GetOverlayCanvas(void) { return __pOverlayCanvas; } Camera* CameraForm::GetCamera(void) { return __pCameraPreview; } bool CameraForm::IsStarted(void) { return __isStarted; } bool CameraForm::IsSourceStarted(void) { return IsStarted(); } result CameraForm::OnDraw() { result r = E_SUCCESS; r = Form::OnDraw(); if ( IsFailed(r)) { AppLogException("OnDraw failed.."); return r; } return r; } result CameraForm::Start( void ) { result r = E_SUCCESS; Osp::Graphics::BufferInfo bufferInfo; r = __pCameraPreview->Initialize(); if ( IsFailed(r)) { AppLogException("Initializing the camera failed.."); goto CATCH; } // Store the preview information __previewWidth = __pCameraPreview->GetPreviewResolution().width; __previewHeight = __pCameraPreview->GetPreviewResolution().height; __previewPixelFormat = __pCameraPreview->GetPreviewFormat(); switch( __startType ) { case CAMERA_START_NO_PREVIEW_WITHOUT_CALLBACK: case CAMERA_START_NO_PREVIEW_WITH_CALLBACK: r = __pCameraPreview->StartPreview( __startType, null ); if ( IsFailed(r)) { AppLogException("StartPreview with callback failed.."); goto CATCH; } break; case CAMERA_START_PREVIEW_WITH_CALLBACK: case CAMERA_START_PREVIEW_WITHOUT_CALLBACK: r = __pOverlayRegion->GetBackgroundBufferInfo(bufferInfo); if ( IsFailed(r)) { AppLogException("Panel's GetBackgroundBufferInfo failed.."); goto CATCH; } r = __pCameraPreview->StartPreview( __startType, &bufferInfo ); if ( IsFailed(r)) { AppLogException("StartPreview without callback failed.."); goto CATCH; } break; default: r = E_INVALID_ARG; goto CATCH; break; } if (__pSensorManager->IsAvailable(SENSOR_TYPE_ACCELERATION)) { r = __pSensorManager->AddSensorListener(*this, SENSOR_TYPE_ACCELERATION, ACCERERATION_INTERVAL, true); if (IsFailed(r)) { AppLogException("Add acceleration lister failed."); goto CATCH; } } else { AppLogException("Acceleration sensor is not available."); r = E_RESOURCE_UNAVAILABLE; goto CATCH; } __isStarted = true; return E_SUCCESS; CATCH: return r; } result CameraForm::Stop() { result r = E_SUCCESS; r = __pCameraPreview->StopPreview(); if ( IsFailed(r)) { AppLogException("Preview stop failed."); goto CATCH; } r = __pSensorManager->RemoveSensorListener(*this, SENSOR_TYPE_ACCELERATION); if ( IsFailed(r)) { AppLogException("Remove sensor listener failed."); goto CATCH; } __isStarted = false; CATCH: return r; } result CameraForm::Cancel() { result r = CameraForm::Stop(); if ( r == E_SUCCESS ) __pCameraPreview->Terminate(); _SetButtonEnabled(__pBackButton, true); _SetButtonEnabled(__pCaptureButton, true); return r; } bool CameraForm::CleanUp(void) { this->Cancel(); return true; } bool CameraForm::HandleLowBatteryCondition(void) { AppLog("CameraForm::HandleLowBatteryCondition\n"); AppLog("Battery Level is Low: Exit Camera and go to MainForm\n"); this->_GotoMainForm(); return true; } result CameraForm::InitButtons( Orientation orientation ) { result r = E_SUCCESS; Rectangle backButtonRect, captureButtonRect; AppLog("orientation : %d", orientation); backButtonRect = Rectangle(X_FROM_RIGHT(0,SMALL_BTN_WIDTH,BTN_WIDTH_MARGIN) ,Y_FROM_TOP(0,SMALL_BTN_HEIGHT,BTN_HEIGHT_MARGIN) ,SMALL_BTN_WIDTH ,SMALL_BTN_HEIGHT); captureButtonRect = Rectangle(X_FROM_RIGHT(0,SMALL_BTN_WIDTH,BTN_WIDTH_MARGIN) ,Y_FROM_TOP(1,SMALL_BTN_HEIGHT,BTN_HEIGHT_MARGIN) ,SMALL_BTN_WIDTH ,SMALL_BTN_HEIGHT); __pBackButton = new Button(); r = __pBackButton->Construct(backButtonRect,L"Back"); if(IsFailed(r)) { AppLogException( "__pBackButton construct failed."); goto CATCH; } __pCaptureButton = new Button(); r = __pCaptureButton->Construct(captureButtonRect,L"Capture"); if(IsFailed(r)) { AppLogException( "__pCaptureButton construct failed."); goto CATCH; } __pBackButton->SetActionId(IDC_GOTO_MAIN); __pBackButton->AddActionEventListener(*this); r = AddControl(*__pBackButton); if(IsFailed(r)) { AppLogException( "Adding __pBackButton failed."); goto CATCH; } __pCaptureButton->SetActionId(IDC_CAMERA_CAPTURE); __pCaptureButton->AddActionEventListener(*this); r = AddControl(*__pCaptureButton); if(IsFailed(r)) { AppLogException( "Adding __pCaptureButton failed."); goto CATCH; } __pCaptureButton->Draw(); __pBackButton->Draw(); return r; CATCH: RemoveControl(*__pBackButton); RemoveControl(*__pCaptureButton); return r; } void CameraForm::_GotoMainForm() { result r = E_SUCCESS; r = __pCameraPreview->Terminate(); if( IsFailed(r)) { AppLogException( "Terminate failed.."); // return; } //Switch to FormBase r = __pFrame->SetCurrentForm( *__pMainForm ); if( IsFailed(r)) { AppLogException( "SetCurrentForm MainForm failed.."); // return; } //Redraw __pFrame->Draw(); __pFrame->Show(); } int CameraForm::_SelectivePosition( int wideScreenPosition, int normalScreenPosition ) { if ( __orientation == ORIENTATION_PORTRAIT || __orientation == ORIENTATION_PORTRAIT_REVERSE || __orientation == ORIENTATION_NONE ) { return normalScreenPosition; } else { return wideScreenPosition; } } result CameraForm::_SetButtonEnabled ( Osp::Ui::Controls::Button* pButton, bool enable ) { result r = E_SUCCESS; if ( pButton ) { r = pButton->SetEnabled(enable); if ( r != E_SUCCESS ) return r; r = pButton->Draw(); if ( r != E_SUCCESS ) return r; r = pButton->Show(); if ( r != E_SUCCESS ) return r; } return r; } CameraStartType CameraForm::_GetCameraStartType (void) { return __startType; } result CameraForm::__ViewImage(Osp::Base::String& imagePath) { result r = E_SUCCESS; AppControl* pAc = AppManager::FindAppControlN(APPCONTROL_PROVIDER_IMAGE,APPCONTROL_OPERATION_VIEW); if(pAc != null) { ArrayList* pDataList = null; pDataList = new ArrayList(); pDataList->Construct(); String* pData = null; pData = new String(L"type:image"); pDataList->Add(*pData); pData = new String(L"path:"); (*pData).Append(imagePath); pDataList->Add(*pData); r = pAc->Start(pDataList, null); delete pAc; pAc = null; pDataList->RemoveAll(true); delete pDataList; } else { r = E_OBJ_NOT_FOUND; } return r; } result CameraForm::__InitCamera( void ) { result r = E_SUCCESS; IList* pPreviewResolutionList = null; IList* pCaptureResolutionList = null; IListT<PixelFormat>* pCaptureFormatList = null; IListT<PixelFormat>* pPreviewFormatList = null; __pCameraPreview = new CameraPreview(); if(null == __pCameraPreview) { AppLogException("Creating CameraPreview failed.."); return E_OUT_OF_MEMORY; } r = __pCameraPreview->Construct(*this); if (IsFailed(r)) { AppLogException("Construct of camera failed."); goto CATCH; } r = __pCameraPreview->PowerOn(); if (IsFailed(r)) { AppLogException("Power on of camera failed. There is no camera on your system. Please check your camera at first.."); goto CATCH; } pPreviewResolutionList = __pCameraPreview->GetSupportedPreviewResolutionListN(); if ( pPreviewResolutionList != null ) { Dimension* pPreviewResolution = (Dimension*)pPreviewResolutionList->GetAt(pPreviewResolutionList->GetCount ()-1); // supported max resolution r = __pCameraPreview->SetPreviewResolution(*pPreviewResolution); if (IsFailed(r)) { AppLogException("Setting preview resolution failed."); goto CATCH; } pPreviewResolutionList->RemoveAll(true); delete pPreviewResolutionList; pPreviewResolutionList = null; } pCaptureResolutionList = __pCameraPreview->GetSupportedCaptureResolutionListN(); if ( pCaptureResolutionList != null ) { Dimension* pCaptureResolution = (Dimension*)pCaptureResolutionList->GetAt(pCaptureResolutionList->GetCount ()-1); // supported max resolution r = __pCameraPreview->SetCaptureResolution(*pCaptureResolution); if (IsFailed(r)) { AppLogException("Setting capturing resolution failed."); goto CATCH; } pCaptureResolutionList->RemoveAll(true); delete pCaptureResolutionList; pCaptureResolutionList = null; } pCaptureFormatList = __pCameraPreview->GetSupportedCaptureFormatListN(); if ( pCaptureFormatList != null ) { if ( pCaptureFormatList->Contains(PIXEL_FORMAT_JPEG) ) { r = __pCameraPreview->SetCaptureFormat(PIXEL_FORMAT_JPEG); if (IsFailed(r)) { AppLogException("Setting capturing format failed - PIXEL_FORMAT_JPEG ."); goto CATCH; } } else if ( pCaptureFormatList->Contains(PIXEL_FORMAT_RGB565) ) { r = __pCameraPreview->SetCaptureFormat(PIXEL_FORMAT_RGB565); if (IsFailed(r)) { AppLogException("Setting capturing format failed - PIXEL_FORMAT_RGB565."); goto CATCH; } } else { PixelFormat pixelFormat; pCaptureFormatList->GetAt(0, pixelFormat); r = __pCameraPreview->SetCaptureFormat(pixelFormat); } pCaptureFormatList->RemoveAll(); delete pCaptureFormatList; pCaptureFormatList = null; } pPreviewFormatList = __pCameraPreview->GetSupportedPreviewFormatListN(); if ( pPreviewFormatList != null ) { if ( pPreviewFormatList->Contains(PIXEL_FORMAT_YCbCr420_PLANAR) ) { r = __pCameraPreview->SetPreviewFormat(PIXEL_FORMAT_YCbCr420_PLANAR); if (IsFailed(r)) { AppLogException("Setting preview format failed - PIXEL_FORMAT_YCbCr420_PLANAR ."); goto CATCH; } } else if ( pPreviewFormatList->Contains(PIXEL_FORMAT_RGB565) ) { r = __pCameraPreview->SetPreviewFormat(PIXEL_FORMAT_RGB565); if (IsFailed(r)) { AppLogException("Setting preview format failed - PIXEL_FORMAT_RGB565."); goto CATCH; } } else { PixelFormat pixelFormat; pPreviewFormatList->GetAt(0, pixelFormat); r = __pCameraPreview->SetPreviewFormat( pixelFormat ); if (IsFailed(r)) { AppLogException("Setting preview format failed."); goto CATCH; } } pPreviewFormatList->RemoveAll(); delete pPreviewFormatList; pPreviewFormatList = null; } r = __PreparePixelConverting(PREFERRED_PIXEL_FORMAT); if (IsFailed(r)) { AppLogException("Setting preferred pixel setting failed."); goto CATCH; } return E_SUCCESS; CATCH: if ( pPreviewResolutionList ) { pPreviewResolutionList->RemoveAll(true); delete pPreviewResolutionList; } if ( pCaptureResolutionList ) { pCaptureResolutionList->RemoveAll(true); delete pCaptureResolutionList; } if ( pCaptureFormatList ) { pCaptureFormatList->RemoveAll(); delete pCaptureFormatList; } if ( pPreviewFormatList ) { pPreviewFormatList->RemoveAll(); delete pPreviewFormatList; } if ( __pCameraPreview ) { delete __pCameraPreview; __pCameraPreview = null; } return r; } result CameraForm::__InitOverlayRegion( Orientation orientation ) { result r = E_SUCCESS; Rectangle __rect(FORM_X, FORM_Y, FORM_WIDTH, FORM_HEIGHT); AppLog("Bounds is (%d,%d,%d,%d)",__rect.x, __rect.y, __rect.width, __rect.height); bool modified = false; bool isValidRect = OverlayRegion::EvaluateBounds(OVERLAY_REGION_EVALUATION_OPTION_LESS_THAN, __rect, modified); if (false == isValidRect) { AppLog("Failed to EvaluateBounds() : [%s] has arisen.", GetErrorMessage(GetLastResult())); goto CATCH; } if (modified) { AppLog("Bounds is modified to (%d,%d,%d,%d)", __rect.x, __rect.y, __rect.width, __rect.height); } __pOverlayRegion= GetOverlayRegionN(__rect, OVERLAY_REGION_TYPE_PRIMARY_CAMERA); // Get the OverlayCanvas __pOverlayCanvas = GetCanvasN(__rect); // For transparency __pOverlayCanvas->SetBackgroundColor(Color(0,0,0,0)); __pOverlayCanvas->SetForegroundColor(Color::COLOR_WHITE); r = __pOverlayCanvas->Clear(); if(IsFailed(r)) { AppLogException( "Clearing the Canvas failed."); goto CATCH; } return r; CATCH: return r; } result CameraForm::__InitSensor(void) { result r = E_SUCCESS; __pSensorManager = new SensorManager(); r = __pSensorManager->Construct(); return r; } result CameraForm::__TerminateCamera(void) { if ( IsStarted()) CameraForm::Stop(); if ( __pCameraPreview ) __pCameraPreview->Terminate(); __UnpreparePixelConverting(); return E_SUCCESS; } void CameraForm::__TerminateSensor(void) { if ( __pSensorManager ) { delete __pSensorManager; __pSensorManager = null; } } result CameraForm::__DrawPreview(Osp::Ui::Controls::OverlayRegion& overlayRegion, Osp::Base::ByteBuffer& previewedData) { result r = E_SUCCESS; ByteBuffer* pOutPreviewBuffer; OverlayRegionBufferPixelFormat bufferPixelFormat = OVERLAY_REGION_BUFFER_PIXEL_FORMAT_YCbCr420_PLANAR; Osp::Graphics::PixelFormat outPixelFormat = PIXEL_FORMAT_YCbCr420_PLANAR; AppLog("Preview format : %d, Converting pixel format : %d", __previewPixelFormat, PREFERRED_PIXEL_FORMAT); if ( __previewPixelFormat != PREFERRED_PIXEL_FORMAT) { if ( __previewPixelFormat == PIXEL_FORMAT_RGB565 && PREFERRED_PIXEL_FORMAT == PIXEL_FORMAT_YCbCr420_PLANAR) { pOutPreviewBuffer = __ConvertRGB565_2YCbCr420p(&previewedData); outPixelFormat = PIXEL_FORMAT_YCbCr420_PLANAR; } else if ( __previewPixelFormat == PIXEL_FORMAT_YCbCr420_PLANAR && PREFERRED_PIXEL_FORMAT == PIXEL_FORMAT_RGB565) { pOutPreviewBuffer = __ConvertYCbCr420p2RGB565(&previewedData); outPixelFormat = PIXEL_FORMAT_RGB565; } else if ( __previewPixelFormat == PIXEL_FORMAT_YCbCr420_PLANAR && PREFERRED_PIXEL_FORMAT == PIXEL_FORMAT_ARGB8888) { pOutPreviewBuffer = __ConvertYCbCr420p2ARGB8888(&previewedData); outPixelFormat = PIXEL_FORMAT_ARGB8888; } else { pOutPreviewBuffer = &previewedData; outPixelFormat = __previewPixelFormat; } if ( !pOutPreviewBuffer ) return E_SYSTEM; } else { pOutPreviewBuffer = &previewedData; outPixelFormat = __previewPixelFormat; } switch (outPixelFormat) { /** * OverlayRegion's SetInputBuffer API doesn't support the OVERLAY_REGION_BUFFER_PIXEL_FORMAT_ARGB8888 and OVERLAY_REGION_BUFFER_PIXEL_FORMAT_RGB565 format since API version 1.2. * Camera's RGB565 preview data can be converted to YCbCr420Planar format by using __ConvertRGB565_2YCbCr420p method in this sample. * * case PIXEL_FORMAT_RGB565: * bufferPixelFormat = OVERLAY_REGION_BUFFER_PIXEL_FORMAT_RGB565; * break; * case PIXEL_FORMAT_ARGB8888: * bufferPixelFormat = OVERLAY_REGION_BUFFER_PIXEL_FORMAT_ARGB8888; * break; */ case PIXEL_FORMAT_YCbCr420_PLANAR: bufferPixelFormat = OVERLAY_REGION_BUFFER_PIXEL_FORMAT_YCbCr420_PLANAR; break; default: AppLog( "Pixel format not supported."); return E_UNSUPPORTED_FORMAT; } r = overlayRegion.SetInputBuffer(*pOutPreviewBuffer, Dimension(__previewWidth,__previewHeight), bufferPixelFormat); return r; } result CameraForm::__DrawPrimitive(Osp::Graphics::Canvas& overlayCanvas ) { result r = E_SUCCESS; // Draw a line and rectangle overlapping to previewed image. // The native draw APIs should use container's canvas. r = overlayCanvas.DrawLine(Point(0,0), Point(200,200)); // Draw line overlapping to preview image if (IsFailed(r)) { AppLogException( " DrawLine was failed."); return r; } r = overlayCanvas.FillRectangle(Color(0xff0000, false), Rectangle(130,130,50,50)); // Fill rectangle overlapping to preview image if (IsFailed(r)) { AppLogException( " FillRectangle was failed."); return r; } return r; } Osp::Base::ByteBuffer* CameraForm::__ConvertYCbCr420p2RGB565(Osp::Base::ByteBuffer * pB) { int w = __previewWidth; int h = __previewHeight; int hw = w/2; int hh = h/2; unsigned char* pOriY= (unsigned char*)(const_cast<byte*>(pB->GetPointer())); unsigned char* pOriCb= pOriY + w*h; unsigned char* pOriCr = pOriCb + hw*hh; unsigned char* pOut1st = (unsigned char*)(const_cast<byte*>(__pOutByteBuffer->GetPointer())); for(int j=0;j<h;j+=2) { unsigned char* pY0,*pY1, *pCb, *pCr; pY0 = pOriY + j*w; pY1 = pOriY + (j+1)*w; pCb = pOriCb + hw*(j/2); pCr = pOriCr + hw*(j/2); unsigned char* buf = pOut1st + (w*2)*j; unsigned short* pB0= (unsigned short*)buf; buf = pOut1st + (w*2)*(j+1); unsigned short* pB1= (unsigned short*)buf; for( int i=0;i <w;i+=2) { int Y[4],Cb,Cr; Cb = pCb[i/2] - 128; Cr = pCr[i/2] - 128; Y[0]=pY0[i]; Y[1]=pY0[i+1]; Y[2]=pY1[i]; Y[3]=pY1[i+1]; int A,B,C; A= Cr + (Cr>>2) + (Cr>>3) + (Cr>>5); B= (Cb>>2) + (Cb>>4) + (Cb>>5) + (Cr>>1) + (Cr>>3) + (Cr>>4) + (Cr>>5); C= Cb + (Cb>>1) + (Cb>>2) + (Cb>>6); #define CL_R(A) (((A)>>3)&0x1F) #define CL_G(A) (((A)>>2)&0x3F) #define CL_B(A) (((A)>>3)&0x1F) #define RGB565(R, G, B) ( (R<<11) | (G<<5) | (B) ) //FOR BITMAP RGB565 pB0[i] = RGB565(CL_R(Y[0]+A), CL_G(Y[0]-B), CL_B(Y[0]+C)); pB0[i+1] = RGB565(CL_R(Y[1]+A), CL_G(Y[1]-B), CL_B(Y[1]+C)); pB1[i] = RGB565(CL_R(Y[2]+A), CL_G(Y[2]-B), CL_B(Y[2]+C)); pB1[i+1] = RGB565(CL_R(Y[3]+A), CL_G(Y[3]-B), CL_B(Y[3]+C)); } } return __pOutByteBuffer; } Osp::Base::ByteBuffer* CameraForm::__ConvertYCbCr420p2ARGB8888(Osp::Base::ByteBuffer * pB) { int w = __previewWidth; int h = __previewHeight; int hw = w/2; int hh = h/2; unsigned char* pOriY= (unsigned char*)const_cast<byte *>(pB->GetPointer()); unsigned char* pOriCb= pOriY + w*h; unsigned char* pOriCr = pOriCb + hw*hh; unsigned char* pOut1st = const_cast<byte*>(__pOutByteBuffer->GetPointer()); for(int j=0;j<h;j+=2) { unsigned char* pY0,*pY1, *pCb, *pCr; pY0 = pOriY + j*w; pY1 = pOriY + (j+1)*w; pCb = pOriCb + hw*(j/2); pCr = pOriCr + hw*(j/2); unsigned char* buf = pOut1st + (w*4)*j; unsigned int* pB0= (unsigned int*)buf; buf = pOut1st + (w*4)*(j+1); unsigned int* pB1= (unsigned int*)buf; for( int i=0;i <w;i+=2) { int Y[4],Cb,Cr; Cb = pCb[i/2] - 128; Cr = pCr[i/2] - 128; Y[0]=pY0[i]; Y[1]=pY0[i+1]; Y[2]=pY1[i]; Y[3]=pY1[i+1]; int A,B,C; A= Cr + (Cr>>2) + (Cr>>3) + (Cr>>5); B= (Cb>>2) + (Cb>>4) + (Cb>>5) + (Cr>>1) + (Cr>>3) + (Cr>>4) + (Cr>>5); C= Cb + (Cb>>1) + (Cb>>2) + (Cb>>6); #define CL(A) ((A>255)? 255:( (A<0)? 0:A )) //#define RGBA(R, G, B, A) ( (A <<24) | (B<<16) | (G<<8) | (R) )//FOR OPENGLES #define RGBA(R, G, B, A) ( (A <<24) | (R<<16) | (G<<8) | (B) )//FOR BITMAP ARGB8888 pB0[i] = RGBA(CL(Y[0]+A), CL(Y[0]-B), CL(Y[0]+C), 0XFF); pB0[i+1] = RGBA(CL(Y[1]+A), CL(Y[1]-B), CL(Y[1]+C), 0XFF); pB1[i] = RGBA(CL(Y[2]+A), CL(Y[2]-B), CL(Y[2]+C), 0XFF); pB1[i+1] = RGBA(CL(Y[3]+A), CL(Y[3]-B), CL(Y[3]+C), 0XFF); } } return __pOutByteBuffer; } Osp::Base::ByteBuffer* CameraForm::__ConvertRGB565_2YCbCr420p(Osp::Base::ByteBuffer * pB) { int w = __previewWidth; int h = __previewHeight; int hw = w/2; int hh = h/2; unsigned char* pOriB = (unsigned char*)(const_cast<byte*>(pB->GetPointer())); unsigned char* pOutY= (unsigned char*)(const_cast<byte *>(__pOutByteBuffer->GetPointer())); if ( !pOutY || !pOriB ) return null; unsigned char* pOutCb= pOutY + w*h; unsigned char* pOutCr = pOutCb + hw*hh; for (int j=0;j<h;j+=2) { unsigned short* pB0; unsigned short* pB1; unsigned char *pY0,*pY1, *pCb, *pCr; pY0 = pOutY + j*w; pY1 = pOutY + (j+1)*w; pCb = pOutCb + hw*(j/2); pCr = pOutCr + hw*(j/2); pB0 = (unsigned short*)(pOriB + (w*2)*j); pB1 = (unsigned short*)(pOriB + (w*2)*(j+1)); for (int i=0; i<w; i+=2) { int Y[2][2],Cb,Cr; unsigned char R, G, B; unsigned short* pRgb[2][2]; pRgb[0][0] = pB0 + i; pRgb[0][1] = pB0 + i + 1; pRgb[1][0] = pB1 + i; pRgb[1][1] = pB1 + i + 1; #define CL_R_(A) (((A>>11) &0b11111 ) << 3 ) #define CL_G_(A) (((A>>5) &0b00000111111) << 2 ) #define CL_B_(A) ((A&0b0000000000011111) << 3 ) for ( int row=0; row<2; row++ ) { for ( int col=0; col<2; col++ ) { R = (unsigned char)CL_R_(*(pRgb[row][col])); G = (unsigned char)CL_G_(*(pRgb[row][col])); B = (unsigned char)CL_B_(*(pRgb[row][col])); Y[row][col] = (( 66*(int)R + 129*(int)G + 25*(int)B + 128 ) >> 8) + 16; } } Cb = ((-38*(int)R -74*(int)G + 112*(int)B + 128 ) >> 8 ) + 128; Cr = ((112*(int)R -94*(int)G -18*(int)B + 128 ) >> 8 ) + 128; // Boundary check and assign pY0[i] = Y[0][0] < 235 ? Y[0][0] : 235; pY0[i+1] = Y[0][1] < 235 ? Y[0][1] : 235; pY1[i] = Y[1][0] < 235 ? Y[1][0] : 235; pY1[i+1] = Y[1][1] < 235 ? Y[1][1] : 235; *pCb++ = Cb < 240 ? Cb : 240; *pCr++ = Cr < 240 ? Cr : 240; } } return __pOutByteBuffer; } result CameraForm::__PreparePixelConverting( Osp::Graphics::PixelFormat outFormat ) { result r = E_SUCCESS; Dimension previewDim; // Prepare the resources for pixel converting. if( !__pCameraPreview) { AppLog( ">>>>>> Camera object not found."); r = E_OBJ_NOT_FOUND; goto CATCH; } previewDim = __pCameraPreview->GetPreviewResolution(); __UnpreparePixelConverting(); switch ( outFormat ) { case PIXEL_FORMAT_RGB565: __pOutByteBuffer = new ByteBuffer(); r = __pOutByteBuffer->Construct(previewDim.width* previewDim.height * 2 ); break; case PIXEL_FORMAT_ARGB8888: __pOutByteBuffer = new ByteBuffer(); r = __pOutByteBuffer->Construct(previewDim.width* previewDim.height * 4 ); break; case PIXEL_FORMAT_YCbCr420_PLANAR: __pOutByteBuffer = new ByteBuffer(); r = __pOutByteBuffer->Construct(previewDim.width* previewDim.height * 6/4); break; default: break; } if(IsFailed(r)) { AppLogException( "ByteBuffer Construct failed."); goto CATCH; } return r; CATCH: __UnpreparePixelConverting(); return r; } void CameraForm::__UnpreparePixelConverting(void) { if ( __pOutByteBuffer ) { delete __pOutByteBuffer; __pOutByteBuffer = null; } } void CameraForm::OnCameraCaptured ( Osp::Base::ByteBuffer& capturedData, result r ) { result ir = E_SUCCESS; String imagePath = L"/Home/Sample"; MessageBox msgBoxError; int msgBoxErrorResult = 0; int width = 0; int height = 0; int bitsPerPixel = 0; int bytesPerPixel = 0; if ( r == E_SUCCESS ) { if ( __pCameraPreview->GetCaptureFormat() == PIXEL_FORMAT_JPEG ) { File file; imagePath.Append(L".jpg"); if ( File::IsFileExist(imagePath)) { r = File::Remove(imagePath); if (IsFailed(ir)) { AppLogException( "File removing failed ."); goto CATCH_FILE_ERROR; } } ir = file.Construct(imagePath, L"w", true); if (IsFailed(ir)) { AppLogException( "File construct failed ."); goto CATCH_FILE_ERROR; } ir = file.Write(capturedData); if (IsFailed(ir)) { AppLogException( "File writing failed ."); goto CATCH_FILE_ERROR; } } else if ( __pCameraPreview->GetCaptureFormat() == PIXEL_FORMAT_RGB565 ) { BufferInfo info; Bitmap* pBitmap = new Bitmap(); ir = pBitmap->Construct(capturedData,Dimension(__pCameraPreview->GetCaptureResolution().width, __pCameraPreview->GetCaptureResolution().height), BITMAP_PIXEL_FORMAT_RGB565); pBitmap->Lock(info); width = info.width; height = info.height; bitsPerPixel = info.bitsPerPixel; if(bitsPerPixel == 32) bytesPerPixel = 4; else if(bitsPerPixel == 24) bytesPerPixel =3; for(int x=0;x<width;x++) { for (int y=0;y<height;y++) { int* color = ((int *)((byte *) info.pPixels + y * info.pitch + x *bytesPerPixel)); byte* blue = (byte*) color; byte* green = blue+ 1; byte* red = green+ 1; byte gray = ((*blue) * 0.11) + ((*green) * 0.59) + ((*red) *0.3); *red = gray; *green = gray; *blue =gray; } } pBitmap->Unlock(); if (IsFailed(ir)) { AppLogException( "Bitmap construction failed ."); delete pBitmap; goto CATCH_ENCODING_ERROR; } imagePath.Append(L".bmp"); Image* pImage = new Image(); ir = pImage->Construct(); if (IsFailed(ir)) { AppLogException( "Image construction failed ."); delete pBitmap; delete pImage; goto CATCH_ENCODING_ERROR; } AppLog( "Image construct succeeded."); ir = pImage->EncodeToFile(*pBitmap, IMG_FORMAT_JPG, imagePath, true); if ( IsFailed(ir) ) { AppLogException( "Image Encode to file failed."); delete pBitmap; delete pImage; goto CATCH_FILE_ERROR; } delete pImage; delete pBitmap; } else { //Add the codes to save the other format's capture data. } ir = __ViewImage(imagePath); if ( IsFailed(ir) ) { AppLogException("ImageViewer AppContorl not found. ."); goto CATCH_IMAGE_VIEWER_ERROR; } } return; CATCH_ENCODING_ERROR: // Error msgBoxError.Construct(L"WARNING",L"Encoding to File error",MSGBOX_STYLE_OK,0); msgBoxError.ShowAndWait(msgBoxErrorResult); ir = CameraForm::Start(); if ( ir != E_SUCCESS ) { ir = __pCameraPreview->Terminate(); } _SetButtonEnabled(__pBackButton, true); _SetButtonEnabled(__pCaptureButton, true); return; CATCH_FILE_ERROR : // File write error msgBoxError.Construct(L"WARNING",L"File writing error or storage is full",MSGBOX_STYLE_OK,0); msgBoxError.ShowAndWait(msgBoxErrorResult); ir = CameraForm::Start(); if ( ir != E_SUCCESS ) { ir = __pCameraPreview->Terminate(); } _SetButtonEnabled(__pBackButton, true); _SetButtonEnabled(__pCaptureButton, true); return; CATCH_IMAGE_VIEWER_ERROR : // Image Viewer not found msgBoxError.Construct(L"WARNING",L"Image Viewer not found",MSGBOX_STYLE_OK,0); msgBoxError.ShowAndWait(msgBoxErrorResult); ir = CameraForm::Start(); if ( ir != E_SUCCESS ) { ir = __pCameraPreview->Terminate(); } _SetButtonEnabled(__pBackButton, true); _SetButtonEnabled(__pCaptureButton, true); return; } void CameraForm::OnCameraAutoFocused(bool completeCondition ) { result r = E_SUCCESS; r = __pCameraPreview->Capture(); if (IsFailed(r)) { AppLogException("Camera Capture failed.."); } } void CameraForm::OnCameraPreviewed ( Osp::Base::ByteBuffer& previewedData , result r) { result ir = E_SUCCESS; AppLog( "Enter. __startType:%d, r=%s", __startType, GetErrorMessage(r)); if(__skipFrame < 2) { __skipFrame++; return; } if ( r == E_SUCCESS ) { if ( __startType == CAMERA_START_NO_PREVIEW_WITH_CALLBACK ) { ir = __DrawPreview(*__pOverlayRegion, previewedData); if (IsFailed(ir)) { AppLogException( "Draw previewing failed."); return; } } Image* pImage = new Image(); pImage->Construct(); Rectangle rect(FORM_X, FORM_Y, FORM_WIDTH, FORM_HEIGHT); Bitmap* pBitmap = pImage->DecodeN(L"/Res/bada.jpg", BITMAP_PIXEL_FORMAT_RGB565, 50, 50 ); r = __pOverlayCanvas -> DrawBitmap(rect, *pBitmap); if (IsFailed(r)){ AppLog("nao carregou imagem"); } /* if ( __startType != CAMERA_START_NO_PREVIEW_WITHOUT_CALLBACK ) { r = __DrawPrimitive(*__pOverlayCanvas); if (IsFailed(ir)) { AppLogException( "Draw primitive failed."); return; } r = __pOverlayCanvas->Show(); if (IsFailed(ir)) { AppLogException( "The Canvas show failed."); return; } } */ if ( __startType == CAMERA_START_NO_PREVIEW_WITH_CALLBACK ) { ir = __pOverlayRegion->Show(); if (IsFailed(ir)) { AppLogException( "OverlayRegion's show failed."); return; } } } } void CameraForm::OnCameraErrorOccurred( CameraErrorReason r ) { MessageBox msgBoxError; int msgBoxErrorResult = 0; AppLog( "OnCameraErrorOccurred has been called."); switch(r) { case CAMERA_ERROR_OUT_OF_MEMORY: msgBoxError.Construct(L"WARNING",L"Memory full",MSGBOX_STYLE_OK,0); break; case CAMERA_ERROR_DEVICE_FAILED: msgBoxError.Construct(L"WARNING",L"Camera Device Failed",MSGBOX_STYLE_OK,0); break; case CAMERA_ERROR_DEVICE_INTERRUPTED: msgBoxError.Construct(L"WARNING",L"Camera Device Interrupted",MSGBOX_STYLE_OK,0); break; default: msgBoxError.Construct(L"WARNING",L"An Error Occurred",MSGBOX_STYLE_OK,0); break; } // An error occurred msgBoxError.ShowAndWait(msgBoxErrorResult); CameraForm::Cancel(); CameraForm::Start(); _SetButtonEnabled(__pBackButton, true); _SetButtonEnabled(__pCaptureButton, true); } void CameraForm::OnDataReceived( SensorType sensorType, SensorData &sensorData, result r) { if ( r == E_SUCCESS && sensorType == SENSOR_TYPE_ACCELERATION ) { int tempDeviceOrientation = __deviceOrientation; float valueX, valueY, valueZ; r = sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_X, valueX ); r = sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_Y, valueY ); r = sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_Z, valueZ ); if ( IS_UPLIGHT(valueY)) tempDeviceOrientation = DEVICE_PORTRAIT; else if ( IS_UPSIDE_DOWN(valueY)) tempDeviceOrientation = DEVICE_PORTRAIT_REVERSE; else if ( IS_UPLIGHT(valueX)) tempDeviceOrientation = DEVICE_LANDSCAPE; else if ( IS_UPSIDE_DOWN(valueX)) tempDeviceOrientation = DEVICE_LANDSCAPE_REVERSE; if ( tempDeviceOrientation != __deviceOrientation ) { AppLog("Orientation changed. ACCELERATION(%f, %f, %f), Device-orientation:%d", valueX,valueY,valueZ,tempDeviceOrientation); __deviceOrientation = tempDeviceOrientation; } } } void CameraForm::OnKeyReleased (const Control &source, Osp::Ui::KeyCode keyCode) { } void CameraForm::OnKeyLongPressed (const Control &source, Osp::Ui::KeyCode keyCode) { } void CameraForm::OnKeyPressed (const Control &source, Osp::Ui::KeyCode keyCode) { result r = E_SUCCESS; if( __pCameraPreview ) { int zoomLevel = __pCameraPreview->GetZoomLevel(); int maxZoomLevel = __pCameraPreview->GetMaxZoomLevel(); if(keyCode == Osp::Ui::KEY_SIDE_UP) { if ( zoomLevel < maxZoomLevel) { r = __pCameraPreview->ZoomIn(); AppLog("ZoomIn:%s", GetErrorMessage(r)); } } else if(keyCode == Osp::Ui::KEY_SIDE_DOWN) { if ( zoomLevel > 0) { r = __pCameraPreview->ZoomOut(); AppLog("ZoomOut:%s", GetErrorMessage(r)); } } } Osp::Ui::Control::ConsumeInputEvent(); if(IsFailed(r)) { AppLog("Consuming input event failed:%s", GetErrorMessage(r)); } } result CameraForm::ShowButtons() { _SetButtonEnabled(__pBackButton, true); _SetButtonEnabled(__pCaptureButton, true); return E_SUCCESS; }
[ [ [ 1, 24 ], [ 68, 68 ], [ 111, 180 ], [ 182, 182 ], [ 184, 1423 ], [ 1436, 1583 ] ], [ [ 25, 67 ], [ 69, 110 ], [ 181, 181 ], [ 183, 183 ], [ 1424, 1435 ] ] ]
df1ac3e6ea0bac443c557a1940bae883b55eae80
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/Hunter/NewGame/SanController/src/OgreCCSComponent.cpp
259713445c9b7ce4b3e89f0f1a0b73b03d49cc63
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
GB18030
C++
false
false
5,004
cpp
#include "SanControllerBaseStableHeaders.h" #include "OgreCCSComponent.h" #include "COgreCCSInterface.h" #include "CCSCameraControlSystem.h" #include "CCSFreeCameraMode.h" #include "CUpdateInterface.h" using namespace Orz; //KeyListenerWithRecord::KeyListenerWithRecord(void) //{ // //} //KeyListenerWithRecord::KeyListenerWithRecord(void) //{ // //} // virtual bool KeyListenerWithRecord::doKeyPressed(const MouseEvent & evt); // virtual bool KeyListenerWithRecord::doKeyReleased(const MouseEvent & evt); // // virtual bool KeyListenerWithRecord::onKeyPressed(const KeyEvent & evt); // virtual bool KeyListenerWithRecord::onKeyReleased(const KeyEvent & evt); // std::bitse<KC_MEDIASELECT+1> _keyMap; //} OgreCCSComponent::OgreCCSComponent(void):_ccsInterface(new COgreCCSInterface()),_ccs(),_freeCameraMode(),_updateInterface(new CUpdateInterface()), _KC_A(false), _KC_D(false), _KC_UP(false), _KC_W(false), _KC_DOWN(false), _KC_S(false), _KC_PGUP(false), _KC_PGDOWN(false), _KC_RIGHT(false), _KC_LEFT(false) { _ccs.reset(new CCS::CameraControlSystem(Orz::OgreGraphicsManager::getSingleton().getSceneManager(), "CameraControlSystem", Orz::OgreGraphicsManager::getSingleton().getCamera())); _freeCameraMode.reset(new CCS::FreeCameraMode(_ccs.get())); //_ccs->registerCameraMode("Free",camMode9); _freeCameraMode->setMoveFactor(30); _ccs->setCurrentCameraMode(_freeCameraMode.get()); _updateInterface->update = boost::bind(&OgreCCSComponent::update,this, _1); _ccsInterface->print = boost::bind(&OgreCCSComponent::printCameras,this); _ccsInterface->getCCS = boost::bind(&OgreCCSComponent::getCCS,this); IInputManager::getSingleton().addKeyListener(this); IInputManager::getSingleton().addMouseListener(this); } CCS::CameraControlSystem * OgreCCSComponent::getCCS(void) { return _ccs.get(); } bool OgreCCSComponent::update(TimeType interval) { if(_KC_A) _freeCameraMode->goLeft(); if(_KC_D) _freeCameraMode->goRight(); if(_KC_UP ||_KC_W ) _freeCameraMode->goForward(); if(_KC_DOWN || _KC_S) _freeCameraMode->goBackward(); if(_KC_PGUP) _freeCameraMode->goUp(); if(_KC_PGDOWN) _freeCameraMode->goDown(); if(_KC_RIGHT) _freeCameraMode->yaw(-1); if(_KC_LEFT) _freeCameraMode->yaw(1); _ccs->update(interval); return true; } bool OgreCCSComponent::onMousePressed(const MouseEvent & evt) { return false; } ///通知鼠标释放事件 bool OgreCCSComponent::onMouseReleased(const MouseEvent & evt) { return false; } ///通知鼠标移动事件 bool OgreCCSComponent::onMouseMoved(const MouseEvent & evt) { if(_ccs->getCurrentCameraMode() == _freeCameraMode.get()) { _freeCameraMode->yaw(evt.getX()); _freeCameraMode->pitch(evt.getY()); } return false; } ///通知键盘按下事件 bool OgreCCSComponent::onKeyPressed(const KeyEvent & evt) { switch(evt.getKey()) { case KC_A: _KC_A = true; break; case KC_D: _KC_D = true; break; case KC_UP: _KC_UP= true; break; case KC_W: _KC_W = true; break; case KC_DOWN: _KC_DOWN = true; break; case KC_S: _KC_S= true; break; case KC_PGUP: _KC_PGUP = true; break; case KC_PGDOWN: _KC_PGDOWN = true; break; case KC_RIGHT: _KC_RIGHT = true; break; case KC_LEFT: _KC_LEFT = true; break; case Orz::KC_BACK: printCameras(); break; } return false; }; void OgreCCSComponent::printCameras(void) { /* Ogre::Vector3 getCameraPosition() { return mCameraPosition; } Ogre::Quaternion getCameraOrientation() { return mCameraOrientation; }*/ ORZ_LOG_NOTIFICATION_MESSAGE("Camera Message:" + boost::lexical_cast<std::string>(_ccs->getCameraPosition()) +boost::lexical_cast<std::string>(_ccs->getCameraOrientation()));//<<"Camera Message:"<<_ccs->getCameraPosition()<<; } ///通知键盘释放事件 bool OgreCCSComponent::onKeyReleased(const KeyEvent & evt) { switch(evt.getKey()) { case KC_A: _KC_A = false; break; case KC_D: _KC_D = false; break; case KC_UP: _KC_UP= false; break; case KC_W: _KC_W = false; break; case KC_DOWN: _KC_DOWN = false; break; case KC_S: _KC_S= false; break; case KC_PGUP: _KC_PGUP = false; break; case KC_PGDOWN: _KC_PGDOWN = false; break; case KC_RIGHT: _KC_RIGHT = false; break; case KC_LEFT: _KC_LEFT = false; break; } return false; } OgreCCSComponent::~OgreCCSComponent(void) { _ccs->deleteAllCameraModes(); IInputManager::getSingleton().removeMouseListener(this); IInputManager::getSingleton().removeKeyListener(this); } ComponentInterface * OgreCCSComponent::_queryInterface(const TypeInfo & info) const { if(info == TypeInfo(typeid(COgreCCSInterface))) { return _ccsInterface.get(); } else if(info == TypeInfo(typeid(CUpdateInterface))) { return _updateInterface.get(); } return NULL; }
[ [ [ 1, 229 ] ] ]
335c51faa7ba1da902ff680bc46e9525af6b4f5c
f304b2f54319a444f8798bca884139b785c63026
/trunk/langroute.cpp
a291b21cb9e2061092cd08d3bb3d7616661a1d51
[]
no_license
BackupTheBerlios/zcplusplus-svn
4387877a71405be331e78bec6d792da5f8fe6737
ef85b9e4a78a52618014f501c9c1400c9d4f4a42
refs/heads/master
2016-08-05T18:34:41.051270
2011-10-08T10:15:31
2011-10-08T10:15:31
40,805,219
0
0
null
null
null
null
UTF-8
C++
false
false
1,063
cpp
// langroute.cpp #include "langroute.hpp" #include "_CSupport1.hpp" #include "Zaimoni.STL/Logging.h" #include "Zaimoni.STL/POD.hpp" using namespace zaimoni; static const POD_pair<const char*,Lang::LangTypes> LegalLanguages[] = { {"C", Lang::C}, {"C++", Lang::CPlusPlus}, {"c", Lang::C}, {"c++", Lang::CPlusPlus} }; LangConf& lexer_from_lang(unsigned int lang) { switch(lang) { case Lang::C: return *CLexer; case Lang::CPlusPlus: return *CPlusPlusLexer; default: FATAL("Invalid language code"); } } unsigned int lang_index(const char* const lang) { assert(NULL!=lang); size_t i = STATIC_SIZE(LegalLanguages); do if (!strcmp(lang,LegalLanguages[--i].first)) return LegalLanguages[i].second; while(0<i); INC_INFORM("Invalid language '"); INC_INFORM(lang); FATAL("'"); } const char* echo_valid_lang(const char* const x) { if (!is_empty_string(x)) { size_t i = STATIC_SIZE(LegalLanguages); do if (!strcmp(x,LegalLanguages[--i].first)) return x; while(0<i); } return NULL; }
[ "zaimoni@b4372a03-5d62-0410-814a-8f46757a0b64" ]
[ [ [ 1, 48 ] ] ]
0f34a05c7e10553b9cfe7cfc467112ca9b77cf10
d2fc16640fb0156afb6528e744867e2be4eec02c
/src/Images/Images.cpp
896e860b76b31182c81325ab5f415d4be4653ee2
[]
no_license
wlschmidt/lcdmiscellany
8cd93b5403f9c62a127ddd00c8c5dd577cf72e2f
6623ca05cd978d91580673e6d183f2242bb8eb24
refs/heads/master
2021-01-19T02:30:05.104179
2011-11-02T21:52:07
2011-11-02T21:52:07
48,021,331
1
1
null
2016-07-23T09:08:48
2015-12-15T05:20:15
C++
UTF-8
C++
false
false
2,904
cpp
#include "Images.h" //#include <windows.h> //#include <gl\gl.h> #ifdef CHICKEN int ScreenShotGL(const char *path, int w, int h, int format) { if (!path) path = ""; unsigned int len = 0; while (path[len]) len++; char *fileName = (char*) malloc((len+32)*sizeof(char)); if (!fileName) return 0; int i, j; if (len) { len=0; while (path[len]) { fileName[len]=path[len]; len++; } fileName[len++] = '\\'; } strcpy(&fileName[len], "ScreenShot"); /* sprintf(fileName, "%s\\ScreenShot", path); else sprintf(fileName, "ScreenShot"); */ while(fileName[len]) len++; for (i=0; i<10000;i++) { j=1000; int k=0; while (j) { fileName[len+k] = '0'+((i/j)%10); j/=10; k++; } sprintf(&fileName[len+k], ".png"); FILE *f = fopen(fileName, "rb"); if (f) { fclose(f); continue; } sprintf(&fileName[len+k], ".bmp"); f = fopen(fileName, "rb"); if (f) { fclose(f); continue; } if (format==0) sprintf(&fileName[len+k], ".png"); f = fopen(fileName, "wb"); if (!f) continue; glFinish(); glReadBuffer(GL_BACK); if (format==0) { Image *image = new Image(w, h, 3); unsigned char *pixels = (unsigned char*) malloc(sizeof(unsigned char)*h*(w+3)*3); glReadPixels(0,0,w,h,GL_RGB, GL_UNSIGNED_BYTE, pixels); int w2 = w*3; //note that each row is 4-byte aligned if (w2%4) w2 += 4-(w2%4); for (int i=h-1; i>=0; i--) { //int iSource = h-1-i; //int p1 = i*w; //int p2 = 0; int p1 = i*w; int p2 = (h-1-i)*w2; for (int j=0; j<w; j++) { ((Color3*)image->pixels)[p1] = ((Color3*)&pixels[p2])[0]; p1++; p2+=3; } } /*for (int i=h/2; i>=0; i--) { int p1 = i*w; int p2 = (h-1-i)*w; for (int j=0; j<w; j++) { //int p1 = j+i*w; //int p2 = j+(h-1-i)*w; Color3 temp = image->pixels[p1]; image->pixels[p1++] = image->pixels[p2]; image->pixels[p2++] = temp; } }*/ ((int*)(image->pixels+w*h))[0] = 0; ((int*)(image->pixels+w*h))[1] = 0; ((int*)(image->pixels+w*h))[2] = 0; ((int*)(image->pixels+w*h))[3] = 0; //memset(&image->pixels[w*h], 0, 15); SavePNG(f, image); delete image; free(pixels); } else { ImageRGBA *image = new ImageRGBA(w, h); //unsigned char *pixels = (unsigned char*) malloc(sizeof(unsigned char)*h*w*4); glReadPixels(0,0,w,h,GL_RGBA, GL_UNSIGNED_BYTE, image->pixels); for (int i=h/2; i>=0; i--) { int p1 = i*w; int p2 = (h-1-i)*w; for (int j=0; j<w; j++) { //int p1 = j+i*w; //int p2 = j+(h-1-i)*w; Color4 temp = image->pixels[p1]; image->pixels[p1++] = image->pixels[p2]; image->pixels[p2++] = temp; } } SaveBMP(f, image); delete image; } fclose(f); free(fileName); return 1; } free(fileName); return 0; } #endif
[ "mattmenke@88352c64-7129-11de-90d8-1fdda9445408" ]
[ [ [ 1, 119 ] ] ]
f85d9007783ab2779d277d2a6996bcc770f48f35
83ed25c6e6b33b2fabd4f81bf91d5fae9e18519c
/code/ScenePreprocessor.cpp
71ac2d3e1681e1fba3678c220dbdef4d05526e10
[ "BSD-3-Clause" ]
permissive
spring/assimp
fb53b91228843f7677fe8ec18b61d7b5886a6fd3
db29c9a20d0dfa9f98c8fd473824bba5a895ae9e
refs/heads/master
2021-01-17T23:19:56.511185
2011-11-08T12:15:18
2011-11-08T12:15:18
2,017,841
1
1
null
null
null
null
UTF-8
C++
false
false
8,718
cpp
/* Open Asset Import Library (ASSIMP) ---------------------------------------------------------------------- Copyright (c) 2006-2010, ASSIMP Development Team All rights reserved. Redistribution and use of this software 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 ASSIMP team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the ASSIMP Development Team. 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 OWNER 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 "AssimpPCH.h" #include "ScenePreprocessor.h" using namespace Assimp; // --------------------------------------------------------------------------------------------- void ScenePreprocessor::ProcessScene () { ai_assert(scene != NULL); // Process all meshes for (unsigned int i = 0; i < scene->mNumMeshes;++i) ProcessMesh(scene->mMeshes[i]); // - nothing to do for nodes for the moment // - nothing to do for textures for the moment // - nothing to do for lights for the moment // - nothing to do for cameras for the moment // Process all animations for (unsigned int i = 0; i < scene->mNumAnimations;++i) ProcessAnimation(scene->mAnimations[i]); // Generate a default material if none was specified if (!scene->mNumMaterials && scene->mNumMeshes) { scene->mMaterials = new aiMaterial*[2]; aiMaterial* helper; aiString name; scene->mMaterials[scene->mNumMaterials] = helper = new aiMaterial(); aiColor3D clr(0.6f,0.6f,0.6f); helper->AddProperty(&clr,1,AI_MATKEY_COLOR_DIFFUSE); // setup the default name to make this material identifyable name.Set(AI_DEFAULT_MATERIAL_NAME); helper->AddProperty(&name,AI_MATKEY_NAME); DefaultLogger::get()->debug("ScenePreprocessor: Adding default material \'" AI_DEFAULT_MATERIAL_NAME "\'"); for (unsigned int i = 0; i < scene->mNumMeshes;++i) { scene->mMeshes[i]->mMaterialIndex = scene->mNumMaterials; } scene->mNumMaterials++; } } // --------------------------------------------------------------------------------------------- void ScenePreprocessor::ProcessMesh (aiMesh* mesh) { // If aiMesh::mNumUVComponents is *not* set assign the default value of 2 for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) { if (!mesh->mTextureCoords[i]) mesh->mNumUVComponents[i] = 0; else { if( !mesh->mNumUVComponents[i]) mesh->mNumUVComponents[i] = 2; aiVector3D* p = mesh->mTextureCoords[i], *end = p+mesh->mNumVertices; // Ensure unsued components are zeroed. This will make 1D texture channels work // as if they were 2D channels .. just in case an application doesn't handle // this case if (2 == mesh->mNumUVComponents[i]) { for (; p != end; ++p) p->z = 0.f; } else if (1 == mesh->mNumUVComponents[i]) { for (; p != end; ++p) p->z = p->y = 0.f; } else if (3 == mesh->mNumUVComponents[i]) { // Really 3D coordinates? Check whether the third coordinate is != 0 for at least one element for (; p != end; ++p) { if (p->z != 0) break; } if (p == end) { DefaultLogger::get()->warn("ScenePreprocessor: UVs are declared to be 3D but they're obviously not. Reverting to 2D."); mesh->mNumUVComponents[i] = 2; } } } } // If the information which primitive types are there in the // mesh is currently not available, compute it. if (!mesh->mPrimitiveTypes) { for (unsigned int a = 0; a < mesh->mNumFaces; ++a) { aiFace& face = mesh->mFaces[a]; switch (face.mNumIndices) { case 3u: mesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE; break; case 2u: mesh->mPrimitiveTypes |= aiPrimitiveType_LINE; break; case 1u: mesh->mPrimitiveTypes |= aiPrimitiveType_POINT; break; default: mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON; break; } } } // If tangents and normals are given but no bitangents compute them if (mesh->mTangents && mesh->mNormals && !mesh->mBitangents) { mesh->mBitangents = new aiVector3D[mesh->mNumVertices]; for (unsigned int i = 0; i < mesh->mNumVertices;++i) { mesh->mBitangents[i] = mesh->mNormals[i] ^ mesh->mTangents[i]; } } } // --------------------------------------------------------------------------------------------- void ScenePreprocessor::ProcessAnimation (aiAnimation* anim) { double first = 10e10, last = -10e10; for (unsigned int i = 0; i < anim->mNumChannels;++i) { aiNodeAnim* channel = anim->mChannels[i]; /* If the exact duration of the animation is not given * compute it now. */ if (anim->mDuration == -1.) { // Position keys for (unsigned int i = 0; i < channel->mNumPositionKeys;++i) { aiVectorKey& key = channel->mPositionKeys[i]; first = std::min (first, key.mTime); last = std::max (last, key.mTime); } // Scaling keys for (unsigned int i = 0; i < channel->mNumScalingKeys;++i) { aiVectorKey& key = channel->mScalingKeys[i]; first = std::min (first, key.mTime); last = std::max (last, key.mTime); } // Rotation keys for (unsigned int i = 0; i < channel->mNumRotationKeys;++i) { aiQuatKey& key = channel->mRotationKeys[i]; first = std::min (first, key.mTime); last = std::max (last, key.mTime); } } /* Check whether the animation channel has no rotation * or position tracks. In this case we generate a dummy * track from the information we have in the transformation * matrix of the corresponding node. */ if (!channel->mNumRotationKeys || !channel->mNumPositionKeys || !channel->mNumScalingKeys) { // Find the node that belongs to this animation aiNode* node = scene->mRootNode->FindNode(channel->mNodeName); if (node) // ValidateDS will complain later if 'node' is NULL { // Decompose the transformation matrix of the node aiVector3D scaling, position; aiQuaternion rotation; node->mTransformation.Decompose(scaling, rotation,position); // No rotation keys? Generate a dummy track if (!channel->mNumRotationKeys) { channel->mNumRotationKeys = 1; channel->mRotationKeys = new aiQuatKey[1]; aiQuatKey& q = channel->mRotationKeys[0]; q.mTime = 0.; q.mValue = rotation; DefaultLogger::get()->debug("ScenePreprocessor: Dummy rotation track has been generated"); } // No scaling keys? Generate a dummy track if (!channel->mNumScalingKeys) { channel->mNumScalingKeys = 1; channel->mScalingKeys = new aiVectorKey[1]; aiVectorKey& q = channel->mScalingKeys[0]; q.mTime = 0.; q.mValue = scaling; DefaultLogger::get()->debug("ScenePreprocessor: Dummy scaling track has been generated"); } // No position keys? Generate a dummy track if (!channel->mNumPositionKeys) { channel->mNumPositionKeys = 1; channel->mPositionKeys = new aiVectorKey[1]; aiVectorKey& q = channel->mPositionKeys[0]; q.mTime = 0.; q.mValue = position; DefaultLogger::get()->debug("ScenePreprocessor: Dummy position track has been generated"); } } } } if (anim->mDuration == -1.) { DefaultLogger::get()->debug("ScenePreprocessor: Setting animation duration"); anim->mDuration = last - std::min( first, 0. ); } }
[ "aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f" ]
[ [ [ 1, 258 ] ] ]
b2389903051f078145ee05cf9bcae37b1e207235
7b379862f58f587d9327db829ae4c6493b745bb1
/JuceLibraryCode/modules/juce_audio_formats/codecs/juce_WindowsMediaAudioFormat.cpp
a7f7140a70a274bf11e0cd7b7630f25b171fd408
[]
no_license
owenvallis/Nomestate
75e844e8ab68933d481640c12019f0d734c62065
7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd
refs/heads/master
2021-01-19T07:35:14.301832
2011-12-28T07:42:50
2011-12-28T07:42:50
2,950,072
2
0
null
null
null
null
UTF-8
C++
false
false
12,590
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ #if JUCE_WINDOWS namespace WindowsMediaCodec { class JuceIStream : public ComBaseClassHelper <IStream> { public: JuceIStream (InputStream& source_) noexcept : source (source_) { resetReferenceCount(); } JUCE_COMRESULT Commit (DWORD) { return S_OK; } JUCE_COMRESULT Write (const void*, ULONG, ULONG*) { return E_NOTIMPL; } JUCE_COMRESULT Clone (IStream**) { return E_NOTIMPL; } JUCE_COMRESULT SetSize (ULARGE_INTEGER) { return E_NOTIMPL; } JUCE_COMRESULT Revert() { return E_NOTIMPL; } JUCE_COMRESULT LockRegion (ULARGE_INTEGER, ULARGE_INTEGER, DWORD) { return E_NOTIMPL; } JUCE_COMRESULT UnlockRegion (ULARGE_INTEGER, ULARGE_INTEGER, DWORD) { return E_NOTIMPL; } JUCE_COMRESULT Read (void* dest, ULONG numBytes, ULONG* bytesRead) { const int numRead = source.read (dest, numBytes); if (bytesRead != nullptr) *bytesRead = numRead; return numRead == (int) numBytes ? S_OK : S_FALSE; } JUCE_COMRESULT Seek (LARGE_INTEGER position, DWORD origin, ULARGE_INTEGER* resultPosition) { int64 newPos = (int64) position.QuadPart; if (origin == STREAM_SEEK_CUR) { newPos += source.getPosition(); } else if (origin == STREAM_SEEK_END) { const int64 len = source.getTotalLength(); if (len < 0) return E_NOTIMPL; newPos += len; } if (resultPosition != nullptr) resultPosition->QuadPart = newPos; return source.setPosition (newPos) ? S_OK : E_NOTIMPL; } JUCE_COMRESULT CopyTo (IStream* destStream, ULARGE_INTEGER numBytesToDo, ULARGE_INTEGER* bytesRead, ULARGE_INTEGER* bytesWritten) { uint64 totalCopied = 0; int64 numBytes = numBytesToDo.QuadPart; while (numBytes > 0 && ! source.isExhausted()) { char buffer [1024]; const int numToCopy = (int) jmin ((int64) sizeof (buffer), (int64) numBytes); const int numRead = source.read (buffer, numToCopy); if (numRead <= 0) break; destStream->Write (buffer, numRead, nullptr); totalCopied += numRead; } if (bytesRead != nullptr) bytesRead->QuadPart = totalCopied; if (bytesWritten != nullptr) bytesWritten->QuadPart = totalCopied; return S_OK; } JUCE_COMRESULT Stat (STATSTG* stat, DWORD) { if (stat == nullptr) return STG_E_INVALIDPOINTER; zerostruct (*stat); stat->type = STGTY_STREAM; stat->cbSize.QuadPart = jmax ((int64) 0, source.getTotalLength()); return S_OK; } private: InputStream& source; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceIStream); }; //============================================================================== static const char* wmFormatName = "Windows Media"; static const char* const extensions[] = { ".mp3", ".wmv", ".asf", 0 }; //============================================================================== class WMAudioReader : public AudioFormatReader { public: WMAudioReader (InputStream* const input_) : AudioFormatReader (input_, TRANS (wmFormatName)), wmvCoreLib ("Wmvcore.dll"), currentPosition (0), bufferStart (0), bufferEnd (0) { typedef HRESULT (*WMCreateSyncReaderType) (IUnknown*, DWORD, IWMSyncReader**); WMCreateSyncReaderType wmCreateSyncReader = nullptr; wmCreateSyncReader = (WMCreateSyncReaderType) wmvCoreLib.getFunction ("WMCreateSyncReader"); if (wmCreateSyncReader != nullptr) { CoInitialize (0); HRESULT hr = wmCreateSyncReader (nullptr, WMT_RIGHT_PLAYBACK, wmSyncReader.resetAndGetPointerAddress()); if (SUCCEEDED (hr)) hr = wmSyncReader->OpenStream (new JuceIStream (*input)); if (SUCCEEDED (hr)) { WORD streamNum = 1; hr = wmSyncReader->GetStreamNumberForOutput (0, &streamNum); hr = wmSyncReader->SetReadStreamSamples (streamNum, false); scanFileForDetails(); } } } ~WMAudioReader() { if (wmSyncReader != nullptr) { wmSyncReader->Close(); wmSyncReader = nullptr; } } bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer, int64 startSampleInFile, int numSamples) { if (sampleRate <= 0) return false; if (startSampleInFile != currentPosition) { currentPosition = startSampleInFile; wmSyncReader->SetRange (((QWORD) startSampleInFile * 10000000) / sampleRate, 0); bufferStart = bufferEnd = 0; } while (numSamples > 0) { if (bufferEnd <= bufferStart) { INSSBuffer* sampleBuffer = nullptr; QWORD sampleTime, duration; DWORD flags, outputNum; WORD streamNum; HRESULT hr = wmSyncReader->GetNextSample (0, &sampleBuffer, &sampleTime, &duration, &flags, &outputNum, &streamNum); if (SUCCEEDED (hr)) { BYTE* rawData = nullptr; DWORD dataLength = 0; hr = sampleBuffer->GetBufferAndLength (&rawData, &dataLength); jassert (SUCCEEDED (hr)); bufferStart = 0; bufferEnd = (int) dataLength; if (bufferEnd <= 0) return false; buffer.ensureSize (bufferEnd); memcpy (buffer.getData(), rawData, bufferEnd); } else { bufferStart = 0; bufferEnd = 512; buffer.ensureSize (bufferEnd); buffer.fillWith (0); } } const int stride = numChannels * sizeof (int16); const int16* const rawData = static_cast <const int16*> (addBytesToPointer (buffer.getData(), bufferStart)); const int numToDo = jmin (numSamples, (bufferEnd - bufferStart) / stride); for (int i = 0; i < numDestChannels; ++i) { jassert (destSamples[i] != nullptr); const int srcChan = jmin (i, (int) numChannels - 1); const int16* src = rawData + srcChan; int* const dst = destSamples[i] + startOffsetInDestBuffer; for (int j = 0; j < numToDo; ++j) { dst[j] = ((uint32) *src) << 16; src += numChannels; } } bufferStart += numToDo * stride; startOffsetInDestBuffer += numToDo; numSamples -= numToDo; currentPosition += numToDo; } return true; } private: DynamicLibrary wmvCoreLib; ComSmartPtr<IWMSyncReader> wmSyncReader; int64 currentPosition; MemoryBlock buffer; int bufferStart, bufferEnd; void scanFileForDetails() { ComSmartPtr<IWMHeaderInfo> wmHeaderInfo; HRESULT hr = wmSyncReader.QueryInterface (wmHeaderInfo); if (SUCCEEDED (hr)) { QWORD lengthInNanoseconds = 0; WORD lengthOfLength = sizeof (lengthInNanoseconds); WORD streamNum = 0; WMT_ATTR_DATATYPE wmAttrDataType; hr = wmHeaderInfo->GetAttributeByName (&streamNum, L"Duration", &wmAttrDataType, (BYTE*) &lengthInNanoseconds, &lengthOfLength); ComSmartPtr<IWMProfile> wmProfile; hr = wmSyncReader.QueryInterface (wmProfile); if (SUCCEEDED (hr)) { ComSmartPtr<IWMStreamConfig> wmStreamConfig; hr = wmProfile->GetStream (0, wmStreamConfig.resetAndGetPointerAddress()); if (SUCCEEDED (hr)) { ComSmartPtr<IWMMediaProps> wmMediaProperties; hr = wmStreamConfig.QueryInterface (wmMediaProperties); if (SUCCEEDED (hr)) { DWORD sizeMediaType; hr = wmMediaProperties->GetMediaType (0, &sizeMediaType); HeapBlock<WM_MEDIA_TYPE> mediaType; mediaType.malloc (sizeMediaType, 1); hr = wmMediaProperties->GetMediaType (mediaType, &sizeMediaType); if (mediaType->majortype == WMMEDIATYPE_Audio) { const WAVEFORMATEX* const inputFormat = reinterpret_cast<WAVEFORMATEX*> (mediaType->pbFormat); sampleRate = inputFormat->nSamplesPerSec; numChannels = inputFormat->nChannels; bitsPerSample = inputFormat->wBitsPerSample; lengthInSamples = (lengthInNanoseconds * sampleRate) / 10000000; } } } } } } JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WMAudioReader); }; } //============================================================================== WindowsMediaAudioFormat::WindowsMediaAudioFormat() : AudioFormat (TRANS (WindowsMediaCodec::wmFormatName), StringArray (WindowsMediaCodec::extensions)) { } WindowsMediaAudioFormat::~WindowsMediaAudioFormat() {} Array<int> WindowsMediaAudioFormat::getPossibleSampleRates() { return Array<int>(); } Array<int> WindowsMediaAudioFormat::getPossibleBitDepths() { return Array<int>(); } bool WindowsMediaAudioFormat::canDoStereo() { return true; } bool WindowsMediaAudioFormat::canDoMono() { return true; } //============================================================================== AudioFormatReader* WindowsMediaAudioFormat::createReaderFor (InputStream* sourceStream, bool deleteStreamIfOpeningFails) { ScopedPointer<WindowsMediaCodec::WMAudioReader> r (new WindowsMediaCodec::WMAudioReader (sourceStream)); if (r->sampleRate > 0) return r.release(); if (! deleteStreamIfOpeningFails) r->input = nullptr; return nullptr; } AudioFormatWriter* WindowsMediaAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/, double /*sampleRateToUse*/, unsigned int /*numberOfChannels*/, int /*bitsPerSample*/, const StringPairArray& /*metadataValues*/, int /*qualityOptionIndex*/) { jassertfalse; // not yet implemented! return nullptr; } #endif
[ "ow3nskip" ]
[ [ [ 1, 349 ] ] ]
c729df76e3f0aeb601a1c3e126c19902d5d3c3bc
c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac
/src/Engine/Event/EventManager.cpp
7320697f614e0b5a591eefa4e09cb081fe31b35f
[]
no_license
ptrefall/smn6200fluidmechanics
841541a26023f72aa53d214fe4787ed7f5db88e1
77e5f919982116a6cdee59f58ca929313dfbb3f7
refs/heads/master
2020-08-09T17:03:59.726027
2011-01-13T22:39:03
2011-01-13T22:39:03
32,448,422
1
0
null
null
null
null
UTF-8
C++
false
false
605
cpp
#include "precomp.h" #include "EventManager.h" using namespace Engine; using namespace Events; EventManager::CallbackClass &EventManager::GetEvent(const CL_String &name) { return eventHandlers[name]; } void EventManager::SendEvent(const Event &event) { std::map<CL_String, CallbackClass>::iterator it; it = eventHandlers.find(event.getName()); if(it != eventHandlers.end()) { it->second.invoke(event); //cl_log_event("Event", "Published event: " + event.toString()); } else { //cl_log_event("Event", "Published event (no subscribers): " + event.toString()); } }
[ "[email protected]@c628178a-a759-096a-d0f3-7c7507b30227" ]
[ [ [ 1, 25 ] ] ]
b30a9aa81b95fe7fcdf8df1dcf05e6cfe636273f
b22c254d7670522ec2caa61c998f8741b1da9388
/dependencies/OpenSceneGraph/include/osgUtil/RenderStage
564fe58ef325e8d958dff9c104d316fe11ae0a94
[]
no_license
ldaehler/lbanet
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
ecb54fc6fd691f1be3bae03681e355a225f92418
refs/heads/master
2021-01-23T13:17:19.963262
2011-03-22T21:49:52
2011-03-22T21:49:52
39,529,945
0
1
null
null
null
null
UTF-8
C++
false
false
14,470
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #ifndef OSGUTIL_RENDERSTAGE #define OSGUTIL_RENDERSTAGE 1 #include <osg/ColorMask> #include <osg/Viewport> #include <osg/Texture> #include <osg/FrameBufferObject> #include <osg/Camera> #include <osgUtil/RenderBin> #include <osgUtil/PositionalStateContainer> namespace osgUtil { /** * RenderStage base class. Used for encapsulate a complete stage in * rendering - setting up of viewport, the projection and model * matrices and rendering the RenderBin's enclosed with this RenderStage. * RenderStage also has a dependency list of other RenderStages, each * of which must be called before the rendering of this stage. These * 'pre' rendering stages are used for advanced rendering techniques * like multistage pixel shading or impostors. */ class OSGUTIL_EXPORT RenderStage : public RenderBin { public: RenderStage(); RenderStage(SortMode mode); RenderStage(const RenderStage& rhs,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); virtual osg::Object* cloneType() const { return new RenderStage(); } virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new RenderStage(*this,copyop); } // note only implements a clone of type. virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast<const RenderStage*>(obj)!=0L; } virtual const char* className() const { return "RenderStage"; } virtual void reset(); /** Set the draw buffer used at the start of each frame draw. */ void setDrawBuffer(GLenum buffer, bool applyMask = true ) { _drawBuffer = buffer; setDrawBufferApplyMask( applyMask ); } /** Get the draw buffer used at the start of each frame draw. */ GLenum getDrawBuffer() const { return _drawBuffer; } /** Get the apply mask defining whether glDrawBuffer is called at each frame draw. */ bool getDrawBufferApplyMask() const { return _drawBufferApplyMask; } /** Set the apply mask defining whether glDrawBuffer is called at each frame draw. */ void setDrawBufferApplyMask( bool applyMask ) { _drawBufferApplyMask = applyMask; } /** Set the read buffer for any required copy operations to use. */ void setReadBuffer(GLenum buffer, bool applyMask = true) { _readBuffer = buffer; setReadBufferApplyMask( applyMask ); } /** Get the read buffer for any required copy operations to use. */ GLenum getReadBuffer() const { return _readBuffer; } /** Get the apply mask defining whether glReadBuffer is called at each frame draw. */ bool getReadBufferApplyMask() const { return _readBufferApplyMask; } /** Set the apply mask defining whether glReadBuffer is called at each frame draw. */ void setReadBufferApplyMask( bool applyMask ) { _readBufferApplyMask = applyMask; } /** Set the viewport.*/ void setViewport(osg::Viewport* viewport) { _viewport = viewport; } /** Get the const viewport. */ const osg::Viewport* getViewport() const { return _viewport.get(); } /** Get the viewport. */ osg::Viewport* getViewport() { return _viewport.get(); } /** Set the clear mask used in glClear(..). * Defaults to GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT. */ void setClearMask(GLbitfield mask) { _clearMask = mask; } /** Get the clear mask.*/ GLbitfield getClearMask() const { return _clearMask; } void setColorMask(osg::ColorMask* cm) { _colorMask = cm; } osg::ColorMask* getColorMask() { return _colorMask.get(); } const osg::ColorMask* getColorMask() const { return _colorMask.get(); } /** Set the clear color used in glClearColor(..). * glClearColor is only called if mask & GL_COLOR_BUFFER_BIT is true*/ void setClearColor(const osg::Vec4& color) { _clearColor=color; } /** Get the clear color.*/ const osg::Vec4& getClearColor() const { return _clearColor; } /** Set the clear accum used in glClearAccum(..). * glClearAcumm is only called if mask & GL_ACCUM_BUFFER_BIT is true. */ void setClearAccum(const osg::Vec4& color) { _clearAccum=color; } /** Get the clear accum.*/ const osg::Vec4& getClearAccum() const { return _clearAccum; } /** Set the clear depth used in glClearDepth(..). Defaults to 1.0 * glClearDepth is only called if mask & GL_DEPTH_BUFFER_BIT is true. */ void setClearDepth(double depth) { _clearDepth=depth; } /** Get the clear depth.*/ double getClearDepth() const { return _clearDepth; } /** Set the clear stencil value used in glClearStencil(). Defaults to 0; * glClearStencil is only called if mask & GL_STENCIL_BUFFER_BIT is true*/ void setClearStencil(int stencil) { _clearStencil=stencil; } /** Get the clear color.*/ int getClearStencil() const { return _clearStencil; } void setCamera(osg::Camera* camera) { if (_camera!=camera) { _camera = camera; _cameraRequiresSetUp = true; } } osg::Camera* getCamera() { return _camera; } const osg::Camera* getCamera() const { return _camera; } void setCameraRequiresSetUp(bool flag) { _cameraRequiresSetUp = flag; } bool getCameraRequiresSetUp() const { return _cameraRequiresSetUp; } /** Attempt the set the RenderStage from the Camera settings.*/ void runCameraSetUp(osg::RenderInfo& renderInfo); void setTexture(osg::Texture* texture, unsigned int level = 0, unsigned int face=0) { _texture = texture; _level = level; _face = face; } osg::Texture* getTexture() { return _texture.get(); } void setImage(osg::Image* image) { _image = image; } osg::Image* getImage() { return _image.get(); } void setImageReadPixelFormat(GLenum format) { _imageReadPixelFormat = format; } GLenum getImageReadPixelFormat() const { return _imageReadPixelFormat; } void setImageReadPixelDataType(GLenum type) { _imageReadPixelDataType = type; } GLenum getImageReadPixelDataType() const { return _imageReadPixelDataType; } /** Set a framebuffer object to render into. It is permissible for the * framebuffer object to be multisampled, in which case you should also * set a resolve framebuffer object - see setMultisampleResolveFramebufferObject(). */ void setFrameBufferObject(osg::FrameBufferObject* fbo) { _fbo = fbo; } osg::FrameBufferObject* getFrameBufferObject() { return _fbo.get(); } const osg::FrameBufferObject* getFrameBufferObject() const { return _fbo.get(); } /** Sets the destination framebuffer object for glBlitFramebufferEXT to * resolve a multisampled framebuffer object after the RenderStage is * drawn. The resolve framebuffer object must not be multisampled. The * resolve framebuffer object is only necessary if the primary framebuffer * object is multisampled, if not then leave it set to null. */ void setMultisampleResolveFramebufferObject(osg::FrameBufferObject* fbo); osg::FrameBufferObject* getMultisampleResolveFramebufferObject() { return _resolveFbo.get(); } const osg::FrameBufferObject* getMultisampleResolveFramebufferObject() const { return _resolveFbo.get(); } /** Set whether the framebuffer object should be unbound after * rendering. By default this is set to true. Set it to false if the * unbinding is not required. */ void setDisableFboAfterRender(bool disable) {_disableFboAfterRender = disable;} bool getDisableFboAfterRender() const {return _disableFboAfterRender;} void setGraphicsContext(osg::GraphicsContext* context) { _graphicsContext = context; } osg::GraphicsContext* getGraphicsContext() { return _graphicsContext.get(); } const osg::GraphicsContext* getGraphicsContext() const { return _graphicsContext.get(); } void setInheritedPositionalStateContainerMatrix(const osg::Matrix& matrix) { _inheritedPositionalStateContainerMatrix = matrix; } const osg::Matrix& getInheritedPositionalStateContainerMatrix() const { return _inheritedPositionalStateContainerMatrix; } void setInheritedPositionalStateContainer(PositionalStateContainer* rsl) { _inheritedPositionalStateContainer = rsl; } PositionalStateContainer* getInheritedPositionalStateContainer() { return _inheritedPositionalStateContainer.get(); } void setPositionalStateContainer(PositionalStateContainer* rsl) { _renderStageLighting = rsl; } PositionalStateContainer* getPositionalStateContainer() const { if (!_renderStageLighting.valid()) _renderStageLighting = new PositionalStateContainer; return _renderStageLighting.get(); } virtual void addPositionedAttribute(osg::RefMatrix* matrix,const osg::StateAttribute* attr) { getPositionalStateContainer()->addPositionedAttribute(matrix,attr); } virtual void addPositionedTextureAttribute(unsigned int textureUnit, osg::RefMatrix* matrix,const osg::StateAttribute* attr) { getPositionalStateContainer()->addPositionedTextureAttribute(textureUnit, matrix,attr); } void copyTexture(osg::RenderInfo& renderInfo); virtual void sort(); virtual void drawPreRenderStages(osg::RenderInfo& renderInfo,RenderLeaf*& previous); virtual void draw(osg::RenderInfo& renderInfo,RenderLeaf*& previous); virtual void drawInner(osg::RenderInfo& renderInfo,RenderLeaf*& previous, bool& doCopyTexture); virtual void drawPostRenderStages(osg::RenderInfo& renderInfo,RenderLeaf*& previous); virtual void drawImplementation(osg::RenderInfo& renderInfo,RenderLeaf*& previous); void addToDependencyList(RenderStage* rs) { addPreRenderStage(rs); } void addPreRenderStage(RenderStage* rs, int order = 0); void addPostRenderStage(RenderStage* rs, int order = 0); /** Extract stats for current draw list. */ bool getStats(Statistics& stats) const; /** Compute the number of dynamic RenderLeaves.*/ virtual unsigned int computeNumberOfDynamicRenderLeaves() const; struct Attachment { osg::ref_ptr<osg::Image> _image; GLenum _imageReadPixelFormat; GLenum _imageReadPixelDataType; }; void attach(osg::Camera::BufferComponent buffer, osg::Image* image); /** search through any pre and post RenderStage that reference a Camera, and take a reference to each of these cameras to prevent them being deleted while they are still be used by the drawing thread.*/ void collateReferencesToDependentCameras(); /** clear the references to any dependent cameras.*/ void clearReferencesToDependentCameras(); protected: virtual ~RenderStage(); typedef std::pair< int , osg::ref_ptr<RenderStage> > RenderStageOrderPair; typedef std::list< RenderStageOrderPair > RenderStageList; typedef std::vector< osg::ref_ptr<osg::Camera> > Cameras; bool _stageDrawnThisFrame; RenderStageList _preRenderList; RenderStageList _postRenderList; Cameras _dependentCameras; // viewport x,y,width,height. osg::ref_ptr<osg::Viewport> _viewport; GLenum _drawBuffer; bool _drawBufferApplyMask; GLenum _readBuffer; bool _readBufferApplyMask; GLbitfield _clearMask; osg::ref_ptr<osg::ColorMask> _colorMask; osg::Vec4 _clearColor; osg::Vec4 _clearAccum; double _clearDepth; int _clearStencil; bool _cameraRequiresSetUp; osg::Camera* _camera; osg::ref_ptr<osg::Texture> _texture; unsigned int _level; unsigned int _face; osg::ref_ptr<osg::Image> _image; GLenum _imageReadPixelFormat; GLenum _imageReadPixelDataType; std::map< osg::Camera::BufferComponent, Attachment> _bufferAttachmentMap; osg::ref_ptr<osg::FrameBufferObject> _fbo; osg::ref_ptr<osg::FrameBufferObject> _resolveFbo; osg::ref_ptr<osg::GraphicsContext> _graphicsContext; bool _disableFboAfterRender; mutable osg::Matrix _inheritedPositionalStateContainerMatrix; mutable osg::ref_ptr<PositionalStateContainer> _inheritedPositionalStateContainer; mutable osg::ref_ptr<PositionalStateContainer> _renderStageLighting; }; } #endif
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 306 ] ] ]
a061b6e4496372039349a20729fba0b4f8876837
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/odephysics/nodehinge2jointnode_main.cc
23d1728bf2cf3ed091656a76cdbc4eed1d86b4eb
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,455
cc
#define N_IMPLEMENTS nOdeHinge2JointNode //------------------------------------------------------------------------------ // (c) 2003 Vadim Macagon // // nOdeHinge2JointNode is licensed under the terms of the Nebula License. //------------------------------------------------------------------------------ #include "odephysics/nodehinge2jointnode.h" nNebulaScriptClass(nOdeHinge2JointNode, "nodejointnode") #include "odephysics/nodephysicscontext.h" #include "odephysics/nodejoint.h" //------------------------------------------------------------------------------ /** */ nOdeHinge2JointNode::nOdeHinge2JointNode() { // empty } //------------------------------------------------------------------------------ /** */ nOdeHinge2JointNode::~nOdeHinge2JointNode() { // empty } //------------------------------------------------------------------------------ /** @brief Create the underlying nOdeHinge2Joint instance. This must be called before trying to do anything else with the joint. */ void nOdeHinge2JointNode::InitJoint( const char* physContext ) { n_assert( !this->joint ); this->ref_PhysContext = physContext; n_assert( this->ref_PhysContext.isvalid() ); this->joint = this->ref_PhysContext->NewHinge2Joint(); } //------------------------------------------------------------------------------ // EOF //------------------------------------------------------------------------------
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 45 ] ] ]
27f0cbc93b01a8da386624a085f0ec18afc3abca
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/MaterialLibrary.h
00db1ebc31391b5fcd6ebd4aa6f73fd8a4317cdf
[]
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,316
h
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: MaterialLibrary.h Version: 0.09 --------------------------------------------------------------------------- */ #pragma once #ifndef __INC_MATERIALLIBRARY_H_ #define __INC_MATERIALLIBRARY_H_ #include "BaseClass.h" #include "HashTable.h" #include "Prerequisities.h" #include "TypeInfo.h" #include "XMLNode.h" namespace nGENE { /** MaterialLibrary is a container for materials. @remarks At least one library must exist at a time. */ class nGENEDLL MaterialLibrary: public BaseClass, public XMLNode { EXPOSE_TYPE private: /** HashTable containing all materials existing in the library. */ HashTable <wstring, Material*> m_pMaterials; /// Vector containing pointer to materials in the library. vector <Material*> m_vMaterials; /// Names of the global textures. vector <string> m_vTexturesNames; wstring m_stName; /// Library's name wstring m_stAuthor; /// Library Author's name float m_fVersion; /// Library's version number bool m_bLoadOnDemand; /// Are materials loaded on demand void parseTextures(XMLDocument* _node); void parseMaterials(XMLDocument* _node); void saveTextures(XMLNode& _textures); void saveMaterials(XMLNode& _materials); public: MaterialLibrary(bool _loadOnDemand=true); ~MaterialLibrary(); void init(); void cleanup(); void parse(XMLDocument* _document); void load() {} void load(const wstring& _fileName); void save(File* _file); /** Adds existing material to the library. @remarks This method copies the Material object. */ void addMaterial(const wstring& _name, const Material& _material); /** Adds existing material to the library. @remarks This method copies the Material object. */ void addMaterial(const wstring& _name, const Material* _material); /// Creates new material. Material* createMaterial(const wstring& _name); /// Returns material with the given name or NULL if not found. Material* getMaterial(const wstring& _name); /// Returns material with the given index or NULL if not found. Material* getMaterial(uint _index); /// Sets material library name. void setName(const wstring& _name); /// Returns material library name. wstring& getName(); /// Sets library author name. void setAuthorName(const wstring& _author); /// Returns library author name. wstring& getAuthorName(); /// Sets material library version. void setVersionNumber(float _version); /// Returns material library version. float getVersionNumber() const; /// Returns number of materials in library. uint getMaterialsNum() const; /// Are materials loaded on demand? bool isLoadedOnDemand() const; }; inline bool MaterialLibrary::isLoadedOnDemand() const { return m_bLoadOnDemand; } //---------------------------------------------------------------------- inline uint MaterialLibrary::getMaterialsNum() const { return m_pMaterials.size(); } //---------------------------------------------------------------------- inline void MaterialLibrary::setVersionNumber(float _version) { m_fVersion = _version; } //---------------------------------------------------------------------- inline float MaterialLibrary::getVersionNumber() const { return m_fVersion; } //---------------------------------------------------------------------- inline void MaterialLibrary::setAuthorName(const wstring& _author) { m_stAuthor=_author; } //---------------------------------------------------------------------- inline wstring& MaterialLibrary::getAuthorName() { return m_stAuthor; } //---------------------------------------------------------------------- inline void MaterialLibrary::setName(const wstring& _name) { m_stName = _name; } //---------------------------------------------------------------------- inline wstring& MaterialLibrary::getName() { return m_stName; } //---------------------------------------------------------------------- } #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 158 ] ] ]
a42f0a784928db954371824eda9a47c2cf2efd14
ee2e06bda0a5a2c70a0b9bebdd4c45846f440208
/word/src/CWord.h
8ef690d269aebbd7f29efc5dbec6e52c7383c927
[]
no_license
RobinLiu/Test
0f53a376e6753ece70ba038573450f9c0fb053e5
360eca350691edd17744a2ea1b16c79e1a9ad117
refs/heads/master
2021-01-01T19:46:55.684640
2011-07-06T13:53:07
2011-07-06T13:53:07
1,617,721
2
0
null
null
null
null
UTF-8
C++
false
false
569
h
/* * CWord.h * * Created on: Jul 1, 2009 * Author: reliu */ #ifndef CWORD_H_ #define CWORD_H_ using namespace std; #include <string> class CWord { public: CWord(void): repeat_times(1), word(""), line_no(0), word_type(0) {}; CWord(const string &wd): repeat_times(1), word(wd), line_no(0), word_type(0) {}; CWord(const string &wd, int times): repeat_times(times), word(wd), line_no(0), word_type(0) {}; virtual ~CWord(void); long repeat_times; string word; long line_no; int word_type; }; #endif /* CWORD_H_ */
[ "RobinofChina@43938a50-64aa-11de-9867-89bd1bae666e" ]
[ [ [ 1, 32 ] ] ]
ff67518b7fc72782c42ec88671d079cb97140cac
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.2/bctestpreviewpopup/src/bctestpreviewpopupappui.cpp
e73369e402f8feaa8b8703da08b620e3c19d1b3f
[]
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
2,622
cpp
/* * Copyright (c) 2006 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: test bc for previewpopup control api(s) * */ #include <avkon.hrh> #include <aknsutils.h> #include "bctestpreviewpopupAppUi.h" #include "bctestpreviewpopup.hrh" #include "bctestpreviewpopupview.h" #include "bctestutil.h" #include "bctestpreviewpopupcase.h" // ======== MEMBER FUNCTIONS ======== // --------------------------------------------------------------------------- // ctro do nothing // --------------------------------------------------------------------------- // CBCTestPreviewPopupAppUi::CBCTestPreviewPopupAppUi() { } // --------------------------------------------------------------------------- // symbian 2nd phase ctor // --------------------------------------------------------------------------- // void CBCTestPreviewPopupAppUi::ConstructL() { BaseConstructL(); AknsUtils::SetAvkonSkinEnabledL( ETrue ); // init test util iTestUtil = CBCTestUtil::NewL(); // init view CBCTestPreviewPopupView* view = CBCTestPreviewPopupView::NewL(iTestUtil); CleanupStack::PushL( view ); AddViewL( view ); CleanupStack::Pop( view ); ActivateLocalViewL( view->Id() ); // Add test case here. iTestUtil->AddTestCaseL( CBCTestPreviewPopupCase::NewL( view->Container() ), _L("PreviewPopup test case") ); } // ---------------------------------------------------------------------------- // CBCTestPreviewPopupAppUi::~CBCTestPreviewPopupAppUi() // Destructor. // ---------------------------------------------------------------------------- // CBCTestPreviewPopupAppUi::~CBCTestPreviewPopupAppUi() { delete iTestUtil; } // ---------------------------------------------------------------------------- // handle menu command events // ---------------------------------------------------------------------------- // void CBCTestPreviewPopupAppUi::HandleCommandL( TInt aCommand ) { switch ( aCommand ) { case EAknSoftkeyBack: case EEikCmdExit: { Exit(); return; } default: break; } } // End of File
[ "none@none" ]
[ [ [ 1, 91 ] ] ]
b1492114108d4271d7400be57c256cee346aab51
260c113e54a8194a20af884e7fd7e3cadb1cf610
/sllabzzuf/src/object.h
0e44930481b17cba06b3a36a2132114d95401c11
[]
no_license
weimingtom/sllabzzuf
8ce0205cc11ff5cdb569e8b2a629eb6cbbfebfc6
5f22cc5686068b179b3c17010d948ff05f16724c
refs/heads/master
2020-06-09T01:02:00.944446
2011-04-07T05:34:22
2011-04-07T05:34:22
38,219,985
0
0
null
null
null
null
UTF-8
C++
false
false
640
h
#ifndef OBJECT_H_INCLUDED #define OBJECT_H_INCLUDED #include "SDL/SDL.h" #include "SDL/SDL_image.h" #include <fstream> #include <iostream> #include "stage.h" class Object{ protected: int x,y,w,h; SDL_Surface *sprite; SDL_Surface *rawsprite; int friction; int friction_increment; public: Object(); Object(int my_x, int my_y); Object(int my_x, int my_y, int my_w, int my_h); ~Object(); int get_x(); int get_y(); int get_w(); int get_h(); bool move_x(int amount, int current_x, int current_y, Stage stage); bool move_y(int amount, int current_x, int current_y, Stage stage); }; #endif // OBJECT_H_INCLUDED
[ [ [ 1, 32 ] ] ]
26479fba9be4b1ef3b34c233bdefc43f850107b9
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ClientShellDLL/ClientShellShared/LightningFX.h
1d923839c9eb8723143b99208db72855bb7793b5
[]
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
2,744
h
// ----------------------------------------------------------------------- // // // MODULE : LightningFX.h // // PURPOSE : Lightning special fx class - Definition // // CREATED : 4/15/99 // // (c) 1999 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #ifndef __LIGHTNING_FX_H__ #define __LIGHTNING_FX_H__ #include "SpecialFX.h" #include "SoundMgr.h" #include "SFXMsgIds.h" #include "TemplateList.h" #include "PolyLineFX.h" struct LFXCREATESTRUCT : public SFXCREATESTRUCT { LFXCREATESTRUCT(); PLFXCREATESTRUCT lfx; LTVector vLightColor; LTBOOL bOneTimeOnly; LTBOOL bDynamicLight; LTBOOL bPlaySound; LTFLOAT fLightRadius; LTFLOAT fSoundRadius; LTFLOAT fMinDelayTime; LTFLOAT fMaxDelayTime; }; inline LFXCREATESTRUCT::LFXCREATESTRUCT() { vLightColor.Init(); fLightRadius = 0.0f; fSoundRadius = 0.0f; bDynamicLight = LTFALSE; bPlaySound = LTFALSE; bOneTimeOnly = LTFALSE; fMinDelayTime = 0.0f; fMaxDelayTime = 0.0f; } struct PolyVert { PolyVert() { vPos.Init(); fOffset = 0.0f; fPosOffset = 0.0f; } LTVector vPos; LTFLOAT fOffset; LTFLOAT fPosOffset; }; typedef CTList<PolyVert*> PolyVertList; class CLightningFX : public CSpecialFX { public : CLightningFX() : CSpecialFX() { m_hLight = LTNULL; m_fStartTime = 0.0f; m_fEndTime = 0.0f; m_bFirstTime = LTTRUE; m_bPlayedSound = LTTRUE; m_fPlaySoundTime = 0.0f; m_vMidPos.Init(); m_hstrTexture = LTNULL; } ~CLightningFX() { if (g_pLTClient) { if (m_hLight) { g_pLTClient->RemoveObject(m_hLight); } if (m_hstrTexture) { g_pLTClient->FreeString(m_hstrTexture); } } } virtual LTBOOL Init(HLOCALOBJ hServObj, ILTMessage_Read *pMsg); virtual LTBOOL Init(SFXCREATESTRUCT* psfxCreateStruct); virtual LTBOOL Update(); virtual LTBOOL CreateObject(ILTClient* pClientDE); virtual uint32 GetSFXID() { return SFX_LIGHTNING_ID; } protected : LFXCREATESTRUCT m_cs; LTFLOAT m_fStartTime; LTFLOAT m_fEndTime; LTVector m_vMidPos; LTFLOAT m_fPlaySoundTime; LTBOOL m_bPlayedSound; LTBOOL m_bFirstTime; char m_szThunderStr[128]; HOBJECT m_hLight; HSTRING m_hstrTexture; CPolyLineFX m_Line; // Lightning LTBOOL Setup(); void HandleFirstTime(); void UpdateSound(); }; #endif // __LIGHTNING_FX_H__
[ [ [ 1, 132 ] ] ]
784f8029eda3aab96076c436804e6b6808a31aba
0b55a33f4df7593378f58b60faff6bac01ec27f3
/Konstruct/Common/Utility/kpuBoundingSphere.cpp
fb25add567c4ed6e48dfbf64b539b2d675996b0c
[]
no_license
RonOHara-GG/dimgame
8d149ffac1b1176432a3cae4643ba2d07011dd8e
bbde89435683244133dca9743d652dabb9edf1a4
refs/heads/master
2021-01-10T21:05:40.480392
2010-09-01T20:46:40
2010-09-01T20:46:40
32,113,739
1
0
null
null
null
null
UTF-8
C++
false
false
1,661
cpp
#include "StdAfx.h" #include "kpuBoundingSphere.h" #include "kpuBoundingBox.h" #include "kpuBoundingCapsule.h" #include "kpuCollisionDetection.h" kpuBoundingSphere::kpuBoundingSphere(float fRadius, kpuVector vLoc) { m_fRadius = fRadius; m_vLocation = vLoc; m_eType = eVT_Sphere; } kpuBoundingSphere::kpuBoundingSphere(const kpuBoundingSphere& bSphere) { m_fRadius = bSphere.m_fRadius; m_vLocation = bSphere.m_vLocation; m_eType = eVT_Sphere; } kpuBoundingSphere::~kpuBoundingSphere(void) { } void kpuBoundingSphere::operator =(const kpuBoundingSphere& bSphere) { m_fRadius = bSphere.m_fRadius; m_vLocation = bSphere.m_vLocation; } void kpuBoundingSphere::Intersects(kpuBoundingVolume* bOther, const kpuMatrix& matrix, kpuCollisionData& data) { switch ( bOther->GetType() ) { case eVT_Sphere: { kpuBoundingSphere pSphere = *(kpuBoundingSphere*)bOther; pSphere.Transform(matrix); kpuCollisionDetection::SphereVsSphere(m_vLocation, m_fRadius, pSphere.m_vLocation, pSphere.m_fRadius, data); break; } case eVT_Box: { kpuBoundingBox pBox = *(kpuBoundingBox*)bOther; pBox.Transform(matrix); kpuCollisionDetection::SphereVsBox(m_vLocation, m_fRadius, pBox.GetMin(), pBox.GetMax(), data); break; } case eVT_Capsule: { kpuBoundingCapsule pCapsule = *(kpuBoundingCapsule*)bOther; pCapsule.Transform(matrix); kpuCollisionDetection::SphereVsCapsule(m_vLocation, m_fRadius, pCapsule.GetStart(), pCapsule.GetEnd(), pCapsule.GetRadius(), data ); break; } } } void kpuBoundingSphere::Transform(const kpuMatrix &matrix) { m_vLocation *= matrix; }
[ "bflassing@0c57dbdb-4d19-7b8c-568b-3fe73d88484e", "[email protected]@0c57dbdb-4d19-7b8c-568b-3fe73d88484e" ]
[ [ [ 1, 7 ], [ 9, 9 ], [ 12, 24 ], [ 26, 32 ], [ 34, 62 ] ], [ [ 8, 8 ], [ 10, 11 ], [ 25, 25 ], [ 33, 33 ], [ 63, 63 ] ] ]
02d99e5d1ad4fe735f97c09baa6ba3b4039fec9f
3d1740e8f494b7611320feb98388b1c3eb522be9
/pyfileselect2/src/pyfileselect.cpp
0a7ee2ca8bc5f58161d5ff37010fdf71a72cc961
[]
no_license
SymbiSoft/pymgfetch
2bce15faad3596882944de7c95839151e4171c73
3f21602bac734183a40e7278a1388f9bd122044b
refs/heads/master
2021-01-10T15:04:51.855335
2009-09-04T09:36:42
2009-09-04T09:36:42
48,182,406
0
0
null
null
null
null
UTF-8
C++
false
false
18,493
cpp
/* ============================================================================ Name : pyfileselect.cpp Author : Thomas Reitmaier Copyright : Copyright Thomas Reitmaier. Description : Cpyfileselect DLL source ============================================================================ */ // Include Files #include "pyfileselect.h" // Cpyfileselect // Member Functions Cpyfileselect* Cpyfileselect::NewLC() { Cpyfileselect* self = new (ELeave) Cpyfileselect; CleanupStack::PushL(self); self->ConstructL(); return self; } Cpyfileselect* Cpyfileselect::NewL() { Cpyfileselect* self = Cpyfileselect::NewLC(); CleanupStack::Pop(self); return self; } Cpyfileselect::Cpyfileselect() // note, CBase initialises all member variables to zero { } void Cpyfileselect::ConstructL() { // second phase constructor, anything that may leave must be constructed here } Cpyfileselect::~Cpyfileselect() { } const char* Cpyfileselect::MemorySelectionDlg(const TDesC& heading) { CAknMemorySelectionDialog::TMemory memory = CAknMemorySelectionDialog::EPhoneMemory; TBool ret = CAknMemorySelectionDialog::RunDlgLD(memory, // on return, contains the selected memory's name heading, // Dialog's title NULL // Pointer to class implementing // MAknFileSelectionObserver. ); // "return" is true, if user has selected a file if (ret) { if (memory == CAknMemorySelectionDialog::EMemoryCard) { return descriptorToStringL(PathInfo::MemoryCardRootPath()); } else { return descriptorToStringL(PathInfo::PhoneMemoryRootPath()); } } char* emptystring = new (ELeave) char[1]; emptystring[0] = '\0'; return emptystring; } const char* Cpyfileselect::FolderSelectionDlg(TCommonDialogType dialogType, TDesC& memory, const TDesC& heading, const TDesC& rightRoot, const TDesC& left) { TFileName folder; folder.Append(memory); // Create select folder dialog CAknFileSelectionDialog* dlg = CAknFileSelectionDialog::NewL(dialogType); // some dialog customizations: dlg->SetTitleL(heading); dlg->SetRightSoftkeyRootFolderL(rightRoot); // for root folder dlg->SetLeftSoftkeyFileL(left); //dlg->SetLeftSoftkeyFolderL(left); TBool result = EFalse; if (dlg->ExecuteL(folder)) { // we got our folder and finish loop result = ETrue; } delete dlg; if (result) { return descriptorToStringL(folder); } char* emptystring = new (ELeave) char[1]; emptystring[0] = '\0'; return emptystring; } const char* Cpyfileselect::FileSelectionDlg(const TFileName& aPath, const TDesC& heading) { TFileName filename; // Create default filename. (contains only the folder, // e.g. C:\Data\Images\) This is used as a starting folder for browsing image files. filename.Append(aPath); TBool ret = CAknFileSelectionDialog::RunDlgLD(filename, // on return, contains the selected file's name PathInfo::PhoneMemoryRootPath(), // default root path for browsing heading, // Dialog's title NULL // Pointer to class implementing // MAknFileSelectionObserver. ); // "return" is true, if user has selected a file if (ret) { return descriptorToStringL(filename); } char* emptystring = new (ELeave) char[1]; emptystring[0] = '\0'; return emptystring; } const char* Cpyfileselect::descriptorToStringL(const TDesC& aDescriptor) { TInt length = aDescriptor.Length(); HBufC8* buf = HBufC8::NewLC(length); buf->Des().Copy(aDescriptor); char* str = new (ELeave) char[length + 1]; Mem::Copy(str, buf->Ptr(), length); str[length] = '\0'; CleanupStack::PopAndDestroy(buf); return str; } const char* Cpyfileselect::DigitalSoundsPath() { return descriptorToStringL(PathInfo::DigitalSoundsPath()); } const char* Cpyfileselect::GamesPath() { return descriptorToStringL(PathInfo::GamesPath()); } const char* Cpyfileselect::GmsPicturesPath() { return descriptorToStringL(PathInfo::GmsPicturesPath()); } const char* Cpyfileselect::ImagesPath() { return descriptorToStringL(PathInfo::ImagesPath()); } const char* Cpyfileselect::ImagesThumbnailPath() { return descriptorToStringL(PathInfo::ImagesThumbnailPath()); } const char* Cpyfileselect::InstallsPath() { return descriptorToStringL(PathInfo::InstallsPath()); } const char* Cpyfileselect::MemoryCardContactsPath() { return descriptorToStringL(PathInfo::MemoryCardContactsPath()); } const char* Cpyfileselect::MemoryCardRootPath() { return descriptorToStringL(PathInfo::MemoryCardRootPath()); } const char* Cpyfileselect::MmsBackgroundImagesPath() { return descriptorToStringL(PathInfo::MmsBackgroundImagesPath()); } const char* Cpyfileselect::OthersPath() { return descriptorToStringL(PathInfo::OthersPath()); } const char* Cpyfileselect::PhoneMemoryRootPath() { return descriptorToStringL(PathInfo::PhoneMemoryRootPath()); } const char* Cpyfileselect::PresenceLogosPath() { return descriptorToStringL(PathInfo::PresenceLogosPath()); } const char* Cpyfileselect::RomRootPath() { return descriptorToStringL(PathInfo::RomRootPath()); } const char* Cpyfileselect::SimpleSoundsPath() { return descriptorToStringL(PathInfo::SimpleSoundsPath()); } const char* Cpyfileselect::SoundsPath() { return descriptorToStringL(PathInfo::SoundsPath()); } const char* Cpyfileselect::VideosPath() { return descriptorToStringL(PathInfo::VideosPath()); } static PyObject* getDigitalSoundsPath(PyObject* /*self*/, PyObject* args) { Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; TRAPD( err, res = obj->DigitalSoundsPath()); PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static PyObject* getGamesPath(PyObject* /*self*/, PyObject* args) { Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; TRAPD( err, res = obj->GamesPath()); PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static PyObject* getGmsPicturesPath(PyObject* /*self*/, PyObject* args) { Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; TRAPD( err, res = obj->GmsPicturesPath()); PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static PyObject* getImagesPath(PyObject* /*self*/, PyObject* args) { Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; TRAPD( err, res = obj->ImagesPath()); PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static PyObject* getImagesThumbnailPath(PyObject* /*self*/, PyObject* args) { Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; TRAPD( err, res = obj->ImagesThumbnailPath()); PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static PyObject* getInstallsPath(PyObject* /*self*/, PyObject* args) { Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; TRAPD( err, res = obj->InstallsPath()); PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static PyObject* getMemoryCardContactsPath(PyObject* /*self*/, PyObject* args) { Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; TRAPD( err, res = obj->MemoryCardContactsPath()); PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static PyObject* getMemoryCardRootPath(PyObject* /*self*/, PyObject* args) { Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; TRAPD( err, res = obj->MemoryCardRootPath()); PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static PyObject* getMmsBackgroundImagesPath(PyObject* /*self*/, PyObject* args) { Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; TRAPD( err, res = obj->MmsBackgroundImagesPath()); PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static PyObject* getOthersPath(PyObject* /*self*/, PyObject* args) { Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; TRAPD( err, res = obj->OthersPath()); PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static PyObject* getPhoneMemoryRootPath(PyObject* /*self*/, PyObject* args) { Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; TRAPD( err, res = obj->PhoneMemoryRootPath()); PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static PyObject* getPresenceLogosPath(PyObject* /*self*/, PyObject* args) { Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; TRAPD( err, res = obj->PresenceLogosPath()); PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static PyObject* getRomRootPath(PyObject* /*self*/, PyObject* args) { Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; TRAPD( err, res = obj->RomRootPath()); PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static PyObject* getSimpleSoundsPath(PyObject* /*self*/, PyObject* args) { Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; TRAPD( err, res = obj->SimpleSoundsPath()); PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static PyObject* getSoundsPath(PyObject* /*self*/, PyObject* args) { Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; TRAPD( err, res = obj->SoundsPath()); PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static PyObject* getVideosPath(PyObject* /*self*/, PyObject* args) { Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; TRAPD( err, res = obj->VideosPath()); PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static PyObject* select_file(PyObject* /*self*/, PyObject* args) { TInt32 useDefaultTitle; char *ttext = NULL; TInt ttextlen = 0; char *ptext = NULL; TInt ptextlen = 0; TInt err = KErrNone; if (!PyArg_ParseTuple(args, "u#u#i", &ptext, &ptextlen, &ttext, &ttextlen, &useDefaultTitle)) { return Py_BuildValue("s", "Cannot parse arguments."); } Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; TPtrC path((TUint16*) ptext, ptextlen); if (useDefaultTitle == 1) { TRAPD( err, res = obj->FileSelectionDlg(path, KNullDesC) ); } else { TPtrC title((TUint16*) ttext, ttextlen); TRAPD( err, res = obj->FileSelectionDlg(path, title)); } PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static PyObject* select_memory(PyObject* /*self*/, PyObject* args) { TInt32 useDefaultTitle; char *ttext = NULL; TInt ttextlen = 0; TInt err = KErrNone; if (!PyArg_ParseTuple(args, "u#i", &ttext, &ttextlen, &useDefaultTitle)) { return Py_BuildValue("s", "Cannot parse arguments."); } Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; if (useDefaultTitle == 1) { TRAPD( err, res = obj->MemorySelectionDlg(KNullDesC) ); } else { TPtrC title((TUint16*) ttext, ttextlen); TRAPD( err, res = obj->MemorySelectionDlg(title)); } PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static PyObject* select_folder(PyObject* /*self*/, PyObject* args) { char *ttext = NULL; TInt ttextlen = 0; TInt32 useDefaultTitle; char *rtext = NULL; TInt rtextlen = 0; TInt32 useDefaultRight; char *ltext = NULL; TInt ltextlen = 0; TInt32 useDefaultLeft; char *mtext = NULL; TInt mtextlen = 0; TInt32 type; TCommonDialogType dialogType = ECFDDialogTypeSave; if (!PyArg_ParseTuple(args, "iu#u#iu#iu#i", &type, &mtext, &mtextlen, &ttext, &ttextlen,&useDefaultTitle, &rtext, &rtextlen,&useDefaultRight, &ltext, &ltextlen, &useDefaultLeft)) { return Py_BuildValue("s", "Cannot parse arguments."); } switch (type) { case 0: { dialogType = ECFDDialogTypeSave; } break; case 1: { dialogType = ECFDDialogTypeMove; } break; case 2: { dialogType = ECFDDialogTypeCopy; } break; } Cpyfileselect* obj = Cpyfileselect::NewL(); const char* res; TPtrC titleP((TUint16*) ttext, ttextlen); TPtrC memory((TUint16*) mtext, mtextlen); TPtrC leftP((TUint16*) ltext, ltextlen); TPtrC rightP((TUint16*) rtext, rtextlen); TBuf <20> title; title.Append(titleP); TBuf <20> right; right.Append(rightP); TBuf <20> left; left.Append(leftP); if(useDefaultTitle == 1) { title = KNullDesC; } if(useDefaultRight == 1) { right = KNullDesC; } if(useDefaultLeft == 1) { left = KNullDesC; } TRAPD( err, res = obj->FolderSelectionDlg(dialogType,memory, title, right, left) ); PyObject* result; if (err != KErrNone) { result = SPyErr_SetFromSymbianOSErr(err); } else { result = Py_BuildValue("s", res); } delete obj; return result; } static const PyMethodDef pyfileselect_methods[] = { { "select_file", (PyCFunction) select_file, METH_VARARGS, "Returns the path of the selected file." }, { "select_memory", (PyCFunction) select_memory, METH_VARARGS, "Returns the path of the selected memory." }, { "select_folder", (PyCFunction) select_folder, METH_VARARGS, "Returns the path of the selected folder." }, { "videos_path", (PyCFunction) getVideosPath, METH_NOARGS, "This method returns the videos path to be appended to a root path." }, { "others_path", (PyCFunction) getOthersPath, METH_NOARGS, "This method returns the others path to be appended to a root path." }, { "sounds_path", (PyCFunction) getSoundsPath, METH_NOARGS, "This method returns the sounds path to be appended to a root path." }, { "simple_sounds_path", (PyCFunction) getSimpleSoundsPath, METH_NOARGS, "This method returns the simple sounds path to be appended to a root path." }, { "rom_root_path", (PyCFunction) getRomRootPath, METH_NOARGS, "This method returns the root path in ROM." }, { "presence_logos_path", (PyCFunction) getPresenceLogosPath, METH_NOARGS, "This method returns the presence logos path to be appended to a root path." }, { "phone_memory_root_path", (PyCFunction) getPhoneMemoryRootPath, METH_NOARGS, "This method returns the root path in Phone Memory." }, { "mms_background_images_path", (PyCFunction) getMmsBackgroundImagesPath, METH_NOARGS, "This method returns the MMS background images path to be appended to a root path." }, { "memory_card_root_path", (PyCFunction) getMemoryCardRootPath, METH_NOARGS, "This method returns the root path in Memory Card." }, { "memory_card_contacts_path", (PyCFunction) getMemoryCardContactsPath, METH_NOARGS, "This method returns the full path of the contacts folder in the memory card." }, { "installs_path", (PyCFunction) getInstallsPath, METH_NOARGS, "This method returns the installs path to be appended to a root path." }, { "images_path", (PyCFunction) getImagesPath, METH_NOARGS, "This method returns the images path to be appended to a root path." }, { "gms_pictures_path", (PyCFunction) getGmsPicturesPath, METH_NOARGS, "This method returns the GMS pictures path to be appended to a root path." }, { "games_path", (PyCFunction) getGamesPath, METH_NOARGS, "This method returns the games path to be appended to a root path." }, { "digital_sounds_path", (PyCFunction) getDigitalSoundsPath, METH_NOARGS, "This method returns the digital sounds path to be appended to a root path." }, { "images_thumbnail_path", (PyCFunction) getImagesThumbnailPath, METH_NOARGS, "This method returns a thumbnail images path." }, { 0, 0 } }; DL_EXPORT(void) init_pyfileselect() { Py_InitModule("_pyfileselect", (PyMethodDef*) pyfileselect_methods); }
[ [ [ 1, 769 ] ] ]
a9fc81cc5e279eacaf4922a08033adece90740d8
ee065463a247fda9a1927e978143186204fefa23
/Src/Engine/Script/WrapPlayerManager.cpp
c9493bc2e3567db16577dd3f9ea6d10bea415676
[]
no_license
ptrefall/hinsimviz
32e9a679170eda9e552d69db6578369a3065f863
9caaacd39bf04bbe13ee1288d8578ece7949518f
refs/heads/master
2021-01-22T09:03:52.503587
2010-09-26T17:29:20
2010-09-26T17:29:20
32,448,374
1
0
null
null
null
null
UTF-8
C++
false
false
1,413
cpp
#include "WrapPlayerManager.h" #include "WrapIPlayer.h" #include <Engine/Core/CoreManager.h> #include "ScriptManager.h" #include <Engine/Player/PlayerManager.h> #include <Engine/Player/IPlayer.h> using namespace Engine; using namespace Script; using namespace LuaPlus; WrapPlayerManager::WrapPlayerManager(Core::CoreManager *coreMgr) { this->coreMgr = coreMgr; } WrapPlayerManager::~WrapPlayerManager() { } int WrapPlayerManager::init() { LuaObject globals = (*coreMgr->getScriptMgr()->GetGlobalState())->GetGlobals(); lPlayers = globals.CreateTable("Players"); Player::IPlayer *human = coreMgr->getPlayerMgr()->getHuman(); if(human) { wHuman = new WrapIPlayer(coreMgr, this, human, true); wHuman->init(); wPlayers.push_back(wHuman); } for(unsigned int i = 0; i < coreMgr->getPlayerMgr()->getAICount(); i++) { if(coreMgr->getPlayerMgr()->getAI(i)) { WrapIPlayer *agent = new WrapIPlayer(coreMgr, this, coreMgr->getPlayerMgr()->getAI(i)); agent->init(); wPlayers.push_back(agent); } } return 0; } LuaObject WrapPlayerManager::getLPlayer(unsigned int id) { return lPlayers.GetByIndex((int)id); } WrapIPlayer *WrapPlayerManager::getWPlayer(unsigned int id) { for(unsigned int i = 0; i < wPlayers.size(); i++) { if(wPlayers[i]->getPlayer()->getId() == id) { return wPlayers[i]; } } return NULL; }
[ "[email protected]@28a56cb3-1e7c-bc60-7718-65c159e1d2df" ]
[ [ [ 1, 63 ] ] ]
2b2ad35534dbccd4376368612d293b2598f5a721
fbe2cbeb947664ba278ba30ce713810676a2c412
/iptv_root/iptv_appsharing/include/CxAppSharing.h
35b8268359cc3094cae87157f12822b39f76c95a
[]
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
5,104
h
/* AsClient.h ** ---------- ** Application Sharing Main - CxWinApp Interface ** ** ** Author : Guilherme Cox <[email protected]> ** Updated: Wed Dec 6 17:25:34 BRST 2006 */ /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// #pragma once #ifndef __CXAPPSHARING__ #define __CXAPPSHARING__ /////////////////////////////////////////////////////////////////////////////// #include "ASFlags.h" #include "ASCompat.h" #include "ASListener.h" #include "iptv_shared/shared/irm/mediapkt.h" // This macro is used to build a module compatible with NCT version. #ifdef NCT_VERSION #include "CxAppSharingWin.h" #endif /* NCT_VERSION */ /////////////////////////////////////////////////////////////////////////////// #define UNICODE_MAX_PATH (32767) // Used to format error messages; #define AS_BUFFER_SIZE (1024) // Timeout (seconds) to send Bitmap Headers #define AS_BITMAPHEADER_TIMEOUT (10) // Timeout (seconds) to send KeyFrame #define AS_KEYFRAME_TIMEOUT (15) // KeyFrame Fragments #define AS_KEYFRAME_FRAGMENTS (4) // Chunks #define NCHUNK_X (16) #define NCHUNK_Y (16) // frame-rate control // how much time to send a frame (ms) #define AS_SENDDATA_TIME (1000) // // Default Color masks (16 and 32 bpp) // default 5-5-5 16 bbp #define CLR_MASK_16_RED (0x00007C00) #define CLR_MASK_16_GREEN (0x000003E0) #define CLR_MASK_16_BLUE (0x0000001F) //default 8-8-8 32 bpp #define CLR_MASK_32_RED (0x00FF0000) #define CLR_MASK_32_GREEN (0x0000FF00) #define CLR_MASK_32_BLUE (0x000000FF) // Process key event #define INPUT_SIZE (128) /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // ISockBuff class ISockBuff; // CxZLib class CxZLib; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// #pragma pack( push, 1 ) typedef struct _CHANGES_RECORD { ULONG id; ULONG type; //screen_to_screen, blit, newcache, oldcache RECTL rect; POINTL point; } CHANGES_RECORD, *PCHANGES_RECORD; typedef struct _MyBitmapInfo { BITMAPINFOHEADER bmih; unsigned long nRedMask; unsigned long nGreenMask; unsigned long nBlueMask; } CXBITMAPINFO, *PCXBITMAPINFO; enum RecordDataTypes { RDT_BITMAPHEADER, RDT_UPDATE_FRAMESIZE, // to be tested when user change video settings during capture RDT_UPDATE_SCREEN, }; typedef int INT; struct RecordData : public LMediaPkt { unsigned long rd_size; // my size long rd_type; // BitmapHeader, update screen, mouse change cursor, ??? long rd_nLine; long rd_nChunk; long rd_ChunkCount; unsigned long rd_CheckSum; BYTE rd_pData[1]; }; #pragma pack( pop ) /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// class CxAppSharing { private: int m_flMode; // capturing or receiving protected: // This macro is used to build a module compatible with NCT version #ifdef NCT_VERSION // hWnd HWND m_hWnd; // GDI data HDC m_hDCMem; HBITMAP m_hMemBitmap, m_hOldMemBitmap; // Debug Window char szDebugBuf[AS_BUFFER_SIZE]; DebugWin *m_pDebug; #endif // network ISockBuff *m_pSockBuff; long m_nMediaID, m_nSeq; CXBITMAPINFO m_MemBitmapInfo; // ZLib CxZLib *m_pZLib; // Chunk data BYTE *m_pChunkBits; long m_nChunkWidth, m_nChunkHeight, m_nWidthBits, m_nChunkWidthBits; // this class can't be instantiated CxAppSharing( int flMode ); // Listener CxAppSharingListener *m_pListener; public: virtual ~CxAppSharing( void ); virtual bool Initialize( ISockBuff *pSockBuff, long nMediaID, CxAppSharingListener *pListener, HWND p_hWnd = NULL, int p_BitDepth = 16, RECT *p_Bounds = NULL, int p_RefreshTime = 1000, int p_CaptureMode = AS_GDI ) = 0; virtual bool End( void ); long GetMode( void ) { return m_flMode; }; // Listener bool ASEvent( int nEvent, void *pParams, unsigned int nSize ); bool SaveBitmapFile( char *pszFilename, BYTE *pBits, RECTL *pRect ); }; /////////////////////////////////////////////////////////////////////////////// #ifdef _DEBUG bool CxDump( RecordData *prd, unsigned long nSize = 0 ); bool CxDump( char *pszStr ); #endif #endif /* __CXAPPSHARING__ */
[ "heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89" ]
[ [ [ 1, 171 ] ] ]
939434b03786db78a618b504d1e76ad4234fe7a2
5504cdea188dd5ceec6ab38863ef4b4f72c70b21
/pcsxrr/iso/cdriso.cpp
98d69e6279ab987ee35749a706778710b188a4a2
[]
no_license
mauzus/pcsxrr
959051bed227f96045a9bba8971ba5dffc24ad33
1b4c66d6a2938da55761280617d288f3c65870d7
refs/heads/master
2021-03-12T20:00:56.954014
2011-03-21T01:16:35
2011-03-21T01:16:35
32,238,897
1
0
null
null
null
null
UTF-8
C++
false
false
5,210
cpp
/* * Cdrom for Psemu Pro like Emulators * * By: linuzappz <[email protected]> * */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <time.h> #include <string.h> #include <zlib.h> #include <bzlib.h> #include <string> #include "cdriso.h" #include "Config.h" #include "PsxCommon.h" std::string CDR_iso_fileToOpen; char IsoFile[256]; char CdDev[256]; unsigned char cdbuffer[CD_FRAMESIZE_RAW * 10]; unsigned char *pbuffer; int Zmode; // 1 Z - 2 bz2 int fmode; // 0 - file / 1 - Zfile char *Ztable; FILE *cdHandle = NULL; char *methods[] = { ".Z - compress faster", ".bz - compress better" }; char *LibName = "TAS ISO Plugin"; long CDRinit(void) { return 0; } long CDRshutdown(void) { return 0; } void UpdateZmode() { int len = strlen(IsoFile); if (len >= 2) { if (!strncmp(IsoFile+(len-2), ".Z", 2)) { Zmode = 1; return; } } if (len >= 3) { if (!strncmp(IsoFile+(len-3), ".bz", 2)) { Zmode = 2; return; } } Zmode = 0; } long CDRopen(void) { struct stat buf; if (cdHandle != NULL) return 0; /* it's already open */ LoadConf(); if (*IsoFile == 0) { char temp[256]; if(CDR_iso_fileToOpen != "") { LoadConf(); strcpy(IsoFile,CDR_iso_fileToOpen.c_str()); CDR_iso_fileToOpen = ""; } else { CfgOpenFile(); LoadConf(); } strcpy(temp, IsoFile); *IsoFile = 0; SaveConf(); strcpy(IsoFile, temp); } UpdateZmode(); if (Zmode) { FILE *f; char table[256]; fmode = Zmode; strcpy(table, IsoFile); if (Zmode == 1) strcat(table, ".table"); else strcat(table, ".index"); if (stat(table, &buf) == -1) { printf("Error loading %s\n", table); cdHandle = NULL; return 0; } f = fopen(table, "rb"); Ztable = (char*)malloc(buf.st_size); if (Ztable == NULL) { cdHandle = NULL; return 0; } fread(Ztable, 1, buf.st_size, f); fclose(f); } else { fmode = 0; pbuffer = cdbuffer; } cdHandle = fopen(IsoFile, "rb"); if (cdHandle == NULL) { SysMessage("Error loading %s\n", IsoFile); return -1; } return 0; } long CDRclose(void) { if (cdHandle == NULL) return 0; fclose(cdHandle); cdHandle = NULL; if (Ztable) { free(Ztable); Ztable = NULL; } return 0; } // return Starting and Ending Track // buffer: // byte 0 - start track // byte 1 - end track long CDRgetTN(unsigned char *buffer) { buffer[0] = 1; buffer[1] = 1; return 0; } // return Track Time // buffer: // byte 0 - frame // byte 1 - second // byte 2 - minute long CDRgetTD(unsigned char track, unsigned char *buffer) { buffer[2] = 0; buffer[1] = 2; buffer[0] = 0; return 0; } // read track // time : byte 0 - minute ; byte 1 - second ; byte 2 - frame // uses bcd format long CDRreadTrack(unsigned char *time) { if (cdHandle == NULL) return -1; // printf ("CDRreadTrack %d:%d:%d\n", btoi(time[0]), btoi(time[1]), btoi(time[2])); if (!fmode) { fseek(cdHandle, MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2])) * CD_FRAMESIZE_RAW + 12, SEEK_SET); fread(cdbuffer, 1, DATA_SIZE, cdHandle); } else if (fmode == 1) { //.Z unsigned long pos, p; unsigned long size; unsigned char Zbuf[CD_FRAMESIZE_RAW]; p = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2])); pos = *(unsigned long*)&Ztable[p * 6]; fseek(cdHandle, pos, SEEK_SET); p = *(unsigned short*)&Ztable[p * 6 + 4]; fread(Zbuf, 1, p, cdHandle); size = CD_FRAMESIZE_RAW; uncompress(cdbuffer, &size, Zbuf, p); pbuffer = cdbuffer + 12; } else { // .bz unsigned long pos, p, rp; unsigned long size; unsigned char Zbuf[CD_FRAMESIZE_RAW * 10 * 2]; int i; for (i=0; i<10; i++) { if (memcmp(time, &cdbuffer[i * CD_FRAMESIZE_RAW + 12], 3) == 0) { pbuffer = &cdbuffer[i * CD_FRAMESIZE_RAW + 12]; return 0; } } p = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2])); rp = p % 10; p/= 10; pos = *(unsigned long*)&Ztable[p * 4]; fseek(cdHandle, pos, SEEK_SET); p = *(unsigned long*)&Ztable[p * 4 + 4] - pos; fread(Zbuf, 1, p, cdHandle); size = CD_FRAMESIZE_RAW * 10; BZ2_bzBuffToBuffDecompress((char*)cdbuffer, (unsigned int*)&size, (char*)Zbuf, p, 0, 0); pbuffer = cdbuffer + rp * CD_FRAMESIZE_RAW + 12; } return 0; } // return readed track unsigned char* CDRgetBuffer(void) { return pbuffer; } // plays cdda audio // sector : byte 0 - minute ; byte 1 - second ; byte 2 - frame // does NOT uses bcd format long CDRplay(unsigned char *sector) { return 0; } // stops cdda audio long CDRstop(void) { return 0; } long CDRtest(void) { if (*IsoFile == 0) return 0; cdHandle = fopen(IsoFile, "rb"); if (cdHandle == NULL) return -1; fclose(cdHandle); cdHandle = NULL; return 0; } int CDRisoFreeze(gzFile f, int Mode) { gzfreezelarr(cdbuffer); pbuffer = (unsigned char*)((intptr_t)pbuffer-(intptr_t)cdbuffer); gzfreezel(&pbuffer); pbuffer = (unsigned char*)((intptr_t)pbuffer+(intptr_t)cdbuffer); return 0; }
[ "mauzus@b38eb22e-9255-0410-b643-f940c3bf2d76", "mgambrell@b38eb22e-9255-0410-b643-f940c3bf2d76", "[email protected]@b38eb22e-9255-0410-b643-f940c3bf2d76" ]
[ [ [ 1, 17 ], [ 20, 22 ], [ 37, 46 ], [ 48, 50 ], [ 52, 71 ], [ 73, 82 ], [ 93, 136 ], [ 138, 150 ], [ 152, 162 ], [ 164, 173 ], [ 175, 225 ], [ 227, 234 ], [ 236, 241 ], [ 243, 246 ], [ 248, 250 ], [ 252, 261 ] ], [ [ 18, 19 ], [ 25, 36 ], [ 47, 47 ], [ 51, 51 ], [ 72, 72 ], [ 83, 92 ], [ 137, 137 ], [ 151, 151 ], [ 163, 163 ], [ 174, 174 ], [ 226, 226 ], [ 235, 235 ], [ 242, 242 ], [ 247, 247 ], [ 251, 251 ] ], [ [ 23, 24 ], [ 262, 268 ] ] ]
0071ce4877ccb04b75f124705e5d3293c994e44c
dda0d7bb4153bcd98ad5e32e4eac22dc974b8c9d
/base/md5.cpp
49e02a85781888254f0b90dc602554d7ac91785e
[ "BSD-3-Clause" ]
permissive
systembugtj/crash-report
abd45ceedc08419a3465414ad9b3b6a5d6c6729a
205b087e79eb8ed7a9b6a7c9f4ac580707e9cb7e
refs/heads/master
2021-01-19T07:08:04.878028
2011-04-05T04:03:54
2011-04-05T04:03:54
35,228,814
1
0
null
null
null
null
ISO-8859-3
C++
false
false
12,257
cpp
/************************************************************************************* This file is a part of CrashRpt library. Copyright (c) 2003, Michael Carruth 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 author 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. ***************************************************************************************/ /* * This is the C++ implementation of the MD5 Message-Digest * Algorithm desrcipted in RFC 1321. * I translated the C code from this RFC to C++. * There is no warranty. * * Feb. 12. 2005 * Benjamin Grüdelbach */ /* * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All * rights reserved. * * License to copy and use this software is granted provided that it * is identified as the "RSA Data Security, Inc. MD5 Message-Digest * Algorithm" in all material mentioning or referencing this software * or this function. * * License is also granted to make and use derivative works provided * that such works are identified as "derived from the RSA Data * Security, Inc. MD5 Message-Digest Algorithm" in all material * mentioning or referencing the derived work. * * RSA Data Security, Inc. makes no representations concerning either * the merchantability of this software or the suitability of this * software for any particular purpose. It is provided "as is" * without express or implied warranty of any kind. * * These notices must be retained in any copies of any part of this * documentation and/or software. */ //md5 class include #include "md5.h" // Constants for MD5Transform routine. #define S11 7 #define S12 12 #define S13 17 #define S14 22 #define S21 5 #define S22 9 #define S23 14 #define S24 20 #define S31 4 #define S32 11 #define S33 16 #define S34 23 #define S41 6 #define S42 10 #define S43 15 #define S44 21 static unsigned char PADDING[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* F, G, H and I are basic MD5 functions. */ #define F(x, y, z) (((x) & (y)) | ((~x) & (z))) #define G(x, y, z) (((x) & (z)) | ((y) & (~z))) #define H(x, y, z) ((x) ^ (y) ^ (z)) #define I(x, y, z) ((y) ^ ((x) | (~z))) /* ROTATE_LEFT rotates x left n bits. */ #define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) //#define ROTATE_LEFT(x, n) (((x) << (n)) | (( (UINT32) x) >> (32-(n)))) /* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. Rotation is separate from addition to prevent recomputation. */ #define FF(a, b, c, d, x, s, ac) { \ (a) += F ((b), (c), (d)) + (x) + (unsigned long int)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define GG(a, b, c, d, x, s, ac) { \ (a) += G ((b), (c), (d)) + (x) + (unsigned long int)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define HH(a, b, c, d, x, s, ac) { \ (a) += H ((b), (c), (d)) + (x) + (unsigned long int)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define II(a, b, c, d, x, s, ac) { \ (a) += I ((b), (c), (d)) + (x) + (unsigned long int)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } /* MD5 initialization. Begins an MD5 operation, writing a new context. */ void MD5::MD5Init (MD5_CTX *context) { context->count[0] = context->count[1] = 0; context->state[0] = 0x67452301; context->state[1] = 0xefcdab89; context->state[2] = 0x98badcfe; context->state[3] = 0x10325476; } /* MD5 block update operation. Continues an MD5 message-digest operation, processing another message block, and updating the context. */ void MD5::MD5Update (MD5_CTX *context, unsigned char *input, unsigned int inputLen) { unsigned int i, index, partLen; /* Compute number of bytes mod 64 */ index = (unsigned int)((context->count[0] >> 3) & 0x3F); /* Update number of bits */ if ( (context->count[0] += ((unsigned long int)inputLen << 3)) < ((unsigned long int)inputLen << 3)) context->count[1]++; context->count[1] += ((unsigned long int)inputLen >> 29); partLen = 64 - index; /* * Transform as many times as possible. */ if (inputLen >= partLen) { MD5_memcpy ((POINTER)&context->buffer[index], (POINTER)input, partLen); MD5Transform (context->state, context->buffer); for (i = partLen; i + 63 < inputLen; i += 64) MD5Transform (context->state, &input[i]); index = 0; } else i = 0; /* Buffer remaining input */ MD5_memcpy ((POINTER)&context->buffer[index], (POINTER)&input[i], inputLen-i); } /* * MD5 finalization. Ends an MD5 message-digest operation, writing the * the message digest and zeroizing the context. */ void MD5::MD5Final (unsigned char digest[16], MD5_CTX *context) { unsigned char bits[8]; unsigned int index, padLen; /* Save number of bits */ Encode (bits, context->count, 8); /* * Pad out to 56 mod 64. */ index = (unsigned int)((context->count[0] >> 3) & 0x3f); padLen = (index < 56) ? (56 - index) : (120 - index); MD5Update (context, PADDING, padLen); /* Append length (before padding) */ MD5Update (context, bits, 8); /* Store state in digest */ Encode (digest, context->state, 16); /* * Zeroize sensitive information. */ MD5_memset ((POINTER)context, 0, sizeof (*context)); } /* * MD5 basic transformation. Transforms state based on block. */ void MD5::MD5Transform (unsigned long int state[4], unsigned char block[64]) { unsigned long int a = state[0], b = state[1], c = state[2], d = state[3], x[16]; Decode (x, block, 64); /* Round 1 */ FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ /* Round 2 */ GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ /* Round 3 */ HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ /* Round 4 */ II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ state[0] += a; state[1] += b; state[2] += c; state[3] += d; /* * Zeroize sensitive information. */ MD5_memset ((POINTER)x, 0, sizeof (x)); } /* * Encodes input (unsigned long int) into output (unsigned char). Assumes len is * a multiple of 4. */ void MD5::Encode (unsigned char *output, unsigned long int *input, unsigned int len) { unsigned int i, j; for (i = 0, j = 0; j < len; i++, j += 4) { output[j] = (unsigned char)(input[i] & 0xff); output[j+1] = (unsigned char)((input[i] >> 8) & 0xff); output[j+2] = (unsigned char)((input[i] >> 16) & 0xff); output[j+3] = (unsigned char)((input[i] >> 24) & 0xff); } } /* * Decodes input (unsigned char) into output (unsigned long int). Assumes len is * a multiple of 4. */ void MD5::Decode (unsigned long int *output, unsigned char *input, unsigned int len) { unsigned int i, j; for (i = 0, j = 0; j < len; i++, j += 4) output[i] = ((unsigned long int)input[j]) | (((unsigned long int)input[j+1]) << 8) | (((unsigned long int)input[j+2]) << 16) | (((unsigned long int)input[j+3]) << 24); } /* * Note: Replace "for loop" with standard memcpy if possible. */ void MD5::MD5_memcpy (POINTER output, POINTER input, unsigned int len) { unsigned int i; for (i = 0; i < len; i++) output[i] = input[i]; } /* * Note: Replace "for loop" with standard memset if possible. */ void MD5::MD5_memset (POINTER output,int value,unsigned int len) { unsigned int i; for (i = 0; i < len; i++) ((char *)output)[i] = (char)value; } /* * EOF */
[ "[email protected]@9307afbf-8b4c-5d34-949b-c69a0924eb0b" ]
[ [ [ 1, 359 ] ] ]
5cee869a505feb4fff2028822f38491b5acf25d3
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/WallPaper/WallPaperDrawSettingsTextDlg.cpp
fb71352b9c728d2d52fb6e2aba0b47bdf578e822
[]
no_license
code4bones/crawlpaper
edbae18a8b099814a1eed5453607a2d66142b496
f218be1947a9791b2438b438362bc66c0a505f99
refs/heads/master
2021-01-10T13:11:23.176481
2011-04-14T11:04:17
2011-04-14T11:04:17
44,686,513
0
1
null
null
null
null
WINDOWS-1252
C++
false
false
14,115
cpp
/* WallPaperDrawSettingsTextDlg.cpp Dialogo per la pagina relativa alle opzioni per la modalita' di visualizzazione. Luca Piergentili, 10/06/03 [email protected] WallPaper (alias crawlpaper) - the hardcore of Windows desktop http://www.crawlpaper.com/ copyright © 1998-2004 Luca Piergentili, all rights reserved crawlpaper is a registered name, all rights reserved This is a free software, released under the terms of the BSD license. Do not attempt to use it in any form which violates the license or you will be persecuted and charged for this. 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 "crawlpaper" 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 OWNER 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 "env.h" #include "pragma.h" #include "macro.h" #include "strings.h" #include "window.h" #include "CColorStatic.h" #include "CToolTipCtrlEx.h" #include "WallPaperConfig.h" #include "WallPaperDrawSettingsTextDlg.h" #include "resource.h" #include "traceexpr.h" //#define _TRACE_FLAG _TRFLAG_TRACEOUTPUT //#define _TRACE_FLAG _TRFLAG_NOTRACE #define _TRACE_FLAG _TRFLAG_NOTRACE #define _TRACE_FLAG_INFO _TRFLAG_NOTRACE #define _TRACE_FLAG_WARN _TRFLAG_NOTRACE #define _TRACE_FLAG_ERR _TRFLAG_NOTRACE #if (defined(_DEBUG) && defined(_WINDOWS)) && (defined(_AFX) || defined(_AFXDLL)) #ifdef PRAGMA_MESSAGE_VERBOSE #pragma message("\t\t\t"__FILE__"("STR(__LINE__)"): using DEBUG_NEW macro") #endif #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif BEGIN_MESSAGE_MAP(CWallPaperDrawSettingsTextDlg,CPropertyPage) ON_CBN_KILLFOCUS(IDC_COMBO_TEXT,OnKillFocusComboText) ON_CBN_SELCHANGE(IDC_COMBO_TEXT,OnSelChangeComboText) ON_CBN_KILLFOCUS(IDC_COMBO_TEXTPOSITION,OnKillFocusComboTextPosition) ON_CBN_SELCHANGE(IDC_COMBO_TEXTPOSITION,OnSelChangeComboTextPosition) ON_BN_CLICKED(IDC_BUTTON_FONT,OnButtonFont) ON_BN_CLICKED(IDC_BUTTON_FGCOLOR,OnButtonFgColor) ON_BN_CLICKED(IDC_BUTTON_BKCOLOR,OnButtonBkColor) ON_BN_CLICKED(IDC_CHECK_TRANSPARENT,OnCheckBkColorTransparent) END_MESSAGE_MAP() IMPLEMENT_DYNCREATE(CWallPaperDrawSettingsTextDlg,CPropertyPage) /* DoDataExchange() */ void CWallPaperDrawSettingsTextDlg::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); DDX_Control(pDX,IDC_COMBO_TEXT,m_wndComboText); DDX_Control(pDX,IDC_COMBO_TEXTPOSITION,m_wndComboTextPosition); DDX_Check(pDX,IDC_CHECK_TRANSPARENT,m_bFontBkColorTransparent); } /* CreateEx() */ BOOL CWallPaperDrawSettingsTextDlg::CreateEx(CWnd* pParent,UINT nID,CWallPaperConfig* pConfig) { // configurazione corrente m_pConfig = pConfig; // crea il dialogo return(Create(nID,pParent)); } /* OnInitDialog() */ BOOL CWallPaperDrawSettingsTextDlg::OnInitDialog(void) { // classe base CPropertyPage::OnInitDialog(); // combo per selezione tipo stringa (testo) m_nDrawTextMode = m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_DRAWTEXTMODE_KEY); m_wndComboText.SetCurSel(m_nDrawTextMode); // combo per selezione posizione stringa: 0=left/up, 1=right/down m_nDrawTextPosition = m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_DRAWTEXTPOSITION_KEY); m_wndComboTextPosition.SetCurSel(m_nDrawTextPosition); GetDlgItem(IDC_COMBO_TEXTPOSITION)->EnableWindow(m_nDrawTextMode!=0); GetDlgItem(IDC_BUTTON_FONT)->EnableWindow(m_nDrawTextMode!=0); GetDlgItem(IDC_BUTTON_FGCOLOR)->EnableWindow(m_nDrawTextMode!=0); GetDlgItem(IDC_BUTTON_BKCOLOR)->EnableWindow(m_nDrawTextMode!=0); GetDlgItem(IDC_CHECK_TRANSPARENT)->EnableWindow(m_nDrawTextMode!=0); m_hFont = NULL; // strutture per il font ZeroMemory(&m_cf,sizeof(CHOOSEFONT)); m_cf.lStructSize = sizeof(CHOOSEFONT); m_cf.hwndOwner = this->m_hWnd; m_cf.lpLogFont = &m_lf; m_cf.Flags = CF_SCREENFONTS | CF_EFFECTS | CF_INITTOLOGFONTSTRUCT; ZeroMemory(&m_lf,sizeof(LOGFONT)); m_cf.iPointSize = m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_CF_iPointSize); m_cf.rgbColors = m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_CF_rgbColors); m_cf.nFontType = (WORD)m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_CF_nFontType); m_lf.lfHeight = m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_LF_lfHeight); m_lf.lfWidth = m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_LF_lfWidth); m_lf.lfEscapement = m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_LF_lfEscapement); m_lf.lfOrientation = m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_LF_lfOrientation); m_lf.lfWeight = m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_LF_lfWeight); m_lf.lfItalic = (BYTE)m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_LF_lfItalic); m_lf.lfUnderline = (BYTE)m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_LF_lfUnderline); m_lf.lfStrikeOut = (BYTE)m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_LF_lfStrikeOut); m_lf.lfCharSet = (BYTE)m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_LF_lfCharSet); m_lf.lfOutPrecision = (BYTE)m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_LF_lfOutPrecision); m_lf.lfClipPrecision = (BYTE)m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_LF_lfClipPrecision); m_lf.lfQuality = (BYTE)m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_LF_lfQuality); m_lf.lfPitchAndFamily = (BYTE)m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_LF_lfPitchAndFamily); m_strFontName.Format("%s",m_pConfig->GetString(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_LF_lfFaceName)); lstrcpy(m_lf.lfFaceName,m_strFontName); // sample text, sample fg/bg colors m_wndSampleText.SubclassDlgItem(IDC_STATIC_SAMPLE,this); m_wndSampleTextColor.SubclassDlgItem(IDC_STATIC_TEXTCOLOR,this); m_wndSampleBkColor.SubclassDlgItem(IDC_STATIC_BKCOLOR,this); m_crFontTextColor = m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_TEXTCOLOR); m_crFontBkColor = m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_BKCOLOR); m_bFontBkColorTransparent = m_pConfig->GetNumber(WALLPAPER_OPTIONS_KEY,WALLPAPER_FONT_BKCOLORTRANSPARENT); GetDlgItem(IDC_BUTTON_BKCOLOR)->EnableWindow(!m_bFontBkColorTransparent && m_nDrawTextMode!=0); m_wndSampleText.SetWindowText(WALLPAPER_WEB_SITE); m_wndSampleText.SetTextColor(m_crFontTextColor); m_wndSampleText.SetBkColor(m_bFontBkColorTransparent ? ::GetSysColor(COLOR_3DFACE) : m_crFontBkColor); if(m_hFont) ::DeleteObject(m_hFont); m_hFont = ::CreateFontIndirect(&m_lf); CFont* pFont = CFont::FromHandle(m_hFont); m_wndSampleText.SetFont(pFont,TRUE); m_wndSampleTextColor.SetBkColor(m_crFontTextColor); m_wndSampleBkColor.SetBkColor(m_bFontBkColorTransparent ? ::GetSysColor(COLOR_3DFACE) : m_crFontBkColor); // aggiunge i tooltips if(m_Tooltip.Create(this,TTS_ALWAYSTIP)) { m_Tooltip.SetWidth(TOOLTIP_REASONABLE_WIDTH); m_Tooltip.SetDelay(TOOLTIP_REASONABLE_DELAYTIME); m_Tooltip.AddTooltip(GetDlgItem(IDC_COMBO_TEXT),IDC_COMBO_TEXT,IDS_TOOLTIP_OPTIONS_DRAW_TEXTMODE); m_Tooltip.AddTooltip(GetDlgItem(IDC_COMBO_TEXTPOSITION),IDC_COMBO_TEXTPOSITION,IDS_TOOLTIP_OPTIONS_DRAW_TEXTPOS); m_Tooltip.AddTooltip(GetDlgItem(IDC_STATIC_SAMPLE),IDC_STATIC_SAMPLE,IDS_TOOLTIP_OPTIONS_DRAW_TEXTPREVIEW); m_Tooltip.AddTooltip(GetDlgItem(IDC_BUTTON_FONT),IDC_BUTTON_FONT,IDS_TOOLTIP_OPTIONS_DRAW_TEXTFONT); m_Tooltip.AddTooltip(GetDlgItem(IDC_BUTTON_FGCOLOR),IDC_BUTTON_FGCOLOR,IDS_TOOLTIP_OPTIONS_DRAW_TEXTFONTFG); m_Tooltip.AddTooltip(GetDlgItem(IDC_STATIC_TEXTCOLOR),IDC_STATIC_TEXTCOLOR,IDS_TOOLTIP_OPTIONS_DRAW_TEXTFONTFG); m_Tooltip.AddTooltip(GetDlgItem(IDC_BUTTON_BKCOLOR),IDC_BUTTON_BKCOLOR,IDS_TOOLTIP_OPTIONS_DRAW_TEXTFONTBG); m_Tooltip.AddTooltip(GetDlgItem(IDC_STATIC_BKCOLOR),IDC_STATIC_BKCOLOR,IDS_TOOLTIP_OPTIONS_DRAW_TEXTFONTBG); m_Tooltip.AddTooltip(GetDlgItem(IDC_CHECK_TRANSPARENT),IDC_CHECK_TRANSPARENT,IDS_TOOLTIP_OPTIONS_DRAW_TEXTTRANSPBG); } UpdateData(FALSE); return(FALSE); } /* OnKillFocusComboText() */ void CWallPaperDrawSettingsTextDlg::OnKillFocusComboText(void) { char szText[256] = {0}; m_wndComboText.GetWindowText(szText,sizeof(szText)-1); if(strcmp(szText,"<none>")==0) m_nDrawTextMode = DRAWTEXT_NONE; else if(strcmp(szText,"current date/time")==0) m_nDrawTextMode = DRAWTEXT_DATETIME; else if(strcmp(szText,"picture filename")==0) m_nDrawTextMode = DRAWTEXT_FILENAME; else if(strcmp(szText,"picture pathname")==0) m_nDrawTextMode = DRAWTEXT_PATHNAME; else if(strcmp(szText,"quotes")==0) m_nDrawTextMode = DRAWTEXT_QUOTES; GetDlgItem(IDC_COMBO_TEXTPOSITION)->EnableWindow(m_nDrawTextMode!=0); GetDlgItem(IDC_BUTTON_FONT)->EnableWindow(m_nDrawTextMode!=0); GetDlgItem(IDC_BUTTON_FGCOLOR)->EnableWindow(m_nDrawTextMode!=0); GetDlgItem(IDC_BUTTON_BKCOLOR)->EnableWindow(!m_bFontBkColorTransparent && m_nDrawTextMode!=0); GetDlgItem(IDC_CHECK_TRANSPARENT)->EnableWindow(m_nDrawTextMode!=0); } /* OnSelChangeComboText() */ void CWallPaperDrawSettingsTextDlg::OnSelChangeComboText(void) { char szText[256] = {0}; m_wndComboText.GetLBText(m_wndComboText.GetCurSel(),szText); if(strcmp(szText,"<none>")==0) m_nDrawTextMode = DRAWTEXT_NONE; else if(strcmp(szText,"current date/time")==0) m_nDrawTextMode = DRAWTEXT_DATETIME; else if(strcmp(szText,"picture filename")==0) m_nDrawTextMode = DRAWTEXT_FILENAME; else if(strcmp(szText,"picture pathname")==0) m_nDrawTextMode = DRAWTEXT_PATHNAME; else if(strcmp(szText,"quotes")==0) m_nDrawTextMode = DRAWTEXT_QUOTES; GetDlgItem(IDC_COMBO_TEXTPOSITION)->EnableWindow(m_nDrawTextMode!=0); GetDlgItem(IDC_BUTTON_FONT)->EnableWindow(m_nDrawTextMode!=0); GetDlgItem(IDC_BUTTON_FGCOLOR)->EnableWindow(m_nDrawTextMode!=0); GetDlgItem(IDC_BUTTON_BKCOLOR)->EnableWindow(!m_bFontBkColorTransparent && m_nDrawTextMode!=0); GetDlgItem(IDC_CHECK_TRANSPARENT)->EnableWindow(m_nDrawTextMode!=0); } /* OnKillFocusComboTextPosition() */ void CWallPaperDrawSettingsTextDlg::OnKillFocusComboTextPosition(void) { char szText[256] = {0}; m_wndComboTextPosition.GetWindowText(szText,sizeof(szText)-1); if(strcmp(szText,"left/up")==0) m_nDrawTextPosition = 0; else if(strcmp(szText,"right/down")==0) m_nDrawTextPosition = 1; } /* OnSelChangeComboTextPosition() */ void CWallPaperDrawSettingsTextDlg::OnSelChangeComboTextPosition(void) { char szText[256] = {0}; m_wndComboTextPosition.GetWindowText(szText,sizeof(szText)-1); if(strcmp(szText,"left/up")==0) m_nDrawTextPosition = DRAWTEXT_POS_LEFTUP; else if(strcmp(szText,"right/down")==0) m_nDrawTextPosition = DRAWTEXT_POS_RIGHTDOWN; else if(strcmp(szText,"left/down")==0) m_nDrawTextPosition = DRAWTEXT_POS_LEFTDOWN; else if(strcmp(szText,"right/up")==0) m_nDrawTextPosition = DRAWTEXT_POS_RIGHTUP; } /* OnButtonFont() */ void CWallPaperDrawSettingsTextDlg::OnButtonFont(void) { m_cf.rgbColors = m_crFontTextColor; if(::ChooseFont(&m_cf)) { if(m_hFont) ::DeleteObject(m_hFont); m_hFont = ::CreateFontIndirect(&m_lf); CFont* pFont = CFont::FromHandle(m_hFont); m_crFontTextColor = m_cf.rgbColors; m_wndSampleText.SetTextColor(m_cf.rgbColors); m_wndSampleText.SetBkColor(m_bFontBkColorTransparent ? ::GetSysColor(COLOR_3DFACE) : m_crFontBkColor); m_wndSampleText.SetFont(pFont,TRUE); m_wndSampleTextColor.SetBkColor(m_cf.rgbColors); } } /* OnButtonFgColor() */ void CWallPaperDrawSettingsTextDlg::OnButtonFgColor(void) { CColorDialog dlg; dlg.m_cc.Flags |= CC_RGBINIT; dlg.m_cc.Flags |= CC_FULLOPEN; dlg.m_cc.Flags |= CC_ANYCOLOR; dlg.m_cc.rgbResult = m_crFontTextColor; if(dlg.DoModal()) { m_crFontTextColor = m_cf.rgbColors = dlg.GetColor(); m_wndSampleText.SetTextColor(m_cf.rgbColors); m_wndSampleTextColor.SetBkColor(m_crFontTextColor); } } /* OnButtonBkColor() */ void CWallPaperDrawSettingsTextDlg::OnButtonBkColor(void) { CColorDialog dlg; dlg.m_cc.Flags |= CC_RGBINIT; dlg.m_cc.Flags |= CC_FULLOPEN; dlg.m_cc.Flags |= CC_ANYCOLOR; dlg.m_cc.rgbResult = m_crFontBkColor; if(dlg.DoModal()) { m_crFontBkColor = dlg.GetColor(); m_wndSampleText.SetBkColor(m_crFontBkColor); m_wndSampleBkColor.SetBkColor(m_crFontBkColor); } } /* OnCheckBkColorTransparent() */ void CWallPaperDrawSettingsTextDlg::OnCheckBkColorTransparent(void) { m_bFontBkColorTransparent = !m_bFontBkColorTransparent; if(m_bFontBkColorTransparent) { m_wndSampleText.SetBkColor(::GetSysColor(COLOR_3DFACE)); m_wndSampleBkColor.SetBkColor(::GetSysColor(COLOR_3DFACE)); } GetDlgItem(IDC_BUTTON_BKCOLOR)->EnableWindow(!m_bFontBkColorTransparent && m_nDrawTextMode!=0); }
[ [ [ 1, 352 ] ] ]
3e7fcacb9591e12394ca7fd022191f2954e9a9fa
24d8605951b6f0d457c7cfbf99cebc93470c815e
/include/qcolor.h
ea58e2eb0a5d5378194e25cdfc6660b166d6d96d
[]
no_license
OpenMagx/sdk-for-moto-zn5-u9
dea9d91b4636338bd24222363dc7eab8ea2e2a03
0e103109acbb1e438341ec73ac428d037526e7e7
refs/heads/master
2021-01-25T04:02:05.456541
2011-11-16T05:20:05
2011-11-16T05:20:05
2,785,766
1
0
null
null
null
null
UTF-8
C++
false
false
6,990
h
/* * Copyright (C) 2007 Motorola Inc. * * Date Author Comment * 09/25/07 Motorola Motorola customization. */ /**************************************************************************** ** $Id: qt/src/kernel/qcolor.h 2.3.6 edited 2001-01-26 $ ** ** Definition of QColor class ** ** Created : 940112 ** ** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. ** ** This file is part of the kernel module of the Qt GUI Toolkit. ** ** This file may be distributed under the terms of the Q Public License ** as defined by Trolltech AS of Norway and appearing in the file ** LICENSE.QPL included in the packaging of this file. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition ** licenses may use this file in accordance with the Qt Commercial License ** Agreement provided with the Software. ** ** 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.trolltech.com/pricing.html or email [email protected] for ** information about Qt Commercial License Agreements. ** See http://www.trolltech.com/qpl/ for QPL licensing information. ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact [email protected] if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #ifndef QCOLOR_H #define QCOLOR_H #ifndef QT_H #include "qwindowdefs.h" #endif // QT_H const QRgb RGB_DIRTY = 0x80000000; // flags unset color const QRgb RGB_INVALID = 0x40000000; // flags invalid color const QRgb RGB_DIRECT = 0x20000000; // flags directly set pixel const QRgb RGB_MASK = 0x00ffffff; // masks RGB values Q_EXPORT inline int qRed( QRgb rgb ) // get red part of RGB { return (int)((rgb >> 16) & 0xff); } Q_EXPORT inline int qGreen( QRgb rgb ) // get green part of RGB { return (int)((rgb >> 8) & 0xff); } Q_EXPORT inline int qBlue( QRgb rgb ) // get blue part of RGB { return (int)(rgb & 0xff); } Q_EXPORT inline int qAlpha( QRgb rgb ) // get alpha part of RGBA { return (int)((rgb >> 24) & 0xff); } Q_EXPORT inline QRgb qRgb( int r, int g, int b )// set RGB value { return (0xff << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); } Q_EXPORT inline QRgb qRgba( int r, int g, int b, int a )// set RGBA value { return ((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); } Q_EXPORT inline int qGray( int r, int g, int b )// convert R,G,B to gray 0..255 { return (r*11+g*16+b*5)/32; } Q_EXPORT inline int qGray( QRgb rgb ) // convert RGB to gray 0..255 { return qGray( qRed(rgb), qGreen(rgb), qBlue(rgb) ); } class Q_EXPORT QColor { public: enum Spec { Rgb, Hsv }; QColor(); QColor( int r, int g, int b ); QColor( int x, int y, int z, Spec ); QColor( QRgb rgb, uint pixel=0xffffffff); QColor( const QString& name ); QColor( const char *name ); QColor( const QColor & ); QColor &operator=( const QColor & ); QColor(int r, int g, int b, int a); bool isValid() const; bool isDirty() const; QString name() const; void setNamedColor( const QString& name ); void rgb( int *r, int *g, int *b ) const; QRgb rgb() const; void setRgb( int r, int g, int b ); void setRgb( QRgb rgb ); void getRgba(int *r, int *g, int *b, int *a = 0) const; void setRgba(int r, int g, int b, int a = 255); QRgb rgba() const; void setRgba(QRgb rgba); int alpha() const; void setAlpha(int alpha); int red() const; int green() const; int blue() const; void hsv( int *h, int *s, int *v ) const; void getHsv( int &h, int &s, int &v ) const; void setHsv( int h, int s, int v ); QColor light( int f = 150 ) const; QColor dark( int f = 200 ) const; bool operator==( const QColor &c ) const; bool operator!=( const QColor &c ) const; static bool lazyAlloc(); static void setLazyAlloc( bool ); uint alloc(); uint pixel() const; static int maxColors(); static int numBitPlanes(); static int enterAllocContext(); static void leaveAllocContext(); static int currentAllocContext(); static void destroyAllocContext( int ); #if defined(_WS_WIN_) static HPALETTE hPal() { return hpal; } static uint realizePal( QWidget * ); #endif static void initialize(); static void cleanup(); private: void setSystemNamedColor( const QString& name ); static void initGlobalColors(); static QColor* globalColors(); static bool color_init; static bool globals_init; static bool lazy_alloc; #if defined(_WS_WIN_) static HPALETTE hpal; #endif uint pix; QRgb rgbVal; bool Valid; }; inline QColor::QColor() { setRgb(0,0,0); Valid=false; } // default color: black without transparency inline QColor::QColor( int r, int g, int b ) { Valid=true; setRgb( r, g, b ); } inline QColor::QColor(int r, int g, int b, int a) { Valid=true; setRgba(r, g, b, a); } inline bool QColor::isValid() const { return Valid; } inline bool QColor::isDirty() const { return (rgbVal & RGB_DIRTY) != 0; } inline QRgb QColor::rgb() const { return rgbVal | ~RGB_MASK; } inline int QColor::red() const { return qRed(rgbVal); } inline int QColor::green() const { return qGreen(rgbVal); } inline int QColor::blue() const { return qBlue(rgbVal); } inline uint QColor::pixel() const { #ifndef QT_NO_QWS_DEPTH_24_ALPHA return ((QColor*)this)->alloc(); #endif return (rgbVal & RGB_DIRTY) == 0 ? pix : ((QColor*)this)->alloc(); } inline bool QColor::lazyAlloc() { return lazy_alloc; } inline bool QColor::operator==( const QColor &c ) const { return isValid()==c.isValid() && ((((rgbVal | c.rgbVal) & RGB_DIRECT) == 0 && (rgbVal & RGB_MASK) == (c.rgbVal & RGB_MASK)) || ((rgbVal & c.rgbVal & RGB_DIRECT) != 0 && (rgbVal & RGB_MASK) == (c.rgbVal & RGB_MASK) && pix == c.pix)); } inline bool QColor::operator!=( const QColor &c ) const { return !operator==(c); } /***************************************************************************** QColor stream functions *****************************************************************************/ #ifndef QT_NO_DATASTREAM Q_EXPORT QDataStream &operator<<( QDataStream &, const QColor & ); Q_EXPORT QDataStream &operator>>( QDataStream &, QColor & ); #endif #endif // QCOLOR_H
[ [ [ 1, 235 ] ] ]
3efc54ff59c8007d19fe2b3c7f0ba4ee1df59f6e
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/intrusive/example/doc_erasing_and_disposing.cpp
b80bb36fbc658b9da527f9277ebb5154154bd37c
[ "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
1,773
cpp
///////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2006-2008 // // 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/intrusive for documentation. // ///////////////////////////////////////////////////////////////////////////// //[doc_erasing_and_disposing #include <boost/intrusive/list.hpp> using namespace boost::intrusive; //A class that can be inserted in an intrusive list class my_class : public list_base_hook<> { public: my_class(int i) : int_(i) {} int int_; //... }; //Definition of the intrusive list typedef list<my_class> my_class_list; //The predicate function struct is_even { bool operator()(const my_class &c) const { return 0 == (c.int_ % 2); } }; //The disposer object function struct delete_disposer { void operator()(my_class *delete_this) { delete delete_this; } }; int main() { const int MaxElem = 100; //Fill all the nodes and insert them in the list my_class_list list; try{ //Insert new objects in the container for(int i = 0; i < MaxElem; ++i) list.push_back(*new my_class(i)); //Now use remove_and_dispose_if to erase and delete the objects list.remove_and_dispose_if(is_even(), delete_disposer()); } catch(...){ //If something throws, make sure that all the memory is freed list.clear_and_dispose(delete_disposer()); throw; } //Dispose remaining elements list.erase_and_dispose(list.begin(), list.end(), delete_disposer()); return 0; } //]
[ "metrix@Blended.(none)" ]
[ [ [ 1, 70 ] ] ]
8df4923418d920e50d518da2beb7fca0f8ca57c9
00c36cc82b03bbf1af30606706891373d01b8dca
/OpenGUI/OpenGUI_Brush_Caching.h
fd4b0593af002498c7f729a71e3d28f2d4203917
[ "BSD-3-Clause" ]
permissive
VB6Hobbyst7/opengui
8fb84206b419399153e03223e59625757180702f
640be732a25129a1709873bd528866787476fa1a
refs/heads/master
2021-12-24T01:29:10.296596
2007-01-22T08:00:22
2007-01-22T08:00:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,370
h
// OpenGUI (http://opengui.sourceforge.net) // This source code is released under the BSD License // See LICENSE.TXT for details #ifndef A0D166F7_A4DC_4019_8411_83D8DC435DFC #define A0D166F7_A4DC_4019_8411_83D8DC435DFC #include "OpenGUI_PreRequisites.h" #include "OpenGUI_Exports.h" #include "OpenGUI_Types.h" #include "OpenGUI_Brush.h" #include "OpenGUI_RenderTexture.h" namespace OpenGUI { class Screen; // forward declaration //! Brush that caches its output to RTT surfaces if available, with automatic fall back to memory storage if necessary class OPENGUI_API Brush_Caching: public Brush { public: //! Constructor requires a pointer to the Screen that this Brush will eventually be drawn to Brush_Caching( Screen* parentScreen, const FVector2& size ); //! Destructor virtual ~Brush_Caching(); //! sends the contents of this caching Brush into the output stream of the given Brush void emerge( Brush& targetBrush ); virtual const FVector2& getPPU_Raw() const; virtual const FVector2& getUPI_Raw() const; virtual bool isRTTContext() const { return isRTT(); } //! returns \c true if this caching Brush is using a render texture for storage bool isRTT() const { return mRenderTexture.get() != 0; } //! returns \c true if this caching Brush is using memory for storage bool isMemory() const { return !isRTT(); } //! public access to Brush::_clear() void clear() { _clear(); } //! returns \c true if there is content stored that can be emerged bool hasContent() const { return mHasContent; } protected: virtual void appendRenderOperation( RenderOperation &renderOp ); virtual void onActivate(); virtual void onClear(); bool initRTT(); void cleanupRTT(); void clearRTT(); void activateRTT(); void appendRTT( RenderOperation &renderOp ); void emergeRTT( Brush& targetBrush ); void initMemory(); void cleanupMemory(); void clearMemory(); void activateMemory(); void appendMemory( RenderOperation &renderOp ); void emergeMemory( Brush& targetBrush ); private: Screen* mScreen; FVector2 mDrawSize; FVector2 mMaxUV; RenderOperationList mRenderOpList; RenderTexturePtr mRenderTexture; bool mHasContent; }; } // namespace OpenGUI{ #endif // A0D166F7_A4DC_4019_8411_83D8DC435DFC
[ "zeroskill@2828181b-9a0d-0410-a8fe-e25cbdd05f59" ]
[ [ [ 1, 81 ] ] ]
a80511eb0a45bfb3f38cfdb3552f60c7d64877d9
9420f67e448d4990326fd19841dd3266a96601c3
/ mcvr/mcvr/BlackScholesSDE.cpp
4a6628bc4e979b8fe92e438a8c3dc7f95481dca6
[]
no_license
xrr/mcvr
4d8d7880c2fd50e41352fae1b9ede0231cf970a2
b8d3b3c46cfddee281e099945cee8d844cea4e23
refs/heads/master
2020-06-05T11:59:27.857504
2010-02-24T19:32:21
2010-02-24T19:32:21
32,275,830
0
0
null
null
null
null
ISO-8859-1
C++
false
false
603
cpp
#include "BlackScholesSDE.h" #include <math.h> BlackScholesSDE::BlackScholesSDE (double S0, double sigma, double mu, GaussianGenerator* pGG) : BlackScholes(S0, sigma, mu, pGG) { Reset(); } BlackScholesSDE::BlackScholesSDE (void) { Reset(); } void BlackScholesSDE::Reset(void) { BlackScholes::Reset(); _S = S0; _Wt = 0; } BlackScholesSDE::~BlackScholesSDE (void) {} double BlackScholesSDE::NextValue (double dt){ _T += dt; double dWt = _pGG->Next(0,sqrt(dt)); //écart-type, pas variance _S *= 1+mu*dt+sigma*dWt; //équation discrétisée return _S; }
[ "romain.rousseau@fa0ec5f0-0fe6-11df-8179-3f26cfb4ba5f" ]
[ [ [ 1, 27 ] ] ]
f6bed6fd9782fe4e58aec245cddfe6d958f2a43c
611fc0940b78862ca89de79a8bbeab991f5f471a
/src/Stage/SpecialScreens/TeamLogo.h
1eacc57a05fc117f8ba67fb3bbf3797bdf9eda4b
[]
no_license
LakeIshikawa/splstage2
df1d8f59319a4e8d9375b9d3379c3548bc520f44
b4bf7caadf940773a977edd0de8edc610cd2f736
refs/heads/master
2021-01-10T21:16:45.430981
2010-01-29T08:57:34
2010-01-29T08:57:34
37,068,575
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
309
h
#pragma once #include "..\\Stage.h" /* スタッフロール */ class TeamLogo : public Stage { public: TeamLogo(); ~TeamLogo(); void Load(); void UnLoad(); void Process(); private: float mAlpha; enum STATUS{ FADEIN, WAIT, FADEOUT } mStatus; float mTimer; };
[ "lakeishikawa@c9935178-01ba-11df-8f7b-bfe16de6f99b" ]
[ [ [ 1, 29 ] ] ]
ec2f0fd9df4db99dc50a99ef467e82b1cab7eda2
89d2197ed4531892f005d7ee3804774202b1cb8d
/GWEN/src/Controls/TabStrip.cpp
1dc2074b9cb0161fe6d85733ddf4bff8df475cc9
[ "MIT", "Zlib" ]
permissive
hpidcock/gbsfml
ef8172b6c62b1c17d71d59aec9a7ff2da0131d23
e3aa990dff8c6b95aef92bab3e94affb978409f2
refs/heads/master
2020-05-30T15:01:19.182234
2010-09-29T06:53:53
2010-09-29T06:53:53
35,650,825
0
0
null
null
null
null
UTF-8
C++
false
false
4,298
cpp
/* GWEN Copyright (c) 2010 Facepunch Studios See license in Gwen.h */ #include "stdafx.h" #include "Gwen/Gwen.h" #include "Gwen/Skin.h" #include "Gwen/Controls/TabStrip.h" #include "Gwen/Controls/TabControl.h" #include "Gwen/Controls/Highlight.h" #include "Gwen/DragAndDrop.h" #include "Gwen/Utility.h" using namespace Gwen; using namespace Gwen::Controls; GWEN_CONTROL_CONSTRUCTOR( TabStrip ) { m_TabDragControl = NULL; m_bAllowReorder = false; } bool TabStrip::DragAndDrop_HandleDrop( Gwen::DragAndDrop::Package* pPackage, int x, int y ) { Gwen::Point LocalPos = CanvasPosToLocal( Gwen::Point( x, y ) ); TabButton* pButton = dynamic_cast<TabButton*>( DragAndDrop::SourceControl ); TabControl* pTabControl = dynamic_cast<TabControl*>( GetParent() ); if ( pTabControl && pButton ) { if ( pButton->GetTabControl() != pTabControl ) { // We've moved tab controls! pTabControl->AddPage( pButton ); } } Base* DroppedOn = GetControlAt( LocalPos.x, LocalPos.y ); if ( DroppedOn ) { Gwen::Point DropPos = DroppedOn->CanvasPosToLocal( Gwen::Point( x, y ) ); DragAndDrop::SourceControl->BringNextToControl( DroppedOn, DropPos.x > DroppedOn->Width() / 2 ); } else { DragAndDrop::SourceControl->BringToFront(); } return true; } bool TabStrip::DragAndDrop_CanAcceptPackage( Gwen::DragAndDrop::Package* pPackage ) { if ( !m_bAllowReorder ) return false; if ( pPackage->name == "TabButtonMove" ) return true; return false; } void TabStrip::Layout( Skin::Base* skin ) { Point pLargestTab( 5, 5 ); int iNum = 0; for ( Base::List::iterator iter = Children.begin(); iter != Children.end(); ++iter ) { TabButton* pButton = dynamic_cast<TabButton*>(*iter); if ( !pButton ) continue; pButton->SizeToContents(); Margin m; int iActive = pButton->IsActive() ? 0 : 2; int iNotFirst = iNum > 0 ? -1 : 0; int iControlOverhang = -3; if ( m_iDock == Pos::Top ) { m.top = iActive; m.left = iNotFirst; m.bottom = iControlOverhang; pButton->Dock( Pos::Left ); } if ( m_iDock == Pos::Left ) { m.left = iActive * 2; m.right = iControlOverhang; m.top = iNotFirst; pButton->Dock( Pos::Top ); } if ( m_iDock == Pos::Right ) { m.right = iActive * 2; m.left = iControlOverhang; m.top = iNotFirst; pButton->Dock( Pos::Top ); } if ( m_iDock == Pos::Bottom ) { m.bottom = iActive; m.left = iNotFirst; m.top = iControlOverhang; pButton->Dock( Pos::Left ); } pLargestTab.x = Utility::Max( pLargestTab.x, pButton->Width() ); pLargestTab.y = Utility::Max( pLargestTab.y, pButton->Height() ); pButton->SetMargin( m ); iNum++; } if ( m_iDock == Pos::Top || m_iDock == Pos::Bottom ) SetSize( Width(), pLargestTab.y ); if ( m_iDock == Pos::Left || m_iDock == Pos::Right ) SetSize( pLargestTab.x, Height() ); BaseClass::Layout( skin ); } void TabStrip::DragAndDrop_HoverEnter( Gwen::DragAndDrop::Package* pPackage, int x, int y ) { if ( m_TabDragControl ) { Debug::Msg( "ERROR! TabStrip::DragAndDrop_HoverEnter\n" ); } m_TabDragControl = new ControlsInternal::Highlight( this ); m_TabDragControl->SetMouseInputEnabled( false ); m_TabDragControl->SetSize( 3, Height() ); } void TabStrip::DragAndDrop_HoverLeave( Gwen::DragAndDrop::Package* pPackage ) { delete m_TabDragControl; m_TabDragControl = NULL; } void TabStrip::DragAndDrop_Hover( Gwen::DragAndDrop::Package* pPackage, int x, int y ) { Gwen::Point LocalPos = CanvasPosToLocal( Gwen::Point( x, y ) ); Base* DroppedOn = GetControlAt( LocalPos.x, LocalPos.y ); if ( DroppedOn && DroppedOn != this ) { Gwen::Point DropPos = DroppedOn->CanvasPosToLocal( Gwen::Point( x, y ) ); m_TabDragControl->SetBounds( Rect( 0, 0, 3, Height() ) ); m_TabDragControl->BringToFront(); m_TabDragControl->SetPos( DroppedOn->X() - 1, 0 ); if ( DropPos.x > DroppedOn->Width() / 2 ) { m_TabDragControl->MoveBy( DroppedOn->Width()-1, 0 ); } m_TabDragControl->Dock( Pos::None ); } else { m_TabDragControl->Dock( Pos::Left ); m_TabDragControl->BringToFront(); } } void TabStrip::SetTabPosition( int iPos ) { Dock( iPos ); }
[ "haza55@5bf3a77f-ad06-ad18-b9fb-7d0f6dabd793" ]
[ [ [ 1, 176 ] ] ]
563fcec393295b8ea7ff945c78a55d7afdbbf342
cc946ca4fb4831693af2c6f252100b9a83cfc7d0
/uCash.Cybos/uCash.Cybos.CpCybos.h
df3ca631dd1c3f82c08f2139ddb2026be5f34693
[]
no_license
primespace/ucash-cybos
18b8b324689516e08cf6d0124d8ad19c0f316d68
1ccece53844fad0ef8f3abc8bbb51dadafc75ab7
refs/heads/master
2021-01-10T04:42:53.966915
2011-10-14T07:15:33
2011-10-14T07:15:33
52,243,596
7
0
null
null
null
null
UTF-8
C++
false
false
1,401
h
/* * uCash.Cybos Copyright (c) 2011 Taeyoung Park ([email protected]) * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #pragma once namespace uCash { namespace Cybos { class UCASHCYBOS_API CpCybos : public CpCybosObject<CpUtil::ICpCybosPtr, CpUtil::CpCybos> { public: CpCybos(); ~CpCybos(); }; }} // namespace uCash::Cybos
[ [ [ 1, 35 ] ] ]
be01a3f0bdb1b9c52e50e4a9cb7d320347abdd2c
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/Shared/Globals.h
26ecdc8c67af511fd62548ce8c0c22e8f1706daf
[]
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,431
h
// ----------------------------------------------------------------------- // // // MODULE : Globals.h // // PURPOSE : Global data // // CREATED : 4/26/99 // // (c) 1999 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #ifndef _GLOBALS_H_ #define _GLOBALS_H_ // global constants const int MAX_OBJECT_ARRAY_SIZE = 32; #define COORD_CENTER 0x80000000 // Version to use with dinput. #define DIRECTINPUT_VERSION 0x0800 inline BOOL PtInRect(RECT* pRect, int x, int y) { if((x >= pRect->right) || (x < pRect->left) || (y >= pRect->bottom) || (y < pRect->top)) return FALSE; return TRUE; } // Helper classes template<class TYPE> class CRange { public: CRange() { } CRange(TYPE fMin, TYPE fMax) { m_fMin = fMin; m_fMax = fMax; } void Set(TYPE fMin, TYPE fMax) { m_fMin = fMin; m_fMax = fMax; } TYPE GetMin() { return m_fMin; } TYPE GetMax() { return m_fMax; } protected: TYPE m_fMin; TYPE m_fMax; }; // Miscellaneous functions... template< class T > inline T MinAbs( T a, T b) { return (T)fabs(a) < (T)fabs(b) ? a : b; } template< class T > inline T MaxAbs( T a, T b) { return (T)fabs(a) > (T)fabs(b) ? a : b; } template< class T > inline T Clamp( T val, T min, T max ) { return Min( max, Max( val, min )); } #endif // _GLOBALS_H_
[ [ [ 1, 74 ] ] ]
dfb3913e3f73aab8b915b9999612f88a86718eec
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SEFoundation/SEIntersection/SEIntrRay3Triangle3.h
127c926ec593f566ed8d0c6e0f2da00c94d235c5
[]
no_license
pizibing/swingengine
d8d9208c00ec2944817e1aab51287a3c38103bea
e7109d7b3e28c4421c173712eaf872771550669e
refs/heads/master
2021-01-16T18:29:10.689858
2011-06-23T04:27:46
2011-06-23T04:27:46
33,969,301
0
0
null
null
null
null
GB18030
C++
false
false
2,227
h
// Swing Engine Version 1 Source Code // Most of techniques in the engine are mainly based on David Eberly's // Wild Magic 4 open-source code.The author of Swing Engine learned a lot // from Eberly's experience of architecture and algorithm. // Several sub-systems are totally new,and others are re-implimented or // re-organized based on Wild Magic 4's sub-systems. // Copyright (c) 2007-2010. All Rights Reserved // // Eberly's permission: // Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // 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. The license is available for reading at // the location: // http://www.gnu.org/copyleft/lgpl.html #ifndef Swing_IntrRay3Triangle3_H #define Swing_IntrRay3Triangle3_H #include "SEFoundationLIB.h" #include "SEPlatforms.h" #include "SEIntersector.h" #include "SERay3.h" #include "SETriangle3.h" namespace Swing { //---------------------------------------------------------------------------- // Description: // Author:Sun Che // Date:20081220 //---------------------------------------------------------------------------- class SE_FOUNDATION_API SEIntrRay3Triangle3f : public SEIntersector<float, SEVector3f> { public: SEIntrRay3Triangle3f(const SERay3f& rRay, const SETriangle3f& rTriangle); // 对象访问. const SERay3f& GetRay(void) const; const SETriangle3f& GetTriangle(void) const; // test-intersection查询. virtual bool Test(void); // Find-intersection查询.相交点为 // P = origin + t*direction = b0*V0 + b1*V1 + b2*V2 virtual bool Find(void); float GetRayT(void) const; float GetTriB0(void) const; float GetTriB1(void) const; float GetTriB2(void) const; private: // 待检查是否相交的对象. const SERay3f* m_pRay; const SETriangle3f* m_pTriangle; // 相交集相关信息. float m_fRayT, m_fTriB0, m_fTriB1, m_fTriB2; }; } #endif
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 70 ] ] ]
d15dc3ce392daab9a1af8a88077aacc1188b6c77
f3722903fbf248c02dda95a4e0075397c63adc0a
/src/c/unused/blarggapu/Nes_Apu.h
d89107ca71b899c2efdc21f0f3e60db45974e509
[]
no_license
BruceJawn/FlashNES-nesemu
0305fb9e011907f56e6619cf169ac8ba17ce0765
a621e288ffe155a1f016f8c914611bb18e35964a
refs/heads/master
2021-01-16T23:02:02.030960
2011-02-27T00:24:51
2011-02-27T00:24:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,192
h
// NES 2A03 APU sound chip emulator // Nes_Snd_Emu 0.1.7. Copyright (C) 2003-2005 Shay Green. GNU LGPL license. #ifndef NES_APU_H #define NES_APU_H #ifdef assert #undef assert #endif #define assert(n) typedef long cpu_time_t; // CPU clock cycle count typedef unsigned cpu_addr_t; // 16-bit memory address #include "Nes_Oscs.h" struct apu_snapshot_t; class Nonlinear_Buffer; class Nes_Apu { public: Nes_Apu(); ~Nes_Apu(); // Set buffer to generate all sound into, or disable sound if NULL void output( Blip_Buffer* ); // Set memory reader callback used by DMC oscillator to fetch samples. // When callback is invoked, 'user_data' is passed unchanged as the // first parameter. void dmc_reader( int (*callback)( void* user_data, cpu_addr_t ), void* user_data = NULL ); // All time values are the number of CPU clock cycles relative to the // beginning of the current time frame. Before resetting the CPU clock // count, call end_frame( last_cpu_time ). // Write to register (0x4000-0x4017, except 0x4014 and 0x4016) enum { start_addr = 0x4000 }; enum { end_addr = 0x4017 }; void write_register( cpu_time_t, cpu_addr_t, int data ); // Read from status register at 0x4015 enum { status_addr = 0x4015 }; int read_status( cpu_time_t ); // Run all oscillators up to specified time, end current time frame, then // start a new time frame at time 0. Time frames have no effect on emulation // and each can be whatever length is convenient. void end_frame( cpu_time_t ); // Additional optional features (can be ignored without any problem) // Reset internal frame counter, registers, and all oscillators. // Use PAL timing if pal_timing is true, otherwise use NTSC timing. // Set the DMC oscillator's initial DAC value to initial_dmc_dac without // any audible click. void reset( bool pal_timing = false, int initial_dmc_dac = 0 ); // Save/load snapshot of exact emulation state void save_snapshot( apu_snapshot_t* out ) const; void load_snapshot( apu_snapshot_t const& ); // Set overall volume (default is 1.0) void volume( double ); // Reset oscillator amplitudes. Must be called when clearing buffer while // using non-linear sound. void buffer_cleared(); // Set treble equalization (see notes.txt). void treble_eq( const blip_eq_t& ); // Set sound output of specific oscillator to buffer. If buffer is NULL, // the specified oscillator is muted and emulation accuracy is reduced. // The oscillators are indexed as follows: 0) Square 1, 1) Square 2, // 2) Triangle, 3) Noise, 4) DMC. enum { osc_count = 5 }; void osc_output( int index, Blip_Buffer* buffer ); // Set IRQ time callback that is invoked when the time of earliest IRQ // may have changed, or NULL to disable. When callback is invoked, // 'user_data' is passed unchanged as the first parameter. void irq_notifier( void (*callback)( void* user_data ), void* user_data = NULL ); // Get time that APU-generated IRQ will occur if no further register reads // or writes occur. If IRQ is already pending, returns irq_waiting. If no // IRQ will occur, returns no_irq. enum { no_irq = LONG_MAX / 2 + 1 }; enum { irq_waiting = 0 }; cpu_time_t earliest_irq() const; // Count number of DMC reads that would occur if 'run_until( t )' were executed. // If last_read is not NULL, set *last_read to the earliest time that // 'count_dmc_reads( time )' would result in the same result. int count_dmc_reads( cpu_time_t t, cpu_time_t* last_read = NULL ) const; // Run APU until specified time, so that any DMC memory reads can be // accounted for (i.e. inserting CPU wait states). void run_until( cpu_time_t ); // End of public interface. private: friend class Nes_Nonlinearizer; void enable_nonlinear( double volume ); private: // noncopyable Nes_Apu( const Nes_Apu& ); Nes_Apu& operator = ( const Nes_Apu& ); Nes_Osc* oscs [osc_count]; Nes_Square square1; Nes_Square square2; Nes_Noise noise; Nes_Triangle triangle; Nes_Dmc dmc; cpu_time_t last_time; // has been run until this time in current frame cpu_time_t earliest_irq_; cpu_time_t next_irq; int frame_period; int frame_delay; // cycles until frame counter runs next int frame; // current frame (0-3) int osc_enables; int frame_mode; bool irq_flag; void (*irq_notifier_)( void* user_data ); void* irq_data; Nes_Square::Synth square_synth; // shared by squares void irq_changed(); void state_restored(); friend struct Nes_Dmc; }; inline void Nes_Apu::osc_output( int osc, Blip_Buffer* buf ) { assert(( "Nes_Apu::osc_output(): Index out of range", 0 <= osc && osc < osc_count )); oscs [osc]->output = buf; } inline cpu_time_t Nes_Apu::earliest_irq() const { return earliest_irq_; } inline void Nes_Apu::dmc_reader( int (*func)( void*, cpu_addr_t ), void* user_data ) { dmc.rom_reader_data = user_data; dmc.rom_reader = func; } inline void Nes_Apu::irq_notifier( void (*func)( void* user_data ), void* user_data ) { irq_notifier_ = func; irq_data = user_data; } inline int Nes_Apu::count_dmc_reads( cpu_time_t time, cpu_time_t* last_read ) const { return dmc.count_reads( time, last_read ); } #endif
[ [ [ 1, 168 ] ] ]
de8fece4a66682ce99af5cec8172f883957dbd5e
7d349e6342c084a4d11234a0aa0846db41c50303
/themeagent/Theme.cpp
de3435187260fe3e47066e5bd7d4a716c8ffccc2
[]
no_license
Tobbe/themeagent
8f72641228a9cbb4c57e3bcd7475aee5f755eb3d
cbdbf93859ee7ef5d43330da7dd270f7b966f0b2
refs/heads/master
2020-12-24T17:44:42.819782
2009-04-18T22:38:58
2009-04-18T22:38:58
97,412
3
0
null
null
null
null
UTF-8
C++
false
false
3,196
cpp
#include "Theme.h" #include <windows.h> using namespace std; Theme::Theme() { enabled = false; } Theme::Theme(const string &path, const RCFile &rc) { enabled = false; this->path = cleanUpPath(path); this->name = parseName(rc); this->author = parseAuthor(rc); this->version = parseVersion(rc); this->preview = lookForPreview(); this->otsVersion = parseOTSVersion(rc); this->neededModules = parseNeededModules(rc); } string Theme::cleanUpPath(string path) const { TCHAR buffer[MAX_PATH]; TCHAR **lpPart = NULL; GetFullPathName(path.c_str(), MAX_PATH, buffer, lpPart); path = buffer; if (path[path.length() - 1] == '\\') { path = path.substr(0, path.length() - 1); } return path; } string Theme::parseName(const RCFile &rc) const { string name = rc.get("ThemeName"); if (name == "") { //parse name from path size_t index = path.find_last_of("\\/"); if (index == path.length() - 1) { index = path.find_last_of("\\/", path.length() - 2); name = path.substr(index + 1, path.length() - 2 - index); } else { name = path.substr(index + 1); } } return name; } string Theme::parseAuthor(const RCFile &rc) const { return rc.get("ThemeAuthor"); } string Theme::parseVersion(const RCFile &rc) const { return rc.get("ThemeVersion"); } string Theme::lookForPreview() const { string preview; string pngPath(path + "\\preview.png"); string bmpPath(path + "\\preview.bmp"); if (GetFileAttributes(pngPath.c_str()) != INVALID_FILE_ATTRIBUTES) { preview = pngPath; } else if (GetFileAttributes(bmpPath.c_str()) != INVALID_FILE_ATTRIBUTES) { preview = bmpPath; } return preview; } string Theme::parseOTSVersion(const RCFile &rc) const { string majorVersion = rc.get("OtsMajorVersion"); string minorVersion = rc.get("OtsMinorVersion"); if (majorVersion == "") { return ""; } else if (minorVersion == "") { return majorVersion; } return majorVersion + "." + minorVersion; } ModuleList Theme::parseNeededModules(RCFile rc) const { string module; ModuleList mList; do { module = rc.getMultiple("*NetLoadModule"); mList.add(Module(module)); } while (module != ""); return mList; } string Theme::getName() const { return name; } string Theme::getAuthor() const { return author; } string Theme::getVersion() const { return version; } string Theme::getPreview() const { return preview; } string Theme::getPath() const { return path; } string Theme::getFolder() const { //parse folder from path string folder; size_t index = path.find_last_of("\\/"); if (index == path.length() - 1) { index = path.find_last_of("\\/", path.length() - 2); folder = path.substr(index + 1, path.length() - 2 - index); } else { folder = path.substr(index + 1); } return folder; } string Theme::getOTSVersion() const { return otsVersion; } ModuleList Theme::getNeededModules() const { return neededModules; } bool Theme::getEnabled() const { return enabled; } void Theme::setEnabled(bool enabled) { this->enabled = enabled; }
[ [ [ 1, 180 ] ] ]
bbb040b21d14cfcc737f323a96cde06b65826b1d
3bfe835203f793ee00bdf261c26992b1efea69ed
/misc/Win32Framework/Windows Sample/Main.cpp
9c31c170504a9f314d62c08fce6243163b21821b
[]
no_license
yxrkt/DigiPen
0bdc1ed3ee06e308b4942a0cf9de70831c65a3d3
e1bb773d15f63c88ab60798f74b2e424bcc80981
refs/heads/master
2020-06-04T20:16:05.727685
2009-11-18T00:26:56
2009-11-18T00:26:56
814,145
1
3
null
null
null
null
UTF-8
C++
false
false
168
cpp
#include "App.h" int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE, LPSTR, INT ) { App app( hInstance ); int result = app.Run(); return result; }
[ [ [ 1, 10 ] ] ]
1f2a0852732229c810210da2606903a4080fe1ce
ffe0a7d058b07d8f806d610fc242d1027314da23
/V3e/mc/src/irc/ClientSocket.h
e09998b0bf4766c3b1074f40ce52255ebb2ea8c1
[]
no_license
Cybie/mangchat
27bdcd886894f8fdf2c8956444450422ea853211
2303d126245a2b4778d80dda124df8eff614e80e
refs/heads/master
2016-09-11T13:03:57.386786
2009-12-13T22:09:37
2009-12-13T22:09:37
32,145,077
0
0
null
null
null
null
UTF-8
C++
false
false
357
h
#ifndef _CLIENT_SOCKET_H_ #define _CLIENT_SOCKET_H_ #include "Socket.h" class ClientSocket : public BaseSocket { public: ClientSocket(void); ClientSocket(SOCK_TYPE _sock_id); ~ClientSocket(void); public: bool Connect(const char *addr, int port); void Close() { _Close(); }; void Send(std::string _data); }; #endif
[ "cybraxcyberspace@dfcbb000-c142-0410-b1aa-f54c88fa44bd" ]
[ [ [ 1, 18 ] ] ]
404c08e3ccf70ee5935c320b54674ff51f8d9395
9df4b47eb2d37fd7f08b8e723e17f733fd21c92b
/plugintemplate/libs/lib_profiling.h
ce98c276076e80f842e8dffb005449f1cb83dc60
[]
no_license
sn4k3/sourcesdk-plugintemplate
d5a806f8793ad328b21cf8e7af81903c98b07143
d89166b79a92b710d275c817be2fb723f6be64b5
refs/heads/master
2020-04-09T07:11:55.754168
2011-01-23T22:58:09
2011-01-23T22:58:09
32,112,282
1
0
null
null
null
null
UTF-8
C++
false
false
3,420
h
#ifndef LIB_PROFILING_H #define LIB_PROFILING_H //========= Copyright © 2010-2011, Tiago Conceição, All rights reserved. ============ // Plugin Template // // Please Read (LICENSE.txt) and (README.txt) // Dont Forget Visit: // (http://www.sourceplugins.com) -> VPS Plugins // (http://www.sourcemm.net) (http://forums.alliedmods.net/forumdisplay.php?f=52) - MMS Plugins // //=================================================================================== //================================================================================= // Defines //================================================================================= #define LIB_PROFILING_VERSION "1.0" #define LIB_PROFILING_CLASS CProfilingLib #define LIB_PROFILINGDATA_CLASS CProfilingData //================================================================================= // Class //================================================================================= // Profiling class class LIB_PROFILINGDATA_CLASS { public: // Constructor // Set 'startNow' to true, to start profiling // name does nothing, its just to name your profiling func if you want LIB_PROFILINGDATA_CLASS(bool startNow = true, const char *name = NULL); // Destructor ~LIB_PROFILINGDATA_CLASS(void); // Reset class as a new instance void Reset(); // Start a profiling // If force is true, resets the current/finished profiling bool Start(bool force = false); // Stops a profiling // Returns -1, if profiling was not started, otherwise returns time taken, in seconds float Stop(); // Get profiling time taken in seconds // If mustFinish is true then profiling must be finished fist to obtain time, otherwise return time util now. // Returns -1 if profiling not started yet float GetTime(bool mustFinish = false); // Set profiling name // name does nothing, its just to name your profiling func if you want inline void SetName(const char *name){ szname = name; } // Get profiling name inline const char *GetName(){ return szname; } // Does profiling already start? inline bool IsStarted(){ return b_isstarted; } // Does profiling already finish? inline bool IsFinished(){ return b_isfinished; } private: const char *szname; bool b_isstarted; bool b_isfinished; float f_starttime; float f_endtime; }; //================================================================================= // Class //================================================================================= // Provide a collection of CProfilingData class LIB_PROFILING_CLASS { public: // Get wrapper LIB_PROFILINGDATA_CLASS *operator[](const char *name); // Add a profiling function to list. // Returns false if alread exist one with same name. bool Add(const char *name, bool startNow = true); // Remove a profiling function from list. bool Remove(const char *name); // Remove all profiling functions from list. void RemoveAll(); // Get a named CProfilingData instance from list. LIB_PROFILINGDATA_CLASS *Get(const char *name); // Get profiling index from name. int GetIndex(const char *name); // Check if a profiling name exists. int Exists(const char *name); // Get how many profiling functions there are in list. int Count() const; private: CUtlVector<LIB_PROFILINGDATA_CLASS *> v_profiling; }; extern LIB_PROFILING_CLASS *VAR_LIB_PROFILING; #endif
[ "[email protected]@2dd402b7-31f5-573d-f87e-a7bc63fa017b" ]
[ [ [ 1, 122 ] ] ]
fea2dec90d7d595b7d4361f66226c30134478065
f2b70f0f8d6f61899eb70b9f2626f1eb44f68cc7
/libs/webcam/src/directx/DirectXWebcamUtils.cpp
75d471adfb5b26a7169856624471d8f0a838c31b
[]
no_license
vikas100/VoxOx
cc36efcbb9a82da03c05ea76093426aafba3bd8c
d4fae14f3f5a4de29abad3b79f4903db01daa913
refs/heads/master
2020-05-18T06:57:08.968725
2011-05-14T01:56:29
2011-05-14T01:56:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,894
cpp
/* * WengoPhone, a voice over Internet phone * Copyright (C) 2004-2005 Wengo * * 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 <webcam/DirectXWebcamUtils.h> #include <iostream> using namespace std; HRESULT FindMyCaptureDevice(IBaseFilter * * pF, BSTR bstrName) { HRESULT hr = E_FAIL; CComPtr < IBaseFilter > pFilter; CComPtr < ICreateDevEnum > pSysDevEnum; CComPtr < IEnumMoniker > pEnumCat = NULL; // Create the System Device Enumerator. pSysDevEnum.CoCreateInstance(CLSID_SystemDeviceEnum); if (!pSysDevEnum) { return E_FAIL; } // Obtain a class enumerator for the video compressor category. pSysDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, & pEnumCat, 0); if (!pEnumCat) { return E_FAIL; } pEnumCat->Reset(); // Enumerate the monikers. //CComPtr<IMoniker> pMoniker; while (true) { //while(pMoniker && pEnumCat->Next(1, &pMoniker, &cFetched) == S_OK) CComPtr < IMoniker > pMoniker; ULONG cFetched; CComPtr < IPropertyBag > pProp; HRESULT hr_work = pEnumCat->Next(1, & pMoniker, & cFetched); if (hr_work != S_OK) { break; } hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag, (void * *) & pProp); if (hr != S_OK) { continue; } VARIANT varName; VariantInit(& varName); // Try to match the friendly name. hr = pProp->Read(L"FriendlyName", & varName, 0); if (SUCCEEDED(hr) && (wcscmp(bstrName, varName.bstrVal) == 0)) { hr = pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void * *) & pFilter); break; } VariantClear(& varName); pMoniker = NULL; // Release for the next loop. } if (pFilter) { *pF = pFilter; (*pF)->AddRef(); // Add ref on the way out. } return hr; } IAMStreamConfig * GetIAMStreamConfig(IBaseFilter * pFilter) { IEnumPins * pEnum = NULL; HRESULT hr = pFilter->EnumPins(& pEnum); if (FAILED(hr)) { return NULL; } IPin * pPin = NULL; while (pEnum->Next(1, & pPin, NULL) == S_OK) { IAMStreamConfig * pIAMS = NULL; hr = pPin->QueryInterface(IID_IAMStreamConfig, (void * *) & pIAMS); if (hr == S_OK) { return pIAMS; } pPin->Release(); } pEnum->Release(); return NULL; }
[ [ [ 1, 102 ] ] ]
681afca961cdb04617a63c8638646b80ca1c61bf
bad6dfe35e27195461f9a9606de4d9979d7ba000
/ocelot/ocelot/executive/interface/LLVMExecutableKernel.h
1c9c071dbf7dafd9caf63777063d978ef3be59d7
[]
no_license
antmanler/Benchmarking-CUDA
96e069151e9c87afedae806957e96d18fcf29a06
640232ac26e7610569cf3287831719310b8e05d1
refs/heads/master
2020-03-09T23:07:56.672057
2011-03-16T19:47:22
2011-03-16T19:47:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,050
h
/*! \file LLVMExecutableKernel.h \date Friday September 4, 2009 \author Gregory Diamos <[email protected]> \brief The header file for the LLVMRuntime class */ #ifndef LLVM_EXECUTABLE_KERNEL_H_INCLUDED #define LLVM_EXECUTABLE_KERNEL_H_INCLUDED #include <ocelot/ir/interface/LLVMKernel.h> #include <ocelot/ir/interface/PTXKernel.h> #include <ocelot/ir/interface/Texture.h> #include <ocelot/executive/interface/LLVMContext.h> #include <ocelot/executive/interface/ExecutableKernel.h> #include <ocelot/translator/interface/Translator.h> #include <hydrazine/interface/Thread.h> #include <boost/thread.hpp> #include <stack> namespace llvm { class ExecutionEngine; class Module; class Context; } namespace executive { /*! \brief Executes an LLVMKernel using the LLVM JIT */ class LLVMExecutableKernel : public executive::ExecutableKernel { private: /*! \brief A map from a variable identifier to its allocation */ typedef std::unordered_map< std::string, size_t > AllocationMap; /*! \brief A type for referring to a specific PTX thread */ typedef unsigned int ThreadContext; /*! \brief A function pointer to the translated kernel */ typedef unsigned int (*Function)( LLVMContext* ); /*! \brief A class for managing global llvm state */ class LLVMState { public: /*! \brief LLVM module */ llvm::Module* module; /*! \brief LLVM JIT Engine */ llvm::ExecutionEngine* jit; public: /*! \brief Build the jit */ LLVMState(); /*! \brief Destroy the jit */ ~LLVMState(); public: /*! \brief Initialize the jit */ void initialize(); }; /*! \brief Used as a synchronization point for atomic operations */ class AtomicOperationCache { private: /*! \brief Controls access to the cache */ boost::mutex _mutex; public: /*! \brief Create the mutex */ AtomicOperationCache(); /*! \brief Destroy the mutex */ ~AtomicOperationCache(); public: /*! \brief Locks access to the cache */ void lock(); /*! \brief Unlocks the cache */ void unlock(); }; /*! \brief A worker thread executes a subset of CTAs in a kernel */ class Worker : public hydrazine::Thread { public: /*! \brief A message to the thread */ class Message { public: /*! \brief A type for determining what kind of message is being sent */ enum Type { Kill, LaunchKernelWithBarriers, LaunchKernelWithoutBarriers, Acknowledgement, Invalid }; public: /*! \brief The type of message to the thread */ Type type; /*! \brief The LLVM code being executed */ Function function; /*! \brief The context being executed */ LLVMContext* context; /*! \brief The begining cta of the grid */ unsigned int begin; /*! \brief The ending cta of the grid */ unsigned int end; /*! \brief The step */ unsigned int step; /*! \brief The resume point offset */ unsigned int resumePointOffset; public: Message( Type t = Invalid, Function f = 0, LLVMContext* c = 0, unsigned int begin = 0, unsigned int end = 0, unsigned int step = 0, unsigned int r = 0 ); }; private: /*! \brief This is the 'main' function for the worker */ void execute(); /*! \brief Launch a series of ctas with barriers */ void launchKernelWithBarriers( Function f, LLVMContext* c, unsigned int begin, unsigned int end, unsigned int step, unsigned int rp ); /*! \brief Launch a series of ctas without barriers */ void launchKernelWithoutBarriers( Function f, LLVMContext* c, unsigned int begin, unsigned int end, unsigned int step ); /*! \brief Launch a specific cta with barriers */ void launchCtaWithBarriers( Function f, LLVMContext* c, unsigned int rp ); /*! \brief Launch a specific cta without barriers */ void launchCtaWithoutBarriers( Function f, LLVMContext* c ); }; /*! \brief Controls the execution of worker threads */ class ExecutionManager { private: /*! \brief A vector of created threads */ typedef std::vector< Worker > WorkerVector; /*! \brief A vector of LLVM contexts */ typedef std::vector< LLVMContext > ContextVector; /*! \brief A vector of messages */ typedef std::vector< Worker::Message > MessageVector; private: /*! \brier The currently active worker threads */ WorkerVector _workers; /*! \brief One context for each worker */ ContextVector _contexts; /*! \brief One message for each worker */ MessageVector _messages; /*! \brief The max threads per CTA */ unsigned int _maxThreadsPerCta; public: /*! \brief The constructor boots up the workers */ ExecutionManager(); /*! \brief The destructor tears down the workers */ ~ExecutionManager(); public: /*! \brief Launches a kernel on a grid using a context */ void launch( Function f, LLVMContext* context, bool barriers, unsigned int resumePointOffset, unsigned int externalSharedMemory ); /*! \brief Changes the number of worker threads */ void setThreadCount( unsigned int threads ); /*! \brief Changes the max number of threads per cta */ void setMaxThreadsPerCta( unsigned int threads ); /*! \brief Clears all active threads */ void clear(); /*! \brief Gets the current number of threads */ unsigned int threads() const; }; public: /*! \brief A class of opaque thread visible state */ class OpaqueState { public: /*! \brief A map from a basic block id to the block */ typedef std::unordered_map< ir::ControlFlowGraph::BasicBlock::Id, ir::ControlFlowGraph::const_iterator > BlockIdMap; public: /*! \brief Texture variables */ TextureVector textures; /*! \brief Clock timer */ hydrazine::Timer timer; /*! \brief Debugging information for blocks */ BlockIdMap blocks; /*! \brief Atomic operation cache */ AtomicOperationCache* cache; /*! \brief A reference to the kernel */ const LLVMExecutableKernel* kernel; public: /*! \brief Starts the timer on creation */ OpaqueState(); }; private: /*! \brief Contains the LLVM JIT for all LLVM kernels */ static LLVMState _state; /*! \brief Contains the ExecutionManager for all LLVM kernels */ static ExecutionManager _manager; private: /*! \brief The memory requirements and execution context */ LLVMContext _context; private: /*! \brief LLVM module */ llvm::Module* _module; /*! \brief The translated function */ Function _function; /*! \brief The stored ptx kernel used for translation */ ir::PTXKernel* _ptx; /*! \brief Does this kernel require barrier support? */ bool _barrierSupport; /*! \brief The barrier resume point variable */ std::string _resumePoint; /*! \brief The resume point offset */ unsigned int _resumePointOffset; /*! \brief Constant memory mapping */ AllocationMap _constants; /*! \brief Opaque state */ OpaqueState _opaque; /*! \brief Optimization level for this kernel */ translator::Translator::OptimizationLevel _optimizationLevel; /*! \brief Cache atomics from different threads */ AtomicOperationCache _cache; private: /*! \brief Determine the padding required to satisfy alignment */ static unsigned int _pad( size_t& size, unsigned int alignment ); public: /*! \brief Get a string representation of a thread id */ static std::string threadIdString( const LLVMContext& c ); /*! \brief Get a string representation of a thread id */ static unsigned int threadId( const LLVMContext& c ); /*! \brief Optimize an llvm module using standard passes */ static void _optimizeLLVMFunction( llvm::Module* module, unsigned int level, bool space ); private: /*! \brief Run various PTX optimizer passes on the kernel */ void _optimizePtx(); /*! \brief Create the LLVM module from the code */ void _translateKernel(); /*! \brief Run various LLVM optimizer passes on the kernel */ void _optimize(); /*! \brief Allocate parameter memory */ void _allocateParameterMemory( ); /*! \brief Allocate shared memory */ void _allocateSharedMemory( ); /*! \brief Allocate global memory */ void _allocateGlobalMemory( ); /*! \brief Allocate local memory */ void _allocateLocalMemory( ); /*! \brief Allocate constant memory */ void _allocateConstantMemory( ); /*! \brief Allocate texture memory */ void _allocateTextureMemory( ); /*! \brief Scan the kernel and determine memory requirements */ void _allocateMemory( ); /*! \brief Reload global memory */ void _updateGlobalMemory( ); /*! \brief Reload constant memory */ void _updateConstantMemory( ); private: /*! \brief Build debugging information */ void _buildDebuggingInformation(); public: /*! \brief Creates a new instance of the runtime bound to a kernel*/ LLVMExecutableKernel( ir::Kernel& kernel, executive::Device* d = 0, translator::Translator::OptimizationLevel l = translator::Translator::NoOptimization); /*! \brief Clean up the runtime */ ~LLVMExecutableKernel(); public: /*! \brief Launch a kernel on a 2D grid */ void launchGrid( int width, int height ); /*! \brief Sets the shape of a cta in the kernel */ void setKernelShape( int x, int y, int z ); /*! \brief Declare an amount of external shared memory */ void setExternSharedMemorySize( unsigned int bytes ); /*! \brief Describes the device used to execute the kernel */ void setWorkerThreads( unsigned int threadLimit ); /*! \brief Reload parameter memory */ void updateParameterMemory(); /*! \brief Indicate that other memory has been updated */ void updateMemory(); /*! \brief Get a vector of all textures references by the kernel */ TextureVector textureReferences() const; public: /*! adds a trace generator to the EmulatedKernel */ void addTraceGenerator(trace::TraceGenerator *generator); /*! removes a trace generator from an EmulatedKernel */ void removeTraceGenerator(trace::TraceGenerator *generator); public: /*! \brief Get the number of threads per cta */ unsigned int threads() const; /*! \brief Get the local id of the current thread */ unsigned int threadId() const; /*! \brief Determine the location of a given PTX statement in the original source file */ std::string location(unsigned int statement) const; /*! \brieg Get the instruction contained in a given statement */ std::string instruction(unsigned int statement) const; }; } #endif
[ "fccoelho@tiamat.(none)" ]
[ [ [ 1, 360 ] ] ]
349bc05393be7f4a0c247a1350cc5f49f02c848c
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/nebula2/src/kernel/nenv_cmds.cc
2c49bec8d5c10ff0fb3112697c9ef9f1c88325b3
[]
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
9,737
cc
//------------------------------------------------------------------- // kernel/nenv_dispatch.cc // This file was machine generated. // (C) 2000 A.Weissflog/A.Flemming //------------------------------------------------------------------- #include "precompiled/pchnkernel.h" #include "kernel/nenv.h" #include "kernel/nkernelserver.h" #include "kernel/npersistserver.h" #include "kernel/ncmdproto.h" //#include "precompiled/pchnkernel.h" static void n_gettype(void *, nCmd *); static void n_geti(void *, nCmd *); static void n_getf(void *, nCmd *); static void n_getb(void *, nCmd *); static void n_gets(void *, nCmd *); static void n_geto(void *, nCmd *); static void n_getf4(void*, nCmd*); static void n_seti(void *, nCmd *); static void n_setf(void *, nCmd *); static void n_setb(void *, nCmd *); static void n_sets(void *, nCmd *); static void n_seto(void *, nCmd *); static void n_setf4(void*, nCmd*); //------------------------------------------------------------------- /** @scriptclass nenv @cppclass nEnv @superclass nroot @classinfo The nenv class is similar to an environment variable. Just create, set the type and value, and query it */ void n_initcmds_nEnv(nClass *cl) { cl->BeginCmds(); cl->AddCmd("s_gettype_v", 'GTYP', n_gettype); cl->AddCmd("i_geti_v", 'GETI', n_geti); cl->AddCmd("f_getf_v", 'GETF', n_getf); cl->AddCmd("b_getb_v", 'GETB', n_getb); cl->AddCmd("s_gets_v", 'GETS', n_gets); cl->AddCmd("o_geto_v", 'GETO', n_geto); cl->AddCmd("ffff_getf4_v", 'GTV4', n_getf4); cl->AddCmd("v_seti_i", 'SETI', n_seti); cl->AddCmd("v_setf_f", 'SETF', n_setf); cl->AddCmd("v_setb_b", 'SETB', n_setb); cl->AddCmd("v_sets_s", 'SETS', n_sets); cl->AddCmd("v_seto_o", 'SETO', n_seto); cl->AddCmd("v_setf4_ffff", 'STV4', n_setf4); cl->EndCmds(); } //------------------------------------------------------------------- /** @cmd gettype @input v @output s (Type = [void int float bool string object float4]) @info Returns the datatype the variable is set to. If void is returned the variable is empty. */ static void n_gettype(void *o, nCmd *cmd) { nEnv *self = (nEnv *) o; char *st; nArg::Type t = self->GetType(); switch (t) { case nArg::Int: st = "int"; break; case nArg::Float: st = "float"; break; case nArg::String: st = "string"; break; case nArg::Bool: st = "bool"; break; case nArg::Object: st = "object"; break; case nArg::Float4: st = "float4"; break; default: st="void"; break; } cmd->Out()->SetS(st); } //------------------------------------------------------------------- /** @cmd geti @input v @output i (Value) @info Returns the content of the variable if it is an int variable. If it's not an int variable, 0 is returned and an error message is printed. */ static void n_geti(void *o, nCmd *cmd) { nEnv *self = (nEnv *) o; cmd->Out()->SetI(self->GetI()); } //------------------------------------------------------------------- /** @cmd getf @input v @output f (Value) @info Returns the content of the variable if it is a float variable. If it's not a float variable, 0.0 is returned and an error message is printed. */ static void n_getf(void *o, nCmd *cmd) { nEnv *self = (nEnv *) o; cmd->Out()->SetF(self->GetF()); } //------------------------------------------------------------------- /** @cmd getb @input v @output b (Value) @info Returns the content of the variable if it is a bool variable. If it's not a bool, false is returned and an error message is printed. */ static void n_getb(void *o, nCmd *cmd) { nEnv *self = (nEnv *) o; cmd->Out()->SetB(self->GetB()); } //------------------------------------------------------------------- /** @cmd gets @input v @output s (Value) @info Returns the content of the variable if it is a string variable. If it's not a string variable, "" is returned and an error message is printed. */ static void n_gets(void *o, nCmd *cmd) { nEnv *self = (nEnv *) o; cmd->Out()->SetS(self->GetS()); } //------------------------------------------------------------------- /** @cmd geto @input v @output o (ObjectHandle) @info Returns the content of the variable as an object handle. If it's not an object handle, NULL is returned and an error message is printed. */ static void n_geto(void *o, nCmd *cmd) { nEnv *self = (nEnv *) o; cmd->Out()->SetO(self->GetO()); } //------------------------------------------------------------------- /** @cmd getf4 @input v @output f(X), f(Y), f(Z), f(W) @info Return content as 4D vector. */ static void n_getf4(void* slf, nCmd* cmd) { nEnv* self = (nEnv*) slf; const nFloat4& f = self->GetF4(); cmd->Out()->SetF(f.x); cmd->Out()->SetF(f.y); cmd->Out()->SetF(f.z); cmd->Out()->SetF(f.w); } //------------------------------------------------------------------- /** @cmd seti @input i (Value) @output v @info Sets the content of the variable to the passed integer value. */ static void n_seti(void *o, nCmd *cmd) { nEnv *self = (nEnv *) o; self->SetI(cmd->In()->GetI()); } //------------------------------------------------------------------- /** @cmd setf @input f (Value) @output v @info Sets the content of the variable to the passed float value. */ static void n_setf(void *o, nCmd *cmd) { nEnv *self = (nEnv *) o; self->SetF(cmd->In()->GetF()); } //------------------------------------------------------------------- /** @cmd setb @input b (Value) @output v @info Sets the content of the variable to the passed boolean value. */ static void n_setb(void *o, nCmd *cmd) { nEnv *self = (nEnv *) o; self->SetB(cmd->In()->GetB()); } //------------------------------------------------------------------- /** @cmd sets @input s (Value) @output v @info Sets the content of the variable to the passed string. */ static void n_sets(void *o, nCmd *cmd) { nEnv *self = (nEnv *) o; self->SetS(cmd->In()->GetS()); } //------------------------------------------------------------------- /** @cmd seto @input s (ObjectHandle) @output v @info Sets the content of the variable to the passed object handle. */ static void n_seto(void *o, nCmd *cmd) { nEnv *self = (nEnv *) o; self->SetO((nRoot *)cmd->In()->GetO()); } //------------------------------------------------------------------- /** @cmd setf4 @input f(X), f(Y), f(Z), f(W) @output v @info Sets the content of the variable to a 4D vector. */ static void n_setf4(void* slf, nCmd* cmd) { nEnv* self = (nEnv*) slf; nFloat4 f; f.x = cmd->In()->GetF(); f.y = cmd->In()->GetF(); f.z = cmd->In()->GetF(); f.w = cmd->In()->GetF(); self->SetF4(f); } //------------------------------------------------------------------- /** - 02-Jan-99 floh machine generated */ bool nEnv::SaveCmds(nPersistServer *fs) { bool retval = false; if (nRoot::SaveCmds(fs)) { nCmd *cmd; switch (this->GetType()) { case nArg::Int: cmd = fs->GetCmd(this, 'SETI'); cmd->In()->SetI(this->GetI()); fs->PutCmd(cmd); break; case nArg::Float: cmd = fs->GetCmd(this, 'SETF'); cmd->In()->SetF(this->GetF()); fs->PutCmd(cmd); break; case nArg::String: cmd = fs->GetCmd(this, 'SETS'); cmd->In()->SetS(this->GetS()); fs->PutCmd(cmd); break; case nArg::Bool: cmd = fs->GetCmd(this, 'SETB'); cmd->In()->SetB(this->GetB()); fs->PutCmd(cmd); break; case nArg::Object: cmd = fs->GetCmd(this, 'SETO'); cmd->In()->SetO(this->GetO()); fs->PutCmd(cmd); break; case nArg::Float4: { cmd = fs->GetCmd(this, 'STV4'); const nFloat4& f = this->GetF4(); cmd->In()->SetF(f.x); cmd->In()->SetF(f.y); cmd->In()->SetF(f.z); cmd->In()->SetF(f.w); fs->PutCmd(cmd); } break; case nArg::Pointer: n_assert2_always( "You can not save a memory pointer" ); break; default: break; } retval = true; } return retval; } //------------------------------------------------------------------- // EOF //-------------------------------------------------------------------
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 414 ] ] ]
917fb8bf9feb43f26ccc6b7149e3e5e698ba1198
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/character/ncharskinrenderer.cc
85182f9fea02022d1c5392167259d42f55a60c79
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,361
cc
#define N_IMPLEMENTS nCharacterServer //------------------------------------------------------------------------------ // ncharskinrenderer.cc // (C) 2002 RadonLabs GmbH //------------------------------------------------------------------------------ #include "character/ncharskinrenderer.h" #include "shadow/nshadowcaster.h" #include "shadow/nshadowserver.h" #include "character/ncharskeleton.h" #include "character/ncharjoint.h" //------------------------------------------------------------------------------ /** */ nCharSkinRenderer::nCharSkinRenderer(nKernelServer* kernelServer, nRoot* owner) : dynVBuf(kernelServer, owner) { // empty } //------------------------------------------------------------------------------ /** */ nCharSkinRenderer::~nCharSkinRenderer() { if (this->refShadowCaster.isvalid()) { this->refShadowCaster->Release(); this->refShadowCaster.invalidate(); } } //------------------------------------------------------------------------------ /** */ void nCharSkinRenderer::Initialize(nShadowServer* shadowServer, nVertexBuffer* srcVertexBuffer, nShadowCaster* srcShadowCaster, bool readOnly) { n_assert(!this->IsValid()); n_assert(shadowServer); n_assert(srcVertexBuffer); // release old shadow caster if exists if (this->refShadowCaster.isvalid()) { this->refShadowCaster->Release(); this->refShadowCaster.invalidate(); } // initialize the dynamic vertex buffer int vertexType = srcVertexBuffer->GetVertexType(); n_assert(vertexType & N_VT_JW); vertexType &= ~N_VT_JW; int numVertices = srcVertexBuffer->GetNumVertices(); this->dynVBuf.SetReadOnly(readOnly); this->dynVBuf.Initialize(vertexType, numVertices); // clone optional shadow caster if (srcShadowCaster) { int numCoords = srcShadowCaster->GetNumCoords(); int numEdges = srcShadowCaster->GetNumEdges(); this->refShadowCaster = shadowServer->NewCaster(0); this->refShadowCaster->Initialize(numCoords, numEdges); this->refShadowCaster->CopyEdges(srcShadowCaster, 0, numEdges); } // make sure dest vertex buffer is large enough n_assert(srcVertexBuffer->GetNumVertices() <= this->dynVBuf.GetNumVertices()); } //------------------------------------------------------------------------------ /** */ bool nCharSkinRenderer::IsValid() { return this->dynVBuf.IsValid(); } //------------------------------------------------------------------------------ /** */ void nCharSkinRenderer::Render(const nCharSkeleton* charSkeleton, nIndexBuffer* indexBuffer, nVertexBuffer* srcSkin, nPixelShader* pixelShader, nTextureArray* textureArray) { n_assert(charSkeleton && indexBuffer && srcSkin); n_assert(this->dynVBuf.IsValid()); // prepare dynamic vertex buffer for writing nVertexBuffer* dstSkin = this->dynVBuf.Begin(indexBuffer, pixelShader, textureArray); // lock source vertex buffer for reading srcSkin->LockVertices(); // get src and dst vertex component pointers float* srcCoord = srcSkin->coord_ptr; float* dstCoord = dstSkin->coord_ptr; float* srcNorm = srcSkin->norm_ptr; float* dstNorm = dstSkin->norm_ptr; ulong* srcColor = srcSkin->color_ptr; ulong* dstColor = dstSkin->color_ptr; float *srcUV[N_MAXNUM_TEXCOORDS]; float *dstUV[N_MAXNUM_TEXCOORDS]; int i; int numTexCoordSets = 0; for (i = 0; i < N_MAXNUM_TEXCOORDS; i++) { srcUV[i] = srcSkin->uv_ptr[i]; dstUV[i] = dstSkin->uv_ptr[i]; if (srcUV[i]) { numTexCoordSets++; } else break; } float *srcWgt = srcSkin->w_ptr; int *srcJoint = srcSkin->j_ptr; int numVertices = srcSkin->GetNumVertices(); int srcStride = srcSkin->stride4; int dstStride = dstSkin->stride4; // we assume that the source vertex buffer has at least coords and normals n_assert(srcCoord && srcNorm); // shadow caster coordinate pointer vector3* shadowCoordPtr = 0; if (this->refShadowCaster.isvalid()) { this->refShadowCaster->Lock(); shadowCoordPtr = this->refShadowCaster->GetCoordPtr(); } // for each vertex... (-> important to write target buffer continously!) vector3 v0,v1,n0,n1; for (i = 0; i < numVertices; i++) { // read source coordinate and normal v0.set(srcCoord[0], srcCoord[1], srcCoord[2]); n0.set(srcNorm[0], srcNorm[1], srcNorm[2]); srcCoord += srcStride; srcNorm += srcStride; // compute weighted coord and normal int j; v1.set(0.0f,0.0f,0.0f); n1.set(0.0f,0.0f,0.0f); for (j = 0; j < 4; j++) { float w = srcWgt[j]; if (w > 0.0f) { const nCharJoint& joint = charSkeleton->GetJoint(srcJoint[j]); v1 += (joint.GetSkinMatrix44() * v0) * w; n1 += (joint.GetSkinMatrix33() * n0) * w; } } srcJoint += srcStride; srcWgt += srcStride; // write dst coord dstCoord[0] = v1.x; dstCoord[1] = v1.y; dstCoord[2] = v1.z; dstCoord += dstStride; // write dst norm dstNorm[0] = n1.x; dstNorm[1] = n1.y; dstNorm[2] = n1.z; dstNorm += dstStride; // update shadow caster coordinate if (shadowCoordPtr) { shadowCoordPtr->set(v1); shadowCoordPtr++; } // copy color and uv coordinates if necessary if (srcColor) { dstColor[0] = srcColor[0]; srcColor += srcStride; dstColor += dstStride; } int k; for (k = 0; k < numTexCoordSets; k++) { dstUV[k][0] = srcUV[k][0]; dstUV[k][1] = srcUV[k][1]; srcUV[k] += srcStride; dstUV[k] += dstStride; } } // instead of keeping track of the exact bounding box, // we create a very conservative bounding box (twice // the diameter of the original bounding box) vector3 bbdiam = srcSkin->GetBBox().vmax - srcSkin->GetBBox().vmin; float l = 2.0f * bbdiam.len(); vector3 vmin(-l, -l, -l); vector3 vmax(+l, +l, +l); bbox3 bbox(vmin, vmax); dstSkin->SetBBox(bbox); // unlock and finish if (shadowCoordPtr) { this->refShadowCaster->Unlock(); } srcSkin->UnlockVertices(); this->dynVBuf.End(numVertices, indexBuffer->GetNumIndices()); } //------------------------------------------------------------------------------ /** */ nShadowCaster* nCharSkinRenderer::GetShadowCaster() const { if (this->refShadowCaster.isvalid()) { return this->refShadowCaster.get(); } else { return 0; } } //------------------------------------------------------------------------------
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 240 ] ] ]
720dbe5fdc523d13317625975af9a61d3c44165f
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/branches/persistence2/engine/rules/src/EffectFactory.cpp
0c00f30b724b9fe16b49eaec77b4fca344ec2093
[ "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
1,645
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 "EffectFactory.h" template <> rl::EffectFactoryManager* Ogre::Singleton<rl::EffectFactoryManager>::ms_Singleton = 0; namespace rl { EffectFactoryManager::EffectFactoryManager() : mFactory(NULL) { } Effect* EffectFactoryManager::createEffect(const Ogre::String& name, int stufe) { if (mFactory == NULL) { LOG_ERROR(Logger::RULES, "Could not create effect "+name+". No factory registered"); return NULL; } Effect* rval = mFactory->createEffect(name, stufe); if (rval == NULL) { LOG_ERROR(Logger::RULES, "Effect "+name+" was not created."); } return rval; } void EffectFactoryManager::setEffectFactory(rl::EffectFactory *factory) { mFactory = factory; } }
[ "timm@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 55 ] ] ]
9206643bc1668bdef766627875290d8147a0ebdc
a590fbaf14f8e623cdbad4751df1a4e17569051c
/Headers/Platform/Point.h
2a85ddc86929d6328759346665acec3c477b037a
[]
no_license
ninoles/snake-3d
e47326d26f37622b907bf980f8c05c9cc84a1dea
11b9c1b5054c85814872d6ecf628de6a38c743a8
refs/heads/master
2016-09-05T21:53:57.403056
2010-02-05T02:23:32
2010-02-05T02:23:32
41,636,616
0
0
null
null
null
null
UTF-8
C++
false
false
781
h
/* * Point.h * * Created on: 30/12/2009 * Author: Henrique Jonas */ #ifndef POINT_H_ #define POINT_H_ #include <irrlicht.h> #include <Newton.h> #include "../Base/FrameAnimatedNode.h" #define REPETITIONS 20 namespace platform{ class Point{ private: base::FrameAnimatedNode *_mesh; int _value; int _currentRepetition; void initComponent(); public: Point(irr::scene::ISceneManager *__sceneManager, NewtonWorld *__newtonW, int __id); void insertPointInPosition(irr::core::vector3df __position); void setVisible(bool __visible); void setMaxPoints(int __maxPoints); int getValue(); bool isRepetitions(); base::FrameAnimatedNode* getAnimatedNode(); }; } #endif /* POINT_H_ */
[ "[email protected]", "henrique@henrique-laptop" ]
[ [ [ 1, 15 ], [ 17, 46 ] ], [ [ 16, 16 ] ] ]
2bf55c08e9eaf62de21e8b775f6ac34c0f3fcb52
847cccd728e768dc801d541a2d1169ef562311cd
/src/StringSystem/TextData.h
ce975e6903408ea6936b06ec36a1df2cdc918a2d
[]
no_license
aadarshasubedi/Ocerus
1bea105de9c78b741f3de445601f7dee07987b96
4920b99a89f52f991125c9ecfa7353925ea9603c
refs/heads/master
2021-01-17T17:50:00.472657
2011-03-25T13:26:12
2011-03-25T13:26:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
521
h
/// @file /// Definition of the data StringSystem works with. #ifndef TextData_h__ #define TextData_h__ #include "Base.h" #include "CEGUIString.h" namespace StringSystem { /// Type of the data stored by the StringSystem. typedef CEGUI::String TextData; /// Container used for storing the text data. typedef map<StringKey, TextData> TextDataMap; /// Container used for storing the text data in various groups. typedef map<StringKey, TextDataMap> GroupTextDataMap; } #endif // TextData_h__
[ [ [ 1, 7 ], [ 9, 12 ], [ 14, 16 ], [ 20, 22 ] ], [ [ 8, 8 ], [ 13, 13 ], [ 17, 19 ] ] ]
189a8711250bb23c17bcfa0cc3a54c95a95d9dd8
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/framework/psvi/XSNotationDeclaration.cpp
38e348a288e36c1f443f7e02d8d136adb8611f2b
[ "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
4,012
cpp
/* * Copyright 2003,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: XSNotationDeclaration.cpp,v $ * Revision 1.8 2004/09/08 13:56:09 peiyongz * Apache License Version 2.0 * * Revision 1.7 2003/11/21 22:34:45 neilg * More schema component model implementation, thanks to David Cargill. * In particular, this cleans up and completes the XSModel, XSNamespaceItem, * XSAttributeDeclaration and XSAttributeGroup implementations. * * Revision 1.6 2003/11/21 17:34:04 knoaman * PSVI update * * Revision 1.5 2003/11/14 22:47:53 neilg * fix bogus log message from previous commit... * * Revision 1.4 2003/11/14 22:33:30 neilg * Second phase of schema component model implementation. * Implement XSModel, XSNamespaceItem, and the plumbing necessary * to connect them to the other components. * Thanks to David Cargill. * * Revision 1.3 2003/11/06 15:30:04 neilg * first part of PSVI/schema component model implementation, thanks to David Cargill. This covers setting the PSVIHandler on parser objects, as well as implementing XSNotation, XSSimpleTypeDefinition, XSIDCDefinition, and most of XSWildcard, XSComplexTypeDefinition, XSElementDeclaration, XSAttributeDeclaration and XSAttributeUse. * * Revision 1.2 2003/09/17 17:45:37 neilg * remove spurious inlines; hopefully this will make Solaris/AIX compilers happy. * * Revision 1.1 2003/09/16 14:33:36 neilg * PSVI/schema component model classes, with Makefile/configuration changes necessary to build them * */ #include <xercesc/framework/psvi/XSNotationDeclaration.hpp> #include <xercesc/framework/psvi/XSModel.hpp> #include <xercesc/framework/XMLNotationDecl.hpp> #include <xercesc/framework/psvi/XSModel.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // XSNotationDeclaration: Constructors and Destructors // --------------------------------------------------------------------------- XSNotationDeclaration::XSNotationDeclaration ( XMLNotationDecl* const xmlNotationDecl , XSAnnotation* const annot , XSModel* const xsModel , MemoryManager * const manager ) : XSObject(XSConstants::NOTATION_DECLARATION, xsModel, manager) , fXMLNotationDecl(xmlNotationDecl) , fAnnotation(annot) { } XSNotationDeclaration::~XSNotationDeclaration() { } // --------------------------------------------------------------------------- // XSNotationDeclaration: XSModel virtual methods // --------------------------------------------------------------------------- const XMLCh *XSNotationDeclaration::getName() { return fXMLNotationDecl->getName(); } const XMLCh *XSNotationDeclaration::getNamespace() { return fXSModel->getURIStringPool()->getValueForId(fXMLNotationDecl->getNameSpaceId()); } XSNamespaceItem *XSNotationDeclaration::getNamespaceItem() { return fXSModel->getNamespaceItem(getNamespace()); } // --------------------------------------------------------------------------- // XSNotationDeclaration: access methods // --------------------------------------------------------------------------- const XMLCh *XSNotationDeclaration::getSystemId() { return fXMLNotationDecl->getSystemId(); } const XMLCh *XSNotationDeclaration::getPublicId() { return fXMLNotationDecl->getPublicId(); } XERCES_CPP_NAMESPACE_END
[ [ [ 1, 111 ] ] ]
23e96a04e0c1cf470312de4650582ba0890c74d1
65c92f6c171a0565fe5275ecc48033907090d69d
/Client/Plugins/Attendance/Implementation/AddAttendance.cpp
19c1a874b0588393a228f2207e9e08808739ae2a
[]
no_license
freakyzoidberg/horus-edu
653ac573887d83a803ddff1881924ab82b46f5f6
2757766a6cb8c1f1a1b0a8e209700e6e3ccea6bc
refs/heads/master
2020-05-20T03:08:15.276939
2010-01-07T14:34:51
2010-01-07T14:34:51
32,684,226
0
0
null
null
null
null
UTF-8
C++
false
false
13,031
cpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Horus 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 3 of the License, or * * (at your option) any later version. * * * * Horus 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 Horus. If not, see <http://www.gnu.org/licenses/>. * * * * The orginal content of this material was realized as part of * * 'Epitech Innovative Project' www.epitech.eu * * * * You are required to preserve the names of the original authors * * of this content in every copy of this material * * * * Authors : * * - BERTHOLON Romain * * - GRANDEMANGE Adrien * * - LACAVE Pierre * * - LEON-BONNET Valentin * * - NANOUCHE Abderrahmane * * - THORAVAL Gildas * * - VIDAL Jeremy * * * * You are also invited but not required to send a mail to the original * * authors of this content in case of modification of this material * * * * Contact: [email protected] * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include "AddAttendance.h" AddAttendance::AddAttendance(QWidget *parent, TreeData *tree, UserData *_user, ScheduleDataPlugin *event, AttendanceDataPlugin *attendanceDataPlugin) { user = _user; _scheduleDataPlugin = event; _attendanceDataPlugin = attendanceDataPlugin; node = tree; cours = 0; setupUi(); //connect(dateAttendance, SIGNAL(dateChanged(const QDate &)), this, SLOT(dChanged(const QDate &))); //connect(allCourse, SIGNAL(stateChanged(int)), this, SLOT(allChecked(int))); //fillCourse(event); proxyModel = new QSortFilterProxyModel(); //userList->setModel(new UserPerClass(user->allDatas(), -10, this)); } void AddAttendance::fillCourse(ScheduleDataPlugin *event) { // courList.append(new CourPanel("Mathematiques")); // courList.append(new CourPanel("Physique")); // courList.append(new CourPanel("Histoire")); // courList.append(new CourPanel("Anglais")); // // for (int i = 0; i < courList.size(); i++) // { // rightSide->addWidget(courList.at(i), i + 1, 0); // } // absLayout->addLayout(rightSide); // absLayout->setAlignment(rightSide, Qt::AlignTop); // absLayout->setStretch(0, 1); // absLayout->setStretch(1, 3); // rightSide->addLayout(buttonLayout->layout(), 5, 0); } void AddAttendance::setupUi() { QBoxLayout *mainLayout; QBoxLayout *leftLayout; QBoxLayout *rightLayout; QBoxLayout *informationsLayout; QScrollArea *scrollArea; QFrame *informationsFrame; QLabel *informationsTitle; QLabel *actionsTitle; QPushButton *applyButton; QPushButton *okButton; QPushButton *resetButton; QPushButton *cancelButton; QWidget *scrollWidget; mainLayout = new QBoxLayout(QBoxLayout::LeftToRight, this); mainLayout->setSpacing(0); mainLayout->setMargin(2); scrollArea = new QScrollArea(this); scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scrollArea->setWidgetResizable(true); scrollWidget = new QWidget(this); leftLayout = new QBoxLayout(QBoxLayout::TopToBottom, scrollWidget); leftLayout->setSpacing(0); leftLayout->setMargin(0); leftLayout->addWidget(getLessonsFrame()); leftLayout->addWidget(new QWidget(scrollWidget), 1); // leftLayout->addWidget(new CourPanel(_scheduleDataPlugin->schedule(node), dateAttendance->date())); scrollArea->setWidget(scrollWidget); mainLayout->addWidget(scrollArea); rightLayout = new QBoxLayout(QBoxLayout::TopToBottom); rightLayout->setMargin(0); rightLayout->setSpacing(2); informationsFrame = new QFrame(this); informationsLayout = new QBoxLayout(QBoxLayout::TopToBottom, informationsFrame); informationsLayout->setSpacing(0); informationsLayout->setMargin(0); informationsFrame->setMinimumWidth(200); informationsTitle = new QLabel(tr("Informations:"), informationsFrame); informationsTitle->setProperty("isTitle", true); informationsTitle->setProperty("isRound", true); informationsLayout->addWidget(informationsTitle); rightLayout->addWidget(informationsFrame); actionsTitle = new QLabel(tr("Actions:"), this); actionsTitle->setProperty("isTitle", true); actionsTitle->setProperty("isRound", true); rightLayout->addWidget(actionsTitle); okButton = new QPushButton(QIcon(":/Icons/ok.png"), tr("OK"), this); rightLayout->addWidget(okButton); applyButton = new QPushButton(QIcon(":/Icons/save.png"), tr("Apply"), this); rightLayout->addWidget(applyButton); resetButton = new QPushButton(QIcon(":/Icons/reset.png"), tr("Reset"), this); rightLayout->addWidget(resetButton); cancelButton = new QPushButton(QIcon(":/Icons/back.png"), tr("Cancel"), this); rightLayout->addWidget(cancelButton); rightLayout->addWidget(new QWidget(this), 1); mainLayout->addLayout(rightLayout); connect(okButton, SIGNAL(clicked()), this, SLOT(saved())); connect(okButton, SIGNAL(clicked()), this, SLOT(exited())); connect(applyButton, SIGNAL(clicked()), this, SLOT(saved())); connect(resetButton, SIGNAL(clicked()), this, SLOT(reseted())); connect(cancelButton, SIGNAL(clicked()), this, SLOT(exited())); // absLayout = new QHBoxLayout(this); // rightSide = new QGridLayout(); // leftSide = new QVBoxLayout(); // buttonLayout = new QHBoxLayout(); // userName = new QLineEdit(); // leftSide->addWidget(userName); // classList = new QComboBox(); // leftSide->addWidget(classList); // userList = new QListView(); // leftSide->addWidget(userList); // absLayout->addLayout(leftSide); // dateAttendance = new QDateEdit(); // dateAttendance->setMaximumSize(100, 30); // dateAttendance->setDate(QDate::currentDate()); // rightSide->addWidget(dateAttendance); // rightSide->setSpacing(0); // allCourse = new QCheckBox(tr("Check All")); // okButton = new QPushButton(tr("Valider")); // buttonLayout->addWidget(allCourse); // buttonLayout->addWidget(okButton); } QWidget *AddAttendance::getLessonsFrame() { QLabel *label; lessonFrame = new QFrame(); lessonFrame->setProperty("isFormFrame", true); lessonMainLayout = new QBoxLayout(QBoxLayout::TopToBottom, lessonFrame); lessonMainLayout->setSpacing(0); lessonMainLayout->setMargin(0); lessonTitle = new QLabel(tr("Absence informations"), lessonFrame); lessonTitle->setProperty("isFormTitle", true); lessonMainLayout->addWidget(lessonTitle); lessonBottomLayout = new QGridLayout(); lessonBottomLayout->setSpacing(4); lessonBottomLayout->setMargin(8); lessonBottomLayout->setColumnMinimumWidth(0, 150); label = new QLabel(tr("Last name"), lessonFrame); label->setProperty("isFormLabel", true); lessonBottomLayout->addWidget(label, 0, 0); QLineEdit *lastNameField = new QLineEdit(lessonFrame); lastNameField->setText(user->name()); lastNameField->setDisabled(true); lessonBottomLayout->addWidget(lastNameField, 0, 1); label = new QLabel(tr("First name"), lessonFrame); label->setProperty("isFormLabel", true); lessonBottomLayout->addWidget(label, 0, 2); QLineEdit *firstNameField = new QLineEdit(user->surname(), lessonFrame); firstNameField->setText(user->surname()); firstNameField->setDisabled(true); lessonBottomLayout->addWidget(firstNameField, 0, 3); label = new QLabel(tr("Date"), lessonFrame); label->setProperty("isFormLabel", true); lessonBottomLayout->addWidget(label, 1, 0); dateAttendance = new QDateEdit(lessonFrame); dateAttendance->setDate(QDate::currentDate()); dateAttendance->setCalendarPopup(true); connect(dateAttendance, SIGNAL(dateChanged(const QDate &)), this, SLOT(dChanged(const QDate &))); lessonBottomLayout->addWidget(dateAttendance, 1, 1); label = new QLabel(tr("Type"), lessonFrame); label->setProperty("isFormLabel", true); lessonBottomLayout->addWidget(label, 1, 2); typeList = new QComboBox(lessonFrame); typeList->addItem(tr("Absence"), 1); typeList->addItem(tr("Retard"), 2); lessonBottomLayout->addWidget(typeList, 1, 3); // lessonBottomLayout->addWidget(firstNameField, 0, 3); // label = new QLabel(tr("Birth date"), lessonFrame); // label->setProperty("isFormLabel", true); // lessonBottomLayout->addWidget(label, 1, 0); // birthDateField = new QDateEdit(lessonFrame); // birthDateField->setDate(QDate::currentDate()); // birthDateField->setCalendarPopup(true); // birthDateField->setDisplayFormat(tr("dd/MM/yy")); // lessonBottomLayout->addWidget(birthDateField, 1, 1); // label = new QLabel(tr("Birth place"), lessonFrame); // label->setProperty("isFormLabel", true); // lessonBottomLayout->addWidget(label, 1, 2); // birthPlaceField = new QLineEdit(lessonFrame); // completer = new QCompleter(_userDataPlugin->listModel(), this); // completer->setCompletionColumn(4); // completer->setCaseSensitivity(Qt::CaseInsensitive); // birthPlaceField->setCompleter(completer); // lessonBottomLayout->addWidget(birthPlaceField, 1, 3); // label = new QLabel(tr("Gender"), lessonFrame); // label->setProperty("isFormLabel", true); // lessonBottomLayout->addWidget(label, 2, 0); lessonMainLayout->addLayout(lessonBottomLayout); cours = new CourPanel(_scheduleDataPlugin->schedule(node), dateAttendance->date(), _attendanceDataPlugin, user); lessonMainLayout->addWidget(cours); return (lessonFrame); } void AddAttendance::dChanged(const QDate &date) { if (cours != 0) { lessonMainLayout->removeWidget(cours); cours->close(); cours = 0; } cours = new CourPanel(_scheduleDataPlugin->schedule(node), dateAttendance->date() , _attendanceDataPlugin, user); lessonMainLayout->addWidget(cours); } void AddAttendance::allChecked(int state) { // for (int i = 0; i < courList.size(); i++) // { // if (state == 2) // courList[i]->absenceCheck->setChecked(true); // else // courList[i]->absenceCheck->setChecked(false); // } } void AddAttendance::saved() { for (int i = 0; i < cours->lessonList.size(); i++) { if (cours->lessonList.at(i)->state->isChecked() == true) { AttendanceData *a = _attendanceDataPlugin->newAttendance(user, dateAttendance->date(), cours->lessonList.at(i)->name->text()); a->setDate(dateAttendance->date()); a->setLesson(cours->lessonList.at(i)->name->text()); a->setStartTime(cours->lessonList.at(i)->start->time()); a->setEndTime(cours->lessonList.at(i)->end->time()); a->setType(typeList->itemData(typeList->currentIndex()).toInt()); a->create(); } } } void AddAttendance::exited() { emit exit(); } void AddAttendance::reseted() { }
[ "abderman@cb2ab776-01a4-11df-b136-7f7962f7bc17" ]
[ [ [ 1, 284 ] ] ]
03edcc4bfa23ee22f9bc71224b11a6e36340ed2e
d7df4671497eadc8f86567ed2631bcf2cdb1cd74
/MagicBowl/SimpleTimer.h
160385272f01f2b8084f4d197f00a2d1df4ba267
[]
no_license
PSP-Archive/MagicBowl
6081838f014ebc7941896d57b01534c71e4d0ad4
0790e93f8072ea7169b6fcd9f20d1b66e5066c3d
refs/heads/master
2023-06-25T03:33:33.083679
2010-08-29T14:22:14
2010-08-29T14:22:14
388,950,939
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
1,356
h
/* * SimpleTimer.h Provides a simple Timer class * * Copyright (C) 2009 André Borrmann * * 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 3 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, see <http://www.gnu.org/licenses/>. * */ #ifndef CLSIMPLETIMER_H_ #define CLSIMPLETIMER_H_ extern "C"{ #include <pspkernel.h> #include <pspdebug.h> #include <psprtc.h> } class ClSimpleTimer { public: ClSimpleTimer(); virtual ~ClSimpleTimer(); /* * reset delta counter */ void reset(); /* * returns delta seconds since last reset */ float getDeltaSeconds(); /* * was the timer reseted ? * return true if the timer was resetted once */ bool isReset(); protected: u64 lastTick; float tickFrequency; //reciproke off tickFrequ bool reseted; }; #endif /* CLSIMPLETIMER_H_ */
[ "anmabagima@d0c0c054-8719-4030-88c3-0e07ff0e07ca" ]
[ [ [ 1, 54 ] ] ]
154ca0d0b19bee548c550451fa41f176f91aeabb
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/CommonSources/stlStringUtils.h
4565bf991d245294f1e1165d560e3eab97886cb9
[]
no_license
outcast1000/Jaangle
062c7d8d06e058186cb65bdade68a2ad8d5e7e65
18feb537068f1f3be6ecaa8a4b663b917c429e3d
refs/heads/master
2020-04-08T20:04:56.875651
2010-12-25T10:44:38
2010-12-25T10:44:38
19,334,292
3
0
null
null
null
null
UTF-8
C++
false
false
5,289
h
// /* // * // * Copyright (C) 2003-2010 Alexandros Economou // * // * This file is part of Jaangle (http://www.jaangle.com) // * // * 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, 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 GNU Make; see the file COPYING. If not, write to // * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. // * http://www.gnu.org/copyleft/gpl.html // * // */ #ifndef _stlStringUtils_h_ #define _stlStringUtils_h_ #ifndef _STRING_ #include <string> #endif namespace std { typedef basic_string<TCHAR> tstring; } #ifdef _UNITTESTING BOOL TestStlStringUtils(); #endif void trimLeft(std::basic_string<char> &str, const char* delims = " \t\r\n"); void trimLeft(std::basic_string<wchar_t> &str, const wchar_t* delims = L" \t\r\n"); void trimRight(std::basic_string<char> &str, const char* delims = " \t\r\n"); void trimRight(std::basic_string<wchar_t> &str, const wchar_t* delims = L" \t\r\n"); void trim(std::basic_string<char> &str, const char* delims = " \t\r\n"); void trim(std::basic_string<wchar_t> &str, const wchar_t* delims = L" \t\r\n"); //"replace" replaces maxtimes the replacewhat with the replaceWithWhat "target" string //if maxtimes = 0 (default) replaces All 'replacewhat' template<class T> UINT replace(std::basic_string<T>& target, const std::basic_string<T>& replaceWhat, const std::basic_string<T>& replaceWithWhat, UINT maxTimes) { UINT count = 0; while(1) { const int pos = (const int) target.find(replaceWhat); if (pos==-1) break; target.replace(pos,replaceWhat.size(),replaceWithWhat); count++; if (maxTimes == count) break; } return count; } template<class T> UINT replace(std::basic_string<T>& target, const std::basic_string<T>& replaceWhat, const std::basic_string<T>& replaceWithWhat) { return replace(target, replaceWhat, replaceWithWhat, 0); } template<class T> UINT replace(std::basic_string<T>& target, const T* replaceWhat, const T* replaceWithWhat, UINT maxTimes) { UINT replaces = 0; size_t pos = target.find(replaceWhat); const T *eos = replaceWhat; while( *eos++ ) ; size_t lenWhat = (size_t)(eos - replaceWhat - 1); eos = replaceWithWhat; while( *eos++ ) ; size_t lenWithWhat = (size_t)(eos - replaceWithWhat - 1); UINT count = 0; while (pos != std::tstring::npos) { replaces++; target.replace(pos, lenWhat, replaceWithWhat); pos = target.find(replaceWhat, pos + lenWithWhat); count++; if (maxTimes == count) break; } return replaces; } template<class T> UINT replace(std::basic_string<T>& target, const T* replaceWhat, const T* replaceWithWhat) { return replace(target, replaceWhat, replaceWithWhat, 0); } template<class T> INT RemoveEnclosedString(std::basic_string<T>& text, const T* fndStart, const T* fndEnd); BOOL Ansi2Unicode(std::wstring& unicode, const std::string& ansi, UINT winCodePage = CP_ACP); template<class _Elem> INT getToken(std::basic_string<_Elem>& input, INT startPos, std::basic_string<_Elem>& delimiter, std::basic_string<_Elem>& token) { size_t endPos = input.find(delimiter, startPos); if (endPos == std::basic_string<_Elem>::npos) return -1; token = input.substr(startPos, endPos - startPos); return INT (endPos + delimiter.size()); } #ifdef _VECTOR_ //Appends the splits of the "input" param to the results //If the delimiter is not found it appends the whole string //returns the number of splits that it has found //results is not cleared from any previous items template<class _Elem> INT splitString(const std::basic_string<_Elem>& input, const std::basic_string<_Elem>& delimiter, std::vector<std::basic_string<_Elem> >& results, bool includeEmpties = true) { if (input.empty() || delimiter.empty()) return 0; size_t delimSize = delimiter.size(); INT startPos = 0; INT endPos = input.find (delimiter, 0); INT vecSize = results.size(); while(endPos != std::basic_string<_Elem>::npos) { if (startPos == endPos && includeEmpties) results.push_back(std::basic_string<_Elem>()); else results.push_back(input.substr(startPos, endPos - startPos)); startPos = endPos + delimSize; endPos = input.find (delimiter, startPos); } results.push_back(input.substr(startPos)); return results.size() - 1 - vecSize;//Splits } //std::vector<std::tstring> splitString( // std::tstring& input, // const TCHAR seperator); // //std::vector<std::tstring> splitString( // std::tstring& input, // const std::tstring& seperator); #endif #endif
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
[ [ [ 1, 186 ] ] ]
026245734afee1d4a190d450401a061a390e5051
90834e9db9d61688c796d0a30e77dd3acc2a9492
/SauerbratenRemote/src/engine/texture.cpp
350877bd9772e87aeb383a41050057ed6149ede7
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "MIT", "Zlib" ]
permissive
zot/Plexus-original
1a79894797ca209af566bb67f72d6164869d7742
f9c3c66c697066e63ea0509c5ff9a8d6b27e369a
refs/heads/master
2020-09-20T21:51:57.194398
2009-04-21T12:45:19
2009-04-21T12:45:19
224,598,317
0
0
null
null
null
null
UTF-8
C++
false
false
41,122
cpp
// texture.cpp: texture slot management #include "pch.h" #include "engine.h" static inline void reorienttexture(uchar *src, int sw, int sh, int bpp, uchar *dst, bool flipx, bool flipy, bool swapxy, bool normals = false) { int stridex = bpp, stridey = bpp; if(swapxy) stridex *= sh; else stridey *= sw; if(flipx) { dst += (sw-1)*stridex; stridex = -stridex; } if(flipy) { dst += (sh-1)*stridey; stridey = -stridey; } loopi(sh) { uchar *curdst = dst; loopj(sw) { loopk(bpp) curdst[k] = *src++; if(normals) { if(flipx) curdst[0] = 255-curdst[0]; if(flipy) curdst[1] = 255-curdst[1]; if(swapxy) swap(curdst[0], curdst[1]); } curdst += stridex; } dst += stridey; } } SDL_Surface *texreorient(SDL_Surface *s, bool flipx, bool flipy, bool swapxy, int type = TEX_DIFFUSE) { SDL_Surface *d = SDL_CreateRGBSurface(SDL_SWSURFACE, swapxy ? s->h : s->w, swapxy ? s->w : s->h, s->format->BitsPerPixel, s->format->Rmask, s->format->Gmask, s->format->Bmask, s->format->Amask); if(!d) fatal("create surface"); reorienttexture((uchar *)s->pixels, s->w, s->h, s->format->BytesPerPixel, (uchar *)d->pixels, flipx, flipy, swapxy, type==TEX_NORMAL); SDL_FreeSurface(s); return d; } SDL_Surface *texrotate(SDL_Surface *s, int numrots, int type = TEX_DIFFUSE) { // 1..3 rotate through 90..270 degrees, 4 flips X, 5 flips Y if(numrots<1 || numrots>5) return s; return texreorient(s, numrots>=2 && numrots<=4, // flip X on 180/270 degrees numrots<=2 || numrots==5, // flip Y on 90/180 degrees (numrots&5)==1, // swap X/Y on 90/270 degrees type); } SDL_Surface *texoffset(SDL_Surface *s, int xoffset, int yoffset) { xoffset = max(xoffset, 0); xoffset %= s->w; yoffset = max(yoffset, 0); yoffset %= s->h; if(!xoffset && !yoffset) return s; SDL_Surface *d = SDL_CreateRGBSurface(SDL_SWSURFACE, s->w, s->h, s->format->BitsPerPixel, s->format->Rmask, s->format->Gmask, s->format->Bmask, s->format->Amask); if(!d) fatal("create surface"); int depth = s->format->BytesPerPixel; uchar *src = (uchar *)s->pixels; loop(y, s->h) { uchar *dst = (uchar *)d->pixels+((y+yoffset)%d->h)*d->pitch; memcpy(dst+xoffset*depth, src, (s->w-xoffset)*depth); memcpy(dst, src+(s->w-xoffset)*depth, xoffset*depth); src += s->pitch; } SDL_FreeSurface(s); return d; } void texmad(SDL_Surface *s, const vec &mul, const vec &add) { int maxk = min(int(s->format->BytesPerPixel), 3); uchar *src = (uchar *)s->pixels; loopi(s->h*s->w) { loopk(maxk) { float val = src[k]*mul[k] + 255*add[k]; src[k] = uchar(min(max(val, 0.0f), 255.0f)); } src += s->format->BytesPerPixel; } } static SDL_Surface stubsurface; SDL_Surface *texffmask(SDL_Surface *s, int minval) { if(renderpath!=R_FIXEDFUNCTION) return s; if(nomasks || s->format->BytesPerPixel<3) { SDL_FreeSurface(s); return &stubsurface; } bool glow = false, envmap = true; uchar *src = (uchar *)s->pixels; loopi(s->h*s->w) { if(src[1]>minval) glow = true; if(src[2]>minval) { glow = envmap = true; break; } src += s->format->BytesPerPixel; } if(!glow && !envmap) { SDL_FreeSurface(s); return &stubsurface; } SDL_Surface *m = SDL_CreateRGBSurface(SDL_SWSURFACE, s->w, s->h, envmap ? 16 : 8, 0, 0, 0, 0); if(!m) fatal("create surface"); uchar *dst = (uchar *)m->pixels; src = (uchar *)s->pixels; loopi(s->h*s->w) { *dst++ = src[1]; if(envmap) *dst++ = src[2]; src += s->format->BytesPerPixel; } SDL_FreeSurface(s); return m; } void texdup(SDL_Surface *s, int srcchan, int dstchan) { if(srcchan==dstchan || max(srcchan, dstchan) >= s->format->BytesPerPixel) return; uchar *src = (uchar *)s->pixels; loopi(s->h*s->w) { src[dstchan] = src[srcchan]; src += s->format->BytesPerPixel; } } SDL_Surface *texdecal(SDL_Surface *s) { if(renderpath!=R_FIXEDFUNCTION || hasTE) return s; SDL_Surface *m = SDL_CreateRGBSurface(SDL_SWSURFACE, s->w, s->h, 16, 0, 0, 0, 0); if(!m) fatal("create surface"); uchar *dst = (uchar *)m->pixels, *src = (uchar *)s->pixels; loopi(s->h*s->w) { *dst++ = *src; *dst++ = 255 - *src; src += s->format->BytesPerPixel; } SDL_FreeSurface(s); return m; } VAR(hwtexsize, 1, 0, 0); VAR(hwcubetexsize, 1, 0, 0); VAR(hwmaxaniso, 1, 0, 0); VARFP(maxtexsize, 0, 0, 1<<12, initwarning("texture quality", INIT_LOAD)); VARFP(texreduce, 0, 0, 12, initwarning("texture quality", INIT_LOAD)); VARFP(texcompress, 0, 1<<10, 1<<12, initwarning("texture quality", INIT_LOAD)); VARFP(trilinear, 0, 1, 1, initwarning("texture filtering", INIT_LOAD)); VARFP(bilinear, 0, 1, 1, initwarning("texture filtering", INIT_LOAD)); VARFP(aniso, 0, 0, 16, initwarning("texture filtering", INIT_LOAD)); GLenum compressedformat(GLenum format, int w, int h, bool force = false) { #ifdef __APPLE__ #undef GL_COMPRESSED_RGB_S3TC_DXT1_EXT #undef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT #define GL_COMPRESSED_RGB_S3TC_DXT1_EXT GL_COMPRESSED_RGB_ARB #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT GL_COMPRESSED_RGBA_ARB #endif if(hasTC && texcompress && (force || max(w, h) >= texcompress)) switch(format) { case GL_RGB5: case GL_RGB8: case GL_RGB: return GL_COMPRESSED_RGB_S3TC_DXT1_EXT; case GL_RGBA: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; } return format; } int formatsize(GLenum format) { switch(format) { case GL_LUMINANCE: case GL_ALPHA: return 1; case GL_LUMINANCE_ALPHA: return 2; case GL_RGB: return 3; case GL_RGBA: return 4; default: return 4; } } VARFP(hwmipmap, 0, 0, 1, initwarning("texture filtering", INIT_LOAD)); void createtexture(int tnum, int w, int h, void *pixels, int clamp, bool mipit, GLenum component, GLenum subtarget, bool compress, bool filter) { GLenum target = subtarget; switch(subtarget) { case GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB: case GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB: case GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB: case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB: case GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB: case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB: target = GL_TEXTURE_CUBE_MAP_ARB; break; } if(tnum) { glBindTexture(target, tnum); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexParameteri(target, GL_TEXTURE_WRAP_S, clamp&1 ? GL_CLAMP_TO_EDGE : GL_REPEAT); if(target!=GL_TEXTURE_1D) glTexParameteri(target, GL_TEXTURE_WRAP_T, clamp&2 ? GL_CLAMP_TO_EDGE : GL_REPEAT); if(target==GL_TEXTURE_2D && hasAF && min(aniso, hwmaxaniso) > 0) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, min(aniso, hwmaxaniso)); glTexParameteri(target, GL_TEXTURE_MAG_FILTER, filter && bilinear ? GL_LINEAR : GL_NEAREST); glTexParameteri(target, GL_TEXTURE_MIN_FILTER, mipit ? (trilinear ? (bilinear ? GL_LINEAR_MIPMAP_LINEAR : GL_NEAREST_MIPMAP_LINEAR) : (bilinear ? GL_LINEAR_MIPMAP_NEAREST : GL_NEAREST_MIPMAP_NEAREST)) : (filter && bilinear ? GL_LINEAR : GL_NEAREST)); if(hasGM && mipit && pixels) glTexParameteri(target, GL_GENERATE_MIPMAP_SGIS, hwmipmap ? GL_TRUE : GL_FALSE); } GLenum format = component, type = GL_UNSIGNED_BYTE; switch(component) { case GL_FLOAT_RG16_NV: case GL_FLOAT_R32_NV: case GL_RGB16F_ARB: case GL_RGB32F_ARB: format = GL_RGB; type = GL_FLOAT; break; case GL_RGBA16F_ARB: case GL_RGBA32F_ARB: format = GL_RGBA; type = GL_FLOAT; break; case GL_DEPTH_COMPONENT: type = GL_FLOAT; break; case GL_RGB5: case GL_RGB8: case GL_RGB16: format = GL_RGB; break; case GL_RGBA8: case GL_RGBA16: format = GL_RGBA; break; } uchar *scaled = NULL; int hwlimit = target==GL_TEXTURE_CUBE_MAP_ARB ? hwcubetexsize : hwtexsize, sizelimit = mipit && maxtexsize ? min(maxtexsize, hwlimit) : hwlimit; if(pixels && max(w, h) > sizelimit && (!mipit || sizelimit < hwlimit)) { int oldw = w, oldh = h; while(w > sizelimit || h > sizelimit) { w /= 2; h /= 2; } scaled = new uchar[w*h*formatsize(format)]; gluScaleImage(format, oldw, oldh, type, pixels, w, h, type, scaled); pixels = scaled; } if(mipit && pixels) { GLenum compressed = compressedformat(component, w, h, compress); if(target==GL_TEXTURE_1D) { if(hasGM && hwmipmap) glTexImage1D(subtarget, 0, compressed, w, 0, format, type, pixels); else if(gluBuild1DMipmaps(subtarget, compressed, w, format, type, pixels)) { if(compressed==component || gluBuild1DMipmaps(subtarget, component, w, format, type, pixels)) conoutf(CON_ERROR, "could not build mipmaps"); } } else if(hasGM && hwmipmap) glTexImage2D(subtarget, 0, compressed, w, h, 0, format, type, pixels); else if(gluBuild2DMipmaps(subtarget, compressed, w, h, format, type, pixels)) { if(compressed==component || gluBuild2DMipmaps(subtarget, component, w, h, format, type, pixels)) conoutf(CON_ERROR, "could not build mipmaps"); } } else if(target==GL_TEXTURE_1D) glTexImage1D(subtarget, 0, component, w, 0, format, type, pixels); else glTexImage2D(subtarget, 0, component, w, h, 0, format, type, pixels); if(scaled) delete[] scaled; } hashtable<char *, Texture> textures; Texture *notexture = NULL; // used as default, ensured to be loaded static GLenum texformat(int bpp) { switch(bpp) { case 8: return GL_LUMINANCE; case 16: return GL_LUMINANCE_ALPHA; case 24: return GL_RGB; case 32: return GL_RGBA; default: return 0; } } static void resizetexture(int &w, int &h, bool mipit = true, GLenum format = GL_RGB, GLenum target = GL_TEXTURE_2D) { if(mipit) return; int hwlimit = target==GL_TEXTURE_CUBE_MAP_ARB ? hwcubetexsize : hwtexsize, sizelimit = mipit && maxtexsize ? min(maxtexsize, hwlimit) : hwlimit; int w2 = w, h2 = h; if(!hasNP2 && (w&(w-1) || h&(h-1))) { w2 = h2 = 1; while(w2 < w) w2 *= 2; while(h2 < h) h2 *= 2; if(w2 > sizelimit || (w - w2)/2 < (w2 - w)/2) w2 /= 2; if(h2 > sizelimit || (h - h2)/2 < (h2 - h)/2) h2 /= 2; } while(w2 > sizelimit || h2 > sizelimit) { w2 /= 2; h2 /= 2; } w = w2; h = h2; } static Texture *newtexture(Texture *t, const char *rname, SDL_Surface *s, int clamp = 0, bool mipit = true, bool canreduce = false, bool transient = false, bool compress = false) { if(!t) { char *key = newstring(rname); t = &textures[key]; t->name = key; } t->clamp = clamp; t->mipmap = mipit; t->type = s==&stubsurface ? Texture::STUB : (transient ? Texture::TRANSIENT : Texture::IMAGE); if(t->type==Texture::STUB) { t->w = t->h = t->xs = t->ys = t->bpp = 0; return t; } t->bpp = s->format->BitsPerPixel; t->w = t->xs = s->w; t->h = t->ys = s->h; glGenTextures(1, &t->id); if(canreduce) loopi(texreduce) { if(t->w > 1) t->w /= 2; if(t->h > 1) t->h /= 2; } GLenum format = texformat(t->bpp); resizetexture(t->w, t->h, mipit, format); uchar *pixels = (uchar *)s->pixels; if(t->w != t->xs || t->h != t->ys) { if(t->w*t->h > t->xs*t->ys) pixels = new uchar[formatsize(format)*t->w*t->h]; gluScaleImage(format, t->xs, t->ys, GL_UNSIGNED_BYTE, s->pixels, t->w, t->h, GL_UNSIGNED_BYTE, pixels); } createtexture(t->id, t->w, t->h, pixels, clamp, mipit, format, GL_TEXTURE_2D, compress); if(pixels!=s->pixels) delete[] pixels; SDL_FreeSurface(s); return t; } #if SDL_BYTEORDER == SDL_BIG_ENDIAN #define RMASK 0xff000000 #define GMASK 0x00ff0000 #define BMASK 0x0000ff00 #define AMASK 0x000000ff #else #define RMASK 0x000000ff #define GMASK 0x0000ff00 #define BMASK 0x00ff0000 #define AMASK 0xff000000 #endif SDL_Surface *creatergbasurface(SDL_Surface *os) { SDL_Surface *ns = SDL_CreateRGBSurface(SDL_SWSURFACE, os->w, os->h, 32, RMASK, GMASK, BMASK, AMASK); if(!ns) fatal("creatergbsurface"); SDL_BlitSurface(os, NULL, ns, NULL); SDL_FreeSurface(os); return ns; } SDL_Surface *scalesurface(SDL_Surface *os, int w, int h) { SDL_Surface *ns = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, os->format->BitsPerPixel, os->format->Rmask, os->format->Gmask, os->format->Bmask, os->format->Amask); if(!ns) fatal("scalesurface"); gluScaleImage(texformat(os->format->BitsPerPixel), os->w, os->h, GL_UNSIGNED_BYTE, os->pixels, w, h, GL_UNSIGNED_BYTE, ns->pixels); SDL_FreeSurface(os); return ns; } static vec parsevec(const char *arg) { vec v(0, 0, 0); int i = 0; for(; arg[0] && (!i || arg[0]=='/') && i<3; arg += strcspn(arg, "/,><"), i++) { if(i) arg++; v[i] = atof(arg); } if(i==1) v.y = v.z = v.x; return v; } static SDL_Surface *texturedata(const char *tname, Slot::Tex *tex = NULL, bool msg = true, bool *compress = NULL) { const char *cmds = NULL, *file = tname; if(!tname) { if(!tex) return NULL; if(tex->name[0]=='<') { cmds = tex->name; file = strrchr(tex->name, '>'); if(!file) { if(msg) conoutf(CON_ERROR, "could not load texture packages/%s", tex->name); return NULL; } file++; } else file = tex->name; static string pname; s_sprintf(pname)("packages/%s", file); file = path(pname); } else if(tname[0]=='<') { cmds = tname; file = strrchr(tname, '>'); if(!file) { if(msg) conoutf(CON_ERROR, "could not load texture %s", tname); return NULL; } file++; } if(cmds) { if(renderpath==R_FIXEDFUNCTION && !strncmp(cmds, "<noff>", 6)) return &stubsurface; } if(msg) show_out_of_renderloop_progress(0, file); SDL_Surface *s = IMG_Load(findfile(file, "rb")); if(!s) { if(msg) conoutf(CON_ERROR, "could not load texture %s", file); return NULL; } int bpp = s->format->BitsPerPixel; if(!texformat(bpp)) { SDL_FreeSurface(s); conoutf(CON_ERROR, "texture must be 8, 16, 24, or 32 bpp: %s", file); return NULL; } while(cmds) { const char *cmd = NULL, *end = NULL, *arg[3] = { NULL, NULL, NULL }; cmd = &cmds[1]; end = strchr(cmd, '>'); if(!end) break; cmds = strchr(cmd, '<'); size_t len = strcspn(cmd, ":,><"); loopi(3) { arg[i] = strchr(i ? arg[i-1] : cmd, i ? ',' : ':'); if(!arg[i] || arg[i] >= end) arg[i] = ""; else arg[i]++; } if(!strncmp(cmd, "mad", len)) texmad(s, parsevec(arg[0]), parsevec(arg[1])); else if(!strncmp(cmd, "ffcolor", len)) { if(renderpath==R_FIXEDFUNCTION) texmad(s, parsevec(arg[0]), parsevec(arg[1])); } else if(!strncmp(cmd, "ffmask", len)) { s = texffmask(s, atoi(arg[0])); if(s == &stubsurface) return s; } else if(!strncmp(cmd, "dup", len)) texdup(s, atoi(arg[0]), atoi(arg[1])); else if(!strncmp(cmd, "decal", len)) s = texdecal(s); else if(!strncmp(cmd, "offset", len)) s = texoffset(s, atoi(arg[0]), atoi(arg[1])); else if(!strncmp(cmd, "rotate", len)) s = texrotate(s, atoi(arg[0]), tex ? tex->type : 0); else if(!strncmp(cmd, "reorient", len)) s = texreorient(s, atoi(arg[0])>0, atoi(arg[1])>0, atoi(arg[2])>0, tex ? tex->type : TEX_DIFFUSE); else if(!strncmp(cmd, "compress", len)) { if(compress) *compress = true; if(!hasTC) { int scale = atoi(arg[0]); if(scale > 1) s = scalesurface(s, s->w/scale, s->h/scale); } } } return s; } void loadalphamask(Texture *t) { if(t->alphamask || t->bpp!=32) return; SDL_Surface *s = texturedata(t->name, NULL, false); if(!s || !s->format->Amask) { if(s) SDL_FreeSurface(s); return; } uint alpha = s->format->Amask; t->alphamask = new uchar[s->h * ((s->w+7)/8)]; uchar *srcrow = (uchar *)s->pixels, *dst = t->alphamask-1; loop(y, s->h) { uint *src = (uint *)srcrow; loop(x, s->w) { int offset = x%8; if(!offset) *++dst = 0; if(*src & alpha) *dst |= 1<<offset; src++; } srcrow += s->pitch; } SDL_FreeSurface(s); } Texture *textureload(const char *name, int clamp, bool mipit, bool msg) { string tname; s_strcpy(tname, name); Texture *t = textures.access(path(tname)); if(t) return t; bool compress = false; SDL_Surface *s = texturedata(tname, NULL, msg, &compress); return s ? newtexture(NULL, tname, s, clamp, mipit, false, false, compress) : notexture; } void settexture(const char *name, bool clamp) { glBindTexture(GL_TEXTURE_2D, textureload(name, clamp, true, false)->id); } vector<Slot> slots; Slot materialslots[MATF_VOLUME+1]; int curtexnum = 0, curmatslot = -1; void texturereset() { curtexnum = 0; slots.setsize(0); } COMMAND(texturereset, ""); void materialreset() { loopi(MATF_VOLUME+1) materialslots[i].reset(); } COMMAND(materialreset, ""); void texture(char *type, char *name, int *rot, int *xoffset, int *yoffset, float *scale) { if(curtexnum<0 || curtexnum>=0x10000) return; struct { const char *name; int type; } types[] = { {"c", TEX_DIFFUSE}, {"u", TEX_UNKNOWN}, {"d", TEX_DECAL}, {"n", TEX_NORMAL}, {"g", TEX_GLOW}, {"s", TEX_SPEC}, {"z", TEX_DEPTH}, {"e", TEX_ENVMAP} }; int tnum = -1, matslot = findmaterial(type); loopi(sizeof(types)/sizeof(types[0])) if(!strcmp(types[i].name, type)) { tnum = i; break; } if(tnum<0) tnum = atoi(type); if(tnum==TEX_DIFFUSE) { if(matslot>=0) curmatslot = matslot; else { curmatslot = -1; curtexnum++; } } else if(curmatslot>=0) matslot=curmatslot; else if(!curtexnum) return; Slot &s = matslot>=0 ? materialslots[matslot] : (tnum!=TEX_DIFFUSE ? slots.last() : slots.add()); s.loaded = false; s.texmask |= 1<<tnum; if(s.sts.length()>=8) conoutf(CON_WARN, "warning: too many textures in slot %d", curtexnum); Slot::Tex &st = s.sts.add(); st.type = tnum; st.combined = -1; st.t = NULL; s_strcpy(st.name, name); path(st.name); if(tnum==TEX_DIFFUSE) { setslotshader(s); s.rotation = clamp(*rot, 0, 5); s.xoffset = max(*xoffset, 0); s.yoffset = max(*yoffset, 0); s.scale = *scale <= 0 ? 1 : *scale; } } COMMAND(texture, "ssiiif"); void autograss(char *name) { Slot &s = slots.last(); DELETEA(s.autograss); s_sprintfd(pname)("packages/%s", name); s.autograss = newstring(name[0] ? pname : "packages/textures/grass.png"); } COMMAND(autograss, "s"); void texscroll(float *scrollS, float *scrollT) { if(slots.empty()) return; Slot &s = slots.last(); s.scrollS = *scrollS/1000.0f; s.scrollT = *scrollT/1000.0f; } COMMAND(texscroll, "ff"); void texoffset_(int *xoffset, int *yoffset) { if(slots.empty()) return; Slot &s = slots.last(); s.xoffset = max(*xoffset, 0); s.yoffset = max(*yoffset, 0); } COMMANDN(texoffset, texoffset_, "ii"); void texrotate_(int *rot) { if(slots.empty()) return; Slot &s = slots.last(); s.rotation = clamp(*rot, 0, 5); } COMMANDN(texrotate, texrotate_, "i"); void texscale(float *scale) { if(slots.empty()) return; Slot &s = slots.last(); s.scale = *scale <= 0 ? 1 : *scale; } COMMAND(texscale, "f"); static int findtextype(Slot &s, int type, int last = -1) { for(int i = last+1; i<s.sts.length(); i++) if((type&(1<<s.sts[i].type)) && s.sts[i].combined<0) return i; return -1; } #define writetex(t, body) \ { \ uchar *dst = (uchar *)t->pixels; \ loop(y, t->h) loop(x, t->w) \ { \ body; \ dst += t->format->BytesPerPixel; \ } \ } #define sourcetex(s) uchar *src = &((uchar *)s->pixels)[s->format->BytesPerPixel*(y*s->w + x)]; static void addbump(SDL_Surface *c, SDL_Surface *n) { writetex(c, sourcetex(n); loopk(3) dst[k] = int(dst[k])*(int(src[2])*2-255)/255; ); } static void addglow(SDL_Surface *c, SDL_Surface *g, const vec &glowcolor) { writetex(c, sourcetex(g); loopk(3) dst[k] = clamp(int(dst[k]) + int(src[k]*glowcolor[k]), 0, 255); ); } static void blenddecal(SDL_Surface *c, SDL_Surface *d) { writetex(c, sourcetex(d); uchar a = src[3]; loopk(3) dst[k] = (int(src[k])*int(a) + int(dst[k])*int(255-a))/255; ); } static void mergespec(SDL_Surface *c, SDL_Surface *s) { writetex(c, sourcetex(s); dst[3] = (int(src[0]) + int(src[1]) + int(src[2]))/3; ); } static void mergedepth(SDL_Surface *c, SDL_Surface *z) { writetex(c, sourcetex(z); dst[3] = src[0]; ); } static void addname(vector<char> &key, Slot &slot, Slot::Tex &t, bool combined = false, const char *prefix = NULL) { if(combined) key.add('&'); if(prefix) { while(*prefix) key.add(*prefix++); } s_sprintfd(tname)("packages/%s", t.name); for(const char *s = path(tname); *s; key.add(*s++)); } static void texcombine(Slot &s, int index, Slot::Tex &t, bool forceload = false) { if(renderpath==R_FIXEDFUNCTION && t.type!=TEX_DIFFUSE && t.type!=TEX_GLOW && !forceload) { t.t = notexture; return; } vector<char> key; addname(key, s, t); switch(t.type) { case TEX_DIFFUSE: if(renderpath==R_FIXEDFUNCTION) { for(int i = -1; (i = findtextype(s, (1<<TEX_DECAL)|(1<<TEX_NORMAL), i))>=0;) { s.sts[i].combined = index; addname(key, s, s.sts[i], true); } break; } // fall through to shader case case TEX_NORMAL: { if(renderpath==R_FIXEDFUNCTION) break; int i = findtextype(s, t.type==TEX_DIFFUSE ? (1<<TEX_SPEC) : (1<<TEX_DEPTH)); if(i<0) break; s.sts[i].combined = index; addname(key, s, s.sts[i], true); break; } } key.add('\0'); t.t = textures.access(key.getbuf()); if(t.t) return; bool compress = false; SDL_Surface *ts = texturedata(NULL, &t, true, &compress); if(!ts) { t.t = notexture; return; } switch(t.type) { case TEX_DIFFUSE: if(renderpath==R_FIXEDFUNCTION) { loopv(s.sts) { Slot::Tex &b = s.sts[i]; if(b.combined!=index) continue; SDL_Surface *bs = texturedata(NULL, &b); if(!bs) continue; if(bs->w!=ts->w || bs->h!=ts->h) bs = scalesurface(bs, ts->w, ts->h); switch(b.type) { case TEX_DECAL: if(bs->format->BitsPerPixel==32) blenddecal(ts, bs); break; case TEX_NORMAL: addbump(ts, bs); break; } SDL_FreeSurface(bs); } break; } // fall through to shader case case TEX_NORMAL: loopv(s.sts) { Slot::Tex &a = s.sts[i]; if(a.combined!=index) continue; SDL_Surface *as = texturedata(NULL, &a); if(!as) break; if(ts->format->BitsPerPixel!=32) ts = creatergbasurface(ts); if(as->w!=ts->w || as->h!=ts->h) as = scalesurface(as, ts->w, ts->h); switch(a.type) { case TEX_SPEC: mergespec(ts, as); break; case TEX_DEPTH: mergedepth(ts, as); break; } SDL_FreeSurface(as); break; // only one combination } break; } t.t = newtexture(NULL, key.getbuf(), ts, 0, true, true, true, compress); } Slot dummyslot; Slot &lookuptexture(int slot, bool load) { Slot &s = slot<0 && slot>=-MATF_VOLUME ? materialslots[-slot] : (slots.inrange(slot) ? slots[slot] : (slots.empty() ? dummyslot : slots[0])); if(s.loaded || !load) return s; loopv(s.sts) { Slot::Tex &t = s.sts[i]; if(t.combined>=0) continue; switch(t.type) { case TEX_ENVMAP: if(hasCM && (renderpath!=R_FIXEDFUNCTION || (slot<0 && slot>=-MATF_VOLUME))) t.t = cubemapload(t.name); break; default: texcombine(s, i, t, slot<0 && slot>=-MATF_VOLUME); break; } } s.loaded = true; return s; } Shader *lookupshader(int slot) { return slot<0 && slot>=-MATF_VOLUME ? materialslots[-slot].shader : (slots.inrange(slot) ? slots[slot].shader : defaultshader); } Texture *loadthumbnail(Slot &slot) { if(slot.thumbnail) return slot.thumbnail; vector<char> name; addname(name, slot, slot.sts[0], false, "<thumbnail>"); int glow = -1; if(slot.texmask&(1<<TEX_GLOW)) { loopvj(slot.sts) if(slot.sts[j].type==TEX_GLOW) { glow = j; break; } if(glow >= 0) { s_sprintfd(prefix)("<mad:%.2f/%.2f/%.2f>", slot.glowcolor.x, slot.glowcolor.y, slot.glowcolor.z); addname(name, slot, slot.sts[glow], true, prefix); } } name.add('\0'); Texture *t = textures.access(path(name.getbuf())); if(t) slot.thumbnail = t; else { SDL_Surface *s = texturedata(NULL, &slot.sts[0], false), *g = glow >= 0 ? texturedata(NULL, &slot.sts[glow], false) : NULL; if(!s) slot.thumbnail = notexture; else { int xs = s->w, ys = s->h; if(s->w > 64 || s->h > 64) s = scalesurface(s, min(s->w, 64), min(s->h, 64)); if(g) { if(g->w != s->w || g->h != s->h) g = scalesurface(g, s->w, s->h); addglow(s, g, slot.glowcolor); } t = newtexture(NULL, name.getbuf(), s, 0, false, false, true); t->xs = xs; t->ys = ys; slot.thumbnail = t; } if(g) SDL_FreeSurface(g); } return t; } // environment mapped reflections cubemapside cubemapsides[6] = { { GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB, "lf", true, true, true }, { GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB, "rt", false, false, true }, { GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB, "ft", true, false, false }, { GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB, "bk", false, true, false }, { GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB, "dn", false, false, true }, { GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB, "up", false, false, true }, }; GLuint cubemapfromsky(int size) { extern Texture *sky[6]; if(!sky[0]) return 0; int tsize = 0, cmw, cmh; GLint tw[6], th[6]; loopi(6) { glBindTexture(GL_TEXTURE_2D, sky[i]->id); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &tw[i]); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &th[i]); tsize = max(tsize, (int)max(tw[i], th[i])); } cmw = cmh = min(tsize, size); resizetexture(cmw, cmh, true, GL_RGB5, GL_TEXTURE_CUBE_MAP_ARB); GLuint tex; glGenTextures(1, &tex); int bufsize = 3*max(cmw, tsize)*max(cmh, tsize); uchar *pixels = new uchar[2*bufsize], *rpixels = &pixels[bufsize]; loopi(6) { glBindTexture(GL_TEXTURE_2D, sky[i]->id); glPixelStorei(GL_PACK_ALIGNMENT, 1); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels); if(tw[i]!=cmw || th[i]!=cmh) gluScaleImage(GL_RGB, tw[i], th[i], GL_UNSIGNED_BYTE, pixels, cmw, cmh, GL_UNSIGNED_BYTE, pixels); cubemapside &side = cubemapsides[i]; reorienttexture(pixels, cmw, cmh, 3, rpixels, side.flipx, side.flipy, side.swapxy); createtexture(!i ? tex : 0, cmw, cmh, rpixels, 3, true, GL_RGB5, side.target); } delete[] pixels; return tex; } Texture *cubemaploadwildcard(Texture *t, const char *name, bool mipit, bool msg) { if(!hasCM) return NULL; string tname; if(!name) s_strcpy(tname, t->name); else { s_strcpy(tname, name); t = textures.access(path(tname)); if(t) return t; } char *wildcard = strchr(tname, '*'); SDL_Surface *surface[6]; string sname; if(!wildcard) s_strcpy(sname, tname); GLenum format = 0; int tsize = 0; bool compress = false; loopi(6) { if(wildcard) { s_strncpy(sname, tname, wildcard-tname+1); s_strcat(sname, cubemapsides[i].name); s_strcat(sname, wildcard+1); } surface[i] = texturedata(sname, NULL, msg, &compress); if(!surface[i]) { loopj(i) SDL_FreeSurface(surface[j]); return NULL; } if(!format) format = texformat(surface[i]->format->BitsPerPixel); else if(texformat(surface[i]->format->BitsPerPixel)!=format) { if(surface[i] && msg) conoutf(CON_ERROR, "cubemap texture %s doesn't match other sides' format", sname); loopj(i) SDL_FreeSurface(surface[j]); return NULL; } tsize = max(tsize, max(surface[i]->w, surface[i]->h)); } if(name) { char *key = newstring(tname); t = &textures[key]; t->name = key; } t->bpp = surface[0]->format->BitsPerPixel; t->mipmap = mipit; t->clamp = 3; t->type = Texture::CUBEMAP; t->w = t->xs = tsize; t->h = t->ys = tsize; resizetexture(t->w, t->h, mipit, format, GL_TEXTURE_CUBE_MAP_ARB); glGenTextures(1, &t->id); uchar *pixels = NULL; loopi(6) { cubemapside &side = cubemapsides[i]; SDL_Surface *s = texreorient(surface[i], side.flipx, side.flipy, side.swapxy); if(s->w != t->w || s->h != t->h) { if(!pixels) pixels = new uchar[formatsize(format)*t->w*t->h]; gluScaleImage(format, s->w, s->h, GL_UNSIGNED_BYTE, s->pixels, t->w, t->h, GL_UNSIGNED_BYTE, pixels); } createtexture(!i ? t->id : 0, t->w, t->h, s->w != t->w || s->h != t->h ? pixels : s->pixels, 3, mipit, format, side.target, compress); SDL_FreeSurface(s); } if(pixels) delete[] pixels; return t; } Texture *cubemapload(const char *name, bool mipit, bool msg) { if(!hasCM) return NULL; string pname; s_strcpy(pname, makerelpath("packages", name)); path(pname); Texture *t = NULL; if(!strchr(pname, '*')) { s_sprintfd(jpgname)("%s_*.jpg", pname); t = cubemaploadwildcard(NULL, jpgname, mipit, false); if(!t) { s_sprintfd(pngname)("%s_*.png", pname); t = cubemaploadwildcard(NULL, pngname, mipit, false); if(!t && msg) conoutf(CON_ERROR, "could not load envmap %s", name); } } else t = cubemaploadwildcard(NULL, pname, mipit, msg); return t; } VARFP(envmapsize, 4, 7, 9, setupmaterials()); VAR(envmapradius, 0, 128, 10000); struct envmap { int radius, size; vec o; GLuint tex; }; static vector<envmap> envmaps; static GLuint skyenvmap = 0; void clearenvmaps() { if(skyenvmap) { glDeleteTextures(1, &skyenvmap); skyenvmap = 0; } loopv(envmaps) glDeleteTextures(1, &envmaps[i].tex); envmaps.setsize(0); } VAR(aaenvmap, 0, 2, 4); GLuint genenvmap(const vec &o, int envmapsize) { int rendersize = 1<<(envmapsize+aaenvmap), sizelimit = min(hwcubetexsize, min(screen->w, screen->h)); if(maxtexsize) sizelimit = min(sizelimit, maxtexsize); while(rendersize > sizelimit) rendersize /= 2; int texsize = min(rendersize, 1<<envmapsize); if(!aaenvmap) rendersize = texsize; GLuint tex; glGenTextures(1, &tex); glViewport(0, 0, rendersize, rendersize); glPixelStorei(GL_PACK_ALIGNMENT, 1); float yaw = 0, pitch = 0; uchar *pixels = new uchar[3*rendersize*rendersize]; loopi(6) { const cubemapside &side = cubemapsides[i]; switch(side.target) { case GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB: // lf yaw = 270; pitch = 0; break; case GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB: // rt yaw = 90; pitch = 0; break; case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB: // ft yaw = 0; pitch = 0; break; case GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB: // bk yaw = 180; pitch = 0; break; case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB: // dn yaw = 90; pitch = -90; break; case GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB: // up yaw = 90; pitch = 90; break; } glFrontFace((side.flipx==side.flipy)!=side.swapxy ? GL_CCW : GL_CW); drawcubemap(rendersize, o, yaw, pitch, side); glReadPixels(0, 0, rendersize, rendersize, GL_RGB, GL_UNSIGNED_BYTE, pixels); if(texsize<rendersize) gluScaleImage(GL_RGB, rendersize, rendersize, GL_UNSIGNED_BYTE, pixels, texsize, texsize, GL_UNSIGNED_BYTE, pixels); createtexture(tex, texsize, texsize, pixels, 3, true, GL_RGB5, side.target); } glFrontFace(GL_CCW); delete[] pixels; glViewport(0, 0, screen->w, screen->h); clientkeepalive(); return tex; } void initenvmaps() { if(!hasCM) return; clearenvmaps(); skyenvmap = cubemapfromsky(1<<envmapsize); const vector<extentity *> &ents = et->getents(); loopv(ents) { const extentity &ent = *ents[i]; if(ent.type != ET_ENVMAP) continue; envmap &em = envmaps.add(); em.radius = ent.attr1 ? max(0, min(10000, int(ent.attr1))) : envmapradius; em.size = ent.attr2 ? max(4, min(9, int(ent.attr2))) : 0; em.o = ent.o; em.tex = 0; } } void genenvmaps() { if(envmaps.empty()) return; show_out_of_renderloop_progress(0, "generating environment maps..."); loopv(envmaps) { envmap &em = envmaps[i]; em.tex = genenvmap(em.o, em.size ? em.size : envmapsize); } } ushort closestenvmap(const vec &o) { ushort minemid = EMID_SKY; float mindist = 1e16f; loopv(envmaps) { envmap &em = envmaps[i]; float dist = em.o.dist(o); if(dist < em.radius && dist < mindist) { minemid = EMID_RESERVED + i; mindist = dist; } } return minemid; } ushort closestenvmap(int orient, int x, int y, int z, int size) { vec loc(x, y, z); int dim = dimension(orient); if(dimcoord(orient)) loc[dim] += size; loc[R[dim]] += size/2; loc[C[dim]] += size/2; return closestenvmap(loc); } GLuint lookupenvmap(Slot &slot) { loopv(slot.sts) if(slot.sts[i].type==TEX_ENVMAP && slot.sts[i].t) return slot.sts[i].t->id; return skyenvmap; } GLuint lookupenvmap(ushort emid) { if(emid==EMID_SKY || emid==EMID_CUSTOM) return skyenvmap; if(emid==EMID_NONE || !envmaps.inrange(emid-EMID_RESERVED)) return 0; GLuint tex = envmaps[emid-EMID_RESERVED].tex; return tex ? tex : skyenvmap; } void writetgaheader(FILE *f, SDL_Surface *s, int bits) { fwrite("\0\0\x02\0\0\0\0\0\0\0\0\0", 1, 12, f); ushort dim[] = { s->w, s->h }; endianswap(dim, sizeof(ushort), 2); fwrite(dim, sizeof(short), 2, f); fputc(bits, f); fputc(0, f); } void flipnormalmapy(char *destfile, char *normalfile) // RGB (jpg/png) -> BGR (tga) { SDL_Surface *ns = IMG_Load(findfile(path(normalfile), "rb")); if(!ns) return; FILE *f = openfile(path(destfile), "wb"); if(f) { writetgaheader(f, ns, 24); for(int y = ns->h-1; y>=0; y--) loop(x, ns->w) { uchar *nd = (uchar *)ns->pixels+(x+y*ns->w)*3; fputc(nd[2], f); fputc(255-nd[1], f); fputc(nd[0], f); } fclose(f); } if(ns) SDL_FreeSurface(ns); } void mergenormalmaps(char *heightfile, char *normalfile) // BGR (tga) -> BGR (tga) (SDL loads TGA as BGR!) { SDL_Surface *hs = IMG_Load(findfile(path(heightfile), "rb")); SDL_Surface *ns = IMG_Load(findfile(path(normalfile), "rb")); if(hs && ns) { uchar def_n[] = { 255, 128, 128 }; FILE *f = openfile(normalfile, "wb"); if(f) { writetgaheader(f, ns, 24); for(int y = ns->h-1; y>=0; y--) loop(x, ns->w) { int off = (x+y*ns->w)*3; uchar *hd = hs ? (uchar *)hs->pixels+off : def_n; uchar *nd = ns ? (uchar *)ns->pixels+off : def_n; #define S(x) x/255.0f*2-1 vec n(S(nd[0]), S(nd[1]), S(nd[2])); vec h(S(hd[0]), S(hd[1]), S(hd[2])); n.mul(2).add(h).normalize().add(1).div(2).mul(255); uchar o[3] = { (uchar)n.x, (uchar)n.y, (uchar)n.z }; fwrite(o, 3, 1, f); #undef S } fclose(f); } } if(hs) SDL_FreeSurface(hs); if(ns) SDL_FreeSurface(ns); } COMMAND(flipnormalmapy, "ss"); COMMAND(mergenormalmaps, "sss"); void cleanuptextures() { clearenvmaps(); loopv(slots) slots[i].cleanup(); loopi(MATF_VOLUME+1) materialslots[i].cleanup(); vector<Texture *> transient; enumerate(textures, Texture, tex, DELETEA(tex.alphamask); if(tex.id) { glDeleteTextures(1, &tex.id); tex.id = 0; } if(tex.type==Texture::TRANSIENT) transient.add(&tex); ); loopv(transient) textures.remove(transient[i]->name); } bool reloadtexture(const char *name) { Texture *t = textures.access(path(name, true)); if(t) return reloadtexture(*t); return false; } bool reloadtexture(Texture &tex) { if(tex.id) return true; switch(tex.type) { case Texture::STUB: case Texture::IMAGE: { bool compress = false; SDL_Surface *s = texturedata(tex.name, NULL, true, &compress); if(!s || !newtexture(&tex, NULL, s, tex.clamp, tex.mipmap, false, false, compress)) return false; break; } case Texture::CUBEMAP: if(!cubemaploadwildcard(&tex, NULL, tex.mipmap, true)) return false; break; } return true; } void reloadtex(char *name) { Texture *t = textures.access(path(name, true)); if(!t) { conoutf("texture %s is not loaded", name); return; } if(t->type==Texture::TRANSIENT) { conoutf("can't reload transient texture %s", name); return; } DELETEA(t->alphamask); Texture oldtex = *t; t->id = 0; if(!reloadtexture(*t)) { if(t->id) glDeleteTextures(1, &t->id); *t = oldtex; conoutf("failed to reload texture %s", name); } } COMMAND(reloadtex, "s"); void reloadtextures() { enumerate(textures, Texture, tex, reloadtexture(tex)); }
[ "bill@sheba.(none)" ]
[ [ [ 1, 1259 ] ] ]
5a135326728da983f30788977809eb520c81780e
0f40e36dc65b58cc3c04022cf215c77ae31965a8
/src/apps/vis/elements/vis_drawable_edge_dynamic.cpp
6ad13d0ee896512f87d2a0daec62e1861d1cd3ce
[ "MIT", "BSD-3-Clause" ]
permissive
venkatarajasekhar/shawn-1
08e6cd4cf9f39a8962c1514aa17b294565e849f8
d36c90dd88f8460e89731c873bb71fb97da85e82
refs/heads/master
2020-06-26T18:19:01.247491
2010-10-26T17:40:48
2010-10-26T17:40:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,630
cpp
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004,2005 by SwarmNet (www.swarmnet.de) ** ** and SWARMS (www.swarms.de) ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the GNU General Public License, version 2. ** ************************************************************************/ #include "../buildfiles/_apps_enable_cmake.h" #ifdef ENABLE_VIS #include "apps/vis/elements/vis_drawable_edge_dynamic.h" #ifdef HAVE_BOOST_REGEX #include <boost/regex.hpp> #endif namespace vis { const std::string DrawableEdgeDynamic::PREFIX("dynamic"); // ---------------------------------------------------------------------- DrawableEdgeDynamic:: DrawableEdgeDynamic( const shawn::Node& v1, const shawn::Node& v2, const std::string& p, const std::string& np, const std::string source_regex, const std::string target_regex) : DrawableEdge( std::string("edge.") + p, v1, v2 ), props_ ( NULL ), node_prefix (np), source_regex_(source_regex), target_regex_(target_regex) {} // ---------------------------------------------------------------------- DrawableEdgeDynamic:: ~DrawableEdgeDynamic() {} // ---------------------------------------------------------------------- void DrawableEdgeDynamic:: init( void ) throw() { props_ = new EdgePropertySet; props_->init(*this); DrawableEdge::init(); } // ---------------------------------------------------------------------- void DrawableEdgeDynamic:: draw( cairo_t* cr, double t, const Context& C ) const throw(std::runtime_error) { Drawable::draw(cr,t,C); if( visible() ) { double lw = edge_properties().line_width(t); shawn::Vec col = edge_properties().color(t); double blend = edge_properties().blend(t); cairo_save(cr); cairo_set_line_width( cr, lw ); cairo_set_source_rgba(cr,col.x(),col.y(),col.z(),1.0-blend); // Create all edges: #ifndef HAVE_BOOST_REGEX for( shawn::World::const_node_iterator it = visualization().world().begin_nodes(), endit = visualization().world().end_nodes(); it != endit; ++it ) { for( shawn::Node::const_adjacency_iterator ait = it->begin_adjacent_nodes(), endait = it->end_adjacent_nodes(); ait != endait; ++ait ) { if( *it != *ait && (ait->label() > it->label()) ) { const DrawableNode* dsrc = drawable_node(*it,DrawableNodeDefault::PREFIX); const DrawableNode* dtgt = drawable_node(*ait,DrawableNodeDefault::PREFIX); shawn::Vec pos1 = dsrc->position(t); shawn::Vec pos2 = dtgt->position(t); cairo_move_to(cr,pos1.x(),pos1.y()); cairo_line_to(cr,pos2.x(),pos2.y()); cairo_stroke(cr); } } } #else boost::regex sources(source_regex_); boost::regex targets(target_regex_); std::cout << source_regex_ << std::endl; for( shawn::World::const_node_iterator it = visualization().world().begin_nodes(), endit = visualization().world().end_nodes(); it != endit; ++it ) { if( boost::regex_search(it->label(),sources)) { for( shawn::Node::const_adjacency_iterator ait = it->begin_adjacent_nodes(), endait = it->end_adjacent_nodes(); ait != endait; ++ait ) if( *it != *ait ) if( boost::regex_search(ait->label(),targets) ) if( (ait->label() > it->label()) || (!boost::regex_search(it->label(),targets)) || (!boost::regex_search(ait->label(),sources)) ) { const DrawableNode* dsrc = drawable_node(*it,DrawableNodeDefault::PREFIX); const DrawableNode* dtgt = drawable_node(*ait,DrawableNodeDefault::PREFIX); shawn::Vec pos1 = dsrc->position(t); shawn::Vec pos2 = dtgt->position(t); cairo_move_to(cr,pos1.x(),pos1.y()); cairo_line_to(cr,pos2.x(),pos2.y()); cairo_stroke(cr); } } } #endif cairo_restore(cr); } } // ---------------------------------------------------------------------- const PropertySet& DrawableEdgeDynamic:: properties( void ) const throw() { assert( props_.is_not_null() ); return *props_; } // ---------------------------------------------------------------------- PropertySet& DrawableEdgeDynamic:: properties_w( void ) throw() { assert( props_.is_not_null() ); return *props_; } // ---------------------------------------------------------------------- const DrawableNode* DrawableEdgeDynamic:: drawable_node( const shawn::Node& v, const std::string& nprefix ) const throw( std::runtime_error ) { std::string n = nprefix+std::string(".")+v.label(); ConstElementHandle eh = visualization().element( n ); if( eh.is_null() ) throw std::runtime_error(std::string("no such element: ")+n); const DrawableNode* dn = dynamic_cast<const DrawableNode*>(eh.get()); if( dn == NULL ) throw std::runtime_error(std::string("element is no DrawableNode: ")+n); return dn; } } #endif
[ [ [ 1, 172 ] ] ]
866ac21ff724358394f564073afc967ff4ef17e1
335783c9e5837a1b626073d1288b492f9f6b057f
/source/fbxcmd/daolib/stdafx.h
81f664a96aed806b8a552ce8dbb3aaa280842e9f
[ "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
739
h
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once // _WIN32 will detect windows on most compilers #include <stdio.h> #include <tchar.h> #include <string.h> #include <iomanip> #include <iostream> #include <vector> #include <map> #include <set> #include <cmath> #include <algorithm> #include <stdexcept> #include <exception> #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <shlwapi.h> extern "C" { #include "win32config.h" #include <libxml/xmlmemory.h> #include <libxml/encoding.h> #include <libxml/xmlwriter.h> #include <libxml/parser.h> }; //#include "common.h"
[ "tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792" ]
[ [ [ 1, 38 ] ] ]
4394648f8703a28fe101c3fb92b4a32d7d960b91
de98f880e307627d5ce93dcad1397bd4813751dd
/3libs/ut/include/EVNTLOG.h
430d7b7302637e5f569778904d58667eb33d7c33
[]
no_license
weimingtom/sls
7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8
d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd
refs/heads/master
2021-01-10T22:20:55.638757
2011-03-19T06:23:49
2011-03-19T06:23:49
44,464,621
2
0
null
null
null
null
WINDOWS-1252
C++
false
false
13,290
h
// ========================================================================== // Class Specification : COXEventLog // ========================================================================== // Header file : evntlog.h // Version: 9.3 // This software along with its related components, documentation and files ("The Libraries") // is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is // governed by a software license agreement ("Agreement"). Copies of the Agreement are // available at The Code Project (www.codeproject.com), as part of the package you downloaded // to obtain this file, or directly from our office. For a copy of the license governing // this software, you may contact us at [email protected], or by calling 416-849-8900. // Creation Date : 27 November 1995 // Last Modification : 27 November 1995 // ////////////////////////////////////////////////////////////////////////// // Properties: // NO Abstract class (does not have any objects) // YES Derived from CObject // NO Is a Cwnd. // NO Two stage creation (constructor & Create()) // NO Has a message map // NO Needs a resource (template) // NO Persistent objects (saveable on disk) // NO Uses exceptions // ////////////////////////////////////////////////////////////////////////// // Desciption : // This class makes the reading and writing to the eventlog of // Windows NT very easy // Remark: // Prerequisites (necessary conditions): // *** ///////////////////////////////////////////////////////////////////////////// #ifndef __EVENT_LOG_H__ #define __EVENT_LOG_H__ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include "OXDllExt.h" enum EventType { eventError = EVENTLOG_ERROR_TYPE, eventWarning = EVENTLOG_WARNING_TYPE, eventInformation = EVENTLOG_INFORMATION_TYPE, eventSuccess = EVENTLOG_AUDIT_SUCCESS, eventFailure = EVENTLOG_AUDIT_FAILURE }; class OX_CLASS_DECL COXEventLog : public CObject { DECLARE_DYNAMIC(COXEventLog) // Data members ------------------------------------------------------------- public: CString m_sComputerName; CString m_sLogName; protected: HANDLE m_LogHandle; HANDLE m_EventSourceHandle; DWORD m_ErrorCode; DWORD m_NumberOfBytesRead; DWORD m_NumberOfBytesInNextRecord; private: // Member functions --------------------------------------------------------- public: COXEventLog(); // --- In : // --- Out : // --- Returns : // --- Effect : Contructor of object // It will initialize the internal state COXEventLog(LPCTSTR pszSourceName); // --- In : pszSourceName : Points to a null-terminated string that // specifies the name of the source referenced by the returned // handle. The source name must be a subkey of a logfile entry // under the EventLog key in the registry. For example, the source // name WinApp would be valid if the registry had the following form: // HKEY_LOCAL_MACHINE // System // CurrentControlSet // Services // EventLog // Application // WinApp // Security // System // If the source name cannot be found, the event logging service uses // the Application logfile with no message files for the event // identifier or category. // --- Out : // --- Returns : // --- Effect : Contructor of object // It will initialize the internal state virtual BOOL Backup(LPCTSTR pszNameOfBackupFile); // --- In : pszNameOfBackupFile : Points to a null-terminated string that names // the backup file. The backup filename may contain a server // name to save the backup file on a remote server. // --- Out : // --- Returns : succeeded or not // --- Effect : saves the specified event log to a backup file. The function // does not clear the event log. virtual BOOL Clear(LPCTSTR pszNameOfBackupFile); // --- In : pszNameOfBackupFile : Points to the null-terminated string specifying // the name of a file in which a current copy of the event logfile // will be placed. If this file already exists, the function fails. // The backup filename may contain a server name to save the // backup file on a remote server. If the lpBackupFileName parameter // is NULL, the current event logfile is not backed up. // --- Out : // --- Returns : succeeded or not // --- Effect : The ClearEventLog function clears the event log, // and if name_of_backup_file is not NULL, saves the current copy // of the logfile to a backup file. virtual BOOL Close(); // --- In : // --- Out : // --- Returns : succeeded or not // --- Effect : Closes the event log virtual BOOL CreateApplicationLog(LPCTSTR pszApplicationName, LPCTSTR pszFileContainingMessageTableResource, DWORD dwSupportedTypes); // --- In : pszApplicationName : name of the subkey toi create in the registry // pszFileContainingMessageTableResource : value of the subkey // dwSupportedTypes : types supported // --- Out : // --- Returns : succeeded or not // --- Effect : Creates a log entry in the registry for an application with // name application_name and value the name file_containing_message_table_resource virtual BOOL DeleteApplicationLog(LPCTSTR pszApplicationName); // --- In : application_name : subkey to delete // --- Out : // --- Returns : succeeded or not // --- Effect : Removes a log entry out of the registry virtual BOOL DeregisterSource(); // --- In : // --- Out : // --- Returns : succeeded or not // --- Effect : closes registrysource registered by the RegisterSource function. virtual DWORD GetErrorCode() const; // --- In : // --- Out : // --- Returns : the errorcode // --- Effect : Returns the last error that occurred when executing the last command virtual BOOL GetNumberOfRecords(DWORD& dwNumberOfRecords); // --- In : // --- Out : dwNumberOfRecords : number of records // --- Returns : succeeded or not // --- Effect : retrieves the number of records in the current event log. virtual BOOL GetNumberOfBytesInNextRecord(DWORD& dwNumberOfBytesInNextRecord); // --- In : // --- Out : dwNumberOfRecords : number of bytes in next record // --- Returns : succeeded or not // --- Effect : retrieves the number of bytes in the next record of the current event log. virtual BOOL NotifyChange(HANDLE hEventHandle, HANDLE hLogHandle = NULL); // --- In : hEventHandle : A handle to a Win32 event. This is the event that becomes // signaled when an event is written to the event log file // specified by log_handle. // hLogHandle : Handle to an event log file // --- Out : // --- Returns : succeeded or not // --- Effect : lets an application receive notification when an event is written // to the event log file specified by log_handle. When the event is // written to the event log file, the function causes the event object // specified by event_handle to become signaled. virtual BOOL OpenBackup(LPCTSTR pszNameOfBackupFile, LPCTSTR pszNameOfComputer = NULL); // --- In : pszNameOfBackupFile : Points to a null-terminated string that specifies // the name of the backup file. The backup filename may contain a server // name to open a backup file on a remote server (in this case, the // lpszUNCServerName parameter must be NULL). // pszNameOfComputer : Points to a null-terminated string that specifies // the Universal Naming Convention (UNC) name of the server on which // this operation is to be performed. If this parameter is NULL, the // operation is performed on the local computer. // --- Out : // --- Returns : succeeded or not // --- Effect : opens a backup event log. virtual BOOL Open(LPCTSTR pszLogName, LPCTSTR pszNameOfComputer = NULL); // --- In : pszLogName : Points to a null-terminated string that specifies the name // of the source that will be opened. The source // name must be a subkey of a logfile entry under the EventLog key in // the registry. For example, the source name WinApp would be valid if // the registry had the following form: // HKEY_LOCAL_MACHINE // System // CurrentControlSet // Services // EventLog // Application // WinApp // Security // System // // If the source name cannot be found, the event logging service uses // the Application logfile with no message files for the event identifier // or category. // pszNameOfComputer : Points to a null-terminated string that specifies // the Universal Naming Convention (UNC) name of the server on which // this operation is to be performed. If this parameter is NULL, the // operation is performed on the local computer. // --- Out : // --- Returns : succeeded or not // --- Effect : opens an event log. virtual BOOL Read(DWORD dwRecordNumber, LPVOID pBuffer, DWORD& dwNumberOfBytesToRead, DWORD dwHowToRead = EVENTLOG_FORWARDS_READ | EVENTLOG_SEQUENTIAL_READ); // --- In : dwRecordNumber : see ::ReadEventLog parameter dwRecordOffset // dwHowToRead : see ::ReadEventLog parameter dwReadFlags // --- Out : pBuffer : see ::ReadEventLog parameter lpBuffer // dwNumberOfBytesToRead : see ::ReadEventLog parameter nNumberOfBytesToRead // --- Returns : succeeded or not // --- Effect : reads a whole number of entries from the specified event log. The // function can be used to read log entries in forward or reverse // chronological order. virtual BOOL RegisterSource(LPCTSTR pszSourceName, LPCTSTR pszNameOfComputer = NULL); // --- In : pszSourceName : Points to a null-terminated string that specifies the name // of the source that will be opened. The source // name must be a subkey of a logfile entry under the EventLog key in // the registry. For example, the source name WinApp would be valid if // the registry had the following form: // HKEY_LOCAL_MACHINE // System // CurrentControlSet // Services // EventLog // Application // WinApp // Security // System // // If the source name cannot be found, the event logging service uses // the Application logfile with no message files for the event identifier // or category. // pszNameOfComputer : Points to a null-terminated string that specifies // the Universal Naming Convention (UNC) name of the server on which // this operation is to be performed. If this parameter is NULL, the // operation is performed on the local computer. // --- Out : // --- Returns : succeeded or not // --- Effect : register source_name with name_of_computer at the eventlog virtual BOOL Report(EventType eEventType, DWORD dwEventIdentifier, WORD wCategory = 0, WORD wNumberOfStrings = 0, LPCTSTR* pszStringArray = NULL, DWORD dwNumberOfRawDataBytes = 0, LPVOID pRawDataBuffer = NULL, PSID pUserSecurityIdentifier = NULL); // --- In : see ::ReportEvent // --- Out : // --- Returns : succeeded or not // --- Effect : writes an entry at the end of the current event log. virtual BOOL Report(LPCTSTR pszLogName, DWORD dwMessageStringResourceID, WORD wNumberOfStrings = 0, LPCTSTR* pszStringArray = NULL); // --- In : see ::ReportEvent // --- Out : // --- Returns : succeeded or not // --- Effect : opens the eventlog, writes an entry at the end of the current // event logand closes it again virtual void ReportError(LPCTSTR pszStringToReport); // --- In : pszStringToReport : data to write // --- Out : // --- Returns : succeeded or not // --- Effect : writes an error entry at the end of the current event log. virtual void ReportInformation(LPCTSTR pszStringToReport); // --- In : pszStringToReport : data to write // --- Out : // --- Returns : succeeded or not // --- Effect : writes an info entry at the end of the current event log. #if defined(_DEBUG) virtual void Dump(CDumpContext& dump_context) const; virtual void AssertValid() const; #endif // _DEBUG virtual ~COXEventLog(); // --- In : // --- Out : // --- Returns : // --- Effect : Destructor of object protected: void Initialize(); }; #endif // __EVENT_LOG_H__
[ [ [ 1, 329 ] ] ]
c7be9124d61f3e5accb6e251e7d7cb6e15ec69c7
e02fa80eef98834bf8a042a09d7cb7fe6bf768ba
/TEST_MyGUI_Source/MyGUIEngine/src/MyGUI_List.cpp
a0131ac168d937c5f839f4924bf330dad9de220b
[]
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
22,407
cpp
/*! @file @author Albert Semenov @date 11/2007 @module */ #include "MyGUI_Prerequest.h" #include "MyGUI_Common.h" #include "MyGUI_CastWidget.h" #include "MyGUI_List.h" #include "MyGUI_Button.h" #include "MyGUI_VScroll.h" #include "MyGUI_WidgetOIS.h" #include "MyGUI_WidgetSkinInfo.h" namespace MyGUI { List::List(const IntCoord& _coord, char _align, const WidgetSkinInfoPtr _info, CroppedRectanglePtr _parent, WidgetCreator * _creator, const Ogre::String & _name) : Widget(_coord, _align, _info, _parent, _creator, _name), mWidgetScroll(null), mWidgetClient(null), mTopIndex(0), mOffsetTop(0), mRangeIndex(-1), mLastRedrawLine(0), mIndexSelect(ITEM_NONE), mLineActive(ITEM_NONE), mIsFocus(false), mNeedVisibleScroll(true) { // нам нужен фокус клавы mNeedKeyFocus = true; for (VectorWidgetPtr::iterator iter=mWidgetChild.begin(); iter!=mWidgetChild.end(); ++iter) { if ((*iter)->_getInternalString() == "VScroll") { mWidgetScroll = castWidget<VScroll>(*iter); mWidgetScroll->eventScrollChangePosition = newDelegate(this, &List::notifyScrollChangePosition); mWidgetScroll->eventMouseButtonPressed = newDelegate(this, &List::notifyMousePressed); } else if ((*iter)->_getInternalString() == "Client") { mWidgetClient = (*iter); mWidgetClient->eventMouseButtonPressed = newDelegate(this, &List::notifyMousePressed); } } MYGUI_ASSERT(null != mWidgetScroll, "Child VScroll not found in skin (List must have VScroll)"); MYGUI_ASSERT(null != mWidgetClient, "Child Widget Client not found in skin (List must have Client)"); // парсим свойства const MapString & param = _info->getParams(); MapString::const_iterator iter = param.find("SkinLine"); if (iter != param.end()) mSkinLine = iter->second; MYGUI_ASSERT(false == mSkinLine.empty(), "SkinLine property or skin not found (List must have SkinLine property)"); iter = param.find("HeightLine"); if (iter != param.end()) mHeightLine = utility::parseInt(iter->second); if (mHeightLine < 1) mHeightLine = 1; mWidgetScroll->setScrollPage((size_t)mHeightLine); updateScroll(); updateLine(); } void List::_onMouseWheel(int _rel) { notifyMouseWheel(null, _rel); // !!! ОБЯЗАТЕЛЬНО вызывать в конце метода Widget::_onMouseWheel(_rel); } void List::_onKeySetFocus(WidgetPtr _old) { mIsFocus = true; _updateState(); // !!! ОБЯЗАТЕЛЬНО вызывать в конце метода Widget::_onKeySetFocus(_old); } void List::_onKeyLostFocus(WidgetPtr _new) { mIsFocus = false; _updateState(); // !!! ОБЯЗАТЕЛЬНО вызывать в конце метода Widget::_onKeyLostFocus(_new); } void List::_onKeyButtonPressed(int _key, Char _char) { // очень секретный метод, запатентованный механизм движения курсора if (getItemCount() == 0) { // !!! ОБЯЗАТЕЛЬНО вызывать в конце метода Widget::_onKeyButtonPressed(_key, _char); return; } size_t sel = mIndexSelect; if (_key == OIS::KC_UP) { if (sel != 0) { if (sel == ITEM_NONE) sel = 0; else sel --; } } else if (_key == OIS::KC_DOWN) { if (sel == ITEM_NONE) sel = 0; else sel ++; if (sel >= getItemCount()) { // старое значение sel = mIndexSelect; } } else if (_key == OIS::KC_HOME) { if (sel != 0) sel = 0; } else if (_key == OIS::KC_END) { if (sel != (getItemCount() - 1)) { sel = getItemCount() - 1; } } else if (_key == OIS::KC_PGUP) { if (sel != 0) { if (sel == ITEM_NONE) sel = 0; else { size_t page = mWidgetClient->getHeight() / mHeightLine; if (sel <= page) sel = 0; else sel -= page; } } } else if (_key == OIS::KC_PGDOWN) { if (sel != (getItemCount() - 1)) { if (sel == ITEM_NONE) sel = 0; else { sel += mWidgetClient->getHeight() / mHeightLine; if (sel >= getItemCount()) sel = getItemCount() - 1; } } } else if (_key == OIS::KC_RETURN) { if (sel != ITEM_NONE) { eventListSelectAccept(this); Widget::_onKeyButtonPressed(_key, _char); // выходим, так как изменили колличество строк return; } } if (sel != mIndexSelect) { if ( false == isItemVisible(sel)) { beginToIndex(sel); _sendEventChangeScroll(mWidgetScroll->getScrollPosition()); } setItemSelect(sel); // изменилась позиция eventListChangePosition(this, mIndexSelect); } // !!! ОБЯЗАТЕЛЬНО вызывать в конце метода Widget::_onKeyButtonPressed(_key, _char); } void List::notifyMouseWheel(MyGUI::WidgetPtr _sender, int _rel) { if (mRangeIndex <= 0) return; int offset = (int)mWidgetScroll->getScrollPosition(); if (_rel < 0) offset += mHeightLine; else offset -= mHeightLine; if (offset >= mRangeIndex) offset = mRangeIndex; else if (offset < 0) offset = 0; if ((int)mWidgetScroll->getScrollPosition() == offset) return; mWidgetScroll->setScrollPosition(offset); _setScrollView(offset); _sendEventChangeScroll(offset); } void List::notifyScrollChangePosition(MyGUI::WidgetPtr _sender, size_t _position) { _setScrollView(_position); _sendEventChangeScroll(_position); } void List::notifyMousePressed(MyGUI::WidgetPtr _sender, bool _left) { if (false == _left) return; if (_sender == mWidgetScroll) return; // если выделен клиент, то сбрасываем if (_sender == mWidgetClient) { if (mIndexSelect != ITEM_NONE) { _selectIndex(mIndexSelect, false); mIndexSelect = ITEM_NONE; eventListChangePosition(this, mIndexSelect); } eventListMouseItemActivate(this, mIndexSelect); // если не клиент, то просчитывам } else { size_t index = (size_t)_sender->_getInternalData() + mTopIndex; if (mIndexSelect != index) { _selectIndex(mIndexSelect, false); _selectIndex(index, true); mIndexSelect = index; eventListChangePosition(this, mIndexSelect); } eventListMouseItemActivate(this, mIndexSelect); } } void List::setSize(const IntSize& _size) { Widget::setSize(_size); updateScroll(); updateLine(); } void List::setPosition(const IntCoord& _coord) { Widget::setPosition(_coord); updateScroll(); updateLine(); } void List::updateScroll() { mRangeIndex = (mHeightLine * (int)mStringArray.size()) - mWidgetClient->getHeight(); if ( (false == mNeedVisibleScroll) || (mRangeIndex < 1) || (mWidgetScroll->getLeft() <= mWidgetClient->getLeft()) ) { if (mWidgetScroll->isShow()) { mWidgetScroll->hide(); // увеличиваем клиентскую зону на ширину скрола mWidgetClient->setSize(mWidgetClient->getWidth() + mWidgetScroll->getWidth(), mWidgetClient->getHeight()); } mWidgetScroll->setScrollRange(mRangeIndex + 1); return; } if (false == mWidgetScroll->isShow()) { mWidgetClient->setSize(mWidgetClient->getWidth() - mWidgetScroll->getWidth(), mWidgetClient->getHeight()); mWidgetScroll->show(); } mWidgetScroll->setScrollRange(mRangeIndex + 1); } void List::updateLine(bool _reset) { // сбрасываем if (_reset) { mOldSize.clear(); mLastRedrawLine = 0; } // позиция скролла int position = mTopIndex * mHeightLine + mOffsetTop; // если высота увеличивалась то добавляем виджеты if (mOldSize.height < mCoord.height) { int height = (int)mWidgetLines.size() * mHeightLine - mOffsetTop; // до тех пор, пока не достигнем максимального колличества, и всегда на одну больше while ( (height <= (mWidgetClient->getHeight() + mHeightLine)) && (mWidgetLines.size() < mStringArray.size()) ) { // создаем линию WidgetPtr line = mWidgetClient->createWidgetT("Button", mSkinLine, 0, height, mWidgetClient->getWidth(), mHeightLine, ALIGN_TOP | ALIGN_HSTRETCH); // подписываемся на всякие там события line->eventMouseButtonPressed = newDelegate(this, &List::notifyMousePressed); line->eventMouseWheel = newDelegate(this, &List::notifyMouseWheel); line->eventMouseSetFocus = newDelegate(this, &List::notifyMouseSetFocus); line->eventMouseLostFocus = newDelegate(this, &List::notifyMouseLostFocus); // присваиваем порядковый номер, длу простоты просчета line->_setInternalData((int)mWidgetLines.size()); // и сохраняем mWidgetLines.push_back(line); height += mHeightLine; }; // проверяем на возможность не менять положение списка if (position >= mRangeIndex) { // размер всех помещается в клиент if (mRangeIndex <= 0) { // обнуляем, если надо if (position || mOffsetTop || mTopIndex) { position = 0; mTopIndex = 0; mOffsetTop = 0; mLastRedrawLine = 0; // чтобы все перерисовалось // выравниваем int offset = 0; for (size_t pos=0; pos<mWidgetLines.size(); pos++) { mWidgetLines[pos]->setPosition(0, offset); offset += mHeightLine; } } } else { // прижимаем список к нижней границе int count = mWidgetClient->getHeight() / mHeightLine; mOffsetTop = mHeightLine - (mWidgetClient->getHeight() % mHeightLine); if (mOffsetTop == mHeightLine) { mOffsetTop = 0; count --; } int top = (int)mStringArray.size() - count - 1; // выравниваем int offset = 0 - mOffsetTop; for (size_t pos=0; pos<mWidgetLines.size(); pos++) { mWidgetLines[pos]->setPosition(0, offset); offset += mHeightLine; } // высчитываем положение, должно быть максимальным position = top * mHeightLine + mOffsetTop; // если индех изменился, то перерисовываем линии if (top != mTopIndex) { mTopIndex = top; _redrawItemRange(); } } } // увеличился размер, но прокрутки вниз небыло, обновляем линии снизу _redrawItemRange(mLastRedrawLine); } // if (old_cy < mCoord.height) // просчитываем положение скролла mWidgetScroll->setScrollPosition(position); mOldSize.width = mCoord.width; mOldSize.height = mCoord.height; } void List::_redrawItemRange(size_t _start) { // перерисовываем линии, только те, что видны size_t pos = _start; for (; pos<mWidgetLines.size(); pos++) { // индекс в нашем массиве size_t index = pos + (size_t)mTopIndex; // не будем заходить слишком далеко if (index >= mStringArray.size()) { // запоминаем последнюю перерисованную линию mLastRedrawLine = pos; break; } if (mWidgetLines[pos]->getTop() > mWidgetClient->getHeight()) { // запоминаем последнюю перерисованную линию mLastRedrawLine = pos; break; } // если был скрыт, то покажем if (false == mWidgetLines[pos]->isShow()) mWidgetLines[pos]->show(); // обновляем текст mWidgetLines[pos]->setCaption(mStringArray[index]); // если нужно выделить ,то выделим if (index == mIndexSelect) { if (!static_cast<ButtonPtr>(mWidgetLines[pos])->getButtonPressed()) static_cast<ButtonPtr>(mWidgetLines[pos])->setButtonPressed(true); } else { if (static_cast<ButtonPtr>(mWidgetLines[pos])->getButtonPressed()) static_cast<ButtonPtr>(mWidgetLines[pos])->setButtonPressed(false); } } // если цикл весь прошли, то ставим максимальную линию if (pos >= mWidgetLines.size()) mLastRedrawLine = pos; } // перерисовывает индекс void List::_redrawItem(size_t _index) { // невидно if (_index < (size_t)mTopIndex) return; _index -= (size_t)mTopIndex; // тоже невидно if (_index >= mLastRedrawLine) return; MYGUI_DEBUG_ASSERT(_index < mWidgetLines.size(), "index out range"); // перерисовываем mWidgetLines[_index]->setCaption(mStringArray[_index + mTopIndex]); } void List::insertItem(size_t _index, const Ogre::DisplayString & _item) { if (_index > mStringArray.size()) _index = mStringArray.size(); // вставляем физически _insertString(_index, _item); // если надо, то меняем выделенный элемент if ( (mIndexSelect != ITEM_NONE) && (_index <= mIndexSelect) ) mIndexSelect++; // строка, до первого видимого элемента if ( (_index <= (size_t)mTopIndex) && (mRangeIndex > 0) ) { mTopIndex ++; // просчитываем положение скролла mWidgetScroll->setScrollRange(mWidgetScroll->getScrollRange() + mHeightLine); mWidgetScroll->setScrollPosition(mTopIndex * mHeightLine + mOffsetTop); mRangeIndex += mHeightLine; } else { // высчитывам положение строки int offset = ((int)_index - mTopIndex) * mHeightLine - mOffsetTop; // строка, после последнего видимого элемента, плюс одна строка (потому что для прокрутки нужно на одну строчку больше) if (mWidgetClient->getHeight() < (offset - mHeightLine)) { // просчитываем положение скролла mWidgetScroll->setScrollRange(mWidgetScroll->getScrollRange() + mHeightLine); mWidgetScroll->setScrollPosition(mTopIndex * mHeightLine + mOffsetTop); mRangeIndex += mHeightLine; // строка в видимой области } else { // обновляем все updateScroll(); updateLine(true); // позже сюда еще оптимизацию по колличеству перерисовок } } } void List::deleteItem(size_t _index) { // доверяй, но проверяй MYGUI_ASSERT(_index < mStringArray.size(), "deleteItemString: index '" << _index << "' out of range"); // удяляем физически строку _deleteString(_index); // если надо, то меняем выделенный элемент if (mStringArray.empty()) mIndexSelect = ITEM_NONE; else if (mIndexSelect != ITEM_NONE) { if (_index < mIndexSelect) mIndexSelect--; else if ( (_index == mIndexSelect) && (mIndexSelect == (mStringArray.size())) ) mIndexSelect--; } // если виджетов стало больше , то скрываем крайний if (mWidgetLines.size() > mStringArray.size()) { mWidgetLines[mStringArray.size()]->hide(); } // строка, до первого видимого элемента if (_index < (size_t)mTopIndex) { mTopIndex --; // просчитываем положение скролла mWidgetScroll->setScrollRange(mWidgetScroll->getScrollRange() - mHeightLine); mWidgetScroll->setScrollPosition(mTopIndex * mHeightLine + mOffsetTop); mRangeIndex -= mHeightLine; } else { // высчитывам положение удаляемой строки int offset = ((int)_index - mTopIndex) * mHeightLine - mOffsetTop; // строка, после последнего видимого элемента if (mWidgetClient->getHeight() < offset) { // просчитываем положение скролла mWidgetScroll->setScrollRange(mWidgetScroll->getScrollRange() - mHeightLine); mWidgetScroll->setScrollPosition(mTopIndex * mHeightLine + mOffsetTop); mRangeIndex -= mHeightLine; // строка в видимой области } else { // обновляем все updateScroll(); updateLine(true); // позже сюда еще оптимизацию по колличеству перерисовок } } } void List::_deleteString(size_t _index) { for (size_t pos=_index+1; pos<mStringArray.size(); pos++) { mStringArray[pos-1] = mStringArray[pos]; } mStringArray.pop_back(); } void List::_insertString(size_t _index, const Ogre::DisplayString & _item) { mStringArray.push_back(""); for (size_t pos=mStringArray.size()-1; pos > _index; pos--) { mStringArray[pos] = mStringArray[pos-1]; } mStringArray[_index] = _item; } void List::setItemSelect(size_t _index) { if (mIndexSelect == _index) return; _selectIndex(mIndexSelect, false); _selectIndex(_index, true); mIndexSelect = _index; } void List::_selectIndex(size_t _index, bool _select) { if (_index >= mStringArray.size()) return; // не видно строки if (_index < (size_t)mTopIndex) return; // высчитывам положение строки int offset = ((int)_index - mTopIndex) * mHeightLine - mOffsetTop; // строка, после последнего видимого элемента if (mWidgetClient->getHeight() < offset) return; static_cast<ButtonPtr>(mWidgetLines[_index-mTopIndex])->setButtonPressed(_select); } void List::beginToIndex(size_t _index) { if (_index >= mStringArray.size()) return; if (mRangeIndex <= 0) return; int offset = (int)_index * mHeightLine; if (offset >= mRangeIndex) offset = mRangeIndex; if ((int)mWidgetScroll->getScrollPosition() == offset) return; mWidgetScroll->setScrollPosition(offset); notifyScrollChangePosition(null, offset); } // видим ли мы элемент, полностью или нет bool List::isItemVisible(size_t _index, bool _fill) { // если элемента нет, то мы его не видим (в том числе когда их вообще нет) if (_index >= mStringArray.size()) return false; // если скрола нет, то мы палюбак видим if (mRangeIndex <= 0) return true; // строка, до первого видимого элемента if (_index < (size_t)mTopIndex) return false; // строка это верхний выделенный if (_index == (size_t)mTopIndex) { if ( (mOffsetTop != 0) && (_fill) ) return false; // нам нужна полностью видимость return true; } // высчитывам положение строки int offset = ((int)_index - mTopIndex) * mHeightLine - mOffsetTop; // строка, после последнего видимого элемента if (mWidgetClient->getHeight() < offset) return false; // если мы внизу и нам нужен целый if ((mWidgetClient->getHeight() < (offset + mHeightLine)) && (_fill) ) return false; return true; } void List::deleteAllItems() { mTopIndex = 0; mIndexSelect = ITEM_NONE; mOffsetTop = 0; mStringArray.clear(); for (size_t pos=0; pos<mWidgetLines.size(); pos++) mWidgetLines[pos]->hide(); // обновляем все updateScroll(); updateLine(true); } void List::setItem(size_t _index, const Ogre::DisplayString & _item) { MYGUI_ASSERT(_index < mStringArray.size(), "setItemString: index " << _index <<" out of range"); mStringArray[_index]=_item; _redrawItem(_index); } const Ogre::DisplayString & List::getItem(size_t _index) { MYGUI_ASSERT(_index < mStringArray.size(), "getItemString: index " << _index <<" out of range"); return mStringArray[_index]; } void List::notifyMouseSetFocus(MyGUI::WidgetPtr _sender, MyGUI::WidgetPtr _old) { mLineActive = _sender->_getInternalData(); eventListMouseItemFocus(this, mLineActive + (size_t)mTopIndex); } void List::notifyMouseLostFocus(MyGUI::WidgetPtr _sender, MyGUI::WidgetPtr _new) { if ((null == _new) || (_new->getParent() != mWidgetClient)) { mLineActive = ITEM_NONE; eventListMouseItemFocus(this, ITEM_NONE); } } void List::_setItemFocus(size_t _position, bool _focus) { size_t index = (_position - mTopIndex); if (index < mWidgetLines.size()) static_cast<ButtonPtr>(mWidgetLines[index])->_setMouseFocus(_focus); } void List::needVisibleScroll(bool _visible) { if (mNeedVisibleScroll == _visible) return; mNeedVisibleScroll = _visible; updateScroll(); } void List::setScrollPosition(size_t _position) { if (mWidgetScroll->getScrollRange() > _position) { mWidgetScroll->setScrollPosition(_position); _setScrollView(_position); } } void List::_setScrollView(size_t _position) { mOffsetTop = ((int)_position % mHeightLine); // смещение с отрицательной стороны int offset = 0 - mOffsetTop; for (size_t pos=0; pos<mWidgetLines.size(); pos++) { mWidgetLines[pos]->setPosition(IntPoint(0, offset)); offset += mHeightLine; } // если индех изменился, то перерисовываем линии int top = ((int)_position / mHeightLine); if (top != mTopIndex) { mTopIndex = top; _redrawItemRange(); } // прорисовываем все нижние строки, если они появились _redrawItemRange(mLastRedrawLine); } void List::_sendEventChangeScroll(size_t _position) { eventListChangeScroll(this, _position); if (ITEM_NONE != mLineActive) eventListMouseItemFocus(this, mLineActive + (size_t)mTopIndex); } } // namespace MyGUI
[ [ [ 1, 688 ] ] ]
ad6e00a3a38214ad513cec514446cdf2769d77bd
74e7667ad65cbdaa869c6e384fdd8dc7e94aca34
/MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/spot_touch_native.cpp
fc10d192150408ea567eaf61c75bd2b3680dcaa8
[ "BSD-3-Clause", "OpenSSL", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
gezidan/NETMF-LPC
5093ab223eb9d7f42396344ea316cbe50a2f784b
db1880a03108db6c7f611e6de6dbc45ce9b9adce
refs/heads/master
2021-01-18T10:59:42.467549
2011-06-28T08:11:24
2011-06-28T08:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,437
cpp
//----------------------------------------------------------------------------- // // ** DO NOT EDIT THIS FILE! ** // This file was generated by a tool // re-running the tool will overwrite this file. // //----------------------------------------------------------------------------- #include "spot_touch_native.h" static const CLR_RT_MethodHandler method_lookup[] = { NULL, Library_spot_touch_native_Microsoft_SPOT_Touch_Ink::SetInkRegion___STATIC__VOID__U4__I4__I4__I4__I4__I4__I4__I4__MicrosoftSPOTGraphicsMicrosoftSPOTBitmap, Library_spot_touch_native_Microsoft_SPOT_Touch_Ink::ResetInkRegion___STATIC__VOID, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, Library_spot_touch_native_Microsoft_SPOT_Touch_TouchCollectorConfiguration::EnableTouchCollection___STATIC__VOID__I4__I4__I4__I4__I4__MicrosoftSPOTGraphicsMicrosoftSPOTBitmap, Library_spot_touch_native_Microsoft_SPOT_Touch_TouchCollectorConfiguration::GetTouchPoints___STATIC__VOID__BYREF_I4__SZARRAY_I2__SZARRAY_I2, Library_spot_touch_native_Microsoft_SPOT_Touch_TouchCollectorConfiguration::GetTouchInput___STATIC__VOID__MicrosoftSPOTTouchTouchCollectorConfigurationTouchInput__BYREF_I4__BYREF_I4__BYREF_I4, Library_spot_touch_native_Microsoft_SPOT_Touch_TouchCollectorConfiguration::SetTouchInput___STATIC__VOID__MicrosoftSPOTTouchTouchCollectorConfigurationTouchInput__I4__I4__I4, NULL, Library_spot_touch_native_Microsoft_SPOT_Touch_TouchEventProcessor::ProcessEvent___MicrosoftSPOTNativeMicrosoftSPOTBaseEvent__U4__U4__mscorlibSystemDateTime, NULL, NULL, NULL, Library_spot_touch_native_Microsoft_SPOT_Touch_TouchPanel::SetCalibration___VOID__I4__SZARRAY_I2__SZARRAY_I2__SZARRAY_I2__SZARRAY_I2, Library_spot_touch_native_Microsoft_SPOT_Touch_TouchPanel::GetCalibrationPointCount___VOID__BYREF_I4, Library_spot_touch_native_Microsoft_SPOT_Touch_TouchPanel::StartCalibration___VOID, Library_spot_touch_native_Microsoft_SPOT_Touch_TouchPanel::GetCalibrationPoint___VOID__I4__BYREF_I4__BYREF_I4, Library_spot_touch_native_Microsoft_SPOT_Touch_TouchPanel::EnableInternal___VOID__BOOLEAN, NULL, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_Microsoft_SPOT_Touch = { "Microsoft.SPOT.Touch", 0x4940D53E, method_lookup };
[ [ [ 1, 55 ] ] ]
481c7f90925753e6ba261d5285df760fd8bbabf9
d9a78f212155bb978f5ac27d30eb0489bca87c3f
/PB/src/PbFt/fttourneylist.cpp
1aa7f9bf4cec3fefa81dbd3d64b36ccccd1c49e1
[]
no_license
marchon/pokerbridge
1ed4a6a521f8644dcd0b6ec66a1ac46879b8473c
97d42ef318bf08f3bc0c0cb1d95bd31eb2a3a8a9
refs/heads/master
2021-01-10T07:15:26.496252
2010-05-17T20:01:29
2010-05-17T20:01:29
36,398,892
0
0
null
null
null
null
UTF-8
C++
false
false
1,147
cpp
#include "stdafx.h" #include "fttourneylist.h" #include "pbtourney.h" FTTourneyList::FTTourneyList(QWidget *w, QObject *parent) : FTList(w, parent) { } void FTTourneyList::onListUpdated() { FTList *list = qobject_cast<FTList*>(sender()); Q_FOREACH(PBTourneyInfo* ti, _info) { ti->deleteLater(); } _info.clear(); for(int i=0;i<list->rowCount();i++) { PBTourneyInfo* ti = new PBTourneyInfo(this); bool parsedOk = parse(list, i, ti); if(parsedOk) _info.append(ti); } emit tourneysUpdated(); } bool FTTourneyList::parse(FTList *list, int row, PBTourneyInfo *ti) { bool parsedOk = true; int col = list->indexOfColumn("Buy-In"); if(col>=0) if(!parseBuyIn(list->value(row, col), ti)) parsedOk = false; col = list->indexOfColumn("Status"); if(col>=0) { QString s = list->value(row, col); if(s=="Registering") ti->setTourneyStatus("Registering"); else if(s=="Running") ti->setTourneyStatus("Running"); } return parsedOk; } bool FTTourneyList::parseBuyIn(QString sBuyin, PBTourneyInfo *ti) { ti->setBuyIn(10); ti->setRake(1); return true; }
[ "[email protected]", "mikhail.mitkevich@a5377438-2eb2-11df-b28a-19025b8c0740" ]
[ [ [ 1, 43 ], [ 45, 45 ], [ 47, 57 ] ], [ [ 44, 44 ], [ 46, 46 ] ] ]
f02f77253089be909d3071dc59021a1f9f2ffb02
6ee200c9dba87a5d622c2bd525b50680e92b8dab
/Walkyrie Dx9/Valkyrie/Moteur/FuseeMissileExplode.h
35e340f6471831b5ae99db13bd042406f7fd88c8
[]
no_license
Ishoa/bizon
4dbcbbe94d1b380f213115251e1caac5e3139f4d
d7820563ab6831d19e973a9ded259d9649e20e27
refs/heads/master
2016-09-05T11:44:00.831438
2010-03-10T23:14:22
2010-03-10T23:14:22
32,632,823
0
0
null
null
null
null
UTF-8
C++
false
false
1,013
h
#ifndef _FUSEEMISSILEEXPLODE_H #define _FUSEEMISSILEEXPLODE_H #include "Particlesystem.h" #include "Scene.h" class CFuseeMissileExplode { protected: enum EEtatFuseeExplode { e_Lancement, e_Fusee, e_Wait, e_Explode, e_Finish, }; EEtatFuseeExplode e_EtatFuseeExplode; CParticleSystem* m_pParticleSystemFusee; LPDIRECT3DDEVICE9 m_pD3DDevice; D3DXVECTOR3 m_vPositionDepart; float m_fVitessefusee; float m_fDistanceExplode; D3DXVECTOR3 m_vDir; bool m_bGauche; CScene* m_pScene; public: CFuseeMissileExplode(CScene* pScene); CFuseeMissileExplode(); bool CreateAndInit(char **g_pTextNameFusee , int nTailleFusee,char **g_pTextNameExplode , int nTailleExplode); void DestructionObjet(); void Rendu3D(); void Animation(float fDeltaTemps, bool bTir); void SetPositionDepart(D3DXVECTOR3 vPositionDepart){m_vPositionDepart = vPositionDepart;} void SetVitesseFusee(float fVitessefusee){m_fVitessefusee = fVitessefusee;} }; #endif
[ "Colas.Vincent@ab19582e-f48f-11de-8f43-4547254af6c6" ]
[ [ [ 1, 51 ] ] ]
981b9f228f2a092957e493f5f6b4f27886b7ae80
7b4c786d4258ce4421b1e7bcca9011d4eeb50083
/开发项目/4Test/AddDlg.cpp
78abf1dade718e6fd62f6baa3fea2e0856e34ddc
[]
no_license
lzq123218/guoyishi-works
dbfa42a3e2d3bd4a984a5681e4335814657551ef
4e78c8f2e902589c3f06387374024225f52e5a92
refs/heads/master
2021-12-04T11:11:32.639076
2011-05-30T14:12:43
2011-05-30T14:12:43
null
0
0
null
null
null
null
GB18030
C++
false
false
2,772
cpp
// AddDlg.cpp : implementation file // #include "stdafx.h" #include "4Test.h" #include "AddDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // AddDlg dialog AddDlg::AddDlg(CWnd* pParent /*=NULL*/) : CDialog(AddDlg::IDD, pParent) { //{{AFX_DATA_INIT(AddDlg) m_path = _T(""); m_strA = _T(""); m_strQ = _T(""); //}}AFX_DATA_INIT } void AddDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(AddDlg) DDX_Text(pDX, IDC_EDIT_PATH, m_path); DDX_Text(pDX, IDC_EDIT_A, m_strA); DDX_Text(pDX, IDC_EDIT_Q, m_strQ); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(AddDlg, CDialog) //{{AFX_MSG_MAP(AddDlg) ON_BN_CLICKED(IDC_BUTTON_SELECT, OnButtonSelect) ON_BN_CLICKED(IDSAVE, OnSave) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // AddDlg message handlers void AddDlg::OnButtonSelect() { CString filter; filter = "考试程序文件(*.kaoshi)|*.kaoshi||"; CFileDialog dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY, filter ); if ( dlg.DoModal() != IDOK ) { return; } m_path = dlg.GetPathName(); CFileStatus status; if ( !CFile::GetStatus( m_path, status ) ) { MessageBox( "该文件不存在!" ); return; } if ( !theFile.Open( m_path, CFile::modeReadWrite ) ) { MessageBox( "该文件无法打开或写入!" ); return; } // MessageBox( "Test: " + m_path ); UpdateData( FALSE ); } void AddDlg::OnSave() { UpdateData( TRUE ); CString strs[2] = { m_strQ, m_strA }; CString strFinds[2] = { "(%Q%)", "(%A%)" }; for ( int i = 0; i < 2; ++i ) { for ( int j = 0; j < 2; ++j ) { if ( strs[i].IsEmpty() == TRUE ) { // 空内容,错误处理 MessageBox( "输入为空,请输入内容!" ); return; } if ( strs[i].Find(strFinds[j], 0) >= 0 ) { // 包含特征字符,错误处理 MessageBox( "错误输入,请修改内容!" ); return; } } } if ( SaveQA( m_strQ, m_strA ) ) { // 保存输入结果 // MessageBox( "Save" ); } else { return; } m_strQ.Empty(); // 清空问题输入框,方便下次输入 m_strA.Empty(); // 清空回答输入框,方便下次输入 UpdateData( FALSE ); // 刷新界面。 } BOOL AddDlg::SaveQA(CString strQ, CString strA) { if ( theFile.GetFileName().IsEmpty() ) { MessageBox( "保存路径有问题,请重新确认!" ); return FALSE; } CString str; str = "\r\n(%Q%)\r\n" + strQ + "\r\n(%A%)\r\n" + strA; theFile.SeekToEnd(); theFile.Write( str, str.GetLength() ); return TRUE; }
[ "baicaibang@70501136-4834-11de-8855-c187e5f49513" ]
[ [ [ 1, 116 ] ] ]
62f829895b47a41a602860110a12b4d1efd1eb74
4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4
/extern/tclap/UnlabeledValueArg.h
2b9d9a62d26f9bebc9f541bf40b10618ecb4959d
[]
no_license
saggita/nvidia-mesh-tools
9df27d41b65b9742a9d45dc67af5f6835709f0c2
a9b7fdd808e6719be88520e14bc60d58ea57e0bd
refs/heads/master
2020-12-24T21:37:11.053752
2010-09-03T01:39:02
2010-09-03T01:39:02
56,893,300
0
1
null
null
null
null
UTF-8
C++
false
false
11,640
h
/****************************************************************************** * * file: UnlabeledValueArg.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * 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 TCLAP_UNLABELED_VALUE_ARGUMENT_H #define TCLAP_UNLABELED_VALUE_ARGUMENT_H #include <string> #include <vector> #include <tclap/ValueArg.h> #include <tclap/OptionalUnlabeledTracker.h> namespace TCLAP { /** * The basic unlabeled argument that parses a value. * This is a template class, which means the type T defines the type * that a given object will attempt to parse when an UnlabeledValueArg * is reached in the list of args that the CmdLine iterates over. */ template<class T> class UnlabeledValueArg : public ValueArg<T> { // If compiler has two stage name lookup (as gcc >= 3.4 does) // this is requried to prevent undef. symbols using ValueArg<T>::_ignoreable; using ValueArg<T>::_hasBlanks; using ValueArg<T>::_extractValue; using ValueArg<T>::_typeDesc; using ValueArg<T>::_name; using ValueArg<T>::_description; using ValueArg<T>::_alreadySet; using ValueArg<T>::toString; public: /** * UnlabeledValueArg constructor. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param typeDesc - A short, human readable description of the * type that this object expects. This is used in the generation * of the USAGE statement. The goal is to be helpful to the end user * of the program. * \param ignoreable - Allows you to specify that this argument can be * ignored if the '--' flag is set. This defaults to false (cannot * be ignored) and should generally stay that way unless you have * some special need for certain arguments to be ignored. * \param v - Optional Vistor. You should leave this blank unless * you have a very good reason. */ UnlabeledValueArg( const std::string& name, const std::string& desc, bool req, T value, const std::string& typeDesc, bool ignoreable = false, Visitor* v = NULL); /** * UnlabeledValueArg constructor. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param typeDesc - A short, human readable description of the * type that this object expects. This is used in the generation * of the USAGE statement. The goal is to be helpful to the end user * of the program. * \param parser - A CmdLine parser object to add this Arg to * \param ignoreable - Allows you to specify that this argument can be * ignored if the '--' flag is set. This defaults to false (cannot * be ignored) and should generally stay that way unless you have * some special need for certain arguments to be ignored. * \param v - Optional Vistor. You should leave this blank unless * you have a very good reason. */ UnlabeledValueArg( const std::string& name, const std::string& desc, bool req, T value, const std::string& typeDesc, CmdLineInterface& parser, bool ignoreable = false, Visitor* v = NULL ); /** * UnlabeledValueArg constructor. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param constraint - A pointer to a Constraint object used * to constrain this Arg. * \param ignoreable - Allows you to specify that this argument can be * ignored if the '--' flag is set. This defaults to false (cannot * be ignored) and should generally stay that way unless you have * some special need for certain arguments to be ignored. * \param v - Optional Vistor. You should leave this blank unless * you have a very good reason. */ UnlabeledValueArg( const std::string& name, const std::string& desc, bool req, T value, Constraint<T>* constraint, bool ignoreable = false, Visitor* v = NULL ); /** * UnlabeledValueArg constructor. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param constraint - A pointer to a Constraint object used * to constrain this Arg. * \param parser - A CmdLine parser object to add this Arg to * \param ignoreable - Allows you to specify that this argument can be * ignored if the '--' flag is set. This defaults to false (cannot * be ignored) and should generally stay that way unless you have * some special need for certain arguments to be ignored. * \param v - Optional Vistor. You should leave this blank unless * you have a very good reason. */ UnlabeledValueArg( const std::string& name, const std::string& desc, bool req, T value, Constraint<T>* constraint, CmdLineInterface& parser, bool ignoreable = false, Visitor* v = NULL); /** * Handles the processing of the argument. * This re-implements the Arg version of this method to set the * _value of the argument appropriately. Handling specific to * unlabled arguments. * \param i - Pointer the the current argument in the list. * \param args - Mutable list of strings. */ virtual bool processArg(int* i, std::vector<std::string>& args); /** * Overrides shortID for specific behavior. */ virtual std::string shortID(const std::string& val="val") const; /** * Overrides longID for specific behavior. */ virtual std::string longID(const std::string& val="val") const; /** * Overrides operator== for specific behavior. */ virtual bool operator==(const Arg& a ) const; /** * Instead of pushing to the front of list, push to the back. * \param argList - The list to add this to. */ virtual void addToList( std::list<Arg*>& argList ) const; }; /** * Constructor implemenation. */ template<class T> UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name, const std::string& desc, bool req, T val, const std::string& typeDesc, bool ignoreable, Visitor* v) : ValueArg<T>("", name, desc, req, val, typeDesc, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(req, toString()); } template<class T> UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name, const std::string& desc, bool req, T val, const std::string& typeDesc, CmdLineInterface& parser, bool ignoreable, Visitor* v) : ValueArg<T>("", name, desc, req, val, typeDesc, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(req, toString()); parser.add( this ); } /** * Constructor implemenation. */ template<class T> UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name, const std::string& desc, bool req, T val, Constraint<T>* constraint, bool ignoreable, Visitor* v) : ValueArg<T>("", name, desc, req, val, constraint, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(req, toString()); } template<class T> UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name, const std::string& desc, bool req, T val, Constraint<T>* constraint, CmdLineInterface& parser, bool ignoreable, Visitor* v) : ValueArg<T>("", name, desc, req, val, constraint, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(req, toString()); parser.add( this ); } /** * Implementation of processArg(). */ template<class T> bool UnlabeledValueArg<T>::processArg(int *i, std::vector<std::string>& args) { if ( _alreadySet ) return false; if ( _hasBlanks( args[*i] ) ) return false; // never ignore an unlabeled arg _extractValue( args[*i] ); _alreadySet = true; return true; } /** * Overriding shortID for specific output. */ template<class T> std::string UnlabeledValueArg<T>::shortID(const std::string& val) const { std::string id = "<" + _typeDesc + ">"; return id; } /** * Overriding longID for specific output. */ template<class T> std::string UnlabeledValueArg<T>::longID(const std::string& val) const { // Ideally we would like to be able to use RTTI to return the name // of the type required for this argument. However, g++ at least, // doesn't appear to return terribly useful "names" of the types. std::string id = "<" + _typeDesc + ">"; return id; } /** * Overriding operator== for specific behavior. */ template<class T> bool UnlabeledValueArg<T>::operator==(const Arg& a ) const { if ( _name == a.getName() || _description == a.getDescription() ) return true; else return false; } template<class T> void UnlabeledValueArg<T>::addToList( std::list<Arg*>& argList ) const { argList.push_back( const_cast<Arg*>(static_cast<const Arg* const>(this)) ); } } #endif
[ "castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c" ]
[ [ [ 1, 341 ] ] ]
5f63c440cc741239e38ec011850ca93b1f8c5a18
299a1b0fca9e1de3858a5ebeaf63be6dc3a02b48
/tags/051101b/dingus/dingus/physics/PhysContext.cpp
c64af6937cdd1d3cfb0bf2c75d307ec6605f4389
[]
no_license
BackupTheBerlios/dingus-svn
331d7546a6e7a5a3cb38ffb106e57b224efbf5df
1223efcf4c2079f58860d7fa685fa5ded8f24f32
refs/heads/master
2016-09-05T22:15:57.658243
2006-09-02T10:10:47
2006-09-02T10:10:47
40,673,143
0
0
null
null
null
null
UTF-8
C++
false
false
773
cpp
// -------------------------------------------------------------------------- // Dingus project - a collection of subsystems for game/graphics applications // -------------------------------------------------------------------------- #include "stdafx.h" #include "PhysContext.h" using namespace dingus; CPhysContext::CPhysContext() : mContactCount(0) { mID = dWorldCreate(); } CPhysContext::~CPhysContext() { dWorldDestroy( mID ); } void CPhysContext::perform( float stepsize, int iterations ) { if( iterations > 0 ) dWorldStepFast1( mID, stepsize, iterations ); else { //dWorldStep( mID, stepsize ); dWorldSetQuickStepNumIterations( mID, 40 ); dWorldQuickStep( mID, stepsize ); } mContacts.clear(); mContactCount = 0; }
[ "nearaz@73827abb-88f4-0310-91e6-a2b8c1a3e93d" ]
[ [ [ 1, 32 ] ] ]
0e8c10f8f24a3af27d2a676ea6b335dfa426149a
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/SMDK/Limn/LimnDW/LimnDW/LimnGlbl.cpp
d49c8bcff6495bfdd263dc053e4ec902eb70af52
[]
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
32,921
cpp
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #include "stdafx.h" #include "math.h" #include "md_headers.h" #define __LIMNGLBL_CPP #include "limnglbl.h" //#pragma comment(lib, "rpcrt4.lib") const int DoDbg = 0; ///////////////////////////////////////////////////////////////////////////// // Class CDiamondWizardConfiguration // IMPLEMENT_DYNAMIC(CDiamondWizardConfiguration, CObject) // ///////////////////////////////////////////////////////////////////////////////////// // CDiamondWizardConfiguration::CDiamondWizardConfiguration( void ) // Constructor { m_bInitialised = false; m_numOreSizes = 0; m_numDiamondSizes = 0; m_numSGs = 0; m_numLimnStreamDataColumns = 0; m_nRowCount = 0; m_nColCount = 0; m_nDataBlockCount = 0; SetID( -1 ) ; } // // Helper/Calculation functions to return various DiamondWizard info // // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // int CDiamondWizardConfiguration::Initialise( LPXLOPER OreSizeData, // Initialisation - set up calculated data LPXLOPER DiamondSizeData, LPXLOPER SGData, LPXLOPER DiamondSG, LPXLOPER Revenue, LPXLOPER LiberationMatrix, LPXLOPER PassSizePercents ) { #ifdef NOT_DEFINED int iDSz ; int iOSz ; int iSG ; int idx ; FreeLocalData() ; // tidy up from any previous calls to this routine // bring in the ore size data g->Excel.fn( xlCoerce, xlp(OreSizeData), xl(xltypeMulti) ) ; if (g->Excel.resultXltype() != xltypeMulti) return xlerrRef ; // valid reference m_numOreSizes = g->Excel.resultRows() ; m_OreSizesTop = new double[m_numOreSizes] ; // define local arraya m_OreSizesBottom = new double[m_numOreSizes] ; m_OreSize = new double[m_numOreSizes] ; if (g->Excel.resultColumns() == 1) { for ( iOSz = 0 ; iOSz < m_numOreSizes ; iOSz++ ) { if (g->Excel.resultArrayXltype(iOSz) == xltypeNum ) { m_OreSizesBottom[iOSz] = 0.0 ; m_OreSizesTop[iOSz] = 0.0 ; m_OreSize[iOSz] = g->Excel.resultArrayNum(iOSz) ; // get the data for each element } else { return xlerrNum ; // error return, range has non number } } } else if (g->Excel.resultColumns() == 3) { idx = 0 ; for ( iOSz = 0 ; iOSz < m_numOreSizes ; iOSz++ ) { if (g->Excel.resultArrayXltype(iOSz) == xltypeNum ) { m_OreSizesBottom[iOSz] = g->Excel.resultArrayNum(idx++) ; // get the data for each element m_OreSizesTop[iOSz] = g->Excel.resultArrayNum(idx++) ; m_OreSize[iOSz] = g->Excel.resultArrayNum(idx++) ; } else { return xlerrNum ; // error return, range has non number } } } else { return xlerrRef ; // must be 1 or 3 columns wide } // bring in the diamond size data g->Excel.fn( xlCoerce, xlp(DiamondSizeData), xl(xltypeMulti) ) ; if (g->Excel.resultXltype() != xltypeMulti) return xlerrRef ; // valid reference m_numDiamondSizes = g->Excel.resultRows() ; m_DiamondSizesTop = new double[m_numDiamondSizes] ; // define local arrays m_DiamondSizesBottom = new double[m_numDiamondSizes] ; m_DiamondSize = new double[m_numDiamondSizes] ; if (g->Excel.resultColumns() == 1) { for ( iDSz = 0 ; iDSz < m_numDiamondSizes ; iDSz++ ) { if (g->Excel.resultArrayXltype(iDSz) == xltypeNum ) { m_DiamondSizesBottom[iDSz] = 0.0 ; m_DiamondSizesTop[iDSz] = 0.0 ; m_DiamondSize[iDSz] = g->Excel.resultArrayNum(iDSz) ; // get the data for each element } else { return xlerrNum ; // error return, range has non number } } } else if (g->Excel.resultColumns() == 3) { idx = 0 ; for ( iDSz = 0 ; iDSz < m_numDiamondSizes ; iDSz++ ) { if (g->Excel.resultArrayXltype(iDSz) == xltypeNum ) { m_DiamondSizesBottom[iDSz] = g->Excel.resultArrayNum(idx++) ; // get the data for each element m_DiamondSizesTop[iDSz] = g->Excel.resultArrayNum(idx++) ; m_DiamondSize[iDSz] = g->Excel.resultArrayNum(idx++) ; } else { return xlerrNum ; // error return, range has non number } } } else { return xlerrRef ; // must be 1 or 3 columns wide } // bring in the SG data g->Excel.fn( xlCoerce, xlp(SGData), xl(xltypeMulti) ) ; if (g->Excel.resultXltype() != xltypeMulti) return xlerrRef ; // valid reference m_numSGs = g->Excel.resultRows() ; m_SGsTop = new double[m_numSGs] ; // define local arrays m_SGsBottom = new double[m_numSGs] ; m_SG = new double[m_numSGs] ; if (g->Excel.resultColumns() == 1) { for ( iSG = 0 ; iSG < m_numSGs ; iSG++ ) { if (g->Excel.resultArrayXltype(iSG) == xltypeNum ) { m_SGsBottom[iSG] = 0.0 ; m_SGsTop[iSG] = 0.0 ; m_SG[iSG] = g->Excel.resultArrayNum(iSG) ; // get the data for each element } else { return xlerrNum ; // error return, range has non number } } } else if (g->Excel.resultColumns() == 3) { idx = 0 ; for ( iSG = 0 ; iSG < m_numSGs ; iSG++ ) { if (g->Excel.resultArrayXltype(iSG) == xltypeNum ) { m_SGsBottom[iSG] = g->Excel.resultArrayNum(idx++) ; // get the data for each element m_SGsTop[iSG] = g->Excel.resultArrayNum(idx++) ; m_SG[iSG] = g->Excel.resultArrayNum(idx++) ; } else { return xlerrNum ; // error return, range has non number } } } else { return xlerrRef ; // must be 1 or 3 columns wide } // precalculate something used a lot in indexing innto the array m_numLimnStreamDataColumns = m_numSGs + m_numDiamondSizes * ( INT((m_numSGs+1)/2 ) ) ; // bring in the diamond SG g->Excel.fn( xlCoerce, xlp(DiamondSG), xl(xltypeNum) ) ; if (g->Excel.resultXltype() != xltypeNum) return xlerrNum ; // valid number m_DiamondSG = g->Excel.resultNum() ; // get it // bring in the Revenue data g->Excel.fn( xlCoerce, xlp(Revenue), xl(xltypeMulti) ) ; if (g->Excel.resultXltype() != xltypeMulti) return xlerrRef ; // valid reference if (g->Excel.resultColumns() != 1) return xlerrRef ; // only 1 column wide if (g->Excel.resultRows() != m_numDiamondSizes) return xlerrRef ; // and as long as diamond sizes m_Revenue = new double[m_numDiamondSizes] ; // define a local array for ( iDSz = 0 ; iDSz < m_numDiamondSizes ; iDSz++ ) { if (g->Excel.resultArrayXltype(iDSz) == xltypeNum ) { m_Revenue[iDSz] = g->Excel.resultArrayNum(iDSz) ; // get the data for each element } else { return xlerrNum ; // error return, range has non number } } // bring in the Liberation data g->Excel.fn( xlCoerce, xlp(LiberationMatrix), xl(xltypeMulti) ) ; if (g->Excel.resultXltype() != xltypeMulti) return xlerrRef ; // valid reference if (g->Excel.resultColumns() != m_numDiamondSizes) return xlerrRef ; // as wide as the diamond sizes if (g->Excel.resultRows() != m_numOreSizes) return xlerrRef ; // and as long as ore sizes m_Liberation = new bool[m_numDiamondSizes*m_numOreSizes] ; // define a local array double aValue ; bool bValue ; int ida = 0 ; idx = 0 ; for ( iOSz = 0 ; iOSz < m_numOreSizes ; iOSz++ ) { for ( iDSz = 0 ; iDSz < m_numDiamondSizes ; iDSz++ ) { if (g->Excel.resultArrayXltype(ida) == xltypeNum ) { aValue = g->Excel.resultArrayNum(ida++) ; // get the data for each element bValue = false ; if ( aValue > 0.5 ) bValue = true ; idx = liberatedDiamondIndex( iDSz, iOSz ) ; m_Liberation[idx] = bValue ; } else { return xlerrNum ; // error return, range has non number } } } // bring in the Passing Size Percents g->Excel.fn( xlCoerce, xlp(PassSizePercents), xl(xltypeMulti) ) ; if (g->Excel.resultXltype() != xltypeMulti) return xlerrRef ; // valid reference if (g->Excel.resultColumns() != 1) return xlerrRef ; // single column if (g->Excel.resultRows() != 3) return xlerrRef ; // 3 rows m_PassSizePercents = new double[3] ; // define a local array for ( int iPSP = 0 ; iPSP < 3 ; iPSP++ ) { if (g->Excel.resultArrayXltype(iPSP) == xltypeNum ) { m_PassSizePercents[iPSP] = g->Excel.resultArrayNum(iPSP) ; // get the data for each element } else { return xlerrNum ; // error return, range has non number } } // Calculate locked diamond SGs double oreVolume ; double diamondVolume ; double particleOreMass ; double particleDiamondMass ; double theSG ; double volK = (4 / 3) * 3.1415912 ; // Set up SG array m_LockedParticleSG = new double[m_numDiamondSizes*m_numOreSizes*m_numSGs] ; for ( iDSz = 0 ; iDSz < m_numDiamondSizes ; iDSz++ ) { for ( iOSz = 0 ; iOSz < m_numOreSizes ; iOSz++ ) { for ( iSG = 0 ; iSG < m_numSGs ; iSG++ ) { oreVolume = volK * pow((m_OreSize[iOSz] / 2), 3) ; diamondVolume = volK * pow((m_DiamondSize[iDSz] / 2), 3) ; particleOreMass = m_SG[iSG] * (oreVolume - diamondVolume) ; particleDiamondMass = m_DiamondSG * diamondVolume ; theSG = (particleOreMass + particleDiamondMass) / oreVolume ; if ( theSG > m_DiamondSG ) theSG = m_DiamondSG ; m_LockedParticleSG[ lockedParticleIndex(iDSz, iOSz, iSG) ] = theSG ; } } } return xlerrNull ; #else return -1; #endif } //=========================================================================== // // // //=========================================================================== bool CDiamondWizardConfiguration::Initialise()//LPCTSTR Fn) { if (m_bInitialised) return m_bInitialised; CString PFFn(CfgFiles()); PFFn+="LimnCfg";//Fn;// "LimnPSD.ini"; if (PFFn.Right(4).CompareNoCase(".INI")!=0) PFFn+=".ini"; CProfINIFile PF(PFFn); m_DiamondSG = PF.RdDouble("General", "DiamondSG", 3.515); m_RevenueSym = PF.RdStr("General", "RevenueSym", "?"); m_LiberationFactor = PF.RdDouble("General", "LiberationFactor", 1.0); m_PassSizePercents.SetSize(3); m_PassSizePercents[0]=PF.RdDouble("General", "PassSizePercent.0", 25.0)*0.01; m_PassSizePercents[1]=PF.RdDouble("General", "PassSizePercent.1", 50.0)*0.01; m_PassSizePercents[2]=PF.RdDouble("General", "PassSizePercent.2", 75.0)*0.01; m_PassSizePercentsText.SetSize(m_PassSizePercents.GetCount()); for (int i=0; i<m_PassSizePercents.GetCount(); i++) m_PassSizePercentsText[i].Format("PassingSize-%i%%", int(m_PassSizePercents[i]*100.0+0.5)); CString Tg, Line, PrevTkn0; LPCTSTR SeriesSections[] = {"OreSG", "OreSize", "DiamondSize"}; for (int iSeries=0; iSeries<3; iSeries++) { for (int iInt=0; ; iInt++) { Tg.Format("I%04i", iInt); Line = PF.RdStr(SeriesSections[iSeries], Tg, ""); if (Line.GetLength()==0) break; CSVColArray Tkns; int N=ParseCSVTokens(Line.GetBuffer(), Tkns); if (N<=0) break; if (iInt>0) { double Top = SafeAtoF(PrevTkn0); double Bottom = SafeAtoF(Tkns[0]); if (iSeries==0) Exchange(Top, Bottom); double GeoMean = Bottom>0.0 ? Sqrt(Top*Bottom):Top/Sqrt(2.0); double ArtMean = Bottom>0.0 ? 0.5*(Top+Bottom):Top/2.0; CString Text = Tkns[1]; switch (iSeries) { case 0: { m_SGsTop.Add(Top); m_SGsBottom.Add(Bottom); m_SG.Add(ArtMean); m_SGText.Add(Text); Text.Format("%.2f", ArtMean); m_SGTextShort.Add(Text); break; } case 1: { m_OreSizesTop.Add(Top); m_OreSizesBottom.Add(Bottom); m_OreSize.Add(GeoMean); m_OreSizesTopSI.Add(Top*0.001); m_OreSizesBottomSI.Add(Bottom*0.001); m_OreSizeSI.Add(GeoMean*0.001); m_OreSizeText.Add(Text); break; } case 2: { m_DiamondSizesTop.Add(Top); m_DiamondSizesBottom.Add(Bottom); m_DiamondSize.Add(GeoMean); m_DiamondSizesTopSI.Add(Top*0.001); m_DiamondSizesBottomSI.Add(Bottom*0.001); m_DiamondSizeSI.Add(GeoMean*0.001); m_DiamondSizeText.Add(Text); m_Revenue.Add(SafeAtoF(Tkns[2], 0.0)); break; } } } PrevTkn0=Tkns[0]; } } m_numOreSizes = m_OreSize.GetCount(); m_numDiamondSizes = m_DiamondSize.GetCount(); m_numSGs = m_SG.GetCount(); // precalculate something used a lot in indexing innto the array m_numLimnStreamDataColumns = m_numSGs + m_numDiamondSizes * ( INT((m_numSGs+1)/2 ) ) ; m_Liberation.SetSize(m_numDiamondSizes*m_numOreSizes); // define a local array for (int iOSz = 0 ; iOSz < m_numOreSizes ; iOSz++ ) { for (int iDSz = 0 ; iDSz < m_numDiamondSizes ; iDSz++ ) { bool bValue = m_DiamondSize[iDSz]>=m_LiberationFactor*m_OreSize[iOSz]; m_Liberation[liberatedDiamondIndex( iDSz, iOSz )] = bValue ; } } LoadArrayData(CfgFiles(), "Default", 0, "Densimetrics", 1.0, m_numSGs, m_numOreSizes, m_ReferenceDensimetrics, NULL); // Do a Whole bunch of checks !!!!!!!!!! // Calculate locked diamond SGs double oreVolume ; double diamondVolume ; double particleOreMass ; double particleDiamondMass ; double theSG ; double volK = (4 / 3) * 3.1415912 ; // Set up SG array m_LockedParticleSG.SetSize(m_numDiamondSizes*m_numOreSizes*m_numSGs); for (int iDSz = 0 ; iDSz < m_numDiamondSizes ; iDSz++ ) { for (int iOSz = 0 ; iOSz < m_numOreSizes ; iOSz++ ) { for (int iSG = 0 ; iSG < m_numSGs ; iSG++ ) { oreVolume = volK * pow((m_OreSize[iOSz] / 2), 3) ; diamondVolume = volK * pow((m_DiamondSize[iDSz] / 2), 3) ; particleOreMass = m_SG[iSG] * (oreVolume - diamondVolume) ; particleDiamondMass = m_DiamondSG * diamondVolume ; theSG = (particleOreMass + particleDiamondMass) / oreVolume ; if ( theSG > m_DiamondSG ) theSG = m_DiamondSG ; m_LockedParticleSG[ lockedParticleIndex(iDSz, iOSz, iSG) ] = theSG ; } } } m_nRowCount = (m_numOreSizes*2); m_nColCount = (m_numSGs + m_numDiamondSizes * ((m_numSGs+1)/2)); m_nDataBlockCount = m_nRowCount * m_nColCount; // Specie IDs etc m_OreSpNames.SetSize(nSGs()); m_OreSpIds.SetSize(nSGs()); m_OreSpPhases.SetSize(nSGs()); CString Name; int id; for (int iSG=0; iSG<nSGs(); iSG++) { Tg.Format("Ore%04i", iSG); Name=PF.RdStr("SpecieNames", Tg, "?"); Name.Trim(); id = gs_MVDefn.Lookup(Name); if (id>=0) { m_OreSpNames[iSG] = Name; m_OreSpIds[iSG] = id; m_OreSpPhases[iSG] = gs_MVDefn[id].Phase(); } else { _asm int 3; //LogError } } Name=PF.RdStr("SpecieNames", "Diamond", "?"); Name.Trim(); id = gs_MVDefn.Lookup(Name); if (id>=0) { m_DiamondSpName = Name; m_DiamondSpId = id; m_DiamondPhase = gs_MVDefn[id].Phase(); } else { _asm int 3; //LogError } Name=PF.RdStr("SpecieNames", "Water", "?"); Name.Trim(); id = gs_MVDefn.Lookup(Name); if (id>=0) { m_WaterSpName = Name; m_WaterSpId = id; m_WaterPhase = gs_MVDefn[id].Phase(); } else { _asm int 3; //LogError } Name=PF.RdStr("SpecieNames", "FeSi", "?"); Name.Trim(); id = gs_MVDefn.Lookup(Name); if (id>=0) { m_FeSiSpName = Name; m_FeSiSpId = id;; m_FeSiPhase = gs_MVDefn[id].Phase(); } else { _asm int 3; //LogError } m_SpIds.SetSize(m_nDataBlockCount); m_SpPhases.SetSize(m_nDataBlockCount); for (int i=0; i<m_nDataBlockCount; i++) { m_SpIds[i]=-1; m_SpPhases[i]=0; } m_SeqIndex.Add(iWaterLimnStreamIndex()); m_SpIds[iWaterLimnStreamIndex()] = m_WaterSpId; m_SpPhases[iWaterLimnStreamIndex()] = m_WaterPhase; m_SeqIndex.Add(iFeSiLimnStreamIndex()); m_SpIds[iFeSiLimnStreamIndex()] = m_FeSiSpId; m_SpPhases[iFeSiLimnStreamIndex()] = m_FeSiPhase; m_MassFactor.SetSize(gs_MVDefn.Count()); for (int i=0; i<gs_MVDefn.Count(); i++) m_MassFactor[i]=0.001*3600; // everything to Tons/h; m_MassFactor[m_DiamondSpId]=5000.0*3600; // diamonds in Carats/h; for (int iOSz = 0 ; iOSz < nOreSizes() ; iOSz++ ) { for (int iSG = 0 ; iSG < nSGs(); iSG++ ) { int i = iODLimnStreamIndex(iOSz, iSG); m_SeqIndex.Add(i); m_SpIds[i] = m_OreSpIds[iSG]; m_SpPhases[i] = m_OreSpPhases[iSG]; } } for (int iSG = 0 ; iSG < nSGs(); iSG++ ) { for (int iOSz = 0 ; iOSz < nOreSizes() ; iOSz++ ) { for (int iDSz = 0 ; iDSz< nDiamondSizes(); iDSz++ ) { int i = iDDLimnStreamIndex(iDSz, iOSz, iSG); m_SeqIndex.Add(i); m_SpIds[i] = m_DiamondSpId; m_SpPhases[i] = m_DiamondPhase; } } } m_bInitialised = true; if(DoDbg) { MDebug Dbg; Dbg.PrintLn("Limn Config ==================================================="); Dbg.PrintLn(""); Dbg.PrintLn("DiamondSG : %10.3f", m_DiamondSG); Dbg.PrintLn("RevenueSym : %10s", m_RevenueSym); Dbg.PrintLn("LiberationFactor : %10.3f", m_LiberationFactor); Dbg.PrintLn(""); for (int i=0; i<m_PassSizePercents.GetCount(); i++) Dbg.PrintLn("PassSizePercent[%i] : %10.3f '%s'", i, m_PassSizePercents[i], m_PassSizePercentsText[i]); Dbg.PrintLn(""); Dbg.PrintLn("Ore SGs:%i", nSGs()); for (int i=0; i<nSGs(); i++) Dbg.PrintLn("%3i %8.2f %8.2f %8.2f '%s'", i, SGsBottom(i), SGsTop(i), MeanSG(i), SGText(i)); Dbg.PrintLn(""); Dbg.PrintLn("Ore Sizes:%i", nOreSizes()); for (int i=0; i<nOreSizes(); i++) Dbg.PrintLn("%3i %8.2f %8.2f %8.2f '%s'", i, OreSizesBottom(i)*1000, OreSizesTop(i)*1000, MeanOreSize(i)*1000, OreSizeText(i)); Dbg.PrintLn(""); Dbg.PrintLn("Diamond Sizes:%i", nDiamondSizes()); for (int i=0; i<nDiamondSizes(); i++) Dbg.PrintLn("%3i %8.2f %8.2f %8.2f '%s'", i, DiamondSizesBottom(i)*1000, DiamondSizesTop(i)*1000, MeanDiamondSize(i)*1000, DiamondSizeText(i)); Dbg.PrintLn(""); Dbg.PrintLn("Liberation"); Dbg.Print("%10s", ""); for (int iDSz = 0 ; iDSz < m_numDiamondSizes ; iDSz++ ) Dbg.Print(" %+6.2f", MeanDiamondSize(iDSz)*1000); Dbg.PrintLn(""); for ( iOSz = 0 ; iOSz < m_numOreSizes ; iOSz++ ) { Dbg.Print("%+10.2f", MeanOreSize(iOSz)*1000); for ( iDSz = 0 ; iDSz < m_numDiamondSizes; iDSz++ ) Dbg.Print(" %6s", IsLiberatedDiamond( iDSz, iOSz )?"Lib":"."); Dbg.PrintLn(""); } Dbg.PrintLn(""); Dbg.PrintLn("LockedParticleSG"); for (int iDSz = 0 ; iDSz < m_numDiamondSizes ; iDSz++ ) { Dbg.PrintLn("%10s", DiamondSizeText(iDSz)); Dbg.Indent(2); for (int iOSz = 0 ; iOSz < m_numOreSizes ; iOSz++ ) { Dbg.Print("%+10.2f", MeanOreSize(iOSz)*1000); for (int iSG = 0 ; iSG < m_numSGs ; iSG++ ) { Dbg.Print("%+10.3f", m_LockedParticleSG[ lockedParticleIndex(iDSz, iOSz, iSG) ]); } Dbg.PrintLn(""); } Dbg.Indent(-2); } Dbg.PrintLn("==============================================================="); } return m_bInitialised; }; // // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // void CDiamondWizardConfiguration::FreeLocalData( void ) // Tidy up local data allocations { m_OreSize.SetSize(0); m_OreSizesTop.SetSize(0); m_OreSizesTop.SetSize(0); m_OreSizesBottom.SetSize(0); m_DiamondSize.SetSize(0); m_DiamondSizesTop.SetSize(0); m_DiamondSizesBottom.SetSize(0); m_SG.SetSize(0); m_SGsTop.SetSize(0); m_SGsBottom.SetSize(0); m_Revenue.SetSize(0); m_Liberation.SetSize(0); m_LockedParticleSG.SetSize(0); m_PassSizePercents.SetSize(0); } // // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // // CDiamondWizardConfiguration::~CDiamondWizardConfiguration( void ) // Destructor { FreeLocalData() ; } // // // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // // // index into linear data space representing the 2D // spreadsheet representing the 3D diamond deportment data int CDiamondWizardConfiguration::iODIndex ( int iOSz, int iSG ) { return iSG + m_numSGs * iOSz; } // index into linear data space representing the 2D // spreadsheet representing the 3D diamond deportment data int CDiamondWizardConfiguration::iDDIndex( int iDSz, int iOSz, int iSG ) { return iDSz + m_numDiamondSizes*( (INT((m_numSGs+1)/2) * ( (iSG % 2)*m_numOreSizes + iOSz)) + INT(iSG/2) ) ; } // Diamond Data Index into linear data space representing the Limn Stream data, // i.e. the 2D spreadsheet representing 2D ore mass data and the 3D diamond deportment data. int CDiamondWizardConfiguration::iDDLimnStreamIndex ( int iDSz, int iOSz, int iSG ) { return m_numSGs + iDSz + m_numLimnStreamDataColumns * ((iSG % 2) * m_numOreSizes) + (m_numLimnStreamDataColumns * iOSz) + (m_numDiamondSizes * INT(iSG/2)) ; // } // Ore Data Index into linear data space representing the Limn Stream data, // i.e. the 2D spreadsheet representing 2D ore mass data and the 3D diamond deportment data. int CDiamondWizardConfiguration::iODLimnStreamIndex ( int iOSz, int iSG ) { return iSG + iOSz * m_numLimnStreamDataColumns ; } // // // Water Index into linear data space representing the Limn Stream data, // i.e. the 2D spreadsheet representing 2D ore mass data and the 3D diamond deportment data. int CDiamondWizardConfiguration::iWaterLimnStreamIndex() { return (1+m_numOreSizes) * m_numLimnStreamDataColumns ; } // // // FeSi Index into linear data space representing the Limn Stream data, // i.e. the 2D spreadsheet representing 2D ore mass data and the 3D diamond deportment data. int CDiamondWizardConfiguration::iFeSiLimnStreamIndex() { return (3+m_numOreSizes) * m_numLimnStreamDataColumns ; } CDiamondWizardConfiguration gs_DWCfg; CDiamondWizardConfigurations gs_DWCfgs; // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // // // ///////////////////////////////////////////////////////////////////////////////////// // // // CDiamondWizardConfigurations class - Collection Class to hold multiple // instances of CDiamondWizardConfiguration objects // // // // NB. There are 2 map relating the configurationID, // the Excel SheetID and the actual configuration Object. // // The primary map relates Excel SheetIDs to the configuration object // A secondary map relates configurationIDs to the configuration object // // This is necessary because, while the configuration recognises itself // by the unique sheetID, the calculation functions that use the // configuration information require an ID that will change whenever // Configuration:Initialise is called, so that the functions dependent // on the configuration get refreshed also. // // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // CDiamondWizardConfigurations::CDiamondWizardConfigurations( void ) // Constructor { ResetID() ; } // // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // // CDiamondWizardConfigurations::~CDiamondWizardConfigurations( void ) // Destructor { #ifdef NOT_DEFINED // Delete all the configuration objects POSITION pos = m_ExcelSheetIDToConfiguration.GetStartPosition(); while( pos != NULL ) { CDiamondWizardConfiguration* pWizdConfig ; DWORD key; m_ExcelSheetIDToConfiguration.GetNextAssoc( pos, key, pWizdConfig ); delete pWizdConfig; } m_ExcelSheetIDToConfiguration.RemoveAll(); #endif } // // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // // int CDiamondWizardConfigurations::IncrementID( void ) { #ifdef NOT_DEFINED m_nextConfigID++ ; if ( m_nextConfigID > 32000 ) { m_nextConfigID = 1 ; } #endif return ID() ; } // // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // // Function to return a Pointer to the configuration, given a configuration ID. // CDiamondWizardConfiguration* CDiamondWizardConfigurations::Configuration( int configID ) { #ifdef NOT_DEFINED POSITION pos = m_configIDToConfiguration.GetStartPosition(); while (pos != NULL) { int iKey; CDiamondWizardConfiguration* pConfig; m_configIDToConfiguration.GetNextAssoc(pos, iKey, pConfig); TRACE("ID, Pointer = %i, 0x%X\n",iKey,pConfig) ; } CDiamondWizardConfiguration* pWizdConfig ; if ( !m_configIDToConfiguration.Lookup( configID, pWizdConfig ) ) { pWizdConfig = NULL ; } return pWizdConfig ; #else return &gs_DWCfg; #endif } // // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // // Function to update the collection. // Creates a new entry, or returns a pointer to a matching entry if one exists. // Increments the ConfigurationID CDiamondWizardConfiguration* CDiamondWizardConfigurations::Update( DWORD ExcelSheetID ) { #ifdef NOT_DEFINED CDiamondWizardConfiguration* pWizdConfig ; if ( !m_ExcelSheetIDToConfiguration.Lookup( ExcelSheetID, pWizdConfig ) ) { pWizdConfig = new CDiamondWizardConfiguration ; m_ExcelSheetIDToConfiguration.SetAt( ExcelSheetID, pWizdConfig ) ; } int configID = pWizdConfig->ID() ; if ( configID != -1 ) { m_configIDToConfiguration.RemoveKey( configID ) ; } configID = IncrementID() ; // bump the global configuration ID pWizdConfig->SetID( configID ) ; // save it with the new configuration m_configIDToConfiguration.SetAt( configID, pWizdConfig ) ; // set up the link return pWizdConfig ; #else return &gs_DWCfg; #endif } //=========================================================================== // // // //=========================================================================== int LoadArrayData(LPCTSTR Root, LPCTSTR File, int iSource, LPCTSTR RangeName, double Scale, int Cols, int Rows, CArray<double,double> &Data, MLog * pLog) { int N=0; CString Fn(Root); Fn+=File; switch (iSource) { case 0: // CSV { Fn+="."; Fn+=RangeName; if (Fn.Right(4).CompareNoCase(".CSV")!=0) Fn+=".CSV"; FILE* f=fopen(Fn, "rt"); if (f) { for (int r=0; r<Rows; r++) { char Buff[16000]; if (fgets(Buff, sizeof(Buff)-1, f)) { CSVColArray Tkns; int NTkns=ParseCSVTokens(Buff, Tkns); for (int c=0; c<Cols; c++) Data.SetAtGrow(c + r*Cols, c<NTkns ? SafeAtoF(Tkns[c])*Scale : 0.0); } } fclose(f); } else { if (pLog) pLog->Message(MMsg_Error, "CSV File %s not opened", Fn); else { _asm int 3; } } break; } case 1: //XLS { if (pLog) pLog->Message(MMsg_Error, "XLS Files not yet implemented"); else { _asm int 3; } break; } } return Data.GetCount(); } //=========================================================================== // // // //=========================================================================== #ifdef NOT_DEFINED CLimnGlobals::CInterval::CInterval() { m_Start = 0; m_End = 0; m_Mean = 0; } CLimnGlobals::CInterval::CInterval(double Start, double End, LPCTSTR Text) { m_Start = Start; m_End = End; m_Mean = Sqrt(Start*End); m_Text = Text; } CLimnGlobals::CLimnGlobals() { m_bInitialised = false; //m_DmdSG = 3.515; }; CLimnGlobals::~CLimnGlobals() { }; bool CLimnGlobals::InitialiseFromINI(LPCTSTR Fn) { m_bInitialised = false; CString PFFn(CfgFiles()); PFFn+=Fn;// "LimnPSD.ini"; CProfINIFile PF(PFFn); CString Tg, Line, PrevTkn0; LPCTSTR SeriesSections[] = {"OreSG", "OreSize", "DiamondSize"}; for (int iSeries=0; iSeries<3; iSeries++) { for (int iInt=0; ; iInt++) { Tg.Format("I%04i", iInt); Line = PF.RdStr(SeriesSections[iSeries], Tg, ""); if (Line.GetLength()==0) break; CSVColArray Tkns; int N=ParseCSVTokens(Line.GetBuffer(), Tkns); if (N<=0) break; if (iInt>0) { switch (iSeries) { case 0: m_OreSG.Add(CInterval(SafeAtoF(PrevTkn0), SafeAtoF(Tkns[0]), Tkns[1])); break; case 1: m_OreSz.Add(CInterval(SafeAtoF(PrevTkn0), SafeAtoF(Tkns[0]), Tkns[1])); break; case 2: m_DmdSz.Add(CInterval(SafeAtoF(PrevTkn0), SafeAtoF(Tkns[0]), Tkns[1])); break; } } PrevTkn0=Tkns[0]; } } m_bInitialised = true; if(DoDbg) { MDebug Dbg; Dbg.PrintLn("LimnPSD"); Dbg.PrintLn("OreSG:%i", OreSGCount()); for (int i=0; i<OreSGCount(); i++) Dbg.PrintLn("%3i %8.2f %8.2f %8.2f '%s'", i, m_OreSG[i].m_Start, m_OreSG[i].m_End, m_OreSG[i].m_Mean, m_OreSG[i].m_Text); Dbg.PrintLn("OreSz:%i", OreSzCount()); for (int i=0; i<OreSzCount(); i++) Dbg.PrintLn("%3i %8.2f %8.2f %8.2f '%s'", i, m_OreSz[i].m_Start, m_OreSz[i].m_End, m_OreSz[i].m_Mean, m_OreSz[i].m_Text); Dbg.PrintLn("OreSz:%i", DmdSzCount()); for (int i=0; i<DmdSzCount(); i++) Dbg.PrintLn("%3i %8.2f %8.2f %8.2f '%s'", i, m_DmdSz[i].m_Start, m_DmdSz[i].m_End, m_DmdSz[i].m_Mean, m_DmdSz[i].m_Text); } return m_bInitialised; }; //=========================================================================== // // // //=========================================================================== CLimnGlobals gs_LimnGlbl; //=========================================================================== // // // //=========================================================================== #endif
[ [ [ 1, 1038 ] ] ]
d8881035a3168f83ff4ffb0557b28599e47e8e0e
836523304390560c1b0b655888a4abef63a1b4a5
/DsoFramer_V2.3.0.1/Lib/dsoframerlib.h
7074eb3f148ba28b7b872ff919510f0b713439e3
[]
no_license
paranoiagu/UDSOnlineEditor
4675ed403fe5acf437ff034a17f3eaa932e7b780
7eaae6fef51a01f09d28021ca6e6f2affa7c9658
refs/heads/master
2021-01-11T03:19:59.238691
2011-10-03T06:02:35
2011-10-03T06:02:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
50,285
h
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 7.00.0500 */ /* at Thu Sep 22 20:13:10 2011 */ /* Compiler settings for .\lib\dsoframer.idl: Oicf, W1, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #pragma warning( disable: 4049 ) /* more than 64k source lines */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 475 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif // __RPCNDR_H_VERSION__ #ifndef __dsoframerlib_h__ #define __dsoframerlib_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef ___FramerControl_FWD_DEFINED__ #define ___FramerControl_FWD_DEFINED__ typedef interface _FramerControl _FramerControl; #endif /* ___FramerControl_FWD_DEFINED__ */ #ifndef ___DFramerCtlEvents_FWD_DEFINED__ #define ___DFramerCtlEvents_FWD_DEFINED__ typedef interface _DFramerCtlEvents _DFramerCtlEvents; #endif /* ___DFramerCtlEvents_FWD_DEFINED__ */ #ifndef __FramerControl_FWD_DEFINED__ #define __FramerControl_FWD_DEFINED__ #ifdef __cplusplus typedef class FramerControl FramerControl; #else typedef struct FramerControl FramerControl; #endif /* __cplusplus */ #endif /* __FramerControl_FWD_DEFINED__ */ #ifdef __cplusplus extern "C"{ #endif #ifndef __DSOFramer_LIBRARY_DEFINED__ #define __DSOFramer_LIBRARY_DEFINED__ /* library DSOFramer */ /* [control][lcid][version][helpstring][uuid] */ typedef enum dsoBorderStyle { dsoBorderNone = 0, dsoBorderFlat = ( dsoBorderNone + 1 ) , dsoBorder3D = ( dsoBorderFlat + 1 ) , dsoBorder3DThin = ( dsoBorder3D + 1 ) } dsoBorderStyle; typedef enum dsoShowDialogType { dsoDialogNew = 0, dsoDialogOpen = ( dsoDialogNew + 1 ) , dsoDialogSave = ( dsoDialogOpen + 1 ) , dsoDialogSaveCopy = ( dsoDialogSave + 1 ) , dsoDialogPrint = ( dsoDialogSaveCopy + 1 ) , dsoDialogPageSetup = ( dsoDialogPrint + 1 ) , dsoDialogProperties = ( dsoDialogPageSetup + 1 ) } dsoShowDialogType; typedef enum dsoFileCommandType { dsoFileNew = 0, dsoFileOpen = ( dsoFileNew + 1 ) , dsoFileClose = ( dsoFileOpen + 1 ) , dsoFileSave = ( dsoFileClose + 1 ) , dsoFileSaveAs = ( dsoFileSave + 1 ) , dsoFilePrint = ( dsoFileSaveAs + 1 ) , dsoFilePageSetup = ( dsoFilePrint + 1 ) , dsoFileProperties = ( dsoFilePageSetup + 1 ) , dsoFilePrintPreview = ( dsoFileProperties + 1 ) } dsoFileCommandType; DEFINE_GUID(LIBID_DSOFramer,0x00460180,0x9E5E,0x11d5,0xB7,0xC8,0xB8,0x26,0x90,0x41,0xDD,0x57); #ifndef ___FramerControl_INTERFACE_DEFINED__ #define ___FramerControl_INTERFACE_DEFINED__ /* interface _FramerControl */ /* [object][oleautomation][dual][hidden][uuid] */ DEFINE_GUID(IID__FramerControl,0x00460181,0x9E5E,0x11d5,0xB7,0xC8,0xB8,0x26,0x90,0x41,0xDD,0x57); #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("00460181-9E5E-11d5-B7C8-B8269041DD57") _FramerControl : public IDispatch { public: virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Activate( void) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_ActiveDocument( /* [retval][out] */ IDispatch **ppdisp) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE CreateNew( /* [in] */ BSTR ProgIdOrTemplate) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Open( /* [in] */ VARIANT Document, /* [optional][in] */ VARIANT ReadOnly, /* [optional][in] */ VARIANT ProgId, /* [optional][in] */ VARIANT WebUsername, /* [optional][in] */ VARIANT WebPassword) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Save( /* [optional][in] */ VARIANT SaveAsDocument, /* [optional][in] */ VARIANT OverwriteExisting, /* [optional][in] */ VARIANT WebUsername, /* [optional][in] */ VARIANT WebPassword) = 0; virtual /* [hidden][id] */ HRESULT STDMETHODCALLTYPE _PrintOutOld( /* [optional][in] */ VARIANT PromptToSelectPrinter) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Close( void) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_Caption( /* [in] */ BSTR bstr) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_Caption( /* [retval][out] */ BSTR *pbstr) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_Titlebar( /* [in] */ VARIANT_BOOL vbool) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_Titlebar( /* [retval][out] */ VARIANT_BOOL *pbool) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_Toolbars( /* [in] */ VARIANT_BOOL vbool) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_Toolbars( /* [retval][out] */ VARIANT_BOOL *pbool) = 0; virtual /* [helpstring][id][nonbrowsable][propput] */ HRESULT STDMETHODCALLTYPE put_ModalState( /* [in] */ VARIANT_BOOL vbool) = 0; virtual /* [id][nonbrowsable][propget] */ HRESULT STDMETHODCALLTYPE get_ModalState( /* [retval][out] */ VARIANT_BOOL *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE ShowDialog( /* [in] */ dsoShowDialogType DlgType) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_EnableFileCommand( /* [in] */ dsoFileCommandType Item, /* [in] */ VARIANT_BOOL vbool) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_EnableFileCommand( /* [in] */ dsoFileCommandType Item, /* [retval][out] */ VARIANT_BOOL *pbool) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_BorderStyle( /* [in] */ dsoBorderStyle style) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_BorderStyle( /* [retval][out] */ dsoBorderStyle *pstyle) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_BorderColor( /* [in] */ /* external definition not present */ OLE_COLOR clr) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_BorderColor( /* [retval][out] */ /* external definition not present */ OLE_COLOR *pclr) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_BackColor( /* [in] */ /* external definition not present */ OLE_COLOR clr) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_BackColor( /* [retval][out] */ /* external definition not present */ OLE_COLOR *pclr) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_ForeColor( /* [in] */ /* external definition not present */ OLE_COLOR clr) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_ForeColor( /* [retval][out] */ /* external definition not present */ OLE_COLOR *pclr) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_TitlebarColor( /* [in] */ /* external definition not present */ OLE_COLOR clr) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_TitlebarColor( /* [retval][out] */ /* external definition not present */ OLE_COLOR *pclr) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_TitlebarTextColor( /* [in] */ /* external definition not present */ OLE_COLOR clr) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_TitlebarTextColor( /* [retval][out] */ /* external definition not present */ OLE_COLOR *pclr) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE ExecOleCommand( /* [in] */ LONG OLECMDID, /* [optional][in] */ VARIANT Options, /* [optional][in] */ VARIANT *vInParam, /* [optional][out][in] */ VARIANT *vInOutParam) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_Menubar( /* [in] */ VARIANT_BOOL vbool) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_Menubar( /* [retval][out] */ VARIANT_BOOL *pbool) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_HostName( /* [in] */ BSTR bstr) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_HostName( /* [retval][out] */ BSTR *pbstr) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_DocumentFullName( /* [retval][out] */ BSTR *pbstr) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE PrintOut( /* [optional][in] */ VARIANT PromptUser, /* [optional][in] */ VARIANT PrinterName, /* [optional][in] */ VARIANT Copies, /* [optional][in] */ VARIANT FromPage, /* [optional][in] */ VARIANT ToPage, /* [optional][in] */ VARIANT OutputFile) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE PrintPreview( void) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE PrintPreviewExit( void) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_IsReadOnly( /* [retval][out] */ VARIANT_BOOL *pbool) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_IsDirty( /* [retval][out] */ VARIANT_BOOL *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE HttpInit( /* [retval][out] */ VARIANT_BOOL *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE HttpAddPostString( /* [in] */ BSTR strName, /* [in] */ BSTR strValue, /* [retval][out] */ VARIANT_BOOL *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE HttpPost( /* [in] */ BSTR bstr, /* [retval][out] */ BSTR *pRet) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetTrackRevisions( /* [in] */ long vbool, /* [retval][out] */ VARIANT_BOOL *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetCurrUserName( /* [in] */ BSTR strCurrUserName, /* [retval][out] */ VARIANT_BOOL *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE HttpAddPostCurrFile( /* [in] */ BSTR strFileID, /* [in] */ BSTR strFileName, /* [retval][out] */ VARIANT_BOOL *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetCurrTime( /* [in] */ BSTR strValue, /* [retval][out] */ VARIANT_BOOL *pbool) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_GetApplication( /* [retval][out] */ IDispatch **ppdisp) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetFieldValue( /* [in] */ BSTR strFieldName, /* [in] */ BSTR strValue, /* [in] */ BSTR strCmdOrSheetName, /* [retval][out] */ VARIANT_BOOL *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetFieldValue( /* [in] */ BSTR strFieldName, /* [in] */ BSTR strCmdOrSheetName, /* [retval][out] */ BSTR *strValue) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetMenuDisplay( /* [in] */ long lMenuFlag, /* [retval][out] */ VARIANT_BOOL *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE ProtectDoc( /* [in] */ long lProOrUn, /* [in] */ long lProType, /* [in] */ BSTR strProPWD, /* [retval][out] */ VARIANT_BOOL *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE ShowRevisions( /* [in] */ long nNewValue, /* [retval][out] */ VARIANT_BOOL *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE InSertFile( /* [in] */ BSTR strFieldPath, /* [in] */ long lPos, /* [retval][out] */ VARIANT_BOOL *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE LoadOriginalFile( /* [in] */ VARIANT strFieldPath, /* [in] */ VARIANT strFileType, /* [retval][out] */ long *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SaveAs( /* [in] */ VARIANT strFileName, /* [in] */ VARIANT dwFileFormat, /* [retval][out] */ long *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE DeleteLocalFile( /* [in] */ BSTR strFilePath) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetTempFilePath( /* [retval][out] */ BSTR *strValue) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE ShowView( /* [in] */ long dwViewType, /* [retval][out] */ long *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE FtpConnect( /* [in] */ BSTR strURL, /* [in] */ long lPort, /* [in] */ BSTR strUser, /* [in] */ BSTR strPwd, /* [retval][out] */ long *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE FtpGetFile( /* [in] */ BSTR strRemoteFile, /* [in] */ BSTR strLocalFile, /* [retval][out] */ long *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE FtpPutFile( /* [in] */ BSTR strLocalFile, /* [in] */ BSTR strRemoteFile, /* [in] */ long blOverWrite, /* [retval][out] */ long *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE FtpDisConnect( /* [retval][out] */ long *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE DownloadFile( /* [in] */ BSTR strRemoteFile, /* [in] */ BSTR strLocalFile, /* [retval][out] */ BSTR *strValue) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE HttpAddPostFile( /* [in] */ BSTR strFileID, /* [in] */ BSTR strFileName, /* [retval][out] */ long *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetRevCount( /* [retval][out] */ long *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetRevInfo( /* [in] */ long lIndex, /* [in] */ long lType, /* [retval][out] */ BSTR *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetValue( /* [in] */ BSTR strValue, /* [in] */ BSTR strName, /* [retval][out] */ long *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetDocVariable( /* [in] */ BSTR strVarName, /* [in] */ BSTR strValue, /* [in] */ long lOpt, /* [retval][out] */ long *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetPageAs( /* [in] */ BSTR strLocalFile, /* [in] */ long lPageNum, /* [in] */ long lType, /* [retval][out] */ long *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE ReplaceText( /* [in] */ BSTR strSearchText, /* [in] */ BSTR strReplaceText, /* [in] */ long lGradation, /* [retval][out] */ long *pbool) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetEnvironmentVariable( /* [in] */ BSTR EnvironmentName, /* [retval][out] */ BSTR *strValue) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetOfficeVersion( /* [in] */ BSTR strName, /* [retval][out] */ BSTR *strValue) = 0; }; #else /* C style interface */ typedef struct _FramerControlVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( _FramerControl * This, /* [in] */ REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( _FramerControl * This); ULONG ( STDMETHODCALLTYPE *Release )( _FramerControl * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( _FramerControl * This, /* [out] */ UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( _FramerControl * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( _FramerControl * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR *rgszNames, /* [range][in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( _FramerControl * This, /* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS *pDispParams, /* [out] */ VARIANT *pVarResult, /* [out] */ EXCEPINFO *pExcepInfo, /* [out] */ UINT *puArgErr); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Activate )( _FramerControl * This); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ActiveDocument )( _FramerControl * This, /* [retval][out] */ IDispatch **ppdisp); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *CreateNew )( _FramerControl * This, /* [in] */ BSTR ProgIdOrTemplate); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Open )( _FramerControl * This, /* [in] */ VARIANT Document, /* [optional][in] */ VARIANT ReadOnly, /* [optional][in] */ VARIANT ProgId, /* [optional][in] */ VARIANT WebUsername, /* [optional][in] */ VARIANT WebPassword); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Save )( _FramerControl * This, /* [optional][in] */ VARIANT SaveAsDocument, /* [optional][in] */ VARIANT OverwriteExisting, /* [optional][in] */ VARIANT WebUsername, /* [optional][in] */ VARIANT WebPassword); /* [hidden][id] */ HRESULT ( STDMETHODCALLTYPE *_PrintOutOld )( _FramerControl * This, /* [optional][in] */ VARIANT PromptToSelectPrinter); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Close )( _FramerControl * This); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Caption )( _FramerControl * This, /* [in] */ BSTR bstr); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Caption )( _FramerControl * This, /* [retval][out] */ BSTR *pbstr); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Titlebar )( _FramerControl * This, /* [in] */ VARIANT_BOOL vbool); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Titlebar )( _FramerControl * This, /* [retval][out] */ VARIANT_BOOL *pbool); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Toolbars )( _FramerControl * This, /* [in] */ VARIANT_BOOL vbool); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Toolbars )( _FramerControl * This, /* [retval][out] */ VARIANT_BOOL *pbool); /* [helpstring][id][nonbrowsable][propput] */ HRESULT ( STDMETHODCALLTYPE *put_ModalState )( _FramerControl * This, /* [in] */ VARIANT_BOOL vbool); /* [id][nonbrowsable][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ModalState )( _FramerControl * This, /* [retval][out] */ VARIANT_BOOL *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *ShowDialog )( _FramerControl * This, /* [in] */ dsoShowDialogType DlgType); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_EnableFileCommand )( _FramerControl * This, /* [in] */ dsoFileCommandType Item, /* [in] */ VARIANT_BOOL vbool); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_EnableFileCommand )( _FramerControl * This, /* [in] */ dsoFileCommandType Item, /* [retval][out] */ VARIANT_BOOL *pbool); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BorderStyle )( _FramerControl * This, /* [in] */ dsoBorderStyle style); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BorderStyle )( _FramerControl * This, /* [retval][out] */ dsoBorderStyle *pstyle); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BorderColor )( _FramerControl * This, /* [in] */ /* external definition not present */ OLE_COLOR clr); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BorderColor )( _FramerControl * This, /* [retval][out] */ /* external definition not present */ OLE_COLOR *pclr); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BackColor )( _FramerControl * This, /* [in] */ /* external definition not present */ OLE_COLOR clr); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BackColor )( _FramerControl * This, /* [retval][out] */ /* external definition not present */ OLE_COLOR *pclr); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_ForeColor )( _FramerControl * This, /* [in] */ /* external definition not present */ OLE_COLOR clr); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ForeColor )( _FramerControl * This, /* [retval][out] */ /* external definition not present */ OLE_COLOR *pclr); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_TitlebarColor )( _FramerControl * This, /* [in] */ /* external definition not present */ OLE_COLOR clr); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TitlebarColor )( _FramerControl * This, /* [retval][out] */ /* external definition not present */ OLE_COLOR *pclr); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_TitlebarTextColor )( _FramerControl * This, /* [in] */ /* external definition not present */ OLE_COLOR clr); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TitlebarTextColor )( _FramerControl * This, /* [retval][out] */ /* external definition not present */ OLE_COLOR *pclr); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *ExecOleCommand )( _FramerControl * This, /* [in] */ LONG OLECMDID, /* [optional][in] */ VARIANT Options, /* [optional][in] */ VARIANT *vInParam, /* [optional][out][in] */ VARIANT *vInOutParam); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Menubar )( _FramerControl * This, /* [in] */ VARIANT_BOOL vbool); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Menubar )( _FramerControl * This, /* [retval][out] */ VARIANT_BOOL *pbool); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_HostName )( _FramerControl * This, /* [in] */ BSTR bstr); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_HostName )( _FramerControl * This, /* [retval][out] */ BSTR *pbstr); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_DocumentFullName )( _FramerControl * This, /* [retval][out] */ BSTR *pbstr); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *PrintOut )( _FramerControl * This, /* [optional][in] */ VARIANT PromptUser, /* [optional][in] */ VARIANT PrinterName, /* [optional][in] */ VARIANT Copies, /* [optional][in] */ VARIANT FromPage, /* [optional][in] */ VARIANT ToPage, /* [optional][in] */ VARIANT OutputFile); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *PrintPreview )( _FramerControl * This); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *PrintPreviewExit )( _FramerControl * This); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_IsReadOnly )( _FramerControl * This, /* [retval][out] */ VARIANT_BOOL *pbool); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_IsDirty )( _FramerControl * This, /* [retval][out] */ VARIANT_BOOL *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *HttpInit )( _FramerControl * This, /* [retval][out] */ VARIANT_BOOL *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *HttpAddPostString )( _FramerControl * This, /* [in] */ BSTR strName, /* [in] */ BSTR strValue, /* [retval][out] */ VARIANT_BOOL *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *HttpPost )( _FramerControl * This, /* [in] */ BSTR bstr, /* [retval][out] */ BSTR *pRet); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetTrackRevisions )( _FramerControl * This, /* [in] */ long vbool, /* [retval][out] */ VARIANT_BOOL *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetCurrUserName )( _FramerControl * This, /* [in] */ BSTR strCurrUserName, /* [retval][out] */ VARIANT_BOOL *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *HttpAddPostCurrFile )( _FramerControl * This, /* [in] */ BSTR strFileID, /* [in] */ BSTR strFileName, /* [retval][out] */ VARIANT_BOOL *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetCurrTime )( _FramerControl * This, /* [in] */ BSTR strValue, /* [retval][out] */ VARIANT_BOOL *pbool); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_GetApplication )( _FramerControl * This, /* [retval][out] */ IDispatch **ppdisp); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetFieldValue )( _FramerControl * This, /* [in] */ BSTR strFieldName, /* [in] */ BSTR strValue, /* [in] */ BSTR strCmdOrSheetName, /* [retval][out] */ VARIANT_BOOL *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetFieldValue )( _FramerControl * This, /* [in] */ BSTR strFieldName, /* [in] */ BSTR strCmdOrSheetName, /* [retval][out] */ BSTR *strValue); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetMenuDisplay )( _FramerControl * This, /* [in] */ long lMenuFlag, /* [retval][out] */ VARIANT_BOOL *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *ProtectDoc )( _FramerControl * This, /* [in] */ long lProOrUn, /* [in] */ long lProType, /* [in] */ BSTR strProPWD, /* [retval][out] */ VARIANT_BOOL *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *ShowRevisions )( _FramerControl * This, /* [in] */ long nNewValue, /* [retval][out] */ VARIANT_BOOL *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *InSertFile )( _FramerControl * This, /* [in] */ BSTR strFieldPath, /* [in] */ long lPos, /* [retval][out] */ VARIANT_BOOL *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *LoadOriginalFile )( _FramerControl * This, /* [in] */ VARIANT strFieldPath, /* [in] */ VARIANT strFileType, /* [retval][out] */ long *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SaveAs )( _FramerControl * This, /* [in] */ VARIANT strFileName, /* [in] */ VARIANT dwFileFormat, /* [retval][out] */ long *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *DeleteLocalFile )( _FramerControl * This, /* [in] */ BSTR strFilePath); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetTempFilePath )( _FramerControl * This, /* [retval][out] */ BSTR *strValue); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *ShowView )( _FramerControl * This, /* [in] */ long dwViewType, /* [retval][out] */ long *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *FtpConnect )( _FramerControl * This, /* [in] */ BSTR strURL, /* [in] */ long lPort, /* [in] */ BSTR strUser, /* [in] */ BSTR strPwd, /* [retval][out] */ long *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *FtpGetFile )( _FramerControl * This, /* [in] */ BSTR strRemoteFile, /* [in] */ BSTR strLocalFile, /* [retval][out] */ long *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *FtpPutFile )( _FramerControl * This, /* [in] */ BSTR strLocalFile, /* [in] */ BSTR strRemoteFile, /* [in] */ long blOverWrite, /* [retval][out] */ long *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *FtpDisConnect )( _FramerControl * This, /* [retval][out] */ long *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *DownloadFile )( _FramerControl * This, /* [in] */ BSTR strRemoteFile, /* [in] */ BSTR strLocalFile, /* [retval][out] */ BSTR *strValue); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *HttpAddPostFile )( _FramerControl * This, /* [in] */ BSTR strFileID, /* [in] */ BSTR strFileName, /* [retval][out] */ long *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetRevCount )( _FramerControl * This, /* [retval][out] */ long *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetRevInfo )( _FramerControl * This, /* [in] */ long lIndex, /* [in] */ long lType, /* [retval][out] */ BSTR *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetValue )( _FramerControl * This, /* [in] */ BSTR strValue, /* [in] */ BSTR strName, /* [retval][out] */ long *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetDocVariable )( _FramerControl * This, /* [in] */ BSTR strVarName, /* [in] */ BSTR strValue, /* [in] */ long lOpt, /* [retval][out] */ long *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetPageAs )( _FramerControl * This, /* [in] */ BSTR strLocalFile, /* [in] */ long lPageNum, /* [in] */ long lType, /* [retval][out] */ long *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *ReplaceText )( _FramerControl * This, /* [in] */ BSTR strSearchText, /* [in] */ BSTR strReplaceText, /* [in] */ long lGradation, /* [retval][out] */ long *pbool); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetEnvironmentVariable )( _FramerControl * This, /* [in] */ BSTR EnvironmentName, /* [retval][out] */ BSTR *strValue); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetOfficeVersion )( _FramerControl * This, /* [in] */ BSTR strName, /* [retval][out] */ BSTR *strValue); END_INTERFACE } _FramerControlVtbl; interface _FramerControl { CONST_VTBL struct _FramerControlVtbl *lpVtbl; }; #ifdef COBJMACROS #define _FramerControl_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define _FramerControl_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define _FramerControl_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define _FramerControl_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define _FramerControl_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define _FramerControl_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define _FramerControl_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define _FramerControl_Activate(This) \ ( (This)->lpVtbl -> Activate(This) ) #define _FramerControl_get_ActiveDocument(This,ppdisp) \ ( (This)->lpVtbl -> get_ActiveDocument(This,ppdisp) ) #define _FramerControl_CreateNew(This,ProgIdOrTemplate) \ ( (This)->lpVtbl -> CreateNew(This,ProgIdOrTemplate) ) #define _FramerControl_Open(This,Document,ReadOnly,ProgId,WebUsername,WebPassword) \ ( (This)->lpVtbl -> Open(This,Document,ReadOnly,ProgId,WebUsername,WebPassword) ) #define _FramerControl_Save(This,SaveAsDocument,OverwriteExisting,WebUsername,WebPassword) \ ( (This)->lpVtbl -> Save(This,SaveAsDocument,OverwriteExisting,WebUsername,WebPassword) ) #define _FramerControl__PrintOutOld(This,PromptToSelectPrinter) \ ( (This)->lpVtbl -> _PrintOutOld(This,PromptToSelectPrinter) ) #define _FramerControl_Close(This) \ ( (This)->lpVtbl -> Close(This) ) #define _FramerControl_put_Caption(This,bstr) \ ( (This)->lpVtbl -> put_Caption(This,bstr) ) #define _FramerControl_get_Caption(This,pbstr) \ ( (This)->lpVtbl -> get_Caption(This,pbstr) ) #define _FramerControl_put_Titlebar(This,vbool) \ ( (This)->lpVtbl -> put_Titlebar(This,vbool) ) #define _FramerControl_get_Titlebar(This,pbool) \ ( (This)->lpVtbl -> get_Titlebar(This,pbool) ) #define _FramerControl_put_Toolbars(This,vbool) \ ( (This)->lpVtbl -> put_Toolbars(This,vbool) ) #define _FramerControl_get_Toolbars(This,pbool) \ ( (This)->lpVtbl -> get_Toolbars(This,pbool) ) #define _FramerControl_put_ModalState(This,vbool) \ ( (This)->lpVtbl -> put_ModalState(This,vbool) ) #define _FramerControl_get_ModalState(This,pbool) \ ( (This)->lpVtbl -> get_ModalState(This,pbool) ) #define _FramerControl_ShowDialog(This,DlgType) \ ( (This)->lpVtbl -> ShowDialog(This,DlgType) ) #define _FramerControl_put_EnableFileCommand(This,Item,vbool) \ ( (This)->lpVtbl -> put_EnableFileCommand(This,Item,vbool) ) #define _FramerControl_get_EnableFileCommand(This,Item,pbool) \ ( (This)->lpVtbl -> get_EnableFileCommand(This,Item,pbool) ) #define _FramerControl_put_BorderStyle(This,style) \ ( (This)->lpVtbl -> put_BorderStyle(This,style) ) #define _FramerControl_get_BorderStyle(This,pstyle) \ ( (This)->lpVtbl -> get_BorderStyle(This,pstyle) ) #define _FramerControl_put_BorderColor(This,clr) \ ( (This)->lpVtbl -> put_BorderColor(This,clr) ) #define _FramerControl_get_BorderColor(This,pclr) \ ( (This)->lpVtbl -> get_BorderColor(This,pclr) ) #define _FramerControl_put_BackColor(This,clr) \ ( (This)->lpVtbl -> put_BackColor(This,clr) ) #define _FramerControl_get_BackColor(This,pclr) \ ( (This)->lpVtbl -> get_BackColor(This,pclr) ) #define _FramerControl_put_ForeColor(This,clr) \ ( (This)->lpVtbl -> put_ForeColor(This,clr) ) #define _FramerControl_get_ForeColor(This,pclr) \ ( (This)->lpVtbl -> get_ForeColor(This,pclr) ) #define _FramerControl_put_TitlebarColor(This,clr) \ ( (This)->lpVtbl -> put_TitlebarColor(This,clr) ) #define _FramerControl_get_TitlebarColor(This,pclr) \ ( (This)->lpVtbl -> get_TitlebarColor(This,pclr) ) #define _FramerControl_put_TitlebarTextColor(This,clr) \ ( (This)->lpVtbl -> put_TitlebarTextColor(This,clr) ) #define _FramerControl_get_TitlebarTextColor(This,pclr) \ ( (This)->lpVtbl -> get_TitlebarTextColor(This,pclr) ) #define _FramerControl_ExecOleCommand(This,OLECMDID,Options,vInParam,vInOutParam) \ ( (This)->lpVtbl -> ExecOleCommand(This,OLECMDID,Options,vInParam,vInOutParam) ) #define _FramerControl_put_Menubar(This,vbool) \ ( (This)->lpVtbl -> put_Menubar(This,vbool) ) #define _FramerControl_get_Menubar(This,pbool) \ ( (This)->lpVtbl -> get_Menubar(This,pbool) ) #define _FramerControl_put_HostName(This,bstr) \ ( (This)->lpVtbl -> put_HostName(This,bstr) ) #define _FramerControl_get_HostName(This,pbstr) \ ( (This)->lpVtbl -> get_HostName(This,pbstr) ) #define _FramerControl_get_DocumentFullName(This,pbstr) \ ( (This)->lpVtbl -> get_DocumentFullName(This,pbstr) ) #define _FramerControl_PrintOut(This,PromptUser,PrinterName,Copies,FromPage,ToPage,OutputFile) \ ( (This)->lpVtbl -> PrintOut(This,PromptUser,PrinterName,Copies,FromPage,ToPage,OutputFile) ) #define _FramerControl_PrintPreview(This) \ ( (This)->lpVtbl -> PrintPreview(This) ) #define _FramerControl_PrintPreviewExit(This) \ ( (This)->lpVtbl -> PrintPreviewExit(This) ) #define _FramerControl_get_IsReadOnly(This,pbool) \ ( (This)->lpVtbl -> get_IsReadOnly(This,pbool) ) #define _FramerControl_get_IsDirty(This,pbool) \ ( (This)->lpVtbl -> get_IsDirty(This,pbool) ) #define _FramerControl_HttpInit(This,pbool) \ ( (This)->lpVtbl -> HttpInit(This,pbool) ) #define _FramerControl_HttpAddPostString(This,strName,strValue,pbool) \ ( (This)->lpVtbl -> HttpAddPostString(This,strName,strValue,pbool) ) #define _FramerControl_HttpPost(This,bstr,pRet) \ ( (This)->lpVtbl -> HttpPost(This,bstr,pRet) ) #define _FramerControl_SetTrackRevisions(This,vbool,pbool) \ ( (This)->lpVtbl -> SetTrackRevisions(This,vbool,pbool) ) #define _FramerControl_SetCurrUserName(This,strCurrUserName,pbool) \ ( (This)->lpVtbl -> SetCurrUserName(This,strCurrUserName,pbool) ) #define _FramerControl_HttpAddPostCurrFile(This,strFileID,strFileName,pbool) \ ( (This)->lpVtbl -> HttpAddPostCurrFile(This,strFileID,strFileName,pbool) ) #define _FramerControl_SetCurrTime(This,strValue,pbool) \ ( (This)->lpVtbl -> SetCurrTime(This,strValue,pbool) ) #define _FramerControl_get_GetApplication(This,ppdisp) \ ( (This)->lpVtbl -> get_GetApplication(This,ppdisp) ) #define _FramerControl_SetFieldValue(This,strFieldName,strValue,strCmdOrSheetName,pbool) \ ( (This)->lpVtbl -> SetFieldValue(This,strFieldName,strValue,strCmdOrSheetName,pbool) ) #define _FramerControl_GetFieldValue(This,strFieldName,strCmdOrSheetName,strValue) \ ( (This)->lpVtbl -> GetFieldValue(This,strFieldName,strCmdOrSheetName,strValue) ) #define _FramerControl_SetMenuDisplay(This,lMenuFlag,pbool) \ ( (This)->lpVtbl -> SetMenuDisplay(This,lMenuFlag,pbool) ) #define _FramerControl_ProtectDoc(This,lProOrUn,lProType,strProPWD,pbool) \ ( (This)->lpVtbl -> ProtectDoc(This,lProOrUn,lProType,strProPWD,pbool) ) #define _FramerControl_ShowRevisions(This,nNewValue,pbool) \ ( (This)->lpVtbl -> ShowRevisions(This,nNewValue,pbool) ) #define _FramerControl_InSertFile(This,strFieldPath,lPos,pbool) \ ( (This)->lpVtbl -> InSertFile(This,strFieldPath,lPos,pbool) ) #define _FramerControl_LoadOriginalFile(This,strFieldPath,strFileType,pbool) \ ( (This)->lpVtbl -> LoadOriginalFile(This,strFieldPath,strFileType,pbool) ) #define _FramerControl_SaveAs(This,strFileName,dwFileFormat,pbool) \ ( (This)->lpVtbl -> SaveAs(This,strFileName,dwFileFormat,pbool) ) #define _FramerControl_DeleteLocalFile(This,strFilePath) \ ( (This)->lpVtbl -> DeleteLocalFile(This,strFilePath) ) #define _FramerControl_GetTempFilePath(This,strValue) \ ( (This)->lpVtbl -> GetTempFilePath(This,strValue) ) #define _FramerControl_ShowView(This,dwViewType,pbool) \ ( (This)->lpVtbl -> ShowView(This,dwViewType,pbool) ) #define _FramerControl_FtpConnect(This,strURL,lPort,strUser,strPwd,pbool) \ ( (This)->lpVtbl -> FtpConnect(This,strURL,lPort,strUser,strPwd,pbool) ) #define _FramerControl_FtpGetFile(This,strRemoteFile,strLocalFile,pbool) \ ( (This)->lpVtbl -> FtpGetFile(This,strRemoteFile,strLocalFile,pbool) ) #define _FramerControl_FtpPutFile(This,strLocalFile,strRemoteFile,blOverWrite,pbool) \ ( (This)->lpVtbl -> FtpPutFile(This,strLocalFile,strRemoteFile,blOverWrite,pbool) ) #define _FramerControl_FtpDisConnect(This,pbool) \ ( (This)->lpVtbl -> FtpDisConnect(This,pbool) ) #define _FramerControl_DownloadFile(This,strRemoteFile,strLocalFile,strValue) \ ( (This)->lpVtbl -> DownloadFile(This,strRemoteFile,strLocalFile,strValue) ) #define _FramerControl_HttpAddPostFile(This,strFileID,strFileName,pbool) \ ( (This)->lpVtbl -> HttpAddPostFile(This,strFileID,strFileName,pbool) ) #define _FramerControl_GetRevCount(This,pbool) \ ( (This)->lpVtbl -> GetRevCount(This,pbool) ) #define _FramerControl_GetRevInfo(This,lIndex,lType,pbool) \ ( (This)->lpVtbl -> GetRevInfo(This,lIndex,lType,pbool) ) #define _FramerControl_SetValue(This,strValue,strName,pbool) \ ( (This)->lpVtbl -> SetValue(This,strValue,strName,pbool) ) #define _FramerControl_SetDocVariable(This,strVarName,strValue,lOpt,pbool) \ ( (This)->lpVtbl -> SetDocVariable(This,strVarName,strValue,lOpt,pbool) ) #define _FramerControl_SetPageAs(This,strLocalFile,lPageNum,lType,pbool) \ ( (This)->lpVtbl -> SetPageAs(This,strLocalFile,lPageNum,lType,pbool) ) #define _FramerControl_ReplaceText(This,strSearchText,strReplaceText,lGradation,pbool) \ ( (This)->lpVtbl -> ReplaceText(This,strSearchText,strReplaceText,lGradation,pbool) ) #define _FramerControl_GetEnvironmentVariable(This,EnvironmentName,strValue) \ ( (This)->lpVtbl -> GetEnvironmentVariable(This,EnvironmentName,strValue) ) #define _FramerControl_GetOfficeVersion(This,strName,strValue) \ ( (This)->lpVtbl -> GetOfficeVersion(This,strName,strValue) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ___FramerControl_INTERFACE_DEFINED__ */ #ifndef ___DFramerCtlEvents_DISPINTERFACE_DEFINED__ #define ___DFramerCtlEvents_DISPINTERFACE_DEFINED__ /* dispinterface _DFramerCtlEvents */ /* [hidden][uuid] */ DEFINE_GUID(DIID__DFramerCtlEvents,0x00460185,0x9E5E,0x11d5,0xB7,0xC8,0xB8,0x26,0x90,0x41,0xDD,0x57); #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("00460185-9E5E-11d5-B7C8-B8269041DD57") _DFramerCtlEvents : public IDispatch { }; #else /* C style interface */ typedef struct _DFramerCtlEventsVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( _DFramerCtlEvents * This, /* [in] */ REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( _DFramerCtlEvents * This); ULONG ( STDMETHODCALLTYPE *Release )( _DFramerCtlEvents * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( _DFramerCtlEvents * This, /* [out] */ UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( _DFramerCtlEvents * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( _DFramerCtlEvents * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR *rgszNames, /* [range][in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( _DFramerCtlEvents * This, /* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS *pDispParams, /* [out] */ VARIANT *pVarResult, /* [out] */ EXCEPINFO *pExcepInfo, /* [out] */ UINT *puArgErr); END_INTERFACE } _DFramerCtlEventsVtbl; interface _DFramerCtlEvents { CONST_VTBL struct _DFramerCtlEventsVtbl *lpVtbl; }; #ifdef COBJMACROS #define _DFramerCtlEvents_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define _DFramerCtlEvents_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define _DFramerCtlEvents_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define _DFramerCtlEvents_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define _DFramerCtlEvents_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define _DFramerCtlEvents_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define _DFramerCtlEvents_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ___DFramerCtlEvents_DISPINTERFACE_DEFINED__ */ DEFINE_GUID(CLSID_FramerControl,0x00460182,0x9E5E,0x11d5,0xB7,0xC8,0xB8,0x26,0x90,0x41,0xDD,0x57); #ifdef __cplusplus class DECLSPEC_UUID("00460182-9E5E-11d5-B7C8-B8269041DD57") FramerControl; #endif #endif /* __DSOFramer_LIBRARY_DEFINED__ */ /* Additional Prototypes for ALL interfaces */ /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
[ [ [ 1, 1224 ] ] ]
3958c58f80d02987631d4f2e599d10337f271f0a
16d6176d43bf822ad8d86d4363c3fee863ac26f9
/hw4/rayFunctions.cpp
b5b04b0ff9391e9d67a372e96decf61dbc972578
[]
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
18,385
cpp
#include "nv_math.h" #include "nv_mathdecl.h" #include "nv_algebra.h" #include "rayFunctions.h" const int INF = 999999; const int NO_INTERSECTION = INF; float distanceBetweenPoints(vec3 vec1,vec3 vec2) { return (sqrtf((vec1.x-vec2.x)*(vec1.x-vec2.x)+(vec1.y-vec2.y)*(vec1.y-vec2.y)+(vec1.z-vec2.z)*(vec1.z-vec2.z))); } //Calculate reflecting ray Ray generateRay(vec3 origin,vec3 direction) { /* After clculating the reflecting ray, we need to trace the ray, and multiply the returned colour by some factor, the reflectivity level. Then just add it to the color. */ Ray ref; ref.origin = origin; ref.direction = direction; normalize(ref.direction); return ref; } //Calculate reflecting ray Ray generateReflectedRay(vec3 intersection, vec3 intersectionNorm, Ray intersectingRay) { /* After clculating the reflecting ray, we need to trace the ray, and multiply the returned colour by some factor, the reflectivity level. Then just add it to the color. */ Ray ref; ref.origin = intersection; ref.direction = dot(intersectionNorm,intersectingRay.direction)*2*intersectionNorm-intersectingRay.direction; normalize(ref.direction); return ref; } //Basically the ray equation. I dont feel like typing it over and over vec3 calculateIntersection(Ray ray, float t) { vec3 intersect = ray.origin + t * ray.direction; return intersect; } float intersectsSphere(Ray ray, Object3D sphere) { vec3 originToCenter = sphere.center - ray.origin; float radiusSquared = sphere.radius * sphere.radius; float originCenterLengthSquared = dot(originToCenter,originToCenter); if (originCenterLengthSquared < radiusSquared) { float tclosestApproach = dot(originToCenter, ray.direction) / dot(ray.direction, ray.direction); float halfChordLengthSquared = (radiusSquared - originCenterLengthSquared) / dot(ray.direction, ray.direction) + tclosestApproach * tclosestApproach; return tclosestApproach + sqrtf(halfChordLengthSquared); } else { float tclosestApproach = dot(originToCenter, ray.direction); if (tclosestApproach < 0) return NO_INTERSECTION; float halfChordLengthSquared = (radiusSquared - originCenterLengthSquared)/dot(ray.direction, ray.direction) + (tclosestApproach * tclosestApproach); // division if (halfChordLengthSquared > 0) return tclosestApproach - sqrtf(halfChordLengthSquared); else return NO_INTERSECTION; } } void shootRay(Ray ray, HitRecord& hit) { //initialize temporary t holder for hit detection hit.t = NO_INTERSECTION; float t1 = (float) INF; bool doesIntersect = false; for (int i = 0; i < allObjects.size(); i++) { if (allObjects[i].type == OBJ_TYPE_TRIANGLE) { Object3D tempTri; mat4 transform = invert(transform,allObjects[i].inverse_transformation); Vertex v0, v1, v2; vec4 v0original = vec4(vertexList[allObjects[i].verts[0]].vert.x,vertexList[allObjects[i].verts[0]].vert.y,vertexList[allObjects[i].verts[0]].vert.z,1); vec4 v1original = vec4(vertexList[allObjects[i].verts[1]].vert.x,vertexList[allObjects[i].verts[1]].vert.y,vertexList[allObjects[i].verts[1]].vert.z,1); vec4 v2original = vec4(vertexList[allObjects[i].verts[2]].vert.x,vertexList[allObjects[i].verts[2]].vert.y,vertexList[allObjects[i].verts[2]].vert.z,1); vec4 v0new = mult(v0new,transform,v0original); vec4 v1new = mult(v1new,transform,v1original); vec4 v2new = mult(v2new,transform,v2original); v0.vert = vec3(v0new.x,v0new.y,v0new.z); v1.vert = vec3(v1new.x,v1new.y,v1new.z); v2.vert = vec3(v2new.x,v2new.y,v2new.z); v0.index = vertexList.size() + 2; v1.index = vertexList.size() + 1; v2.index = vertexList.size(); v0.normal = applyTransformToNormal(vertexList[allObjects[i].verts[0]].normal,allObjects[i]); v1.normal = applyTransformToNormal(vertexList[allObjects[i].verts[1]].normal,allObjects[i]); v2.normal = applyTransformToNormal(vertexList[allObjects[i].verts[2]].normal,allObjects[i]); vertexList.push_back(v0); vertexList.push_back(v1); vertexList.push_back(v2); tempTri.verts[0] = vertexList.size() - 3; tempTri.verts[1] = vertexList.size() - 2; tempTri.verts[2] = vertexList.size() - 1; vec3 normal; doFaceNormal(tempTri,normal); t1 = findPlaneParameter(ray,vertexList[tempTri.verts[0]].vert,normal); if(t1<hit.t) { vec3 intersectpoint = calculateIntersection(ray,t1); doesIntersect = isIntersectsTriangle(ray,tempTri,intersectpoint); if(doesIntersect) { hit.t = t1; hit.intersection.point = intersectpoint; hit.normal = normalofTriangleIntersection(tempTri); hit.intersection.obj = allObjects[i]; } } vertexList.pop_back(); vertexList.pop_back(); vertexList.pop_back(); } if (allObjects[i].type == OBJ_TYPE_SPHERE) { Ray transformedRay = ray;//applyInverseTransformToRay(ray,allObjects[i]); t1 = intersectsSphere(transformedRay,allObjects[i]); if(t1 == NO_INTERSECTION) continue; if(t1<hit.t) { vec3 untransformedPoint = calculateIntersection(transformedRay,t1); hit.intersection.point = untransformedPoint;//applyTransformToPoint(untransformedPoint,allObjects[i]); hit.t = t1; hit.normal = normalofSphereIntersection(allObjects[i],untransformedPoint);//applyTransformToNormal(normalofSphereIntersection(allObjects[i],untransformedPoint),allObjects[i]); hit.intersection.obj = allObjects[i]; } } } } RGBA initializeColorOfRay() { RGBA color; color.a = 0; color.b = 0; color.g = 0; color.r = 0; return color; } void rayTrace(int depth) { printf("\n\n\nBeginning Raytrace now!\n"); int divisions = height * width / 20; int divisionCounter = 0; for (int y=0; y<height; y++) { for (int x=0; x<width; x++) { if ((y * width + x) % divisions == 0) printf("Raytracing... %d%% complete...\n",divisionCounter+=5); vec3 centerVec = eye - center; normalize(centerVec); vec3 rightVec; cross(rightVec,up,centerVec); normalize(rightVec); vec3 upVec; cross(upVec,rightVec,centerVec); float a = (float)tan(((fovx / (float)2.0)) * (nv_pi / 180)) * (((float)x - ((float)width / (float)2.0))/((float)width / (float)2.0)); float b = (float)tan(((fovy / (float)2.0)) * (nv_pi / 180)) * ((((float)height / (float)2.0) - (float)y)/((float)height / (float)2.0)); vec3 screenPlaneIntersection = (a * rightVec) + (b * upVec) - centerVec; HitRecord hit; hit.t = NO_INTERSECTION; Ray ray = generateRay(eye, screenPlaneIntersection); ray.color = initializeColorOfRay(); shootRay(ray,hit); if(hit.t == (float)NO_INTERSECTION) { pixelTable[y * width + x] = backColor; } else { pixelTable[y * width + x] = rayColor(ray,hit,depth); } } } printf("Raytracing complete!\n"); } //This only needs to be used for triangles float findPlaneParameter(Ray ray, vec3 pointOnShape, vec3 planeNormal) { float distance = lengthOfVector(eye-center); if(dot(planeNormal,(ray.direction)) == 0) { return NO_INTERSECTION; } else { float t = - (dot((ray.origin - pointOnShape),planeNormal) / dot(ray.direction,planeNormal)); if(t<0) return NO_INTERSECTION; return t; } } bool isIntersectsTriangle(Ray intersectingRay, Object3D tri, vec3 planeIntersect) { vec3 e1 = vertexList[tri.verts[1]].vert - vertexList[tri.verts[0]].vert; vec3 e2 = vertexList[tri.verts[2]].vert - vertexList[tri.verts[0]].vert; vec3 e3 = planeIntersect - vertexList[tri.verts[0]].vert; vec3 normal = cross(normal,e1,e2); float v0v1LengthSquared, v0v1v0v2LengthSquared, v0v2LengthSquared, v0Pv0v1LengthSquared, v0Pv0v2LengthSquared, D; v0v1LengthSquared = dot(e1,e1); v0v1v0v2LengthSquared = dot(e1,e2); v0v2LengthSquared = dot(e2,e2); v0Pv0v1LengthSquared = dot(e3,e1); v0Pv0v2LengthSquared = dot(e3,e2); D = v0v1v0v2LengthSquared * v0v1v0v2LengthSquared - v0v1LengthSquared * v0v2LengthSquared; beta = (v0v1v0v2LengthSquared * v0Pv0v2LengthSquared - v0v2LengthSquared * v0Pv0v1LengthSquared) / D; if (beta < 0.0 || beta > 1.0) return false; gamma = (v0v1v0v2LengthSquared * v0Pv0v1LengthSquared - v0v1LengthSquared * v0Pv0v2LengthSquared) / D; if (gamma < 0.0 || (beta + gamma) > 1.0) return false; alpha = 1 - beta - gamma; return true; } bool shootShadowRay(Ray ray,HitRecord hit) { //initialize temporary t holder for hit detection float t1; bool doesIntersect = false; bool inShadow = false; for(unsigned int i = 0; i < allObjects.size(); i++) { if (allObjects[i].type == OBJ_TYPE_TRIANGLE) { Object3D tempTri; mat4 transform = invert(transform,allObjects[i].inverse_transformation); Vertex v0, v1, v2; vec4 v0original = vec4(vertexList[allObjects[i].verts[0]].vert.x,vertexList[allObjects[i].verts[0]].vert.y,vertexList[allObjects[i].verts[0]].vert.z,1); vec4 v1original = vec4(vertexList[allObjects[i].verts[1]].vert.x,vertexList[allObjects[i].verts[1]].vert.y,vertexList[allObjects[i].verts[1]].vert.z,1); vec4 v2original = vec4(vertexList[allObjects[i].verts[2]].vert.x,vertexList[allObjects[i].verts[2]].vert.y,vertexList[allObjects[i].verts[2]].vert.z,1); vec4 v0new = mult(v0new,transform,v0original); vec4 v1new = mult(v1new,transform,v1original); vec4 v2new = mult(v2new,transform,v2original); v0.vert = vec3(v0new.x,v0new.y,v0new.z); v1.vert = vec3(v1new.x,v1new.y,v1new.z); v2.vert = vec3(v2new.x,v2new.y,v2new.z); v0.normal = applyTransformToNormal(vertexList[allObjects[i].verts[0]].normal,allObjects[i]); v1.normal = applyTransformToNormal(vertexList[allObjects[i].verts[1]].normal,allObjects[i]); v2.normal = applyTransformToNormal(vertexList[allObjects[i].verts[2]].normal,allObjects[i]); v0.index = vertexList.size() + 2; v1.index = vertexList.size() + 1; v2.index = vertexList.size(); vertexList.push_back(v0); vertexList.push_back(v1); vertexList.push_back(v2); tempTri.verts[0] = vertexList.size() - 3; tempTri.verts[1] = vertexList.size() - 2; tempTri.verts[2] = vertexList.size() - 1; vec3 normal; doFaceNormal(tempTri,normal); t1 = findPlaneParameter(ray,vertexList[tempTri.verts[0]].vert,normal); /* vec3 normal; doFaceNormal(allObjects[i],normal); Ray transformedRay = applyInverseTransformToRay(ray,allObjects[i]); t1 = findPlaneParameter(transformedRay,vertexList[allObjects[i].verts[0]].vert,normal);*/ if(t1<hit.t) { vec3 intersectpoint = calculateIntersection(ray,t1); doesIntersect = isIntersectsTriangle(ray,tempTri,intersectpoint); if(doesIntersect) { inShadow = true; } } vertexList.pop_back(); vertexList.pop_back(); vertexList.pop_back(); if(inShadow) return inShadow; } else if (allObjects[i].type == OBJ_TYPE_SPHERE) { Ray transformedRay = ray;//applyInverseTransformToRay(ray,allObjects[i]); t1 = intersectsSphere(transformedRay,allObjects[i]); if(t1 == NO_INTERSECTION) continue; if(t1<hit.t) { inShadow = true; } if(inShadow) return inShadow; } } return inShadow; } float max(float x, float y) { if (x > y) return x; else if (x < y) return y; else return x; } float min(float x, float y) { if (x < y) return x; else if (x > y) return y; else return x; } RGBA rayColor(Ray ray, HitRecord hit, int depth) { Ray refRay,shadowRay; if (hit.t == NO_INTERSECTION) return backColor; if (depth > MAX_DEPTH) return ray.color; HitRecord refRecord; HitRecord shadowRecord; ray.color = globAmb + hit.intersection.obj.mat.material_emission; //Not sure about computing direction vector for pointlights,so //I'm gonna guess L = light position - point of intersection for(unsigned int i = 0; i < pointLightList.size(); i++) { bool inShade = false; //Calculating shadows section PointLight light = pointLightList[i]; //is this the right way to calculate pointLight direction vec3 lightdirection = (light.pos)-hit.intersection.point; normalize(lightdirection); vec3 halfway = (eye + lightdirection); normalize(halfway); shadowRay = generateRay((hit.intersection.point + (EPSILON * lightdirection)),(lightdirection)); shadowRecord.t = findPlaneParameter(shadowRay,light.pos,lightdirection); inShade = shootShadowRay(shadowRay,shadowRecord); if(inShade==false) { float d = distanceBetweenPoints(light.pos,hit.intersection.point); float attenuatingfact = calculateAttenuation(pointLightList[i].attenuationcoeffs[0],pointLightList[i].attenuationcoeffs[1],pointLightList[i].attenuationcoeffs[2],d); RGBA diffuse_component; diffuse_component.r = min((attenuatingfact * hit.intersection.obj.mat.material_diffuse.r * max(dot(lightdirection,hit.normal),0.005)),1); diffuse_component.g = min((attenuatingfact * hit.intersection.obj.mat.material_diffuse.g * max(dot(lightdirection,hit.normal),0.005)),1); diffuse_component.b = min((attenuatingfact * hit.intersection.obj.mat.material_diffuse.b * max(dot(lightdirection,hit.normal),0.005)),1); diffuse_component.a = min((attenuatingfact * hit.intersection.obj.mat.material_diffuse.a * max(dot(lightdirection,hit.normal),0.005)),1); RGBA specular_component; specular_component.r = min((hit.intersection.obj.mat.material_specular.r * pow(dot(hit.normal, halfway),hit.intersection.obj.mat.shininess)),1); specular_component.g = min((hit.intersection.obj.mat.material_specular.g * pow(dot(hit.normal, halfway),hit.intersection.obj.mat.shininess)),1); specular_component.b = min((hit.intersection.obj.mat.material_specular.b * pow(dot(hit.normal, halfway),hit.intersection.obj.mat.shininess)),1); specular_component.a = min((hit.intersection.obj.mat.material_specular.a * pow(dot(hit.normal, halfway),hit.intersection.obj.mat.shininess)),1); RGBA color = pointLightList[i].color * (diffuse_component + specular_component); ray.color = ray.color + color; } } for(unsigned int i = 0; i < dirLightList.size(); i++) { bool inShade = false; //Calculating shadows section DirectionalLight light = dirLightList[i]; //is this the right way to calculate pointLight direction vec3 lightdirection = light.dir; normalize(lightdirection); shadowRay = generateRay((hit.intersection.point + (EPSILON * lightdirection)),(lightdirection)); vec3 halfway = (eye + lightdirection); normalize(halfway); shadowRecord.t = INF; inShade = shootShadowRay(shadowRay,shadowRecord); if(inShade==false) { RGBA specular_component; specular_component.r = min((hit.intersection.obj.mat.material_specular.r * pow(dot(hit.normal, halfway),hit.intersection.obj.mat.shininess)),1); specular_component.g = min((hit.intersection.obj.mat.material_specular.g * pow(dot(hit.normal, halfway),hit.intersection.obj.mat.shininess)),1); specular_component.b = min((hit.intersection.obj.mat.material_specular.b * pow(dot(hit.normal, halfway),hit.intersection.obj.mat.shininess)),1); specular_component.a = min((hit.intersection.obj.mat.material_specular.a * pow(dot(hit.normal, halfway),hit.intersection.obj.mat.shininess)),1); RGBA diffuse_component; diffuse_component.r = min((hit.intersection.obj.mat.material_diffuse.r * max(dot(lightdirection,hit.normal),0.005)),1); diffuse_component.g = min((hit.intersection.obj.mat.material_diffuse.g * max(dot(lightdirection,hit.normal),0.005)),1); diffuse_component.b = min((hit.intersection.obj.mat.material_diffuse.b * max(dot(lightdirection,hit.normal),0.005)),1); diffuse_component.a = min((hit.intersection.obj.mat.material_diffuse.a * max(dot(lightdirection,hit.normal),0.005)),1); RGBA color = dirLightList[i].color * (diffuse_component + specular_component); ray.color = ray.color + color; } } if (hit.intersection.obj.mat.material_specular.r != 0 || hit.intersection.obj.mat.material_specular.g != 0 || hit.intersection.obj.mat.material_specular.b != 0 || hit.intersection.obj.mat.material_specular.a != 0) { vec3 intersect; intersect.x = hit.intersection.point.x; intersect.y = hit.intersection.point.y; intersect.z = hit.intersection.point.z; vec3 refDirection = (ray.direction - 2 * (dot(hit.normal, ray.direction) * hit.normal)); normalize(refDirection); refRay = generateRay(intersect + EPSILON * refDirection,refDirection); shootRay(refRay,refRecord); ray.color = ray.color + hit.intersection.obj.mat.material_specular * rayColor(refRay,refRecord,depth + 1); } if (ray.color.r > 1) ray.color.r = 1; if (ray.color.b > 1) ray.color.b = 1; if (ray.color.g > 1) ray.color.g = 1; return ray.color; } Ray applyInverseTransformToRay(Ray ray, Object3D obj) { vec4 origin = vec4(ray.origin.x, ray.origin.y, ray.origin.z, 1); vec4 direction = vec4(ray.direction.x, ray.direction.y, ray.direction.z, 0); vec4 newOrigin; mult(newOrigin,obj.inverse_transformation,origin); vec4 newDirection; mult(newDirection,obj.inverse_transformation,direction); Ray newRay; newRay.origin.x = newOrigin.x; newRay.origin.y = newOrigin.y; newRay.origin.z = newOrigin.z; newRay.direction.x = newDirection.x; newRay.direction.y = newDirection.y; newRay.direction.z = newDirection.z; return newRay; } vec3 applyTransformToPoint(vec3 point, Object3D obj) { vec4 pointUntransformed = vec4(point.x,point.y,point.z,1); mat4 transform; invert(transform,obj.inverse_transformation); vec4 transformedPoint; mult(transformedPoint,transform,pointUntransformed); return vec3(transformedPoint.x,transformedPoint.y,transformedPoint.z); } vec3 applyTransformToNormal(vec3 normal, Object3D obj) { vec4 normalUntransformed = vec4(normal.x,normal.y,normal.z,0); mat4 transformTranspose; transpose(transformTranspose,obj.inverse_transformation); vec4 normalTransformed; mult(normalTransformed,transformTranspose,normalUntransformed); normalize(normalTransformed); return vec3(normalTransformed.x,normalTransformed.y,normalTransformed.z); }
[ "dhrumins@074c0a88-b503-11dd-858c-a3a1ac847323" ]
[ [ [ 1, 495 ] ] ]
82095e01cf1186fd7ee571cd588fdd06cf177c25
58496be10ead81e2531e995f7d66017ffdfc6897
/Sources/Common/IStorageFileImpl.cpp
1130d4f199c18cf93716de79d434ebab80719c42
[]
no_license
Diego160289/cross-fw
ba36fc6c3e3402b2fff940342315596e0365d9dd
532286667b0fd05c9b7f990945f42279bac74543
refs/heads/master
2021-01-10T19:23:43.622578
2011-01-09T14:54:12
2011-01-09T14:54:12
38,457,864
0
0
null
null
null
null
UTF-8
C++
false
false
4,497
cpp
//============================================================================ // Date : 22.12.2010 // Author : Tkachenko Dmitry // Copyright : (c) Tkachenko Dmitry ([email protected]) //============================================================================ #include "IStorageFileImpl.h" #include "RefObjQIPtr.h" #include "IStreamFileImpl.h" #include "IEnumImpl.h" namespace IFacesImpl { IStorageFileImpl::IStorageFileImpl() { } IStorageFileImpl::~IStorageFileImpl() { } RetCode IStorageFileImpl::CreateStorage(const char *name, IFaces::IStorage **storage) { Common::ISyncObject Locker(GetSynObj()); if (!name) return retBadParam; try { std::string DirName = StorageName + "/"; DirName += name; Common::RefObjQIPtr<IFaces::IStorage> NewStg(OpenFileStorage(DirName, true, GetSynObj())); if (!System::CreateDir(DirName.c_str())) return retFail; if (NewStg.QueryInterface(storage) != retOk) System::RemoveDir(StorageName.c_str()); return retOk; } catch (std::exception &) { } return retFail; } RetCode IStorageFileImpl::OpenStorage(const char *name, IFaces::IStorage **storage) { Common::ISyncObject Locker(GetSynObj()); if (!name) return retBadParam; try { std::string DirName = StorageName + "/"; DirName += name; return OpenFileStorage(DirName, false, GetSynObj()).QueryInterface(storage); } catch (std::exception &) { } return retFail; } RetCode IStorageFileImpl::CreateStream(const char *name, IFaces::IStream **stream) { Common::ISyncObject Locker(GetSynObj()); try { std::string FileName = StorageName + "/"; FileName += name; Common::RefObjQIPtr<IFaces::IStream> NewStream(OpenFileStream(FileName.c_str(), true, GetSynObj())); return NewStream.QueryInterface(stream); } catch (std::exception &) { } return retFail; } RetCode IStorageFileImpl::OpenStream(const char *name, IFaces::IStream **stream) { Common::ISyncObject Locker(GetSynObj()); try { std::string FileName = StorageName + "/"; FileName += name; Common::RefObjQIPtr<IFaces::IStream> NewStream(OpenFileStream(FileName.c_str(), false, GetSynObj())); return NewStream.QueryInterface(stream); } catch (std::exception &) { } return retFail; } RetCode IStorageFileImpl::RemoveItem(const char *name) { Common::ISyncObject Locker(GetSynObj()); return System::RemoveDir(name) ? retOk : retFail; } RetCode IStorageFileImpl::Enum(IFaces::IEnum **items) const { Common::ISyncObject Locker(GetSynObj()); System::DirItemPoolPtr DirItems = System::EnumDir(StorageName.c_str()); if (!DirItems.get()) return retFail; try { Common::RefObjPtr<IEnumImpl> NewEnum(CreateEnum(GetSynObj())); for (System::DirItemPool::const_iterator i = DirItems->begin() ; i != DirItems->end() ; ++i) { std::string NewItemName = StorageName + "/"; NewItemName += i->first; Common::RefObjPtr<IFaces::IBase> NewItem; if (i->second) NewItem = Common::RefObjQIPtr<IFaces::IBase>(OpenFileStorage(NewItemName, false, GetSynObj())); else NewItem = Common::RefObjQIPtr<IFaces::IBase>(OpenFileStream(NewItemName, false, GetSynObj())); if (!NewItem.Get()) return retFail; NewEnum->AddItem(NewItem); } return NewEnum.QueryInterface(items); } catch (std::exception &) { } return retFail; } void IStorageFileImpl::Init(const std::string &name, bool isNew) { if (name.empty()) throw IStorageFileImplException("Empty dir name"); if (!isNew && !System::ExistsDir(name.c_str())) throw IStorageFileImplException("Dir not exists"); if (isNew && !System::CreateDir(name.c_str())) throw IStorageFileImplException("Can't create dir"); StorageName = name; } Common::RefObjPtr<IStorageFileImpl> OpenFileStorage(const std::string &name, bool createNew, const Common::ISynObj &syn) { Common::RefObjPtr<IStorageFileImpl> Ret = Common::IBaseImpl<IStorageFileImpl>::CreateWithSyn(syn); Ret->Init(name, createNew); return Ret; } }
[ "TkachenkoDmitryV@d548627a-540d-11de-936b-e9512c4d2277" ]
[ [ [ 1, 153 ] ] ]
be07f4fbe0f9d386b139c318432b7f92f26f138e
a3e98a956c86bb542efbce9519ff526f7c82707c
/DTXor.h
f3f6f7b7d24c81eab9e0f4744e194e27027b6831
[]
no_license
arturo182/DTBViewer
8956b65d7ea414d0ef65cd5439e7ef6d62923f8a
4247c1030b77679970b0b26dc9eb295c9aea9e61
refs/heads/master
2021-01-25T10:49:34.699179
2010-09-22T22:44:06
2010-09-22T22:44:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
374
h
#ifndef DTXOR_H #define DTXOR_H #include "DT.h" #include <QtCore/QString> namespace DT { class DTXor { public: static QByteArray encryptString(int keyType, QByteArray str); static QByteArray decryptString(int keyType, QByteArray str); static char keyHistory[11]; static char keyConfig[19]; }; }; #endif // DTXOR_H
[ [ [ 1, 21 ] ] ]
2ae433e492a3a5f66b5b46fcef889d25f4199596
e311980b8c52620c91d697c15ed9d5e77e58ffb8
/Lex.hpp
e6247fce844f7652f138ae1180112a0683dde2c1
[]
no_license
matt-welch/k1-microcontroller-assembler
b58169ad04f91b22150b087de93ffea723e049dc
526ab193d360bf8ca5b5957897dae539f917ec89
refs/heads/master
2016-09-13T13:01:40.440656
2011-12-06T16:53:41
2011-12-06T16:53:41
58,680,398
0
0
null
null
null
null
UTF-8
C++
false
false
1,812
hpp
//************************************************************************************************************** // CLASS: Lex // // DESCRIPTION // Implements the lexical analyzer which returns successive tokens read from the source code file. // // COURSE // CSE220 Programming for Computer Engineering, Fall 2011 // // AUTHOR INFORMATION // Kevin R. Burger [KRB] // James Matthew Welch [JMW] // // Mailing Address: // Computer Science & Engineering // School of Computing, Informatics, and Decision Systems Engineering // Arizona State University // Tempe, AZ 85287-8809 // // Email: burgerk@asu // Web: http://kevin.floorsoup.com // Email: [email protected] // Web: https://bitbucket.org/mwelch/k1-microcontroller-assembler // // MODIFICATION HISTORY: // ------------------------------------------------------------------------------------------------------------- // 21 Nov 2011 [KRB] Initial revision. // 06 Dec 2011 [JMW] Submission for grading //************************************************************************************************************** #ifndef __LEX_HPP__ #define __LEX_HPP__ #include <fstream> #include <string> #include "Types.hpp" //============================================================================================================== // CLASS: Lex //============================================================================================================== class Lex { public: Lex ( std::string const& pSrcFname = "" ); ~Lex ( ); std::string NextToken ( ); void Reset ( ); void SkipRestOfLine ( ); protected: std::ifstream mFin; std::string mSrcFname; }; #endif
[ [ [ 1, 69 ] ] ]
ca75cf2565a46ed7eed1373ae1a2abaea4e0e8a4
6d0c97a1620f395224a14f6a82c0933786f4a557
/src/gdx-cpp/graphics/glutils/MipMapGenerator.cpp
cc317128de51cd0ef9b310789d74e1a5d43c326f
[ "Apache-2.0" ]
permissive
henviso/libgdx-cpp
0c8010604577ff29ea15dc40cf1079c248812516
b4d2944cfbefca28314b228b89afcd94a6a15e0e
refs/heads/master
2021-01-18T12:25:38.826383
2011-09-19T18:11:24
2011-09-19T18:11:24
2,223,345
0
0
null
null
null
null
UTF-8
C++
false
false
5,061
cpp
/* Copyright 2011 Aevum Software aevum @ aevumlab.com 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. @author Victor Vicente de Carvalho [email protected] @author Ozires Bortolon de Faria [email protected] */ #include "MipMapGenerator.hpp" #include "gdx-cpp/graphics/Pixmap.hpp" #include "gdx-cpp/graphics/GL20.hpp" #include "gdx-cpp/graphics/GL10.hpp" #include "gdx-cpp/Application.hpp" #include "gdx-cpp/Graphics.hpp" #include "gdx-cpp/Gdx.hpp" #include <stdexcept> using namespace gdx_cpp; using namespace gdx_cpp::graphics; using namespace gdx_cpp::graphics::glutils; bool MipMapGenerator::useHWMipMap = true; void MipMapGenerator::setUseHardwareMipMap (bool useHWMipMap) { MipMapGenerator::useHWMipMap = useHWMipMap; } void MipMapGenerator::generateMipMap (gdx_cpp::graphics::Pixmap& pixmap,int textureWidth,int textureHeight,bool disposePixmap) { if (!useHWMipMap) { generateMipMapCPU(pixmap, textureWidth, textureHeight, disposePixmap); return; } if (gdx_cpp::Gdx::app->getType() == gdx_cpp::Application::Android) { if (gdx_cpp::Gdx::graphics->isGL20Available()) generateMipMapGLES20(pixmap, disposePixmap); else generateMipMapCPU(pixmap, textureWidth, textureHeight, disposePixmap); } else { generateMipMapDesktop(pixmap, textureWidth, textureHeight, disposePixmap); } } void MipMapGenerator::generateMipMapGLES20 (gdx_cpp::graphics::Pixmap& pixmap,bool disposePixmap) { Gdx::gl->glTexImage2D(GL20::GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); Gdx::gl20->glGenerateMipmap(GL20::GL_TEXTURE_2D); if (disposePixmap) pixmap.dispose(); } void MipMapGenerator::generateMipMapDesktop (gdx_cpp::graphics::Pixmap& pixmap,int textureWidth,int textureHeight,bool disposePixmap) { if (Gdx::graphics->isGL20Available() && (Gdx::graphics->supportsExtension("GL_ARB_framebuffer_object") || Gdx::graphics ->supportsExtension("GL_EXT_framebuffer_object"))) { Gdx::gl->glTexImage2D(GL20::GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); Gdx::gl20->glGenerateMipmap(GL20::GL_TEXTURE_2D); if (disposePixmap) pixmap.dispose(); } else if (Gdx::graphics->supportsExtension("GL_SGIS_generate_mipmap")) { if ((Gdx::gl20 == NULL) && textureWidth != textureHeight) { throw std::runtime_error("texture width and height must be square when using mipmapping in OpenGL ES 1.x"); } Gdx::gl->glTexParameterf(GL20::GL_TEXTURE_2D, GLCommon::GL_GENERATE_MIPMAP, GL10::GL_TRUE); Gdx::gl->glTexImage2D(GL20::GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); if (disposePixmap) pixmap.dispose(); } else { generateMipMapCPU(pixmap, textureWidth, textureHeight, disposePixmap); } } void MipMapGenerator::generateMipMapCPU (Pixmap& pixmap,int textureWidth,int textureHeight,bool disposePixmap) { Gdx::gl->glTexImage2D(GL10::GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); if ((Gdx::gl20 == NULL) && textureWidth != textureHeight) { std::runtime_error("texture width and height must be square when using mipmapping."); } int width = pixmap.getWidth() / 2; int height = pixmap.getHeight() / 2; int level = 1; while (width > 0 && height > 0) { Pixmap tmp(width, height, pixmap.getFormat()); tmp.drawPixmap(pixmap, 0, 0, pixmap.getWidth(), pixmap.getHeight(), 0, 0, width, height); if (level > 1 || disposePixmap) pixmap.dispose(); pixmap = tmp; Gdx::gl->glTexImage2D(GL10::GL_TEXTURE_2D, level, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); width = pixmap.getWidth() / 2; height = pixmap.getHeight() / 2; level++; } pixmap.dispose(); }
[ [ [ 1, 112 ] ] ]
c2d0ff6ffac293c80be5d40e9c38d16c8c64d5a5
2112057af069a78e75adfd244a3f5b224fbab321
/branches/refactor/src_root/include/common/resource/resource_manager.h
1ce91a1d173300093bf50946a8dd96c661268633
[]
no_license
blockspacer/ireon
120bde79e39fb107c961697985a1fe4cb309bd81
a89fa30b369a0b21661c992da2c4ec1087aac312
refs/heads/master
2023-04-15T00:22:02.905112
2010-01-07T20:31:07
2010-01-07T20:31:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,499
h
/* Copyright (C) 2005 ireon.org developers council * $Id: resource_manager.h 288 2005-11-26 09:46:52Z zak $ * 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., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ /** * @file resource_manager.h * Resource manager */ #ifndef _RESOURCE_MANAGER_H #define _RESOURCE_MANAGER_H class CResourceLocation; class CResourceManager { public: static CResourceManager* instance() { if( !m_singleton ) m_singleton = new CResourceManager(); return m_singleton; } void addLocation(const String& loc, const String& type); DataPtr load(const String& name); protected: /// List of resource locations std::vector<CResourceLocation*> m_locations; /// Vector of available resource names std::map<String,CResourceLocation*> m_resources; static CResourceManager* m_singleton; }; #endif
[ [ [ 1, 49 ] ] ]
f3bf0f5199595c2a82699292b888fb58971c8822
6e4f9952ef7a3a47330a707aa993247afde65597
/PROJECTS_ROOT/WireKeys/WP_TextScr/WP_TextScr.cpp
10c0a9474551f56c82b291e48f47f87c6dc02453
[]
no_license
meiercn/wiredplane-wintools
b35422570e2c4b486c3aa6e73200ea7035e9b232
134db644e4271079d631776cffcedc51b5456442
refs/heads/master
2021-01-19T07:50:42.622687
2009-07-07T03:34:11
2009-07-07T03:34:11
34,017,037
2
1
null
null
null
null
UTF-8
C++
false
false
1,612
cpp
// IconsFont.cpp : Defines the initialization routines for the DLL. // #include "stdafx.h" #include <atlbase.h> #include "WP_TextScr.h" #include "HookCode.h" #include "WindowHelper.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern COptions plgOptions; extern CString g_sResult; extern CArray<HWND,HWND> g_Windows; BOOL CALLBACK AddCWin(HWND hwnd,LPARAM lParam) { g_Windows.Add(hwnd); return TRUE; } void GetWindowTopParent(HWND& hWnd) { if(!hWnd){ return; } //hWnd=::GetAncestor(hWnd,GA_ROOT); HWND hWnd2=hWnd; while(hWnd2!=NULL){ hWnd=hWnd2; hWnd2=::GetWindow(hWnd,GW_OWNER); if(!hWnd2){ hWnd2=::GetParent(hWnd); } } return; } WKCallbackInterface*& WKGetPluginContainer(); CString _l(const char* szText); BOOL StartWindProcessing() { if(g_Windows.GetSize()==0){ return 0; } WKGetPluginContainer()->ShowBaloon(_l("Parsing window"),_l("Text grabber"),9000); EnumChildWindows(g_Windows[0],AddCWin,0); g_sResult=""; HRESULT hRes = ::CoInitialize(NULL); CWindowHelper _WindowHelper; _WindowHelper.Attach(g_Windows[0]); g_sResult+=_WindowHelper.GetCombinedTextInfo(); _WindowHelper.Release(); if(g_sResult==""){ //Default approach... char szBuffer[10000]=""; for(int i=0;i<g_Windows.GetSize();i++){ ::GetWindowText(g_Windows[i],szBuffer,sizeof(szBuffer)); if(strlen(szBuffer)>0){ g_sResult+=szBuffer; g_sResult+="\r\n------------------\r\n"; } } } WKGetPluginContainer()->ShowBaloon("","",0); return TRUE; }
[ "wplabs@3fb49600-69e0-11de-a8c1-9da277d31688" ]
[ [ [ 1, 72 ] ] ]
075e56f2cb2846ebfb6ab4456d21a2568f273877
d9d498167237f41a9cf47f4ec2d444a49da4b23b
/zhangxin/example2/monitor_info_TestPattern.h
155b5b8cc81e9f8eb5e67491bc30579aadcf7a22
[]
no_license
wangluyi1982/piggypic
d81cf15a6b58bbb5a9cde3d124333348419c9663
d173e3acc6c3e57267733fb7b80b1b07cb21fa01
refs/heads/master
2021-01-10T20:13:42.615324
2010-03-17T13:44:49
2010-03-17T13:44:49
32,907,995
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
688
h
// *************************************************************** // monitor_info_TestPattern version: 1.0 · date: 07/28/2006 // ------------------------------------------------------------- // // ------------------------------------------------------------- // Copyright (C) 2006 - All Rights Reserved // *************************************************************** // // *************************************************************** #ifndef _monitor_info_TestPattern #define _monitor_info_TestPattern class monitor_info_TestPattern { public: CString MonitorName; int SystemNo; CRect DesktopOfMonitor; protected: private: }; #endif
[ "zhangxin.sanjin@fa8d6de2-2387-11df-88d9-3f628f631586" ]
[ [ [ 1, 24 ] ] ]
b342dcb47684e1479cdeb58ac14ae4f83eb6e2a7
5fea042a436493f474afaf862ea592fa37c506ab
/Loader/inject.cpp
85429b42b37e8d2399471ac849b2876db18a2cd2
[]
no_license
Danteoriginal/twilight-antihack
9fde8fbd2f34954752dc2de3927490d657b43739
4ccc51c13c33abcb5e370ef1b992436e6a1533c9
refs/heads/master
2021-01-13T06:25:31.618338
2009-10-25T14:44:34
2009-10-25T14:44:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,299
cpp
#include "inject.h" void InjectAntihack(HANDLE hProc) { if (!hProc) throw std::exception("Invalid process handle"); HMODULE hModule = GetModuleHandleA("kernel32.dll"); if (!hModule) throw std::exception("Could not acquire module of kernel32.dll"); FARPROC pLoadLibrary = GetProcAddress(hModule, "LoadLibraryA"); if (!pLoadLibrary) throw std::exception("Could not acquire address of LoadLibraryA"); const std::string dllName = "antihack.dll"; int size = dllName.length()+1; void* pRemoteAddress = VirtualAllocEx(hProc, 0, size, MEM_COMMIT, PAGE_READWRITE); if (!pRemoteAddress) throw std::exception("Could not allocate remote memory"); if ( !WriteProcessMemory(hProc, pRemoteAddress, (void*)dllName.c_str(), size, 0) ) throw std::exception("Could not write remote string"); HANDLE hThread = CreateRemoteThread(hProc, 0, 0, (LPTHREAD_START_ROUTINE)pLoadLibrary, pRemoteAddress, 0, 0); if (!hThread) throw std::exception("Could not start remote thread"); WaitForSingleObject(hThread, INFINITE); DWORD dwExit = 0; GetExitCodeThread(hThread, &dwExit); if (!dwExit) throw std::exception("Error while loading remote dll"); if ( !VirtualFreeEx(hProc, pRemoteAddress, size, MEM_DECOMMIT) ) throw std::exception("Could not free remote memory"); }
[ [ [ 1, 33 ] ] ]
b7f6eb0533af3e04ee8e557becdf86b8eb051d16
b4d726a0321649f907923cc57323942a1e45915b
/CODE/GRAPHICS/gropengltnl.cpp
ba9c803002b1f4746ec6efad546425289746af39
[]
no_license
chief1983/Imperial-Alliance
f1aa664d91f32c9e244867aaac43fffdf42199dc
6db0102a8897deac845a8bd2a7aa2e1b25086448
refs/heads/master
2016-09-06T02:40:39.069630
2010-10-06T22:06:24
2010-10-06T22:06:24
967,775
2
0
null
null
null
null
UTF-8
C++
false
false
13,580
cpp
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on the * source. * */ /* * $Logfile: /Freespace2/code/Graphics/GrOpenGLTNL.cpp $ * $Revision: 1.1.1.1 $ * $Date: 2004/08/13 22:47:41 $ * $Author: Spearhawk $ * * source for doing the fun TNL stuff * * $Log: gropengltnl.cpp,v $ * Revision 1.1.1.1 2004/08/13 22:47:41 Spearhawk * no message * * Revision 1.1.1.1 2004/08/13 20:47:16 Darkhill * no message * * Revision 1.1 2004/05/24 07:25:32 taylor * filename case change * * Revision 2.4 2004/04/26 13:05:19 taylor * respect -glow and -spec * * Revision 2.3 2004/04/13 01:55:41 phreak * put in the correct fields for the CVS comments to register * fixed a glowmap problem that occured when rendering glowmapped and non-glowmapped ships * * * $NoKeywords: $ */ #include <windows.h> #include "globalincs/pstypes.h" #include "model/model.h" #include "graphics/gl/gl.h" #include "graphics/gl/glu.h" #include "graphics/gl/glext.h" #include "graphics/2d.h" #include "graphics/grinternal.h" #include "graphics/gropengl.h" #include "graphics/gropenglextension.h" #include "graphics/gropengltexture.h" #include "graphics/gropengllight.h" #include "graphics/gropengltnl.h" #include "math/vecmat.h" #include "render/3d.h" #include "debugconsole/timerbar.h" extern int VBO_ENABLED; extern int GLOWMAP; extern int CLOAKMAP; extern int SPECMAP; extern int NORMMAP; // Angelus extern vector G3_user_clip_normal; extern vector G3_user_clip_point; extern int Interp_multitex_cloakmap; extern int Interp_cloakmap_alpha; int GL_modelview_matrix_depth = 1; int GL_htl_projection_matrix_set = 0; int GL_htl_view_matrix_set = 0; struct opengl_vertex_buffer { int n_poly; vector *vertex_array; uv_pair *texcoord_array; vector *normal_array; int used; uint vbo_vert; uint vbo_norm; uint vbo_tex; }; #define MAX_SUBOBJECTS 64 #ifdef INF_BUILD #define MAX_BUFFERS_PER_SUBMODEL 24 #else #define MAX_BUFFERS_PER_SUBMODEL 16 #endif #define MAX_BUFFERS MAX_POLYGON_MODELS*MAX_SUBOBJECTS*MAX_BUFFERS_PER_SUBMODEL static opengl_vertex_buffer vertex_buffers[MAX_BUFFERS]; //zeros everything out void opengl_init_vertex_buffers() { memset(vertex_buffers,0,sizeof(opengl_vertex_buffer)*MAX_BUFFERS); } int opengl_find_first_free_buffer() { for (int i=0; i < MAX_BUFFERS; i++) { if (!vertex_buffers[i].used) return i; } return -1; } int opengl_check_for_errors() { #ifdef _DEBUG int error=0; if ((error=glGetError()) != GL_NO_ERROR) { mprintf(("!!ERROR!!: %s\n", gluErrorString(error))); return 1; } #endif return 0; } int opengl_mod_depth() { int mv; glGetIntegerv(GL_MODELVIEW_STACK_DEPTH, &mv); return mv; } uint opengl_create_vbo(uint size, void** data) { if (!data) return 0; if (!*data) return 0; if (size == 0) return 0; // Kazan: A) This makes that if (buffer_name) work correctly (false = 0, true = anything not 0) // if glGenBuffersARB() doesn't initialized it for some reason // B) It shuts up MSVC about may be used without been initalized uint buffer_name=0; glGenBuffersARB(1, &buffer_name); //make sure we have one if (buffer_name) { glBindBufferARB(GL_ARRAY_BUFFER_ARB, buffer_name); glBufferDataARB(GL_ARRAY_BUFFER_ARB, size, *data, GL_STATIC_DRAW_ARB ); //just in case if (opengl_check_for_errors()) { return 0; } else { free(*data); *data = NULL; // mprintf(("VBO Created: %d\n", buffer_name)); } } return buffer_name; } int gr_opengl_make_buffer(poly_list *list) { int buffer_num=opengl_find_first_free_buffer(); //we have a valid buffer if (buffer_num > -1) { opengl_vertex_buffer *vbp=&vertex_buffers[buffer_num]; vbp->used=1; vbp->n_poly=list->n_poly; vbp->texcoord_array=(uv_pair*)malloc(list->n_poly * 3 * sizeof(uv_pair)); memset(vbp->texcoord_array,0,list->n_poly*sizeof(uv_pair)); vbp->normal_array=(vector*)malloc(list->n_poly * 3 * sizeof(vector)); memset(vbp->normal_array,0,list->n_poly*sizeof(vector)); vbp->vertex_array=(vector*)malloc(list->n_poly * 3 * sizeof(vector)); memset(vbp->vertex_array,0,list->n_poly*sizeof(vector)); vector *n=vbp->normal_array; vector *v=vbp->vertex_array; uv_pair *t=vbp->texcoord_array; vertex *vl; memcpy(n,list->norm,list->n_poly*sizeof(vector)*3); for (int i=0; i < list->n_poly*3; i++) { vl=&list->vert[i]; v->xyz.x=vl->x; v->xyz.y=vl->y; v->xyz.z=vl->z; v++; t->u=vl->u; t->v=vl->v; t++; } //maybe load it into a vertex buffer object if (VBO_ENABLED) { vbp->vbo_vert=opengl_create_vbo(vbp->n_poly*9*sizeof(float),(void**)&vbp->vertex_array); vbp->vbo_norm=opengl_create_vbo(vbp->n_poly*9*sizeof(float),(void**)&vbp->normal_array); vbp->vbo_tex=opengl_create_vbo(vbp->n_poly*6*sizeof(float),(void**)&vbp->texcoord_array); } } return buffer_num; } void gr_opengl_destroy_buffer(int idx) { opengl_vertex_buffer *vbp=&vertex_buffers[idx]; if (vbp->normal_array) free(vbp->normal_array); if (vbp->texcoord_array) free(vbp->texcoord_array); if (vbp->vertex_array) free(vbp->vertex_array); if (vbp->vbo_norm) glDeleteBuffersARB(1,&vbp->vbo_norm); if (vbp->vbo_vert) glDeleteBuffersARB(1,&vbp->vbo_vert); if (vbp->vbo_tex) glDeleteBuffersARB(1,&vbp->vbo_tex); memset(vbp,0,sizeof(opengl_vertex_buffer)); } //#define DRAW_DEBUG_LINES extern float Model_Interp_scale_x,Model_Interp_scale_y,Model_Interp_scale_z; void gr_opengl_render_buffer(int idx) { Assert(GL_htl_projection_matrix_set); Assert(GL_htl_view_matrix_set); TIMERBAR_PUSH(2); float u_scale,v_scale; if (glIsEnabled(GL_CULL_FACE)) glFrontFace(GL_CW); glColor3ub(255,255,255); opengl_vertex_buffer *vbp=&vertex_buffers[idx]; glEnableClientState(GL_VERTEX_ARRAY); if (vbp->vbo_vert) { glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbp->vbo_vert); glVertexPointer(3,GL_FLOAT,0, (void*)NULL); } else { glVertexPointer(3,GL_FLOAT,0,vbp->vertex_array); } glEnableClientState(GL_NORMAL_ARRAY); if (vbp->vbo_norm) { glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbp->vbo_norm); glNormalPointer(GL_FLOAT,0, (void*)NULL); } else { glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0); glNormalPointer(GL_FLOAT,0,vbp->normal_array); } glClientActiveTextureARB(GL_TEXTURE0_ARB); glEnableClientState(GL_TEXTURE_COORD_ARRAY); if (vbp->vbo_tex) { glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbp->vbo_tex); glTexCoordPointer(2,GL_FLOAT,0,(void*)NULL); } else { glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0); glTexCoordPointer(2,GL_FLOAT,0,vbp->texcoord_array); } if (Interp_multitex_cloakmap > 0) { SPECMAP = -1; // don't add a spec map if we are cloaked GLOWMAP = -1; // don't use a glowmap either, shouldn't see them NORMMAP = -1; // Angelus - or the normal map for that matter glClientActiveTextureARB(GL_TEXTURE1_ARB); glEnableClientState(GL_TEXTURE_COORD_ARRAY); if (vbp->vbo_tex) { glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbp->vbo_tex); glTexCoordPointer(2,GL_FLOAT,0,(void*)NULL); } else { glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0); glTexCoordPointer(2,GL_FLOAT,0,vbp->texcoord_array); } } if ( (GLOWMAP > -1) && !Cmdline_noglow ) { glClientActiveTextureARB(GL_TEXTURE1_ARB); glEnableClientState(GL_TEXTURE_COORD_ARRAY); if (vbp->vbo_tex) { glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbp->vbo_tex); glTexCoordPointer(2,GL_FLOAT,0,(void*)NULL); } else { glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0); glTexCoordPointer(2,GL_FLOAT,0,vbp->texcoord_array); } } if ((SPECMAP > -1) && !Cmdline_nospec && (GL_supported_texture_units > 2)) { glClientActiveTextureARB(GL_TEXTURE2_ARB); glEnableClientState(GL_TEXTURE_COORD_ARRAY); if (vbp->vbo_tex) { glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbp->vbo_tex); glTexCoordPointer(2,GL_FLOAT,0,(void*)NULL); } else { glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0); glTexCoordPointer(2,GL_FLOAT,0,vbp->texcoord_array); } } if ((NORMMAP > -1) /*&& !Cmdline_nospec*/ && (GL_supported_texture_units > 2)) { glClientActiveTextureARB(GL_TEXTURE3_ARB); glEnableClientState(GL_TEXTURE_COORD_ARRAY); if (vbp->vbo_tex) { glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbp->vbo_tex); glTexCoordPointer(2,GL_FLOAT,0,(void*)NULL); } else { glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0); glTexCoordPointer(2,GL_FLOAT,0,vbp->texcoord_array); } } int r,g,b,a,tmap_type; opengl_setup_render_states(r,g,b,a,tmap_type,TMAP_FLAG_TEXTURED,0); if (gr_screen.current_bitmap==CLOAKMAP) { glBlendFunc(GL_ONE,GL_ONE); r=g=b=Interp_cloakmap_alpha; a=255; } gr_tcache_set(gr_screen.current_bitmap, tmap_type, &u_scale, &v_scale, 0, gr_screen.current_bitmap_sx, gr_screen.current_bitmap_sy, 0); glLockArraysEXT(0,vbp->n_poly*3); opengl_pre_render_init_lights(); opengl_change_active_lights(0); glDrawArrays(GL_TRIANGLES,0,vbp->n_poly*3); if((lighting_is_enabled)&&((n_active_gl_lights-1)/max_gl_lights > 0)) { gr_opengl_set_state( TEXTURE_SOURCE_DECAL, ALPHA_BLEND_ALPHA_ADDITIVE, ZBUFFER_TYPE_READ ); opengl_switch_arb(1,0); opengl_switch_arb(2,0); for(int i=1; i< (n_active_gl_lights-1)/max_gl_lights; i++) { opengl_change_active_lights(i); glDrawArrays(GL_TRIANGLES,0,vbp->n_poly*3); } } glUnlockArraysEXT(); TIMERBAR_POP(); if (VBO_ENABLED) { glBindBufferARB(GL_ARRAY_BUFFER_ARB,0); } #if defined(DRAW_DEBUG_LINES) && defined(_DEBUG) glBegin(GL_LINES); glColor3ub(255,0,0); glVertex3d(0,0,0); glVertex3d(20,0,0); glColor3ub(0,255,0); glVertex3d(0,0,0); glVertex3d(0,20,0); glColor3ub(0,0,255); glVertex3d(0,0,0); glVertex3d(0,0,20); glEnd(); #endif } void gr_opengl_start_instance_matrix(vector *offset, matrix* rotation) { Assert(GL_htl_projection_matrix_set); Assert(GL_htl_view_matrix_set); if (!offset) offset = &vmd_zero_vector; if (!rotation) rotation = &vmd_identity_matrix; glMatrixMode(GL_MODELVIEW); glPushMatrix(); vector axis; float ang; vm_matrix_to_rot_axis_and_angle(rotation,&ang,&axis); glTranslatef(offset->xyz.x,offset->xyz.y,offset->xyz.z); glRotatef(fl_degrees(ang),axis.xyz.x,axis.xyz.y,axis.xyz.z); GL_modelview_matrix_depth++; } void gr_opengl_start_instance_angles(vector *pos, angles* rotation) { Assert(GL_htl_projection_matrix_set); Assert(GL_htl_view_matrix_set); matrix m; vm_angles_2_matrix(&m,rotation); gr_opengl_start_instance_matrix(pos,&m); } void gr_opengl_end_instance_matrix() { Assert(GL_htl_projection_matrix_set); Assert(GL_htl_view_matrix_set); glMatrixMode(GL_MODELVIEW); glPopMatrix(); GL_modelview_matrix_depth--; } //the projection matrix; fov, aspect ratio, near, far void gr_opengl_set_projection_matrix(float fov, float aspect, float z_near, float z_far) { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluPerspective(fl_degrees(fov),aspect,z_near,z_far); glMatrixMode(GL_MODELVIEW); GL_htl_projection_matrix_set = 1; } void gr_opengl_end_projection_matrix() { glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); GL_htl_projection_matrix_set = 0; } void gr_opengl_set_view_matrix(vector *pos, matrix* orient) { Assert(GL_htl_projection_matrix_set); Assert(GL_modelview_matrix_depth == 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glPushMatrix(); vector fwd; vector *uvec=&orient->vec.uvec; vm_vec_add(&fwd, pos, &orient->vec.fvec); gluLookAt(pos->xyz.x,pos->xyz.y,-pos->xyz.z, fwd.xyz.x,fwd.xyz.y,-fwd.xyz.z, uvec->xyz.x, uvec->xyz.y,-uvec->xyz.z); glScalef(1,1,-1); glViewport(gr_screen.offset_x,gr_screen.max_h-gr_screen.offset_y-gr_screen.clip_height,gr_screen.clip_width,gr_screen.clip_height); GL_modelview_matrix_depth = 2; GL_htl_view_matrix_set = 1; } void gr_opengl_end_view_matrix() { Assert(GL_modelview_matrix_depth == 2); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glLoadIdentity(); glViewport(0,0,gr_screen.max_w, gr_screen.max_h); GL_modelview_matrix_depth = 1; GL_htl_view_matrix_set = 0; } void gr_opengl_push_scale_matrix(vector *scale_factor) { Assert(GL_htl_projection_matrix_set); Assert(GL_htl_view_matrix_set); glMatrixMode(GL_MODELVIEW); glPushMatrix(); GL_modelview_matrix_depth++; glScalef(scale_factor->xyz.x,scale_factor->xyz.y,scale_factor->xyz.z); } void gr_opengl_pop_scale_matrix() { Assert(GL_htl_projection_matrix_set); Assert(GL_htl_view_matrix_set); glMatrixMode(GL_MODELVIEW); glPopMatrix(); GL_modelview_matrix_depth--; } void gr_opengl_end_clip_plane() { glDisable(GL_CLIP_PLANE0); } void gr_opengl_start_clip_plane() { double clip_equation[4]; vector n; vector p; n=G3_user_clip_normal; p=G3_user_clip_point; clip_equation[0]=n.xyz.x; clip_equation[1]=n.xyz.y; clip_equation[2]=n.xyz.z; clip_equation[3]=-vm_vec_dot(&p, &n); glClipPlane(GL_CLIP_PLANE0, clip_equation); glEnable(GL_CLIP_PLANE0); }
[ [ [ 1, 575 ] ] ]
9e9cd2c43049d1202a2db616865c735b930394a4
208475bcab65438eed5d8380f26eacd25eb58f70
/QianExe/yx_FlashPart4Mng.h
7b7be2ce2c1c4fcacb3f75d709ff461b42e2fb6c
[]
no_license
awzhang/MyWork
83b3f0b9df5ff37330c0e976310d75593f806ec4
075ad5d0726c793a0c08f9158080a144e0bb5ea5
refs/heads/master
2021-01-18T07:57:03.219372
2011-07-05T02:41:55
2011-07-05T02:46:30
15,523,223
1
2
null
null
null
null
UTF-8
C++
false
false
252
h
#ifndef _YX_FLASHPART4MNG_H_ #define _YX_FLASHPART4MNG_H_ class CFlashPart4Mng { public: CFlashPart4Mng(); virtual ~CFlashPart4Mng(); void Init(); void DelOldFile(); DWORD GetToTalFileSize(); void ChkFlash(); }; #endif
[ [ [ 1, 18 ] ] ]
462519d54b5d2816af25b163a325864beb917f79
59066f5944bffb953431bdae0482a2abfb75f49a
/trunk/ogreopcode/include/OgreOpcodeLine.h
33cf76649cae1e6d4be323dc89245988caad84ed
[]
no_license
BackupTheBerlios/conglomerate-svn
5b1afdea5fbcdd8b3cdcc189770b1ad0f8027c58
bbecac90353dca2ae2114d40f5a6697b18c435e5
refs/heads/master
2021-01-01T18:37:56.730293
2006-05-21T03:12:39
2006-05-21T03:12:39
40,668,508
0
0
null
null
null
null
UTF-8
C++
false
false
6,607
h
/////////////////////////////////////////////////////////////////////////////// /// @file OgreLine.h /// @brief TODO. /// /// @author The OgreOpcode Team @date 23-02-2005 /// /////////////////////////////////////////////////////////////////////////////// /// /// This file is part of OgreOpcode. /// /// A lot of the code is based on the Nebula Opcode Collision module, see docs/Nebula_license.txt /// /// OgreOpcode 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. /// /// OgreOpcode 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 OgreOpcode; if not, write to the Free Software /// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /// /////////////////////////////////////////////////////////////////////////////// #ifndef __OgreOpcodeLineClass_h__ #define __OgreOpcodeLineClass_h__ #include "OgreOpcodeMath.h" namespace OgreOpcode { namespace Details { /// Represents a Line segment defined by 2 endpoints. /// TODO: add methods to this class. class _OgreOpcode_Export Line { public: /** Default contructor, making start=end=ZERO */ Line():start(),end() { } /** Complete contructor */ Line( const Vector3& p0, const Vector3& p1 ):start(p0),end(p1) { } /** Complete, headache contructor */ Line( Real x0, Real y0, Real z0, Real x1, Real y1, Real z1 ):start(x0,y0,z0),end(x1,y1,z1) { } /** Copy-contructor */ Line( const Line& line ):start(line.start),end(line.end) { } /// Setups this line void set( const Line& line ) { start = line.start; end = line.end; } /// Sets this line segment void set( Real x0, Real y0, Real z0, Real x1, Real y1, Real z1 ) { start.x = x0; start.y = y0; start.z = z0; end.x = x1; end.y = y1; end.z = z1; } /// Setups this line void set( const Vector3& p0, const Vector3& p1 ) { start = p0; end = p1; } /** Computes the <em>squared</em> distance from this line to the given point. * The linear delta will be stored in t, if not null. */ Real squaredDistance( const Vector3& point, Real *t =NULL ) const; /** Computes the distance from this line to the given point. * The linear delta will be stored in t, if not null. */ Real distance( const Vector3& point, Real *t =NULL ) const; /** Computes the <em>squared</em> distance from this line to the given one. * The vector pointers p0 and p1 will hold the linear deltas to obtain the * closest points in the respective line segments. */ Real squaredDistance( const Line& line, Real* p0 = NULL, Real* p1 = NULL ) const; /** Computes the distance from this line to the given one. * The vector pointers p0 and p1 will hold the linear deltas to obtain the * closest points in the respective line segments. */ Real distance( const Line& line, Real* p0 = NULL, Real* p1 = NULL ) const; /** Computes the <em>squared</em> distance from this line segment to the given Oriented Bounding Box. */ Real squaredDistance( const OrientedBox& obb ) const; /** Computes the distance from this line segment to the given Oriented Bounding Box. */ Real distance( const OrientedBox& obb ) const; ///Sets the starting point void setStart( Real x, Real y, Real z ) { start.x = x; start.y = y; start.z = z; } ///Sets the starting point void setStart( const Vector3& v ) { start = v; } ///Sets the ending point void setEnd( Real x, Real y, Real z ) { end.x = x; end.y = y; end.z = z; } ///Sets the ending point void setEnd( const Vector3& v ) { end = v; } /// Gets the length of this line segment Real length() const { return (start-end).length(); } /// Gets the squared length of this line segment Real length2() const { return (start-end).squaredLength(); } /// Gets the non-normalized direction of this line segment Vector3 getDirection() const { return end - start; } // -------------------------------------------------------------------- // Intersection methods /** Intersection test between this line and the given AABB. */ bool intersect( const Aabb& aabb ) const; /** Intersection test between this line and the given OBB. */ bool intersect( const OrientedBox& obb ) const; /** Intersection test between this line and the given Sphere. */ bool intersect( const Sphere& sphere ) const; /** Intersection test between this line and the given Capsule. */ bool intersect( const Capsule& capsule ) const; /** Generates the parametric point at a given parametric value, using the linear combination. * @return v = start*(1-delta) + end*delta */ Vector3 getPointAt( Real delta ) const { return start + delta*(start-end); } // -------------------------------------------------------------------- // Picking methods /** Picking test between this line and the given AABB. * @param dist Reference to a floating point representing the closest * intersection point trough the distance from the ray origin. */ bool pick( const Aabb& aabb, Real& dist ) const; /** Picking test between this line and the given OBB. * @param dist Reference to a floating point representing the closest * intersection point trough the distance from the ray origin. */ bool pick( const OrientedBox& obb, Real& dist ) const; /** Picking test between this line and the given Sphere. * @param dist Reference to a floating point representing the closest * intersection point trough the distance from the ray origin. */ bool pick( const Sphere& sphere, Real& dist ) const; /** The start point of this line. */ Vector3 start; /** The end point of this line. */ Vector3 end; }; } } #endif
[ "gilvanmaia@4fa2dde5-35f3-0310-a95e-e112236e8438" ]
[ [ [ 1, 210 ] ] ]
7e74ce0644147e73073743f8172f7c6221db16cc
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/Intersection/Wm4IntrSphere3Cone3.cpp
3c682ec66b5a08430e7ea7a0963b7cd72d3130b1
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
4,861
cpp
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #include "Wm4FoundationPCH.h" #include "Wm4IntrSphere3Cone3.h" namespace Wm4 { //---------------------------------------------------------------------------- template <class Real> IntrSphere3Cone3<Real>::IntrSphere3Cone3 (const Sphere3<Real>& rkSphere, const Cone3<Real>& rkCone) : m_rkSphere(rkSphere), m_rkCone(rkCone) { } //---------------------------------------------------------------------------- template <class Real> const Sphere3<Real>& IntrSphere3Cone3<Real>::GetSphere () const { return m_rkSphere; } //---------------------------------------------------------------------------- template <class Real> const Cone3<Real>& IntrSphere3Cone3<Real>::GetCone () const { return m_rkCone; } //---------------------------------------------------------------------------- template <class Real> bool IntrSphere3Cone3<Real>::Test () { Real fInvSin = ((Real)1.0)/m_rkCone.SinAngle; Real fCosSqr = m_rkCone.CosAngle*m_rkCone.CosAngle; Vector3<Real> kCmV = m_rkSphere.Center - m_rkCone.Vertex; Vector3<Real> kD = kCmV + (m_rkSphere.Radius*fInvSin)*m_rkCone.Axis; Real fDSqrLen = kD.SquaredLength(); Real fE = kD.Dot(m_rkCone.Axis); if (fE > (Real)0.0 && fE*fE >= fDSqrLen*fCosSqr) { Real fSinSqr = m_rkCone.SinAngle*m_rkCone.SinAngle; fDSqrLen = kCmV.SquaredLength(); fE = -kCmV.Dot(m_rkCone.Axis); if (fE > (Real)0.0 && fE*fE >= fDSqrLen*fSinSqr) { Real fRSqr = m_rkSphere.Radius*m_rkSphere.Radius; return fDSqrLen <= fRSqr; } return true; } return false; } //---------------------------------------------------------------------------- template <class Real> bool IntrSphere3Cone3<Real>::Find () { // test if cone vertex is in sphere Vector3<Real> kDiff = m_rkSphere.Center - m_rkCone.Vertex; Real fRSqr = m_rkSphere.Radius*m_rkSphere.Radius; Real fLSqr = kDiff.SquaredLength(); if (fLSqr <= fRSqr) { return true; } // test if sphere center is in cone Real fDot = kDiff.Dot(m_rkCone.Axis); Real fDotSqr = fDot*fDot; Real fCosSqr = m_rkCone.CosAngle*m_rkCone.CosAngle; if (fDotSqr >= fLSqr*fCosSqr && fDot > (Real)0.0) { // sphere center is inside cone, so sphere and cone intersect return true; } // Sphere center is outside cone. Problem now reduces to looking for // an intersection between circle and ray in the plane containing // cone vertex and spanned by cone axis and vector from vertex to // sphere center. // Ray is t*D+V (t >= 0) where |D| = 1 and dot(A,D) = cos(angle). // Also, D = e*A+f*(C-V). Plugging ray equation into sphere equation // yields R^2 = |t*D+V-C|^2, so the quadratic for intersections is // t^2 - 2*dot(D,C-V)*t + |C-V|^2 - R^2 = 0. An intersection occurs // if and only if the discriminant is nonnegative. This test becomes // // dot(D,C-V)^2 >= dot(C-V,C-V) - R^2 // // Note that if the right-hand side is nonpositive, then the inequality // is true (the sphere contains V). I have already ruled this out in // the first block of code in this function. Real fULen = Math<Real>::Sqrt(Math<Real>::FAbs(fLSqr-fDotSqr)); Real fTest = m_rkCone.CosAngle*fDot + m_rkCone.SinAngle*fULen; Real fDiscr = fTest*fTest - fLSqr + fRSqr; // compute point of intersection closest to vertex V Real fT = fTest - Math<Real>::Sqrt(fDiscr); Vector3<Real> kB = kDiff - fDot*m_rkCone.Axis; Real fTmp = m_rkCone.SinAngle/fULen; m_kPoint = fT*(m_rkCone.CosAngle*m_rkCone.Axis + fTmp*kB); return fDiscr >= (Real)0.0 && fTest >= (Real)0.0; } //---------------------------------------------------------------------------- template <class Real> const Vector3<Real>& IntrSphere3Cone3<Real>::GetPoint () const { return m_kPoint; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // explicit instantiation //---------------------------------------------------------------------------- template WM4_FOUNDATION_ITEM class IntrSphere3Cone3<float>; template WM4_FOUNDATION_ITEM class IntrSphere3Cone3<double>; //---------------------------------------------------------------------------- }
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 131 ] ] ]
1e21d87639ac7a865b67ec910377ef935f1aa06b
5c4e36054f0752a610ad149dfd81e6f35ccb37a1
/libs/src2.75/BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.cpp
2ecf3c6adb4fbb86262de184a9f3dc97c0a87bb0
[]
no_license
Akira-Hayasaka/ofxBulletPhysics
4141dc7b6dff7e46b85317b0fe7d2e1f8896b2e4
5e45da80bce2ed8b1f12de9a220e0c1eafeb7951
refs/heads/master
2016-09-15T23:11:01.354626
2011-09-22T04:11:35
2011-09-22T04:11:35
1,152,090
6
0
null
null
null
null
UTF-8
C++
false
false
18,019
cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Elsevier CDROM license agreements grants nonexclusive license to use the software for any purpose, commercial or non-commercial as long as the following credit is included identifying the original source of the software: Parts of the source are "from the book Real-Time Collision Detection by Christer Ericson, published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc." */ #include "btVoronoiSimplexSolver.h" #define VERTA 0 #define VERTB 1 #define VERTC 2 #define VERTD 3 #define CATCH_DEGENERATE_TETRAHEDRON 1 void btVoronoiSimplexSolver::removeVertex(int index) { btAssert(m_numVertices>0); m_numVertices--; m_simplexVectorW[index] = m_simplexVectorW[m_numVertices]; m_simplexPointsP[index] = m_simplexPointsP[m_numVertices]; m_simplexPointsQ[index] = m_simplexPointsQ[m_numVertices]; } void btVoronoiSimplexSolver::reduceVertices (const btUsageBitfield& usedVerts) { if ((numVertices() >= 4) && (!usedVerts.usedVertexD)) removeVertex(3); if ((numVertices() >= 3) && (!usedVerts.usedVertexC)) removeVertex(2); if ((numVertices() >= 2) && (!usedVerts.usedVertexB)) removeVertex(1); if ((numVertices() >= 1) && (!usedVerts.usedVertexA)) removeVertex(0); } //clear the simplex, remove all the vertices void btVoronoiSimplexSolver::reset() { m_cachedValidClosest = false; m_numVertices = 0; m_needsUpdate = true; m_lastW = btVector3(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT)); m_cachedBC.reset(); } //add a vertex void btVoronoiSimplexSolver::addVertex(const btVector3& w, const btVector3& p, const btVector3& q) { m_lastW = w; m_needsUpdate = true; m_simplexVectorW[m_numVertices] = w; m_simplexPointsP[m_numVertices] = p; m_simplexPointsQ[m_numVertices] = q; m_numVertices++; } bool btVoronoiSimplexSolver::updateClosestVectorAndPoints() { if (m_needsUpdate) { m_cachedBC.reset(); m_needsUpdate = false; switch (numVertices()) { case 0: m_cachedValidClosest = false; break; case 1: { m_cachedP1 = m_simplexPointsP[0]; m_cachedP2 = m_simplexPointsQ[0]; m_cachedV = m_cachedP1-m_cachedP2; //== m_simplexVectorW[0] m_cachedBC.reset(); m_cachedBC.setBarycentricCoordinates(btScalar(1.),btScalar(0.),btScalar(0.),btScalar(0.)); m_cachedValidClosest = m_cachedBC.isValid(); break; }; case 2: { //closest point origin from line segment const btVector3& from = m_simplexVectorW[0]; const btVector3& to = m_simplexVectorW[1]; btVector3 nearest; btVector3 p (btScalar(0.),btScalar(0.),btScalar(0.)); btVector3 diff = p - from; btVector3 v = to - from; btScalar t = v.dot(diff); if (t > 0) { btScalar dotVV = v.dot(v); if (t < dotVV) { t /= dotVV; diff -= t*v; m_cachedBC.m_usedVertices.usedVertexA = true; m_cachedBC.m_usedVertices.usedVertexB = true; } else { t = 1; diff -= v; //reduce to 1 point m_cachedBC.m_usedVertices.usedVertexB = true; } } else { t = 0; //reduce to 1 point m_cachedBC.m_usedVertices.usedVertexA = true; } m_cachedBC.setBarycentricCoordinates(1-t,t); nearest = from + t*v; m_cachedP1 = m_simplexPointsP[0] + t * (m_simplexPointsP[1] - m_simplexPointsP[0]); m_cachedP2 = m_simplexPointsQ[0] + t * (m_simplexPointsQ[1] - m_simplexPointsQ[0]); m_cachedV = m_cachedP1 - m_cachedP2; reduceVertices(m_cachedBC.m_usedVertices); m_cachedValidClosest = m_cachedBC.isValid(); break; } case 3: { //closest point origin from triangle btVector3 p (btScalar(0.),btScalar(0.),btScalar(0.)); const btVector3& a = m_simplexVectorW[0]; const btVector3& b = m_simplexVectorW[1]; const btVector3& c = m_simplexVectorW[2]; closestPtPointTriangle(p,a,b,c,m_cachedBC); m_cachedP1 = m_simplexPointsP[0] * m_cachedBC.m_barycentricCoords[0] + m_simplexPointsP[1] * m_cachedBC.m_barycentricCoords[1] + m_simplexPointsP[2] * m_cachedBC.m_barycentricCoords[2]; m_cachedP2 = m_simplexPointsQ[0] * m_cachedBC.m_barycentricCoords[0] + m_simplexPointsQ[1] * m_cachedBC.m_barycentricCoords[1] + m_simplexPointsQ[2] * m_cachedBC.m_barycentricCoords[2]; m_cachedV = m_cachedP1-m_cachedP2; reduceVertices (m_cachedBC.m_usedVertices); m_cachedValidClosest = m_cachedBC.isValid(); break; } case 4: { btVector3 p (btScalar(0.),btScalar(0.),btScalar(0.)); const btVector3& a = m_simplexVectorW[0]; const btVector3& b = m_simplexVectorW[1]; const btVector3& c = m_simplexVectorW[2]; const btVector3& d = m_simplexVectorW[3]; bool hasSeperation = closestPtPointTetrahedron(p,a,b,c,d,m_cachedBC); if (hasSeperation) { m_cachedP1 = m_simplexPointsP[0] * m_cachedBC.m_barycentricCoords[0] + m_simplexPointsP[1] * m_cachedBC.m_barycentricCoords[1] + m_simplexPointsP[2] * m_cachedBC.m_barycentricCoords[2] + m_simplexPointsP[3] * m_cachedBC.m_barycentricCoords[3]; m_cachedP2 = m_simplexPointsQ[0] * m_cachedBC.m_barycentricCoords[0] + m_simplexPointsQ[1] * m_cachedBC.m_barycentricCoords[1] + m_simplexPointsQ[2] * m_cachedBC.m_barycentricCoords[2] + m_simplexPointsQ[3] * m_cachedBC.m_barycentricCoords[3]; m_cachedV = m_cachedP1-m_cachedP2; reduceVertices (m_cachedBC.m_usedVertices); } else { // printf("sub distance got penetration\n"); if (m_cachedBC.m_degenerate) { m_cachedValidClosest = false; } else { m_cachedValidClosest = true; //degenerate case == false, penetration = true + zero m_cachedV.setValue(btScalar(0.),btScalar(0.),btScalar(0.)); } break; } m_cachedValidClosest = m_cachedBC.isValid(); //closest point origin from tetrahedron break; } default: { m_cachedValidClosest = false; } }; } return m_cachedValidClosest; } //return/calculate the closest vertex bool btVoronoiSimplexSolver::closest(btVector3& v) { bool succes = updateClosestVectorAndPoints(); v = m_cachedV; return succes; } btScalar btVoronoiSimplexSolver::maxVertex() { int i, numverts = numVertices(); btScalar maxV = btScalar(0.); for (i=0;i<numverts;i++) { btScalar curLen2 = m_simplexVectorW[i].length2(); if (maxV < curLen2) maxV = curLen2; } return maxV; } //return the current simplex int btVoronoiSimplexSolver::getSimplex(btVector3 *pBuf, btVector3 *qBuf, btVector3 *yBuf) const { int i; for (i=0;i<numVertices();i++) { yBuf[i] = m_simplexVectorW[i]; pBuf[i] = m_simplexPointsP[i]; qBuf[i] = m_simplexPointsQ[i]; } return numVertices(); } bool btVoronoiSimplexSolver::inSimplex(const btVector3& w) { bool found = false; int i, numverts = numVertices(); //btScalar maxV = btScalar(0.); //w is in the current (reduced) simplex for (i=0;i<numverts;i++) { if (m_simplexVectorW[i] == w) found = true; } //check in case lastW is already removed if (w == m_lastW) return true; return found; } void btVoronoiSimplexSolver::backup_closest(btVector3& v) { v = m_cachedV; } bool btVoronoiSimplexSolver::emptySimplex() const { return (numVertices() == 0); } void btVoronoiSimplexSolver::compute_points(btVector3& p1, btVector3& p2) { updateClosestVectorAndPoints(); p1 = m_cachedP1; p2 = m_cachedP2; } bool btVoronoiSimplexSolver::closestPtPointTriangle(const btVector3& p, const btVector3& a, const btVector3& b, const btVector3& c,btSubSimplexClosestResult& result) { result.m_usedVertices.reset(); // Check if P in vertex region outside A btVector3 ab = b - a; btVector3 ac = c - a; btVector3 ap = p - a; btScalar d1 = ab.dot(ap); btScalar d2 = ac.dot(ap); if (d1 <= btScalar(0.0) && d2 <= btScalar(0.0)) { result.m_closestPointOnSimplex = a; result.m_usedVertices.usedVertexA = true; result.setBarycentricCoordinates(1,0,0); return true;// a; // barycentric coordinates (1,0,0) } // Check if P in vertex region outside B btVector3 bp = p - b; btScalar d3 = ab.dot(bp); btScalar d4 = ac.dot(bp); if (d3 >= btScalar(0.0) && d4 <= d3) { result.m_closestPointOnSimplex = b; result.m_usedVertices.usedVertexB = true; result.setBarycentricCoordinates(0,1,0); return true; // b; // barycentric coordinates (0,1,0) } // Check if P in edge region of AB, if so return projection of P onto AB btScalar vc = d1*d4 - d3*d2; if (vc <= btScalar(0.0) && d1 >= btScalar(0.0) && d3 <= btScalar(0.0)) { btScalar v = d1 / (d1 - d3); result.m_closestPointOnSimplex = a + v * ab; result.m_usedVertices.usedVertexA = true; result.m_usedVertices.usedVertexB = true; result.setBarycentricCoordinates(1-v,v,0); return true; //return a + v * ab; // barycentric coordinates (1-v,v,0) } // Check if P in vertex region outside C btVector3 cp = p - c; btScalar d5 = ab.dot(cp); btScalar d6 = ac.dot(cp); if (d6 >= btScalar(0.0) && d5 <= d6) { result.m_closestPointOnSimplex = c; result.m_usedVertices.usedVertexC = true; result.setBarycentricCoordinates(0,0,1); return true;//c; // barycentric coordinates (0,0,1) } // Check if P in edge region of AC, if so return projection of P onto AC btScalar vb = d5*d2 - d1*d6; if (vb <= btScalar(0.0) && d2 >= btScalar(0.0) && d6 <= btScalar(0.0)) { btScalar w = d2 / (d2 - d6); result.m_closestPointOnSimplex = a + w * ac; result.m_usedVertices.usedVertexA = true; result.m_usedVertices.usedVertexC = true; result.setBarycentricCoordinates(1-w,0,w); return true; //return a + w * ac; // barycentric coordinates (1-w,0,w) } // Check if P in edge region of BC, if so return projection of P onto BC btScalar va = d3*d6 - d5*d4; if (va <= btScalar(0.0) && (d4 - d3) >= btScalar(0.0) && (d5 - d6) >= btScalar(0.0)) { btScalar w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); result.m_closestPointOnSimplex = b + w * (c - b); result.m_usedVertices.usedVertexB = true; result.m_usedVertices.usedVertexC = true; result.setBarycentricCoordinates(0,1-w,w); return true; // return b + w * (c - b); // barycentric coordinates (0,1-w,w) } // P inside face region. Compute Q through its barycentric coordinates (u,v,w) btScalar denom = btScalar(1.0) / (va + vb + vc); btScalar v = vb * denom; btScalar w = vc * denom; result.m_closestPointOnSimplex = a + ab * v + ac * w; result.m_usedVertices.usedVertexA = true; result.m_usedVertices.usedVertexB = true; result.m_usedVertices.usedVertexC = true; result.setBarycentricCoordinates(1-v-w,v,w); return true; // return a + ab * v + ac * w; // = u*a + v*b + w*c, u = va * denom = btScalar(1.0) - v - w } /// Test if point p and d lie on opposite sides of plane through abc int btVoronoiSimplexSolver::pointOutsideOfPlane(const btVector3& p, const btVector3& a, const btVector3& b, const btVector3& c, const btVector3& d) { btVector3 normal = (b-a).cross(c-a); btScalar signp = (p - a).dot(normal); // [AP AB AC] btScalar signd = (d - a).dot( normal); // [AD AB AC] #ifdef CATCH_DEGENERATE_TETRAHEDRON #ifdef BT_USE_DOUBLE_PRECISION if (signd * signd < (btScalar(1e-8) * btScalar(1e-8))) { return -1; } #else if (signd * signd < (btScalar(1e-4) * btScalar(1e-4))) { // printf("affine dependent/degenerate\n");// return -1; } #endif #endif // Points on opposite sides if expression signs are opposite return signp * signd < btScalar(0.); } bool btVoronoiSimplexSolver::closestPtPointTetrahedron(const btVector3& p, const btVector3& a, const btVector3& b, const btVector3& c, const btVector3& d, btSubSimplexClosestResult& finalResult) { btSubSimplexClosestResult tempResult; // Start out assuming point inside all halfspaces, so closest to itself finalResult.m_closestPointOnSimplex = p; finalResult.m_usedVertices.reset(); finalResult.m_usedVertices.usedVertexA = true; finalResult.m_usedVertices.usedVertexB = true; finalResult.m_usedVertices.usedVertexC = true; finalResult.m_usedVertices.usedVertexD = true; int pointOutsideABC = pointOutsideOfPlane(p, a, b, c, d); int pointOutsideACD = pointOutsideOfPlane(p, a, c, d, b); int pointOutsideADB = pointOutsideOfPlane(p, a, d, b, c); int pointOutsideBDC = pointOutsideOfPlane(p, b, d, c, a); if (pointOutsideABC < 0 || pointOutsideACD < 0 || pointOutsideADB < 0 || pointOutsideBDC < 0) { finalResult.m_degenerate = true; return false; } if (!pointOutsideABC && !pointOutsideACD && !pointOutsideADB && !pointOutsideBDC) { return false; } btScalar bestSqDist = FLT_MAX; // If point outside face abc then compute closest point on abc if (pointOutsideABC) { closestPtPointTriangle(p, a, b, c,tempResult); btVector3 q = tempResult.m_closestPointOnSimplex; btScalar sqDist = (q - p).dot( q - p); // Update best closest point if (squared) distance is less than current best if (sqDist < bestSqDist) { bestSqDist = sqDist; finalResult.m_closestPointOnSimplex = q; //convert result bitmask! finalResult.m_usedVertices.reset(); finalResult.m_usedVertices.usedVertexA = tempResult.m_usedVertices.usedVertexA; finalResult.m_usedVertices.usedVertexB = tempResult.m_usedVertices.usedVertexB; finalResult.m_usedVertices.usedVertexC = tempResult.m_usedVertices.usedVertexC; finalResult.setBarycentricCoordinates( tempResult.m_barycentricCoords[VERTA], tempResult.m_barycentricCoords[VERTB], tempResult.m_barycentricCoords[VERTC], 0 ); } } // Repeat test for face acd if (pointOutsideACD) { closestPtPointTriangle(p, a, c, d,tempResult); btVector3 q = tempResult.m_closestPointOnSimplex; //convert result bitmask! btScalar sqDist = (q - p).dot( q - p); if (sqDist < bestSqDist) { bestSqDist = sqDist; finalResult.m_closestPointOnSimplex = q; finalResult.m_usedVertices.reset(); finalResult.m_usedVertices.usedVertexA = tempResult.m_usedVertices.usedVertexA; finalResult.m_usedVertices.usedVertexC = tempResult.m_usedVertices.usedVertexB; finalResult.m_usedVertices.usedVertexD = tempResult.m_usedVertices.usedVertexC; finalResult.setBarycentricCoordinates( tempResult.m_barycentricCoords[VERTA], 0, tempResult.m_barycentricCoords[VERTB], tempResult.m_barycentricCoords[VERTC] ); } } // Repeat test for face adb if (pointOutsideADB) { closestPtPointTriangle(p, a, d, b,tempResult); btVector3 q = tempResult.m_closestPointOnSimplex; //convert result bitmask! btScalar sqDist = (q - p).dot( q - p); if (sqDist < bestSqDist) { bestSqDist = sqDist; finalResult.m_closestPointOnSimplex = q; finalResult.m_usedVertices.reset(); finalResult.m_usedVertices.usedVertexA = tempResult.m_usedVertices.usedVertexA; finalResult.m_usedVertices.usedVertexB = tempResult.m_usedVertices.usedVertexC; finalResult.m_usedVertices.usedVertexD = tempResult.m_usedVertices.usedVertexB; finalResult.setBarycentricCoordinates( tempResult.m_barycentricCoords[VERTA], tempResult.m_barycentricCoords[VERTC], 0, tempResult.m_barycentricCoords[VERTB] ); } } // Repeat test for face bdc if (pointOutsideBDC) { closestPtPointTriangle(p, b, d, c,tempResult); btVector3 q = tempResult.m_closestPointOnSimplex; //convert result bitmask! btScalar sqDist = (q - p).dot( q - p); if (sqDist < bestSqDist) { bestSqDist = sqDist; finalResult.m_closestPointOnSimplex = q; finalResult.m_usedVertices.reset(); // finalResult.m_usedVertices.usedVertexB = tempResult.m_usedVertices.usedVertexA; finalResult.m_usedVertices.usedVertexC = tempResult.m_usedVertices.usedVertexC; finalResult.m_usedVertices.usedVertexD = tempResult.m_usedVertices.usedVertexB; finalResult.setBarycentricCoordinates( 0, tempResult.m_barycentricCoords[VERTA], tempResult.m_barycentricCoords[VERTC], tempResult.m_barycentricCoords[VERTB] ); } } //help! we ended up full ! if (finalResult.m_usedVertices.usedVertexA && finalResult.m_usedVertices.usedVertexB && finalResult.m_usedVertices.usedVertexC && finalResult.m_usedVertices.usedVertexD) { return true; } return true; }
[ [ [ 1, 605 ] ] ]
0a42fb69533b42cb655db692fa17e563c6b29fc0
12732dc8a5dd518f35c8af3f2a805806f5e91e28
/trunk/Plugin/configuration_object.h
47898cd737e5e60f9cb7b6f2eca6c28d9d724436
[]
no_license
BackupTheBerlios/codelite-svn
5acd9ac51fdd0663742f69084fc91a213b24ae5c
c9efd7873960706a8ce23cde31a701520bad8861
refs/heads/master
2020-05-20T13:22:34.635394
2007-08-02T21:35:35
2007-08-02T21:35:35
40,669,327
0
0
null
null
null
null
UTF-8
C++
false
false
639
h
#ifndef CONF_OBJECT_H #define CONF_OBJECT_H #include "wx/xml/xml.h" #include "smart_ptr.h" #ifdef WXMAKINGDLL_LE_SDK # define WXDLLIMPEXP_LE_SDK WXEXPORT #elif defined(WXUSINGDLL_LE_SDK) # define WXDLLIMPEXP_LE_SDK WXIMPORT #else /* not making nor using FNB as DLL */ # define WXDLLIMPEXP_LE_SDK #endif // WXMAKINGDLL_LE_SDK class wxXmlNode; /** * Interface of configuration objects */ class WXDLLIMPEXP_LE_SDK ConfObject { public: ConfObject(){}; virtual ~ConfObject(){} virtual wxXmlNode *ToXml() const = 0; }; typedef SmartPtr<ConfObject> ConfObjectPtr; #endif // CONFIGURATION_OBJECT_H
[ "eranif@b1f272c1-3a1e-0410-8d64-bdc0ffbdec4b" ]
[ [ [ 1, 29 ] ] ]
1cd3fcc3eab223d07acca8b6deea0478271787f8
6f8721dafe2b841f4eb27237deead56ba6e7a55b
/src/WorldOfAnguis/Graphics/DirectX/World/DXWorldView.cpp
65e67fa1e547e2063814b599070af8b032c5db60
[]
no_license
worldofanguis/WoA
dea2abf6db52017a181b12e9c0f9989af61cfa2a
161c7bb4edcee8f941f31b8248a41047d89e264b
refs/heads/master
2021-01-19T10:25:57.360015
2010-02-19T16:05:40
2010-02-19T16:05:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,001
cpp
/* * ___ ___ __ * \ \ / / / \ * \ \ / / / \ * \ \ /\ / /___ / /\ \ * \ \/ \/ /| | / ____ \ * \___/\___/ |___|/__/ \__\ * World Of Anguis * */ #include "DXWorldView.h" DXWorldView::DXWorldView() { pDevice = NULL; pSprite = NULL; pDisplaySurface = NULL; // Main texture surface | Locaton: video card memory // pWorkSurface = NULL; // Surface used for creating the new masked landscape | Location: comp memory // pOriginalSurface = NULL; // Surface used to hold the original landscape | Location: comp memory // } DXWorldView::~DXWorldView() { SAFE_RELEASE(pDisplaySurface); SAFE_RELEASE(pWorkSurface); SAFE_RELEASE(pOriginalSurface); } void DXWorldView::Draw(int Left,int Top,int Width,int Height) { if(pDisplaySurface == NULL || pSprite == NULL) return; RECT r = {Left,Top,Left+Width,Top+Height}; /* Copy the r region from pDisplaySurface to the screen */ pSprite->Draw(pDisplaySurface,&r,NULL,NULL,0xFFFFFFFF); } void DXWorldView::UpdateSurface(char *Map,int MapWidth,int PPHM,RECT* DirtyRegion) { D3DLOCKED_RECT SurfaceRect; D3DLOCKED_RECT OriginalRect; RECT WholeSurface = {0,0,SurfaceWidth,SurfaceHeight}; if(DirtyRegion == NULL) DirtyRegion = &WholeSurface; else { if(DirtyRegion->top < 0) DirtyRegion->top = 0; if(DirtyRegion->left < 0) DirtyRegion->left = 0; if(DirtyRegion->bottom > SurfaceHeight) DirtyRegion->bottom = SurfaceHeight; if(DirtyRegion->right > SurfaceWidth) DirtyRegion->right = SurfaceWidth; } /* NOTE: We are working in the WorkSurface because we cant access directly the DisplaySurface */ /* NOTE: If the DirtyRegion is specified in the LockRect parameter list * the returned memory address will be the beginning of the dirtyregion */ pWorkSurface->LockRect(0,&SurfaceRect,DirtyRegion,0); // Lock the surfaces for manipulation // pOriginalSurface->LockRect(0,&OriginalRect,DirtyRegion,D3DLOCK_READONLY); // We use the same dirtyregion to avoid memory address conversion // BYTE* Dest = (BYTE*)SurfaceRect.pBits; // Get the pointer to the surface memory // BYTE* Source = (BYTE*)OriginalRect.pBits; for(int h=0;h<DirtyRegion->bottom-DirtyRegion->top;h++) // Copy height: bottom-top // { for(int w=0;w<DirtyRegion->right-DirtyRegion->left;w++) // Copy width: right-left // { if(Map[(((int)((h+DirtyRegion->top)/PPHM))*MapWidth)+((int)((w+DirtyRegion->left)/PPHM))]) // There is something on the map there // *(DWORD*)Dest = *(DWORD*)Source; // Copy 1 pixel from the source to the destination // else *(DWORD*)Dest = 0; Dest +=4; // Move the pointer with 4 bytes (1 pixel (ARGB)) Source +=4; } Dest += SurfaceRect.Pitch-(DirtyRegion->right*4) /*NextLine*/ + (DirtyRegion->left*4); /*DirtyRegionStart */ Source += SurfaceRect.Pitch-(DirtyRegion->right*4) /*NextLine*/ + (DirtyRegion->left*4); /*DirtyRegionStart */ } pWorkSurface->UnlockRect(0); // Unlock the surfaces // pOriginalSurface->UnlockRect(0); /* Update the DisplaySurface */ pDevice->UpdateTexture(pWorkSurface,pDisplaySurface); } bool DXWorldView::LoadWorldTexture(char *File) { if(pDevice == NULL) return false; FILE *FKez; fopen_s(&FKez,File,"rb"); if(FKez == NULL) return false; SAFE_RELEASE(pDisplaySurface); // Destroy the previous stuffs if any // SAFE_RELEASE(pWorkSurface); SAFE_RELEASE(pOriginalSurface); BITMAPFILEHEADER bmfh; // Bitmap file headers // BITMAPINFOHEADER bmih; fread(&bmfh,sizeof(BITMAPFILEHEADER),1,FKez); if(bmfh.bfType != 0x4D42) // check if its a BMP (BM flag) // { fclose(FKez); return false; } fread(&bmih,sizeof(BITMAPINFOHEADER),1,FKez); fclose(FKez); BytesPerPixel = bmih.biBitCount/8; SurfaceWidth = bmih.biWidth; SurfaceHeight = bmih.biHeight; D3DXCreateTextureFromFileEx(pDevice, // Device File, SurfaceWidth, // Width SurfaceHeight, // Height 1, // Levels 0, // Usage D3DFMT_A8R8G8B8, // Format D3DPOOL_SYSTEMMEM, // Memory pool D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255,0,255), // pink = transparent NULL, NULL, &pOriginalSurface); /* NOTE: WorkSurface (texture) for generating the DisplaySurface from the Original and the HitMap * we do it this way because its in the system memory and the DisplaySurface is in the video memory and we dont want to (and cant) access to that */ pDevice->CreateTexture(SurfaceWidth,SurfaceHeight,1,0,D3DFMT_A8R8G8B8,D3DPOOL_SYSTEMMEM,&pWorkSurface,NULL); pDevice->CreateTexture(SurfaceWidth,SurfaceHeight,1,0,D3DFMT_A8R8G8B8,D3DPOOL_DEFAULT,&pDisplaySurface,NULL); // pDevice->UpdateTexture(pOriginalSurface,pDisplaySurface); // Used for testing // return true; }
[ [ [ 1, 74 ], [ 76, 84 ], [ 86, 146 ] ], [ [ 75, 75 ], [ 85, 85 ] ] ]
6283859b9e9f31064a43c33e75c281570942883d
d22b77645ee83ee72fed70cb2a3ca4fb268ada4a
/common/charls/header.cpp
ff668a971f4656d9d33661897895ad4bde52aac3
[]
no_license
catid/Splane
8f94f7d8983cf994955e599fc53ce6f763157486
c9f79f0034d1762948b7c26e42f50f58793067ac
refs/heads/master
2020-04-26T00:28:48.571474
2010-06-02T05:37:43
2010-06-02T05:37:43
628,653
1
0
null
null
null
null
UTF-8
C++
false
false
11,381
cpp
// // (C) Jan de Vaan 2007-2009, all rights reserved. See the accompanying "License.txt" for licensed use. // #include "stdafx.h" #include "header.h" #include "streams.h" #include "decoderstrategy.h" #include "encoderstrategy.h" #include <memory> // JFIF\0 BYTE jfifID[] = {'J','F','I','F','\0'}; bool IsDefault(const JlsCustomParameters* pcustom) { if (pcustom->MAXVAL != 0) return false; if (pcustom->T1 != 0) return false; if (pcustom->T2 != 0) return false; if (pcustom->T3 != 0) return false; if (pcustom->RESET != 0) return false; return true; } // // JpegMarkerSegment // class JpegMarkerSegment : public JpegSegment { public: JpegMarkerSegment(BYTE marker, std::vector<BYTE> vecbyte) { _marker = marker; std::swap(_vecbyte, vecbyte); } virtual void Write(JLSOutputStream* pstream) { pstream->WriteByte(0xFF); pstream->WriteByte(_marker); pstream->WriteWord(USHORT(_vecbyte.size() + 2)); pstream->WriteBytes(_vecbyte); } BYTE _marker; std::vector<BYTE> _vecbyte; }; // // push_back() // void push_back(std::vector<BYTE>& vec, USHORT value) { vec.push_back(BYTE(value / 0x100)); vec.push_back(BYTE(value % 0x100)); } // // CreateMarkerStartOfFrame() // JpegSegment* CreateMarkerStartOfFrame(Size size, LONG cbpp, LONG ccomp) { std::vector<BYTE> vec; vec.push_back(static_cast<BYTE>(cbpp)); push_back(vec, static_cast<USHORT>(size.cy)); push_back(vec, static_cast<USHORT>(size.cx)); // components vec.push_back(static_cast<BYTE>(ccomp)); for (BYTE icomp = 0; icomp < ccomp; icomp++) { // rescaling vec.push_back(icomp + 1); vec.push_back(0x11); //"Tq1" reserved, 0 vec.push_back(0); } return new JpegMarkerSegment(JPEG_SOF, vec); } // // ctor() // JLSOutputStream::JLSOutputStream() : _bCompare(false), _pdata(NULL), _cbyteOffset(0), _cbyteLength(0), _icompLast(0) { } // // dtor() // JLSOutputStream::~JLSOutputStream() { for (size_t i = 0; i < _segments.size(); ++i) { delete _segments[i]; } _segments.empty(); } // // Init() // void JLSOutputStream::Init(Size size, LONG cbpp, LONG ccomp) { _segments.push_back(CreateMarkerStartOfFrame(size, cbpp, ccomp)); } void JLSOutputStream::AddColorTransform(int i) { std::vector<BYTE> rgbyteXform; rgbyteXform.push_back('m'); rgbyteXform.push_back('r'); rgbyteXform.push_back('f'); rgbyteXform.push_back('x'); rgbyteXform.push_back((BYTE)i); _segments.push_back(new JpegMarkerSegment(JPEG_APP8, rgbyteXform)); } // // Write() // size_t JLSOutputStream::Write(BYTE* pdata, size_t cbyteLength) { _pdata = pdata; _cbyteLength = cbyteLength; WriteByte(0xFF); WriteByte(JPEG_SOI); for (size_t i = 0; i < _segments.size(); ++i) { _segments[i]->Write(this); } //_bCompare = false; WriteByte(0xFF); WriteByte(JPEG_EOI); return _cbyteOffset; } JLSInputStream::JLSInputStream(const BYTE* pdata, LONG cbyteLength) : _pdata(pdata), _cbyteOffset(0), _cbyteLength(cbyteLength), _bCompare(false), _info() { } // // Read() // void JLSInputStream::Read(void* pvoid, LONG cbyteAvailable) { ReadHeader(); ReadPixels(pvoid, cbyteAvailable); } // // ReadPixels() // void JLSInputStream::ReadPixels(void* pvoid, LONG cbyteAvailable) { LONG cbytePlane = _info.width * _info.height * ((_info.bitspersample + 7)/8); if (cbyteAvailable < cbytePlane * _info.components) throw JlsException(UncompressedBufferTooSmall); if (_info.ilv == ILV_NONE) { BYTE* pbyte = (BYTE*)pvoid; for (LONG icomp = 0; icomp < _info.components; ++icomp) { ReadScan(pbyte); pbyte += cbytePlane; } } else { ReadScan(pvoid); } } // ReadNBytes() // void JLSInputStream::ReadNBytes(std::vector<char>& dst, int byteCount) { for (int i = 0; i < byteCount; ++i) { dst.push_back((char)ReadByte()); } } // // ReadHeader() // void JLSInputStream::ReadHeader() { if (ReadByte() != 0xFF) throw JlsException(InvalidCompressedData); if (ReadByte() != JPEG_SOI) throw JlsException(InvalidCompressedData); for (;;) { if (ReadByte() != 0xFF) throw JlsException(InvalidCompressedData); BYTE marker = (BYTE)ReadByte(); size_t cbyteStart = _cbyteOffset; LONG cbyteMarker = ReadWord(); switch (marker) { case JPEG_SOS: ReadStartOfScan(); break; case JPEG_SOF: ReadStartOfFrame(); break; case JPEG_COM: ReadComment(); break; case JPEG_LSE: ReadPresetParameters(); break; case JPEG_APP0: ReadJfif(); break; case JPEG_APP7: ReadColorSpace(); break; case JPEG_APP8: ReadColorXForm(); break; // Other tags not supported (among which DNL DRI) default: throw JlsException(ImageTypeNotSupported); } if (marker == JPEG_SOS) { _cbyteOffset = cbyteStart - 2; return; } _cbyteOffset = cbyteStart + cbyteMarker; } } JpegMarkerSegment* EncodeStartOfScan(const JlsParamaters* pparams, LONG icomponent) { BYTE itable = 0; std::vector<BYTE> rgbyte; if (icomponent < 0) { rgbyte.push_back((BYTE)pparams->components); for (LONG icomponent = 0; icomponent < pparams->components; ++icomponent ) { rgbyte.push_back(BYTE(icomponent + 1)); rgbyte.push_back(itable); } } else { rgbyte.push_back(1); rgbyte.push_back((BYTE)icomponent); rgbyte.push_back(itable); } rgbyte.push_back(BYTE(pparams->allowedlossyerror)); rgbyte.push_back(BYTE(pparams->ilv)); rgbyte.push_back(0); // transform return new JpegMarkerSegment(JPEG_SOS, rgbyte); } JpegMarkerSegment* CreateLSE(const JlsCustomParameters* pcustom) { std::vector<BYTE> rgbyte; rgbyte.push_back(1); push_back(rgbyte, (USHORT)pcustom->MAXVAL); push_back(rgbyte, (USHORT)pcustom->T1); push_back(rgbyte, (USHORT)pcustom->T2); push_back(rgbyte, (USHORT)pcustom->T3); push_back(rgbyte, (USHORT)pcustom->RESET); return new JpegMarkerSegment(JPEG_LSE, rgbyte); } // // ReadPresetParameters() // void JLSInputStream::ReadPresetParameters() { LONG type = ReadByte(); switch (type) { case 1: { _info.custom.MAXVAL = ReadWord(); _info.custom.T1 = ReadWord(); _info.custom.T2 = ReadWord(); _info.custom.T3 = ReadWord(); _info.custom.RESET = ReadWord(); return; } } } // // ReadStartOfScan() // void JLSInputStream::ReadStartOfScan() { LONG ccomp = ReadByte(); for (LONG i = 0; i < ccomp; ++i) { ReadByte(); ReadByte(); } _info.allowedlossyerror = ReadByte(); _info.ilv = interleavemode(ReadByte()); if(_info.bytesperline == 0) { int components = _info.ilv == ILV_NONE ? 1 : _info.components; _info.bytesperline = components*_info.width * ((_info.bitspersample+7)/8); } } // // ReadComment() // void JLSInputStream::ReadComment() {} // // ReadJfif() // void JLSInputStream::ReadJfif() { for(int i = 0; i < (int)sizeof(jfifID); i++) { if(jfifID[i] != ReadByte()) return; } _info.jfif.Ver = ReadWord(); // DPI or DPcm _info.jfif.units = ReadByte(); _info.jfif.XDensity = ReadWord(); _info.jfif.YDensity = ReadWord(); // thumbnail _info.jfif.Xthumb = ReadByte(); _info.jfif.Ythumb = ReadByte(); if(_info.jfif.Xthumb > 0 && _info.jfif.pdataThumbnail) { std::vector<char> tempbuff((char*)_info.jfif.pdataThumbnail, (char*)_info.jfif.pdataThumbnail+3*_info.jfif.Xthumb*_info.jfif.Ythumb); ReadNBytes(tempbuff, 3*_info.jfif.Xthumb*_info.jfif.Ythumb); } } // // CreateJFIF() // JpegMarkerSegment* CreateJFIF(const JfifParamaters* jfif) { std::vector<BYTE> rgbyte; for(int i = 0; i < (int)sizeof(jfifID); i++) { rgbyte.push_back(jfifID[i]); } push_back(rgbyte, (USHORT)jfif->Ver); rgbyte.push_back(jfif->units); push_back(rgbyte, (USHORT)jfif->XDensity); push_back(rgbyte, (USHORT)jfif->YDensity); // thumbnail rgbyte.push_back((BYTE)jfif->Xthumb); rgbyte.push_back((BYTE)jfif->Ythumb); if(jfif->Xthumb > 0) { if(jfif->pdataThumbnail) throw JlsException(InvalidJlsParameters); rgbyte.insert(rgbyte.end(), (BYTE*)jfif->pdataThumbnail, (BYTE*)jfif->pdataThumbnail+3*jfif->Xthumb*jfif->Ythumb ); } return new JpegMarkerSegment(JPEG_APP0, rgbyte); } // // ReadStartOfFrame() // void JLSInputStream::ReadStartOfFrame() { _info.bitspersample = ReadByte(); int cline = ReadWord(); int ccol = ReadWord(); _info.width = ccol; _info.height = cline; _info.components= ReadByte(); } // // ReadByte() // BYTE JLSInputStream::ReadByte() { if (_cbyteOffset >= _cbyteLength) throw JlsException(InvalidCompressedData); return _pdata[_cbyteOffset++]; } // // ReadWord() // int JLSInputStream::ReadWord() { int i = ReadByte() * 256; return i + ReadByte(); } void JLSInputStream::ReadScan(void* pvout) { std::auto_ptr<DecoderStrategy> qcodec(JlsCodecFactory<DecoderStrategy>().GetCodec(_info, _info.custom)); Size size = Size(_info.width,_info.height); _cbyteOffset += qcodec->DecodeScan(pvout, size, _pdata + _cbyteOffset, _cbyteLength - _cbyteOffset, _bCompare); } class JpegImageDataSegment: public JpegSegment { public: JpegImageDataSegment(const void* pvoidRaw, const JlsParamaters& info, LONG icompStart, int ccompScan) : _ccompScan(ccompScan), _icompStart(icompStart), _pvoidRaw(pvoidRaw), _info(info) { } void Write(JLSOutputStream* pstream) { JlsParamaters info = _info; info.components = _ccompScan; std::auto_ptr<EncoderStrategy> qcodec(JlsCodecFactory<EncoderStrategy>().GetCodec(info, _info.custom)); size_t cbyteWritten = qcodec->EncodeScan((BYTE*)_pvoidRaw, Size(_info.width, _info.height), pstream->GetPos(), pstream->GetLength(), pstream->_bCompare ? pstream->GetPos() : NULL); pstream->Seek(cbyteWritten); } int _ccompScan; LONG _icompStart; const void* _pvoidRaw; JlsParamaters _info; }; void JLSOutputStream::AddScan(const void* pbyteComp, const JlsParamaters* pparams) { if (pparams->jfif.Ver) { _segments.push_back(CreateJFIF(&pparams->jfif)); } if (!IsDefault(&pparams->custom)) { _segments.push_back(CreateLSE(&pparams->custom)); } _icompLast += 1; _segments.push_back(EncodeStartOfScan(pparams,pparams->ilv == ILV_NONE ? _icompLast : -1)); Size size = Size(pparams->width, pparams->height); int ccomp = pparams->ilv == ILV_NONE ? 1 : pparams->components; _segments.push_back(new JpegImageDataSegment(pbyteComp, *pparams, _icompLast, ccomp)); } // // ReadColorSpace() // void JLSInputStream::ReadColorSpace() {} // // ReadColorXForm() // void JLSInputStream::ReadColorXForm() { std::vector<char> sourceTag; ReadNBytes(sourceTag, 4); if(strncmp(&sourceTag[0],"mrfx", 4) != 0) return; int xform = ReadByte(); switch(xform) { case COLORXFORM_NONE: case COLORXFORM_HP1: case COLORXFORM_HP2: case COLORXFORM_HP3: _info.colorTransform = xform; return; case COLORXFORM_RGB_AS_YUV_LOSSY: case COLORXFORM_MATRIX: throw JlsException(ImageTypeNotSupported); default: throw JlsException(InvalidCompressedData); } }
[ "kuang@.(none)" ]
[ [ [ 1, 568 ] ] ]