blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
16
author_lines
sequencelengths
1
16
6bb215bc22e7cd42a043f8155f64e4b72324319a
2821bd16a5e375893ee2733b9d6a5565edc46685
/SAXParser.h
0d089f29ac389add922344fff7d449e11e2344a9
[]
no_license
zephyrer/activelog
24eab2107dd11f3c1ecb7b8e78e87fb0a6dcb3b2
febf3a1080959c28215d84f0c2f92aff032f4240
refs/heads/master
2021-01-13T02:27:24.587560
2009-07-20T02:47:48
2009-07-20T02:47:48
40,067,861
0
0
null
null
null
null
UTF-8
C++
false
false
167
h
#pragma once class SAXParser { public: SAXParser(void); ~SAXParser(void); public: int ParseData(CString Data); private: ISAXXMLReader* pReader; };
[ "vatechsystems@85faade2-74d6-11de-ba67-499d525147dd" ]
[ [ [ 1, 12 ] ] ]
63bba1645065700dd60359ad3d80b7aecba8c17d
5750620062af54ed24792c39d0bf19a6f8f1e3bf
/src/net.cpp
16af8c569230fe9e9b69992f1ef20dcf4d1289f6
[]
no_license
makomk/soldcoin
4088e49928efe7436eee8bae40b0b1b9ce9e2720
f964acdd1a76d58f7e27e386fffbed22a1916307
refs/heads/master
2021-01-17T22:18:53.603480
2011-09-04T19:29:57
2011-09-04T19:29:57
2,344,688
0
0
null
null
null
null
UTF-8
C++
false
false
55,504
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2011 The SolidCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #include "headers.h" #include "irc.h" #include "db.h" #include "net.h" #include "init.h" #include "strlcpy.h" #ifdef __WXMSW__ #include <string.h> // This file can be downloaded as a part of the Windows Platform SDK // and is required for SolidCoin binaries to work properly on versions // of Windows before XP. If you are doing builds of SolidCoin for // public release, you should uncomment this line. //#include <WSPiApi.h> #endif #ifdef USE_UPNP #include <miniupnpc/miniwget.h> #include <miniupnpc/miniupnpc.h> #include <miniupnpc/upnpcommands.h> #include <miniupnpc/upnperrors.h> #endif using namespace std; using namespace boost; static const int MAX_OUTBOUND_CONNECTIONS = 8; void ThreadMessageHandler2(void* parg); void ThreadSocketHandler2(void* parg); void ThreadOpenConnections2(void* parg); #ifdef USE_UPNP void ThreadMapPort2(void* parg); #endif bool OpenNetworkConnection(const CAddress& addrConnect); // // Global state variables // bool fClient = false; bool fAllowDNS = false; uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK); CAddress addrLocalHost("0.0.0.0", 0, false, nLocalServices); CNode* pnodeLocalHost = NULL; uint64 nLocalHostNonce = 0; array<int, 10> vnThreadsRunning; SOCKET hListenSocket = INVALID_SOCKET; vector<CNode*> vNodes; CCriticalSection cs_vNodes; map<vector<unsigned char>, CAddress> mapAddresses; CCriticalSection cs_mapAddresses; map<CInv, CDataStream> mapRelay; deque<pair<int64, CInv> > vRelayExpiration; CCriticalSection cs_mapRelay; map<CInv, int64> mapAlreadyAskedFor; // Settings int fUseProxy = false; int nConnectTimeout = 5000; CAddress addrProxy("127.0.0.1",9050); unsigned short GetListenPort() { return (unsigned short)(GetArg("-port", GetDefaultPort())); } void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd) { // Filter out duplicate requests if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd) return; pindexLastGetBlocksBegin = pindexBegin; hashLastGetBlocksEnd = hashEnd; PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd); } bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet, int nTimeout) { hSocketRet = INVALID_SOCKET; SOCKET hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (hSocket == INVALID_SOCKET) return false; #ifdef SO_NOSIGPIPE int set = 1; setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int)); #endif bool fProxy = (fUseProxy && addrConnect.IsRoutable()); struct sockaddr_in sockaddr = (fProxy ? addrProxy.GetSockAddr() : addrConnect.GetSockAddr()); #ifdef __WXMSW__ u_long fNonblock = 1; if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR) #else int fFlags = fcntl(hSocket, F_GETFL, 0); if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1) #endif { closesocket(hSocket); return false; } if (connect(hSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR) { // WSAEINVAL is here because some legacy version of winsock uses it if (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINVAL) { struct timeval timeout; timeout.tv_sec = nTimeout / 1000; timeout.tv_usec = (nTimeout % 1000) * 1000; fd_set fdset; FD_ZERO(&fdset); FD_SET(hSocket, &fdset); int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout); if (nRet == 0) { printf("connection timeout\n"); closesocket(hSocket); return false; } if (nRet == SOCKET_ERROR) { printf("select() for connection failed: %i\n",WSAGetLastError()); closesocket(hSocket); return false; } socklen_t nRetSize = sizeof(nRet); #ifdef __WXMSW__ if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR) #else if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR) #endif { printf("getsockopt() for connection failed: %i\n",WSAGetLastError()); closesocket(hSocket); return false; } if (nRet != 0) { printf("connect() failed after select(): %s\n",strerror(nRet)); closesocket(hSocket); return false; } } #ifdef __WXMSW__ else if (WSAGetLastError() != WSAEISCONN) #else else #endif { printf("connect() failed: %i\n",WSAGetLastError()); closesocket(hSocket); return false; } } /* this isn't even strictly necessary CNode::ConnectNode immediately turns the socket back to non-blocking but we'll turn it back to blocking just in case */ #ifdef __WXMSW__ fNonblock = 0; if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR) #else fFlags = fcntl(hSocket, F_GETFL, 0); if (fcntl(hSocket, F_SETFL, fFlags & !O_NONBLOCK) == SOCKET_ERROR) #endif { closesocket(hSocket); return false; } if (fProxy) { printf("proxy connecting %s\n", addrConnect.ToString().c_str()); char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user"; memcpy(pszSocks4IP + 2, &addrConnect.port, 2); memcpy(pszSocks4IP + 4, &addrConnect.ip, 4); char* pszSocks4 = pszSocks4IP; int nSize = sizeof(pszSocks4IP); int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL); if (ret != nSize) { closesocket(hSocket); return error("Error sending to proxy"); } char pchRet[8]; if (recv(hSocket, pchRet, 8, 0) != 8) { closesocket(hSocket); return error("Error reading proxy response"); } if (pchRet[1] != 0x5a) { closesocket(hSocket); if (pchRet[1] != 0x5b) printf("ERROR: Proxy returned error %d\n", pchRet[1]); return false; } printf("proxy connected %s\n", addrConnect.ToString().c_str()); } hSocketRet = hSocket; return true; } // portDefault is in host order bool Lookup(const char *pszName, vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup, int portDefault, bool fAllowPort) { vaddr.clear(); if (pszName[0] == 0) return false; int port = portDefault; char psz[256]; char *pszHost = psz; strlcpy(psz, pszName, sizeof(psz)); if (fAllowPort) { char* pszColon = strrchr(psz+1,':'); char *pszPortEnd = NULL; int portParsed = pszColon ? strtoul(pszColon+1, &pszPortEnd, 10) : 0; if (pszColon && pszPortEnd && pszPortEnd[0] == 0) { if (psz[0] == '[' && pszColon[-1] == ']') { // Future: enable IPv6 colon-notation inside [] pszHost = psz+1; pszColon[-1] = 0; } else pszColon[0] = 0; port = portParsed; if (port < 0 || port > USHRT_MAX) port = USHRT_MAX; } } unsigned int addrIP = inet_addr(pszHost); if (addrIP != INADDR_NONE) { // valid IP address passed vaddr.push_back(CAddress(addrIP, port, nServices)); return true; } if (!fAllowLookup) return false; struct hostent* phostent = gethostbyname(pszHost); if (!phostent) return false; if (phostent->h_addrtype != AF_INET) return false; char** ppAddr = phostent->h_addr_list; while (*ppAddr != NULL && vaddr.size() != nMaxSolutions) { CAddress addr(((struct in_addr*)ppAddr[0])->s_addr, port, nServices); if (addr.IsValid()) vaddr.push_back(addr); ppAddr++; } return (vaddr.size() > 0); } // portDefault is in host order bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup, int portDefault, bool fAllowPort) { vector<CAddress> vaddr; bool fRet = Lookup(pszName, vaddr, nServices, 1, fAllowLookup, portDefault, fAllowPort); if (fRet) addr = vaddr[0]; return fRet; } bool GetMyExternalIP2(const CAddress& addrConnect, const char* pszGet, const char* pszKeyword, unsigned int& ipRet) { SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str()); send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL); string strLine; while (RecvLine(hSocket, strLine)) { if (strLine.empty()) // HTTP response is separated from headers by blank line { loop { if (!RecvLine(hSocket, strLine)) { closesocket(hSocket); return false; } if (pszKeyword == NULL) break; if (strLine.find(pszKeyword) != -1) { strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword)); break; } } closesocket(hSocket); if (strLine.find("<") != -1) strLine = strLine.substr(0, strLine.find("<")); strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r")); while (strLine.size() > 0 && isspace(strLine[strLine.size()-1])) strLine.resize(strLine.size()-1); CAddress addr(strLine,0,true); printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str()); if (addr.ip == 0 || addr.ip == INADDR_NONE || !addr.IsRoutable()) return false; ipRet = addr.ip; return true; } } closesocket(hSocket); return error("GetMyExternalIP() : connection closed"); } // We now get our external IP from the IRC server first and only use this as a backup bool GetMyExternalIP(unsigned int& ipRet) { CAddress addrConnect; const char* pszGet; const char* pszKeyword; if (fUseProxy) return false; for (int nLookup = 0; nLookup <= 1; nLookup++) for (int nHost = 1; nHost <= 2; nHost++) { // We should be phasing out our use of sites like these. If we need // replacements, we should ask for volunteers to put this simple // php file on their webserver that prints the client IP: // <?php echo $_SERVER["REMOTE_ADDR"]; ?> if (nHost == 1) { addrConnect = CAddress("91.198.22.70",80); // checkip.dyndns.org if (nLookup == 1) { CAddress addrIP("checkip.dyndns.org", 80, true); if (addrIP.IsValid()) addrConnect = addrIP; } pszGet = "GET / HTTP/1.1\r\n" "Host: checkip.dyndns.org\r\n" "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n" "Connection: close\r\n" "\r\n"; pszKeyword = "Address:"; } else if (nHost == 2) { addrConnect = CAddress("74.208.43.192", 80); // www.showmyip.com if (nLookup == 1) { CAddress addrIP("www.showmyip.com", 80, true); if (addrIP.IsValid()) addrConnect = addrIP; } pszGet = "GET /simple/ HTTP/1.1\r\n" "Host: www.showmyip.com\r\n" "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n" "Connection: close\r\n" "\r\n"; pszKeyword = NULL; // Returns just IP address } if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet)) return true; } return false; } void ThreadGetMyExternalIP(void* parg) { // Wait for IRC to get it first if (!GetBoolArg("-noirc")) { for (int i = 0; i < 2 * 60; i++) { Sleep(1000); if (fGotExternalIP || fShutdown) return; } } // Fallback in case IRC fails to get it if (GetMyExternalIP(addrLocalHost.ip)) { printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str()); if (addrLocalHost.IsRoutable()) { // If we already connected to a few before we had our IP, go back and addr them. // setAddrKnown automatically filters any duplicate sends. CAddress addr(addrLocalHost); addr.nTime = GetAdjustedTime(); CRITICAL_BLOCK(cs_vNodes) BOOST_FOREACH(CNode* pnode, vNodes) pnode->PushAddress(addr); } } } bool AddAddress(CAddress addr, int64 nTimePenalty, CAddrDB *pAddrDB) { if (!addr.IsRoutable()) return false; if (addr.ip == addrLocalHost.ip) return false; addr.nTime = max((int64)0, (int64)addr.nTime - nTimePenalty); CRITICAL_BLOCK(cs_mapAddresses) { map<vector<unsigned char>, CAddress>::iterator it = mapAddresses.find(addr.GetKey()); if (it == mapAddresses.end()) { // New address printf("AddAddress(%s)\n", addr.ToString().c_str()); mapAddresses.insert(make_pair(addr.GetKey(), addr)); if (pAddrDB) pAddrDB->WriteAddress(addr); else CAddrDB().WriteAddress(addr); return true; } else { bool fUpdated = false; CAddress& addrFound = (*it).second; if ((addrFound.nServices | addr.nServices) != addrFound.nServices) { // Services have been added addrFound.nServices |= addr.nServices; fUpdated = true; } bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60); int64 nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60); if (addrFound.nTime < addr.nTime - nUpdateInterval) { // Periodically update most recently seen time addrFound.nTime = addr.nTime; fUpdated = true; } if (fUpdated) { if (pAddrDB) pAddrDB->WriteAddress(addrFound); else CAddrDB().WriteAddress(addrFound); } } } return false; } void AddressCurrentlyConnected(const CAddress& addr) { CRITICAL_BLOCK(cs_mapAddresses) { // Only if it's been published already map<vector<unsigned char>, CAddress>::iterator it = mapAddresses.find(addr.GetKey()); if (it != mapAddresses.end()) { CAddress& addrFound = (*it).second; int64 nUpdateInterval = 20 * 60; if (addrFound.nTime < GetAdjustedTime() - nUpdateInterval) { // Periodically update most recently seen time addrFound.nTime = GetAdjustedTime(); CAddrDB addrdb; addrdb.WriteAddress(addrFound); } } } } void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1) { // If the dialog might get closed before the reply comes back, // call this in the destructor so it doesn't get called after it's deleted. CRITICAL_BLOCK(cs_vNodes) { BOOST_FOREACH(CNode* pnode, vNodes) { CRITICAL_BLOCK(pnode->cs_mapRequests) { for (map<uint256, CRequestTracker>::iterator mi = pnode->mapRequests.begin(); mi != pnode->mapRequests.end();) { CRequestTracker& tracker = (*mi).second; if (tracker.fn == fn && tracker.param1 == param1) pnode->mapRequests.erase(mi++); else mi++; } } } } } // // Subscription methods for the broadcast and subscription system. // Channel numbers are message numbers, i.e. MSG_TABLE and MSG_PRODUCT. // // The subscription system uses a meet-in-the-middle strategy. // With 100,000 nodes, if senders broadcast to 1000 random nodes and receivers // subscribe to 1000 random nodes, 99.995% (1 - 0.99^1000) of messages will get through. // bool AnySubscribed(unsigned int nChannel) { if (pnodeLocalHost->IsSubscribed(nChannel)) return true; CRITICAL_BLOCK(cs_vNodes) BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->IsSubscribed(nChannel)) return true; return false; } bool CNode::IsSubscribed(unsigned int nChannel) { if (nChannel >= vfSubscribe.size()) return false; return vfSubscribe[nChannel]; } void CNode::Subscribe(unsigned int nChannel, unsigned int nHops) { if (nChannel >= vfSubscribe.size()) return; if (!AnySubscribed(nChannel)) { // Relay subscribe CRITICAL_BLOCK(cs_vNodes) BOOST_FOREACH(CNode* pnode, vNodes) if (pnode != this) pnode->PushMessage("subscribe", nChannel, nHops); } vfSubscribe[nChannel] = true; } void CNode::CancelSubscribe(unsigned int nChannel) { if (nChannel >= vfSubscribe.size()) return; // Prevent from relaying cancel if wasn't subscribed if (!vfSubscribe[nChannel]) return; vfSubscribe[nChannel] = false; if (!AnySubscribed(nChannel)) { // Relay subscription cancel CRITICAL_BLOCK(cs_vNodes) BOOST_FOREACH(CNode* pnode, vNodes) if (pnode != this) pnode->PushMessage("sub-cancel", nChannel); } } CNode* FindNode(unsigned int ip) { CRITICAL_BLOCK(cs_vNodes) { BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->addr.ip == ip) return (pnode); } return NULL; } CNode* FindNode(CAddress addr) { CRITICAL_BLOCK(cs_vNodes) { BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->addr == addr) return (pnode); } return NULL; } CNode* ConnectNode(CAddress addrConnect, int64 nTimeout) { if (addrConnect.ip == addrLocalHost.ip) return NULL; // Look for an existing connection CNode* pnode = FindNode(addrConnect.ip); if (pnode) { if (nTimeout != 0) pnode->AddRef(nTimeout); else pnode->AddRef(); return pnode; } /// debug print printf("trying connection %s lastseen=%.1fhrs lasttry=%.1fhrs\n", addrConnect.ToString().c_str(), (double)(addrConnect.nTime - GetAdjustedTime())/3600.0, (double)(addrConnect.nLastTry - GetAdjustedTime())/3600.0); CRITICAL_BLOCK(cs_mapAddresses) mapAddresses[addrConnect.GetKey()].nLastTry = GetAdjustedTime(); // Connect SOCKET hSocket; if (ConnectSocket(addrConnect, hSocket)) { /// debug print printf("connected %s\n", addrConnect.ToString().c_str()); // Set to nonblocking #ifdef __WXMSW__ u_long nOne = 1; if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) printf("ConnectSocket() : ioctlsocket nonblocking setting failed, error %d\n", WSAGetLastError()); #else if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) printf("ConnectSocket() : fcntl nonblocking setting failed, error %d\n", errno); #endif // Add node CNode* pnode = new CNode(hSocket, addrConnect, false); if (nTimeout != 0) pnode->AddRef(nTimeout); else pnode->AddRef(); CRITICAL_BLOCK(cs_vNodes) vNodes.push_back(pnode); pnode->nTimeConnected = GetTime(); return pnode; } else { return NULL; } } void CNode::CloseSocketDisconnect() { fDisconnect = true; if (hSocket != INVALID_SOCKET) { if (fDebug) printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str()); printf("disconnecting node %s\n", addr.ToString().c_str()); closesocket(hSocket); hSocket = INVALID_SOCKET; } } void CNode::Cleanup() { // All of a nodes broadcasts and subscriptions are automatically torn down // when it goes down, so a node has to stay up to keep its broadcast going. // Cancel subscriptions for (unsigned int nChannel = 0; nChannel < vfSubscribe.size(); nChannel++) if (vfSubscribe[nChannel]) CancelSubscribe(nChannel); } void ThreadSocketHandler(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadSocketHandler(parg)); try { vnThreadsRunning[0]++; ThreadSocketHandler2(parg); vnThreadsRunning[0]--; } catch (std::exception& e) { vnThreadsRunning[0]--; PrintException(&e, "ThreadSocketHandler()"); } catch (...) { vnThreadsRunning[0]--; throw; // support pthread_cancel() } printf("ThreadSocketHandler exiting\n"); } void ThreadSocketHandler2(void* parg) { printf("ThreadSocketHandler started\n"); list<CNode*> vNodesDisconnected; int nPrevNodeCount = 0; loop { // // Disconnect nodes // CRITICAL_BLOCK(cs_vNodes) { // Disconnect unused nodes vector<CNode*> vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect || (pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty())) { // remove from vNodes vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); // close socket and cleanup pnode->CloseSocketDisconnect(); pnode->Cleanup(); // hold in disconnected pool until all refs are released pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60); if (pnode->fNetworkNode || pnode->fInbound) pnode->Release(); vNodesDisconnected.push_back(pnode); } } // Delete disconnected nodes list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected; BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy) { // wait until threads are done using it if (pnode->GetRefCount() <= 0) { bool fDelete = false; TRY_CRITICAL_BLOCK(pnode->cs_vSend) TRY_CRITICAL_BLOCK(pnode->cs_vRecv) TRY_CRITICAL_BLOCK(pnode->cs_mapRequests) TRY_CRITICAL_BLOCK(pnode->cs_inventory) fDelete = true; if (fDelete) { vNodesDisconnected.remove(pnode); delete pnode; } } } } if (vNodes.size() != nPrevNodeCount) { nPrevNodeCount = vNodes.size(); MainFrameRepaint(); } // // Find which sockets have data to receive // struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 50000; // frequency to poll pnode->vSend fd_set fdsetRecv; fd_set fdsetSend; fd_set fdsetError; FD_ZERO(&fdsetRecv); FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); SOCKET hSocketMax = 0; if(hListenSocket != INVALID_SOCKET) FD_SET(hListenSocket, &fdsetRecv); hSocketMax = max(hSocketMax, hListenSocket); CRITICAL_BLOCK(cs_vNodes) { BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->hSocket == INVALID_SOCKET) continue; FD_SET(pnode->hSocket, &fdsetRecv); FD_SET(pnode->hSocket, &fdsetError); hSocketMax = max(hSocketMax, pnode->hSocket); TRY_CRITICAL_BLOCK(pnode->cs_vSend) if (!pnode->vSend.empty()) FD_SET(pnode->hSocket, &fdsetSend); } } vnThreadsRunning[0]--; int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, &fdsetError, &timeout); vnThreadsRunning[0]++; if (fShutdown) return; if (nSelect == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (hSocketMax > -1) { printf("socket select error %d\n", nErr); for (int i = 0; i <= hSocketMax; i++) FD_SET(i, &fdsetRecv); } FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); Sleep(timeout.tv_usec/1000); } // // Accept new connections // if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv)) { struct sockaddr_in sockaddr; socklen_t len = sizeof(sockaddr); SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len); CAddress addr(sockaddr); int nInbound = 0; CRITICAL_BLOCK(cs_vNodes) BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->fInbound) nInbound++; if (hSocket == INVALID_SOCKET) { if (WSAGetLastError() != WSAEWOULDBLOCK) printf("socket error accept failed: %d\n", WSAGetLastError()); } else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS) { closesocket(hSocket); } else { printf("accepted connection %s\n", addr.ToString().c_str()); CNode* pnode = new CNode(hSocket, addr, true); pnode->AddRef(); CRITICAL_BLOCK(cs_vNodes) vNodes.push_back(pnode); } } // // Service each socket // vector<CNode*> vNodesCopy; CRITICAL_BLOCK(cs_vNodes) { vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->AddRef(); } BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (fShutdown) return; // // Receive // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) { TRY_CRITICAL_BLOCK(pnode->cs_vRecv) { CDataStream& vRecv = pnode->vRecv; unsigned int nPos = vRecv.size(); if (nPos > ReceiveBufferSize()) { if (!pnode->fDisconnect) printf("socket recv flood control disconnect (%d bytes)\n", vRecv.size()); pnode->CloseSocketDisconnect(); } else { // typical socket buffer is 8K-64K char pchBuf[0x10000]; int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT); if (nBytes > 0) { vRecv.resize(nPos + nBytes); memcpy(&vRecv[nPos], pchBuf, nBytes); pnode->nLastRecv = GetTime(); } else if (nBytes == 0) { // socket closed gracefully if (!pnode->fDisconnect) printf("socket closed\n"); pnode->CloseSocketDisconnect(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { if (!pnode->fDisconnect) printf("socket recv error %d\n", nErr); pnode->CloseSocketDisconnect(); } } } } } // // Send // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetSend)) { TRY_CRITICAL_BLOCK(pnode->cs_vSend) { CDataStream& vSend = pnode->vSend; if (!vSend.empty()) { int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT); if (nBytes > 0) { vSend.erase(vSend.begin(), vSend.begin() + nBytes); pnode->nLastSend = GetTime(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { printf("socket send error %d\n", nErr); pnode->CloseSocketDisconnect(); } } if (vSend.size() > SendBufferSize()) { if (!pnode->fDisconnect) printf("socket send flood control disconnect (%d bytes)\n", vSend.size()); pnode->CloseSocketDisconnect(); } } } } // // Inactivity checking // if (pnode->vSend.empty()) pnode->nLastSendEmpty = GetTime(); if (GetTime() - pnode->nTimeConnected > 60) { if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) { printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0); pnode->fDisconnect = true; } else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60) { printf("socket not sending\n"); pnode->fDisconnect = true; } else if (GetTime() - pnode->nLastRecv > 90*60) { printf("socket inactivity timeout\n"); pnode->fDisconnect = true; } } } CRITICAL_BLOCK(cs_vNodes) { BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } Sleep(10); } } #ifdef USE_UPNP void ThreadMapPort(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadMapPort(parg)); try { vnThreadsRunning[5]++; ThreadMapPort2(parg); vnThreadsRunning[5]--; } catch (std::exception& e) { vnThreadsRunning[5]--; PrintException(&e, "ThreadMapPort()"); } catch (...) { vnThreadsRunning[5]--; PrintException(NULL, "ThreadMapPort()"); } printf("ThreadMapPort exiting\n"); } void ThreadMapPort2(void* parg) { printf("ThreadMapPort started\n"); char port[6]; sprintf(port, "%d", GetListenPort()); const char * rootdescurl = 0; const char * multicastif = 0; const char * minissdpdpath = 0; struct UPNPDev * devlist = 0; char lanaddr[64]; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0); struct UPNPUrls urls; struct IGDdatas data; int r; r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); if (r == 1) { char intClient[16]; char intPort[6]; string strDesc = "SolidCoin " + FormatFullVersion(); #ifndef __WXMSW__ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port, port, lanaddr, strDesc.c_str(), "TCP", 0); #else r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port, port, lanaddr, strDesc.c_str(), "TCP", 0, "0"); #endif if(r!=UPNPCOMMAND_SUCCESS) printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port, port, lanaddr, r, strupnperror(r)); else printf("UPnP Port Mapping successful.\n"); loop { if (fShutdown || !fUseUPnP) { r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port, "TCP", 0); printf("UPNP_DeletePortMapping() returned : %d\n", r); freeUPNPDevlist(devlist); devlist = 0; FreeUPNPUrls(&urls); return; } Sleep(2000); } } else { printf("No valid UPnP IGDs found\n"); freeUPNPDevlist(devlist); devlist = 0; if (r != 0) FreeUPNPUrls(&urls); loop { if (fShutdown || !fUseUPnP) return; Sleep(2000); } } } void MapPort(bool fMapPort) { if (fUseUPnP != fMapPort) { fUseUPnP = fMapPort; WriteSetting("fUseUPnP", fUseUPnP); } if (fUseUPnP && vnThreadsRunning[5] < 1) { if (!CreateThread(ThreadMapPort, NULL)) printf("Error: ThreadMapPort(ThreadMapPort) failed\n"); } } #else void MapPort(bool /* unused fMapPort */) { // Intentionally left blank. } #endif static const char *strDNSSeed[] = { "bitseed.xf2.org", "bitseed.bitcoin.org.uk", "dnsseed.bluematt.me", }; void DNSAddressSeed() { int found = 0; if (!fTestNet) { printf("Loading addresses from DNS seeds (could take a while)\n"); CAddrDB addrDB; addrDB.TxnBegin(); for (int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) { vector<CAddress> vaddr; if (Lookup(strDNSSeed[seed_idx], vaddr, NODE_NETWORK, -1, true)) { BOOST_FOREACH (CAddress& addr, vaddr) { if (addr.GetByte(3) != 127) { addr.nTime = 0; AddAddress(addr, 0, &addrDB); found++; } } } } addrDB.TxnCommit(); // Save addresses (it's ok if this fails) } printf("%d addresses found from DNS seeds\n", found); } unsigned int pnSeed[] = { 0x74b347ce, }; void ThreadOpenConnections(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadOpenConnections(parg)); try { vnThreadsRunning[1]++; ThreadOpenConnections2(parg); vnThreadsRunning[1]--; } catch (std::exception& e) { vnThreadsRunning[1]--; PrintException(&e, "ThreadOpenConnections()"); } catch (...) { vnThreadsRunning[1]--; PrintException(NULL, "ThreadOpenConnections()"); } printf("ThreadOpenConnections exiting\n"); } void ThreadOpenConnections2(void* parg) { printf("ThreadOpenConnections started\n"); // Connect to specific addresses if (mapArgs.count("-connect")) { for (int64 nLoop = 0;; nLoop++) { BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"]) { CAddress addr(strAddr, fAllowDNS); if (addr.IsValid()) OpenNetworkConnection(addr); for (int i = 0; i < 10 && i < nLoop; i++) { Sleep(500); if (fShutdown) return; } } } } // Connect to manually added nodes first if (mapArgs.count("-addnode")) { BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"]) { CAddress addr(strAddr, fAllowDNS); if (addr.IsValid()) { OpenNetworkConnection(addr); Sleep(500); if (fShutdown) return; } } } // Initiate network connections int64 nStart = GetTime(); loop { // Limit outbound connections vnThreadsRunning[1]--; Sleep(500); loop { int nOutbound = 0; CRITICAL_BLOCK(cs_vNodes) BOOST_FOREACH(CNode* pnode, vNodes) if (!pnode->fInbound) nOutbound++; int nMaxOutboundConnections = MAX_OUTBOUND_CONNECTIONS; nMaxOutboundConnections = min(nMaxOutboundConnections, (int)GetArg("-maxconnections", 125)); if (nOutbound < nMaxOutboundConnections) break; Sleep(2000); if (fShutdown) return; } vnThreadsRunning[1]++; if (fShutdown) return; CRITICAL_BLOCK(cs_mapAddresses) { // Add seed nodes if IRC isn't working static bool fSeedUsed; bool fTOR = (fUseProxy && addrProxy.port == htons(9050)); if (mapAddresses.empty() && (GetTime() - nStart > 60 || fTOR) && !fTestNet) { for (int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. CAddress addr; addr.ip = pnSeed[i]; addr.nTime = 0; AddAddress(addr); } fSeedUsed = true; } if (fSeedUsed && mapAddresses.size() > ARRAYLEN(pnSeed) + 100) { // Disconnect seed nodes set<unsigned int> setSeed(pnSeed, pnSeed + ARRAYLEN(pnSeed)); static int64 nSeedDisconnected; if (nSeedDisconnected == 0) { nSeedDisconnected = GetTime(); CRITICAL_BLOCK(cs_vNodes) BOOST_FOREACH(CNode* pnode, vNodes) if (setSeed.count(pnode->addr.ip)) pnode->fDisconnect = true; } // Keep setting timestamps to 0 so they won't reconnect if (GetTime() - nSeedDisconnected < 60 * 60) { BOOST_FOREACH(PAIRTYPE(const vector<unsigned char>, CAddress)& item, mapAddresses) { if (setSeed.count(item.second.ip) && item.second.nTime != 0) { item.second.nTime = 0; CAddrDB().WriteAddress(item.second); } } } } } // // Choose an address to connect to based on most recently seen // CAddress addrConnect; int64 nBest = INT64_MIN; // Only connect to one address per a.b.?.? range. // Do this here so we don't have to critsect vNodes inside mapAddresses critsect. set<unsigned int> setConnected; CRITICAL_BLOCK(cs_vNodes) BOOST_FOREACH(CNode* pnode, vNodes) setConnected.insert(pnode->addr.ip & 0x0000ffff); CRITICAL_BLOCK(cs_mapAddresses) { BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses) { const CAddress& addr = item.second; if (!addr.IsIPv4() || !addr.IsValid() || setConnected.count(addr.ip & 0x0000ffff)) continue; int64 nSinceLastSeen = GetAdjustedTime() - addr.nTime; int64 nSinceLastTry = GetAdjustedTime() - addr.nLastTry; // Randomize the order in a deterministic way, putting the standard port first int64 nRandomizer = (uint64)(nStart * 4951 + addr.nLastTry * 9567851 + addr.ip * 7789) % (2 * 60 * 60); if (addr.port != htons(GetDefaultPort())) nRandomizer += 2 * 60 * 60; // Last seen Base retry frequency // <1 hour 10 min // 1 hour 1 hour // 4 hours 2 hours // 24 hours 5 hours // 48 hours 7 hours // 7 days 13 hours // 30 days 27 hours // 90 days 46 hours // 365 days 93 hours int64 nDelay = (int64)(3600.0 * sqrt(fabs((double)nSinceLastSeen) / 3600.0) + nRandomizer); // Fast reconnect for one hour after last seen if (nSinceLastSeen < 60 * 60) nDelay = 10 * 60; // Limit retry frequency if (nSinceLastTry < nDelay) continue; // If we have IRC, we'll be notified when they first come online, // and again every 24 hours by the refresh broadcast. if (nGotIRCAddresses > 0 && vNodes.size() >= 2 && nSinceLastSeen > 24 * 60 * 60) continue; // Only try the old stuff if we don't have enough connections if (vNodes.size() >= 8 && nSinceLastSeen > 24 * 60 * 60) continue; // If multiple addresses are ready, prioritize by time since // last seen and time since last tried. int64 nScore = min(nSinceLastTry, (int64)24 * 60 * 60) - nSinceLastSeen - nRandomizer; if (nScore > nBest) { nBest = nScore; addrConnect = addr; } } } if (addrConnect.IsValid()) OpenNetworkConnection(addrConnect); } } bool OpenNetworkConnection(const CAddress& addrConnect) { // // Initiate outbound network connection // if (fShutdown) return false; if (addrConnect.ip == addrLocalHost.ip || !addrConnect.IsIPv4() || FindNode(addrConnect.ip)) return false; vnThreadsRunning[1]--; CNode* pnode = ConnectNode(addrConnect); vnThreadsRunning[1]++; if (fShutdown) return false; if (!pnode) return false; pnode->fNetworkNode = true; return true; } void ThreadMessageHandler(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadMessageHandler(parg)); try { vnThreadsRunning[2]++; ThreadMessageHandler2(parg); vnThreadsRunning[2]--; } catch (std::exception& e) { vnThreadsRunning[2]--; PrintException(&e, "ThreadMessageHandler()"); } catch (...) { vnThreadsRunning[2]--; PrintException(NULL, "ThreadMessageHandler()"); } printf("ThreadMessageHandler exiting\n"); } void ThreadMessageHandler2(void* parg) { printf("ThreadMessageHandler started\n"); SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL); while (!fShutdown) { vector<CNode*> vNodesCopy; CRITICAL_BLOCK(cs_vNodes) { vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->AddRef(); } // Poll the connected nodes for messages CNode* pnodeTrickle = NULL; if (!vNodesCopy.empty()) pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())]; BOOST_FOREACH(CNode* pnode, vNodesCopy) { // Receive messages TRY_CRITICAL_BLOCK(pnode->cs_vRecv) ProcessMessages(pnode); if (fShutdown) return; // Send messages TRY_CRITICAL_BLOCK(pnode->cs_vSend) SendMessages(pnode, pnode == pnodeTrickle); if (fShutdown) return; } CRITICAL_BLOCK(cs_vNodes) { BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } // Wait and allow messages to bunch up. // Reduce vnThreadsRunning so StopNode has permission to exit while // we're sleeping, but we must always check fShutdown after doing this. vnThreadsRunning[2]--; Sleep(100); if (fRequestShutdown) Shutdown(NULL); vnThreadsRunning[2]++; if (fShutdown) return; } } bool BindListenPort(string& strError) { strError = ""; int nOne = 1; addrLocalHost.port = htons(GetListenPort()); #ifdef __WXMSW__ // Initialize Windows Sockets WSADATA wsadata; int ret = WSAStartup(MAKEWORD(2,2), &wsadata); if (ret != NO_ERROR) { strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret); printf("%s\n", strError.c_str()); return false; } #endif // Create socket for listening for incoming connections hListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (hListenSocket == INVALID_SOCKET) { strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } #ifdef SO_NOSIGPIPE // Different way of disabling SIGPIPE on BSD setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int)); #endif #ifndef __WXMSW__ // Allow binding if the port is still in TIME_WAIT state after // the program was closed and restarted. Not an issue on windows. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int)); #endif #ifdef __WXMSW__ // Set to nonblocking, incoming connections will also inherit this if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR) #else if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) #endif { strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } // The sockaddr_in structure specifies the address family, // IP address, and port for the socket that is being bound struct sockaddr_in sockaddr; memset(&sockaddr, 0, sizeof(sockaddr)); sockaddr.sin_family = AF_INET; sockaddr.sin_addr.s_addr = INADDR_ANY; // bind to all IPs on this computer sockaddr.sin_port = htons(GetListenPort()); if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (nErr == WSAEADDRINUSE) strError = strprintf(_("Unable to bind to port %d on this computer. SolidCoin is probably already running."), ntohs(sockaddr.sin_port)); else strError = strprintf("Error: Unable to bind to port %d on this computer (bind returned error %d)", ntohs(sockaddr.sin_port), nErr); printf("%s\n", strError.c_str()); return false; } printf("Bound to port %d\n", ntohs(sockaddr.sin_port)); // Listen for incoming connections if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) { strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } return true; } void StartNode(void* parg) { if (pnodeLocalHost == NULL) pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress("127.0.0.1", 0, false, nLocalServices)); #ifdef __WXMSW__ // Get local host ip char pszHostName[1000] = ""; if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { vector<CAddress> vaddr; if (Lookup(pszHostName, vaddr, nLocalServices, -1, true)) BOOST_FOREACH (const CAddress &addr, vaddr) if (addr.GetByte(3) != 127) { addrLocalHost = addr; break; } } #else // Get local host ip struct ifaddrs* myaddrs; if (getifaddrs(&myaddrs) == 0) { for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (strcmp(ifa->ifa_name, "lo") == 0) continue; if (strcmp(ifa->ifa_name, "lo0") == 0) continue; char pszIP[100]; if (ifa->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); if (inet_ntop(ifa->ifa_addr->sa_family, (void*)&(s4->sin_addr), pszIP, sizeof(pszIP)) != NULL) printf("ipv4 %s: %s\n", ifa->ifa_name, pszIP); // Take the first IP that isn't loopback 127.x.x.x CAddress addr(*(unsigned int*)&s4->sin_addr, GetListenPort(), nLocalServices); if (addr.IsValid() && addr.GetByte(3) != 127) { addrLocalHost = addr; break; } } else if (ifa->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); if (inet_ntop(ifa->ifa_addr->sa_family, (void*)&(s6->sin6_addr), pszIP, sizeof(pszIP)) != NULL) printf("ipv6 %s: %s\n", ifa->ifa_name, pszIP); } } freeifaddrs(myaddrs); } #endif printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str()); if (fUseProxy || mapArgs.count("-connect") || fNoListen) { // Proxies can't take incoming connections addrLocalHost.ip = CAddress("0.0.0.0").ip; printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str()); } else { CreateThread(ThreadGetMyExternalIP, NULL); } // // Start threads // // Map ports with UPnP if (fHaveUPnP) MapPort(fUseUPnP); // Get addresses from IRC and advertise ours if (!CreateThread(ThreadIRCSeed, NULL)) printf("Error: CreateThread(ThreadIRCSeed) failed\n"); // Send and receive from sockets, accept connections CreateThread(ThreadSocketHandler, NULL, true); // Initiate outbound connections if (!CreateThread(ThreadOpenConnections, NULL)) printf("Error: CreateThread(ThreadOpenConnections) failed\n"); // Process messages if (!CreateThread(ThreadMessageHandler, NULL)) printf("Error: CreateThread(ThreadMessageHandler) failed\n"); // Generate coins in the background GenerateSolidCoins(fGenerateSolidCoins, pwalletMain); } bool StopNode() { printf("StopNode()\n"); fShutdown = true; nTransactionsUpdated++; int64 nStart = GetTime(); while (vnThreadsRunning[0] > 0 || vnThreadsRunning[2] > 0 || vnThreadsRunning[3] > 0 || vnThreadsRunning[4] > 0 #ifdef USE_UPNP || vnThreadsRunning[5] > 0 #endif ) { if (GetTime() - nStart > 20) break; Sleep(20); } if (vnThreadsRunning[0] > 0) printf("ThreadSocketHandler still running\n"); if (vnThreadsRunning[1] > 0) printf("ThreadOpenConnections still running\n"); if (vnThreadsRunning[2] > 0) printf("ThreadMessageHandler still running\n"); if (vnThreadsRunning[3] > 0) printf("ThreadSolidCoinMiner still running\n"); if (vnThreadsRunning[4] > 0) printf("ThreadRPCServer still running\n"); if (fHaveUPnP && vnThreadsRunning[5] > 0) printf("ThreadMapPort still running\n"); while (vnThreadsRunning[2] > 0 || vnThreadsRunning[4] > 0) Sleep(20); Sleep(50); return true; } class CNetCleanup { public: CNetCleanup() { } ~CNetCleanup() { // Close sockets BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->hSocket != INVALID_SOCKET) closesocket(pnode->hSocket); if (hListenSocket != INVALID_SOCKET) if (closesocket(hListenSocket) == SOCKET_ERROR) printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError()); #ifdef __WXMSW__ // Shutdown Windows Sockets WSACleanup(); #endif } } instance_of_cnetcleanup;
[ [ [ 1, 1750 ] ] ]
211d4d15ec5b4fc98a1519760f5b9c78b355cb12
048ab1167ffbc2e4e206c220265e729fad405545
/PROGRAMADA_INTENTO_2/triangle.cpp
cbfa4395bb4766cbb66d91e3e16a03881aa2aa8e
[]
no_license
rijoalvi/tarea4graficacion
2802c59352ea5fb7443ea9822dc4afe080c1d466
ed2eed4e6dcd92f5ba810f7e30cfe329d73f93fe
refs/heads/master
2020-06-02T23:49:27.178302
2011-10-29T01:28:08
2011-10-29T01:28:08
32,130,928
0
0
null
null
null
null
UTF-8
C++
false
false
4,945
cpp
/* * triangle.cpp * asrTracer * * Created by Petrik Clarberg on 2006-02-22. * Copyright 2006 __MyCompanyName__. All rights reserved. * */ #include "defines.h" #include "ray.h" #include "triangle.h" #include "mesh.h" /// Triangle overlap distance to avoid problems at edges. static const float overlap = 1e-3f; /** * Constructor. */ Triangle::Triangle() : mMesh(0) { } /** * Constructor initializing the triangle with the given vertices. */ Triangle::Triangle(Mesh* owner, const vertex& vtx1, const vertex& vtx2, const vertex& vtx3) : mMesh(owner) { mVtx[0] = vtx1; mVtx[1] = vtx2; mVtx[2] = vtx3; } /** * Compute the triangle's face normal from the position of its vertices. * The vertices are in counterclockwise order, which mean the normal can * be computed as: n = (v1-v0) x (v2-v0). */ Vector3D Triangle::getFaceNormal() const { Vector3D e1 = getVtxPosition(1) - getVtxPosition(0); // find edge v0-v1 Vector3D e2 = getVtxPosition(2) - getVtxPosition(0); // find edge v0-v2 Vector3D n = e1 % e2; // n = e1 x e2 n.normalize(); return n; } /** * Return the area of the triangle. */ float Triangle::getArea() const { Vector3D e1 = getVtxPosition(1) - getVtxPosition(0); // find edge v0-v1 Vector3D e2 = getVtxPosition(2) - getVtxPosition(0); // find edge v0-v2 Vector3D n = e1 % e2; // n = e1 x e2 float a = 0.5f * std::fabs(n.length()); // area = |n| / 2 return a; } // Implementation of the Intersectable interface. /** * Returns true if the ray intersects the triangle. * This is useful for quickly determining if it's a hit or miss, * but no information about the hit point is returned. */ bool Triangle::intersect(const Ray& ray) const { // TODO: Add boolean triangle intersection test. return false; } /** * Returns true if the ray intersects the triangle. * Information about the hit point is computed and returned in * the Intersection object. */ bool Triangle::intersect(const Ray& ray, Intersection& isect) const { // TODO: Add triangle intersection test. // Remove the "return false"-statement and // uncomment the lines that follows. return false; /* // YOUR TEST HERE float t, u, v, w; // If test passes... // Compute information about the hit point isect.mRay = ray; isect.mObject = this; // Store ptr to the object hit by the ray (this). isect.mMaterial = mMesh->getMaterial(); // Store ptr to the material at the hit point. isect.mPosition = ray.orig + t*ray.dir; // Compute position of intersection isect.mNormal = u*getVtxNormal(0) + v*getVtxNormal(1) + w*getVtxNormal(2); isect.mNormal.normalize(); isect.mView = -ray.dir; // View direction is negative ray direction. isect.mFrontFacing = isect.mView.dot(isect.mNormal) > 0.0f; if (!isect.mFrontFacing) isect.mNormal = -isect.mNormal; isect.mTexture = u*getVtxTexture(0) + v*getVtxTexture(1) + w*getVtxTexture(2); isect.mHitTime = t; isect.mHitParam = UV(u,v); return true; */ } /** * Returns the axis-aligned bounding box enclosing the triangle. */ void Triangle::getAABB(AABB& bb) const { bb = AABB(getVtxPosition(0), getVtxPosition(1), getVtxPosition(2)); } void Triangle::prepare() { Vector3D n = getFaceNormal(); for (int i = 0; i < 3; i++) { const Point3D& p0 = getVtxPosition(i); const Point3D& p1 = getVtxPosition((i+1)%3); const Point3D& p2 = getVtxPosition((i+2)%3); Vector3D e = p2 - p1; Vector3D np = n % e; float a = np.dot(p1); float b = np.dot(p0); float f = 1.0f / (b-a); float d = 1.0f - f*b; mPlanes[i] = f * np; mPlaneOffsets(i) = d; } } /// Returns the position of vertex i=[0,1,2]. const Point3D& Triangle::getVtxPosition(int i) const { return mMesh->mVtxP[mVtx[i].p]; } /// Returns the normal of vertex i=[0,1,2]. const Vector3D& Triangle::getVtxNormal(int i) const { return mMesh->mVtxN[mVtx[i].n]; } /// Returns the texture coordinate of vertex i=[0,1,2]. const UV& Triangle::getVtxTexture(int i) const { return mMesh->mVtxUV[mVtx[i].t]; } UV Triangle::calculateTextureDifferential(const Point3D& p, const Vector3D& dp) const { return mPlanes[0].dot(dp)*getVtxTexture(0) + mPlanes[1].dot(dp)*getVtxTexture(1) + mPlanes[2].dot(dp)*getVtxTexture(2); } Vector3D Triangle::calculateNormalDifferential(const Point3D& p, const Vector3D& dp, bool isFrontFacing) const { Vector3D n = (mPlanes[0].dot(p)+mPlaneOffsets.x)*getVtxNormal(0) + (mPlanes[1].dot(p)+mPlaneOffsets.y)*getVtxNormal(1) + (mPlanes[2].dot(p)+mPlaneOffsets.z)*getVtxNormal(2); Vector3D dn = mPlanes[0].dot(dp)*getVtxNormal(0) + mPlanes[1].dot(dp)*getVtxNormal(1) + mPlanes[2].dot(dp)*getVtxNormal(2); float sign = isFrontFacing ? 1.0f : -1.0f; float nl = n.length(); return sign * (n.dot(n) * dn - n.dot(dn) * n) / (nl*nl*nl); }
[ "[email protected]@5c4c3386-4ac9-2bb3-2425-1b8d11fe38ad" ]
[ [ [ 1, 189 ] ] ]
3e06254c25fdd38e941532b4348278580842b5bd
f8c850e4068e1c2684f082ed81541a0b175cb807
/Lab2March/Bradshaw_David_ComputeChange.cpp
800447cd8c407f763fef10366c6272031e6464d3
[]
no_license
dabrad26/programming-class-cpp
677738e9154de3bd103e41269a21dea21901b5d0
b1b23a187755400abeb9caebdf0ea0636cd2491b
refs/heads/main
2023-02-09T23:00:34.490541
2009-08-20T19:19:19
2009-08-20T19:19:19
327,986,006
0
0
null
null
null
null
UTF-8
C++
false
false
1,866
cpp
#include <iostream> using namespace std; int main() { // Receive the amount cout << "Enter an amount in double: "; double amount; cin >> amount; int remainingAmount = static_cast<int>(amount * 100); // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount; // Display results cout << "Your amount " << amount << " consists of \n"; if (numberOfOneDollars != 0) { cout << "\t" << numberOfOneDollars; if (numberOfOneDollars >= 2) { cout << " dollars\n"; } else { cout << " dollar\n"; } } if (numberOfQuarters != 0) { cout << "\t" << numberOfQuarters; if (numberOfQuarters >= 2) { cout << " quarters\n"; } else { cout << " quarter\n"; } } if (numberOfDimes != 0) { cout << "\t" << numberOfDimes; if (numberOfDimes >= 2) { cout << " dimes\n"; } else { cout << " dime\n"; } } if (numberOfNickels != 0) { cout << "\t" << numberOfNickels; if (numberOfNickels >= 2) { cout << " nickels\n"; } else { cout << " nickel\n"; } } if (numberOfPennies != 0) { cout << "\t" << numberOfPennies; if (numberOfPennies >= 2) { cout << " Pennies\n"; } else { cout << " Penny\n"; } } return 0; }
[ [ [ 1, 83 ] ] ]
3cec80e0221efe57b388075149c51387b306f2a5
7ffee9a5beb93120007459707cced0ca592b251d
/readppm.cpp
b4cd919ab49aa7c86c59f33b94092a134938903d
[]
no_license
skabbes/cs418mp3
403119257f7971e1f7ad36954ea5043a50ee59b8
6fb8218bef4c44defa7a2dddbaaa6a9e1433b49f
refs/heads/master
2021-01-10T19:22:40.697264
2011-04-11T09:11:01
2011-04-11T09:11:01
1,588,687
0
2
null
null
null
null
UTF-8
C++
false
false
2,743
cpp
/* readppm.c Nate Robins, 1997, 2000 [email protected], http://www.pobox.com/~nate PPM File reader. */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "readppm.h" /* readPPM: read a PPM raw (type P6) file. The PPM file has a header * that should look something like: * * P6 * # comment * width height max_value * rgbrgbrgb... * * where "P6" is the magic cookie which identifies the file type and * should be the only characters on the first line followed by a * carriage return. Any line starting with a # mark will be treated * as a comment and discarded. After the magic cookie, three integer * values are expected: width, height of the image and the maximum * value for a pixel (max_value must be < 256 for PPM raw files). The * data section consists of width*height rgb triplets (one byte each) * in binary format (i.e., such as that written with fwrite() or * equivalent). * * The rgb data is returned as an array of unsigned chars (packed * rgb). The malloc()'d memory should be free()'d by the caller. If * an error occurs, an error message is sent to stderr and NULL is * returned. * * filename - name of the .ppm file. * width - will contain the width of the image on return. * height - will contain the height of the image on return. * */ unsigned char* readPPM(const char* filename, int* width, int* height) { FILE* fp; int i, w, h, d; unsigned char* image; char head[70]; /* max line <= 70 in PPM (per spec). */ fp = fopen(filename, "rb"); if (!fp) { perror(filename); return NULL; } /* grab first two chars of the file and make sure that it has the correct magic cookie for a raw PPM file. */ fgets(head, 70, fp); if (strncmp(head, "P6", 2)) { fprintf(stderr, "%s: Not a raw PPM file\n", filename); return NULL; } /* grab the three elements in the header (width, height, maxval). */ i = 0; while(i < 3) { fgets(head, 70, fp); if (head[0] == '#') /* skip comments. */ continue; if (i == 0) i += sscanf(head, "%d %d %d", &w, &h, &d); else if (i == 1) i += sscanf(head, "%d %d", &h, &d); else if (i == 2) i += sscanf(head, "%d", &d); } /* grab all the image data in one fell swoop. */ image = (unsigned char*)malloc(sizeof(unsigned char)*w*h*3); fread(image, sizeof(unsigned char), w*h*3, fp); fclose(fp); *width = w; *height = h; return image; }
[ [ [ 1, 87 ] ] ]
01b6f81307898a3c3284a462d38903269cc8f655
814b49df11675ac3664ac0198048961b5306e1c5
/Code/Engine/Utilities/include/ComponentRotative.h
b0cb1586c9a2f785d2fe420a06022e10b01ec868
[]
no_license
Atridas/biogame
f6cb24d0c0b208316990e5bb0b52ef3fb8e83042
3b8e95b215da4d51ab856b4701c12e077cbd2587
refs/heads/master
2021-01-13T00:55:50.502395
2011-10-31T12:58:53
2011-10-31T12:58:53
43,897,729
0
0
null
null
null
null
UTF-8
C++
false
false
997
h
#pragma once #ifndef __COMPONENT_ROTATIVE__ #define __COMPONENT_ROTATIVE__ #include "base.h" #include "EntityDefines.h" class CComponentRenderableObject; class CComponentRotative: public CBaseComponent { public: ~CComponentRotative() {Done();} CBaseComponent::Type GetType() {return CBaseComponent::ECT_ROTATIVE;}; static CComponentRotative::Type GetStaticType() {return CBaseComponent::ECT_ROTATIVE;}; static CComponentRotative* AddToEntity(CGameEntity *_pEntity, float _fYawRotation, float _fPitchRotation, float _fRollRotation); virtual void PreUpdate(float _fDeltaTime); float m_fYawRotation, m_fPitchRotation, m_fRollRotation; protected: virtual void Release() {}; private: bool Init(CGameEntity* _pEntity, float _fYawRotation, float _fPitchRotation, float _fRollRotation); CComponentRotative(): m_fYawRotation(0.f), m_fPitchRotation(0.f), m_fRollRotation(0.f), m_pCRO(0) {}; CComponentRenderableObject* m_pCRO; }; #endif
[ "mudarra@576ee6d0-068d-96d9-bff2-16229cd70485", "Atridas87@576ee6d0-068d-96d9-bff2-16229cd70485" ]
[ [ [ 1, 7 ], [ 9, 19 ], [ 21, 21 ], [ 23, 23 ], [ 25, 29 ], [ 32, 32 ], [ 34, 36 ] ], [ [ 8, 8 ], [ 20, 20 ], [ 22, 22 ], [ 24, 24 ], [ 30, 31 ], [ 33, 33 ] ] ]
181690d81856abc7c46e0f3921c35500249d9af2
5750620062af54ed24792c39d0bf19a6f8f1e3bf
/src/json/json_spirit_writer_template.h
d42b411e2d0e979e835915741eb91032caeadfdc
[ "MIT" ]
permissive
makomk/soldcoin
4088e49928efe7436eee8bae40b0b1b9ce9e2720
f964acdd1a76d58f7e27e386fffbed22a1916307
refs/heads/master
2021-01-17T22:18:53.603480
2011-09-04T19:29:57
2011-09-04T19:29:57
2,344,688
0
0
null
null
null
null
UTF-8
C++
false
false
7,100
h
#ifndef JSON_SPIRIT_WRITER_TEMPLATE #define JSON_SPIRIT_WRITER_TEMPLATE // Copyright John W. Wilkinson 2007 - 2009. // Distributed under the MIT License, see accompanying file LICENSE.txt // json spirit version 4.03 #include "json_spirit_value.h" #include <cassert> #include <sstream> #include <iomanip> namespace json_spirit { inline char to_hex_char( unsigned int c ) { assert( c <= 0xF ); const char ch = static_cast< char >( c ); if( ch < 10 ) return '0' + ch; return 'A' - 10 + ch; } template< class String_type > String_type non_printable_to_string( unsigned int c ) { typedef typename String_type::value_type Char_type; String_type result( 6, '\\' ); result[1] = 'u'; result[ 5 ] = to_hex_char( c & 0x000F ); c >>= 4; result[ 4 ] = to_hex_char( c & 0x000F ); c >>= 4; result[ 3 ] = to_hex_char( c & 0x000F ); c >>= 4; result[ 2 ] = to_hex_char( c & 0x000F ); return result; } template< typename Char_type, class String_type > bool add_esc_char( Char_type c, String_type& s ) { switch( c ) { case '"': s += to_str< String_type >( "\\\"" ); return true; case '\\': s += to_str< String_type >( "\\\\" ); return true; case '\b': s += to_str< String_type >( "\\b" ); return true; case '\f': s += to_str< String_type >( "\\f" ); return true; case '\n': s += to_str< String_type >( "\\n" ); return true; case '\r': s += to_str< String_type >( "\\r" ); return true; case '\t': s += to_str< String_type >( "\\t" ); return true; } return false; } template< class String_type > String_type add_esc_chars( const String_type& s ) { typedef typename String_type::const_iterator Iter_type; typedef typename String_type::value_type Char_type; String_type result; const Iter_type end( s.end() ); for( Iter_type i = s.begin(); i != end; ++i ) { const Char_type c( *i ); if( add_esc_char( c, result ) ) continue; const wint_t unsigned_c( ( c >= 0 ) ? c : 256 + c ); if( iswprint( unsigned_c ) ) { result += c; } else { result += non_printable_to_string< String_type >( unsigned_c ); } } return result; } // this class generates the JSON text, // it keeps track of the indentation level etc. // template< class Value_type, class Ostream_type > class Generator { typedef typename Value_type::Config_type Config_type; typedef typename Config_type::String_type String_type; typedef typename Config_type::Object_type Object_type; typedef typename Config_type::Array_type Array_type; typedef typename String_type::value_type Char_type; typedef typename Object_type::value_type Obj_member_type; public: Generator( const Value_type& value, Ostream_type& os, bool pretty ) : os_( os ) , indentation_level_( 0 ) , pretty_( pretty ) { output( value ); } private: void output( const Value_type& value ) { switch( value.type() ) { case obj_type: output( value.get_obj() ); break; case array_type: output( value.get_array() ); break; case str_type: output( value.get_str() ); break; case bool_type: output( value.get_bool() ); break; case int_type: output_int( value ); break; /// SolidCoin: Added std::fixed and changed precision from 16 to 8 case real_type: os_ << std::showpoint << std::fixed << std::setprecision(8) << value.get_real(); break; case null_type: os_ << "null"; break; default: assert( false ); } } void output( const Object_type& obj ) { output_array_or_obj( obj, '{', '}' ); } void output( const Array_type& arr ) { output_array_or_obj( arr, '[', ']' ); } void output( const Obj_member_type& member ) { output( Config_type::get_name( member ) ); space(); os_ << ':'; space(); output( Config_type::get_value( member ) ); } void output_int( const Value_type& value ) { if( value.is_uint64() ) { os_ << value.get_uint64(); } else { os_ << value.get_int64(); } } void output( const String_type& s ) { os_ << '"' << add_esc_chars( s ) << '"'; } void output( bool b ) { os_ << to_str< String_type >( b ? "true" : "false" ); } template< class T > void output_array_or_obj( const T& t, Char_type start_char, Char_type end_char ) { os_ << start_char; new_line(); ++indentation_level_; for( typename T::const_iterator i = t.begin(); i != t.end(); ++i ) { indent(); output( *i ); typename T::const_iterator next = i; if( ++next != t.end()) { os_ << ','; } new_line(); } --indentation_level_; indent(); os_ << end_char; } void indent() { if( !pretty_ ) return; for( int i = 0; i < indentation_level_; ++i ) { os_ << " "; } } void space() { if( pretty_ ) os_ << ' '; } void new_line() { if( pretty_ ) os_ << '\n'; } Generator& operator=( const Generator& ); // to prevent "assignment operator could not be generated" warning Ostream_type& os_; int indentation_level_; bool pretty_; }; template< class Value_type, class Ostream_type > void write_stream( const Value_type& value, Ostream_type& os, bool pretty ) { Generator< Value_type, Ostream_type >( value, os, pretty ); } template< class Value_type > typename Value_type::String_type write_string( const Value_type& value, bool pretty ) { typedef typename Value_type::String_type::value_type Char_type; std::basic_ostringstream< Char_type > os; write_stream( value, os, pretty ); return os.str(); } } #endif
[ [ [ 1, 248 ] ] ]
0ae4d58f5f419309c6c0056b83bcf1a76c7110c8
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/dom/deprecated/AttrMapImpl.cpp
02796bf829f30f0f7781735349351a8abab5e9c7
[ "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
2,780
cpp
/* * Copyright 1999-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: AttrMapImpl.cpp,v 1.5 2004/09/08 13:55:42 peiyongz Exp $ */ #include "AttrMapImpl.hpp" #include "NamedNodeMapImpl.hpp" #include "NodeImpl.hpp" #include "ElementImpl.hpp" #include "DocumentImpl.hpp" XERCES_CPP_NAMESPACE_BEGIN AttrMapImpl::AttrMapImpl(NodeImpl *ownerNod) : NamedNodeMapImpl(ownerNod) { hasDefaults(false); } AttrMapImpl::AttrMapImpl(NodeImpl *ownerNod, NamedNodeMapImpl *defaults) : NamedNodeMapImpl(ownerNod) { hasDefaults(false); if (defaults != null) { if (defaults->getLength() > 0) { hasDefaults(true); cloneContent(defaults); } } } AttrMapImpl::~AttrMapImpl() { } AttrMapImpl *AttrMapImpl::cloneAttrMap(NodeImpl *ownerNode_p) { AttrMapImpl *newmap = new (ownerNode_p->getDocument()->getMemoryManager()) AttrMapImpl(ownerNode_p); newmap->cloneContent(this); newmap->attrDefaults = this->attrDefaults; return newmap; } NodeImpl *AttrMapImpl::removeNamedItem(const DOMString &name) { NodeImpl* removed = NamedNodeMapImpl::removeNamedItem(name); // Replace it if it had a default value // (DOM spec level 1 - Element Interface) if (hasDefaults() && (removed != null)) { AttrMapImpl* defAttrs = ((ElementImpl*)ownerNode)->getDefaultAttributes(); AttrImpl* attr = (AttrImpl*)(defAttrs->getNamedItem(name)); if (attr != null) { AttrImpl* newAttr = (AttrImpl*)attr->cloneNode(true); setNamedItem(newAttr); } } return removed; } NodeImpl *AttrMapImpl::removeNamedItemNS(const DOMString &namespaceURI, const DOMString &localName) { NodeImpl* removed = NamedNodeMapImpl::removeNamedItemNS(namespaceURI, localName); // Replace it if it had a default value // (DOM spec level 2 - Element Interface) if (hasDefaults() && (removed != null)) { AttrMapImpl* defAttrs = ((ElementImpl*)ownerNode)->getDefaultAttributes(); AttrImpl* attr = (AttrImpl*)(defAttrs->getNamedItemNS(namespaceURI, localName)); if (attr != null) { AttrImpl* newAttr = (AttrImpl*)attr->cloneNode(true); setNamedItem(newAttr); } } return removed; } XERCES_CPP_NAMESPACE_END
[ [ [ 1, 104 ] ] ]
f8260ff1ab46050afa4e5a54bafd952fad10f01b
508bfb3220be28811600a2cbf0aabae382f78775
/AcademicCrawler-sdk/Qt/Qt-4.6.2/include/Qt/qmatrix4x4.h
5786dbd3cffd9252f6199dc70a9066f02ff75c82
[]
no_license
darkbtf/academic-crawler
295f3bd74b18e700402bc2be59f15694d6195471
5dfcb0f1b88b93aa7545ef233344a41570011532
refs/heads/master
2021-01-01T19:21:00.162442
2011-03-10T16:29:25
2011-03-10T16:29:25
42,468,175
0
0
null
null
null
null
UTF-8
C++
false
false
34,404
h
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMATRIX4X4_H #define QMATRIX4X4_H #include <QtGui/qvector3d.h> #include <QtGui/qvector4d.h> #include <QtGui/qquaternion.h> #include <QtGui/qgenericmatrix.h> #include <QtCore/qrect.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) #ifndef QT_NO_MATRIX4X4 class QMatrix; class QTransform; class QVariant; class Q_GUI_EXPORT QMatrix4x4 { public: inline QMatrix4x4() { setToIdentity(); } explicit QMatrix4x4(const qreal *values); inline QMatrix4x4(qreal m11, qreal m12, qreal m13, qreal m14, qreal m21, qreal m22, qreal m23, qreal m24, qreal m31, qreal m32, qreal m33, qreal m34, qreal m41, qreal m42, qreal m43, qreal m44); #if !defined(QT_NO_MEMBER_TEMPLATES) || defined(Q_QDOC) template <int N, int M> explicit QMatrix4x4(const QGenericMatrix<N, M, qreal>& matrix); #endif QMatrix4x4(const qreal *values, int cols, int rows); QMatrix4x4(const QTransform& transform); QMatrix4x4(const QMatrix& matrix); inline const qreal& operator()(int row, int column) const; inline qreal& operator()(int row, int column); inline QVector4D column(int index) const; inline void setColumn(int index, const QVector4D& value); inline QVector4D row(int index) const; inline void setRow(int index, const QVector4D& value); inline bool isIdentity() const; inline void setToIdentity(); inline void fill(qreal value); qreal determinant() const; QMatrix4x4 inverted(bool *invertible = 0) const; QMatrix4x4 transposed() const; QMatrix3x3 normalMatrix() const; inline QMatrix4x4& operator+=(const QMatrix4x4& other); inline QMatrix4x4& operator-=(const QMatrix4x4& other); inline QMatrix4x4& operator*=(const QMatrix4x4& other); inline QMatrix4x4& operator*=(qreal factor); QMatrix4x4& operator/=(qreal divisor); inline bool operator==(const QMatrix4x4& other) const; inline bool operator!=(const QMatrix4x4& other) const; friend QMatrix4x4 operator+(const QMatrix4x4& m1, const QMatrix4x4& m2); friend QMatrix4x4 operator-(const QMatrix4x4& m1, const QMatrix4x4& m2); friend QMatrix4x4 operator*(const QMatrix4x4& m1, const QMatrix4x4& m2); #ifndef QT_NO_VECTOR3D friend QVector3D operator*(const QMatrix4x4& matrix, const QVector3D& vector); friend QVector3D operator*(const QVector3D& vector, const QMatrix4x4& matrix); #endif #ifndef QT_NO_VECTOR4D friend QVector4D operator*(const QVector4D& vector, const QMatrix4x4& matrix); friend QVector4D operator*(const QMatrix4x4& matrix, const QVector4D& vector); #endif friend QPoint operator*(const QPoint& point, const QMatrix4x4& matrix); friend QPointF operator*(const QPointF& point, const QMatrix4x4& matrix); friend QMatrix4x4 operator-(const QMatrix4x4& matrix); friend QPoint operator*(const QMatrix4x4& matrix, const QPoint& point); friend QPointF operator*(const QMatrix4x4& matrix, const QPointF& point); friend QMatrix4x4 operator*(qreal factor, const QMatrix4x4& matrix); friend QMatrix4x4 operator*(const QMatrix4x4& matrix, qreal factor); friend Q_GUI_EXPORT QMatrix4x4 operator/(const QMatrix4x4& matrix, qreal divisor); friend inline bool qFuzzyCompare(const QMatrix4x4& m1, const QMatrix4x4& m2); #ifndef QT_NO_VECTOR3D void scale(const QVector3D& vector); void translate(const QVector3D& vector); void rotate(qreal angle, const QVector3D& vector); #endif void scale(qreal x, qreal y); void scale(qreal x, qreal y, qreal z); void scale(qreal factor); void translate(qreal x, qreal y); void translate(qreal x, qreal y, qreal z); void rotate(qreal angle, qreal x, qreal y, qreal z = 0.0f); #ifndef QT_NO_QUATERNION void rotate(const QQuaternion& quaternion); #endif void ortho(const QRect& rect); void ortho(const QRectF& rect); void ortho(qreal left, qreal right, qreal bottom, qreal top, qreal nearPlane, qreal farPlane); void frustum(qreal left, qreal right, qreal bottom, qreal top, qreal nearPlane, qreal farPlane); void perspective(qreal angle, qreal aspect, qreal nearPlane, qreal farPlane); #ifndef QT_NO_VECTOR3D void lookAt(const QVector3D& eye, const QVector3D& center, const QVector3D& up); #endif void flipCoordinates(); void copyDataTo(qreal *values) const; QMatrix toAffine() const; QTransform toTransform() const; QTransform toTransform(qreal distanceToPlane) const; QPoint map(const QPoint& point) const; QPointF map(const QPointF& point) const; #ifndef QT_NO_VECTOR3D QVector3D map(const QVector3D& point) const; QVector3D mapVector(const QVector3D& vector) const; #endif #ifndef QT_NO_VECTOR4D QVector4D map(const QVector4D& point) const; #endif QRect mapRect(const QRect& rect) const; QRectF mapRect(const QRectF& rect) const; #if !defined(QT_NO_MEMBER_TEMPLATES) || defined(Q_QDOC) template <int N, int M> QGenericMatrix<N, M, qreal> toGenericMatrix() const; #endif inline qreal *data(); inline const qreal *data() const { return m[0]; } inline const qreal *constData() const { return m[0]; } void optimize(); operator QVariant() const; #ifndef QT_NO_DEBUG_STREAM friend Q_GUI_EXPORT QDebug operator<<(QDebug dbg, const QMatrix4x4 &m); #endif private: qreal m[4][4]; // Column-major order to match OpenGL. int flagBits; // Flag bits from the enum below. enum { Identity = 0x0001, // Identity matrix General = 0x0002, // General matrix, unknown contents Translation = 0x0004, // Contains a simple translation Scale = 0x0008, // Contains a simple scale Rotation = 0x0010 // Contains a simple rotation }; // Construct without initializing identity matrix. QMatrix4x4(int) { flagBits = General; } QMatrix4x4 orthonormalInverse() const; void projectedRotate(qreal angle, qreal x, qreal y, qreal z); friend class QGraphicsRotation; }; inline QMatrix4x4::QMatrix4x4 (qreal m11, qreal m12, qreal m13, qreal m14, qreal m21, qreal m22, qreal m23, qreal m24, qreal m31, qreal m32, qreal m33, qreal m34, qreal m41, qreal m42, qreal m43, qreal m44) { m[0][0] = m11; m[0][1] = m21; m[0][2] = m31; m[0][3] = m41; m[1][0] = m12; m[1][1] = m22; m[1][2] = m32; m[1][3] = m42; m[2][0] = m13; m[2][1] = m23; m[2][2] = m33; m[2][3] = m43; m[3][0] = m14; m[3][1] = m24; m[3][2] = m34; m[3][3] = m44; flagBits = General; } #if !defined(QT_NO_MEMBER_TEMPLATES) template <int N, int M> Q_INLINE_TEMPLATE QMatrix4x4::QMatrix4x4 (const QGenericMatrix<N, M, qreal>& matrix) { const qreal *values = matrix.constData(); for (int matrixCol = 0; matrixCol < 4; ++matrixCol) { for (int matrixRow = 0; matrixRow < 4; ++matrixRow) { if (matrixCol < N && matrixRow < M) m[matrixCol][matrixRow] = values[matrixCol * M + matrixRow]; else if (matrixCol == matrixRow) m[matrixCol][matrixRow] = 1.0f; else m[matrixCol][matrixRow] = 0.0f; } } flagBits = General; } template <int N, int M> QGenericMatrix<N, M, qreal> QMatrix4x4::toGenericMatrix() const { QGenericMatrix<N, M, qreal> result; qreal *values = result.data(); for (int matrixCol = 0; matrixCol < N; ++matrixCol) { for (int matrixRow = 0; matrixRow < M; ++matrixRow) { if (matrixCol < 4 && matrixRow < 4) values[matrixCol * M + matrixRow] = m[matrixCol][matrixRow]; else if (matrixCol == matrixRow) values[matrixCol * M + matrixRow] = 1.0f; else values[matrixCol * M + matrixRow] = 0.0f; } } return result; } #endif inline const qreal& QMatrix4x4::operator()(int aRow, int aColumn) const { Q_ASSERT(aRow >= 0 && aRow < 4 && aColumn >= 0 && aColumn < 4); return m[aColumn][aRow]; } inline qreal& QMatrix4x4::operator()(int aRow, int aColumn) { Q_ASSERT(aRow >= 0 && aRow < 4 && aColumn >= 0 && aColumn < 4); flagBits = General; return m[aColumn][aRow]; } inline QVector4D QMatrix4x4::column(int index) const { Q_ASSERT(index >= 0 && index < 4); return QVector4D(m[index][0], m[index][1], m[index][2], m[index][3]); } inline void QMatrix4x4::setColumn(int index, const QVector4D& value) { Q_ASSERT(index >= 0 && index < 4); m[index][0] = value.x(); m[index][1] = value.y(); m[index][2] = value.z(); m[index][3] = value.w(); flagBits = General; } inline QVector4D QMatrix4x4::row(int index) const { Q_ASSERT(index >= 0 && index < 4); return QVector4D(m[0][index], m[1][index], m[2][index], m[3][index]); } inline void QMatrix4x4::setRow(int index, const QVector4D& value) { Q_ASSERT(index >= 0 && index < 4); m[0][index] = value.x(); m[1][index] = value.y(); m[2][index] = value.z(); m[3][index] = value.w(); flagBits = General; } Q_GUI_EXPORT QMatrix4x4 operator/(const QMatrix4x4& matrix, qreal divisor); inline bool QMatrix4x4::isIdentity() const { if (flagBits == Identity) return true; if (m[0][0] != 1.0f || m[0][1] != 0.0f || m[0][2] != 0.0f) return false; if (m[0][3] != 0.0f || m[1][0] != 0.0f || m[1][1] != 1.0f) return false; if (m[1][2] != 0.0f || m[1][3] != 0.0f || m[2][0] != 0.0f) return false; if (m[2][1] != 0.0f || m[2][2] != 1.0f || m[2][3] != 0.0f) return false; if (m[3][0] != 0.0f || m[3][1] != 0.0f || m[3][2] != 0.0f) return false; return (m[3][3] == 1.0f); } inline void QMatrix4x4::setToIdentity() { m[0][0] = 1.0f; m[0][1] = 0.0f; m[0][2] = 0.0f; m[0][3] = 0.0f; m[1][0] = 0.0f; m[1][1] = 1.0f; m[1][2] = 0.0f; m[1][3] = 0.0f; m[2][0] = 0.0f; m[2][1] = 0.0f; m[2][2] = 1.0f; m[2][3] = 0.0f; m[3][0] = 0.0f; m[3][1] = 0.0f; m[3][2] = 0.0f; m[3][3] = 1.0f; flagBits = Identity; } inline void QMatrix4x4::fill(qreal value) { m[0][0] = value; m[0][1] = value; m[0][2] = value; m[0][3] = value; m[1][0] = value; m[1][1] = value; m[1][2] = value; m[1][3] = value; m[2][0] = value; m[2][1] = value; m[2][2] = value; m[2][3] = value; m[3][0] = value; m[3][1] = value; m[3][2] = value; m[3][3] = value; flagBits = General; } inline QMatrix4x4& QMatrix4x4::operator+=(const QMatrix4x4& other) { m[0][0] += other.m[0][0]; m[0][1] += other.m[0][1]; m[0][2] += other.m[0][2]; m[0][3] += other.m[0][3]; m[1][0] += other.m[1][0]; m[1][1] += other.m[1][1]; m[1][2] += other.m[1][2]; m[1][3] += other.m[1][3]; m[2][0] += other.m[2][0]; m[2][1] += other.m[2][1]; m[2][2] += other.m[2][2]; m[2][3] += other.m[2][3]; m[3][0] += other.m[3][0]; m[3][1] += other.m[3][1]; m[3][2] += other.m[3][2]; m[3][3] += other.m[3][3]; flagBits = General; return *this; } inline QMatrix4x4& QMatrix4x4::operator-=(const QMatrix4x4& other) { m[0][0] -= other.m[0][0]; m[0][1] -= other.m[0][1]; m[0][2] -= other.m[0][2]; m[0][3] -= other.m[0][3]; m[1][0] -= other.m[1][0]; m[1][1] -= other.m[1][1]; m[1][2] -= other.m[1][2]; m[1][3] -= other.m[1][3]; m[2][0] -= other.m[2][0]; m[2][1] -= other.m[2][1]; m[2][2] -= other.m[2][2]; m[2][3] -= other.m[2][3]; m[3][0] -= other.m[3][0]; m[3][1] -= other.m[3][1]; m[3][2] -= other.m[3][2]; m[3][3] -= other.m[3][3]; flagBits = General; return *this; } inline QMatrix4x4& QMatrix4x4::operator*=(const QMatrix4x4& other) { if (flagBits == Identity) { *this = other; return *this; } else if (other.flagBits == Identity) { return *this; } else { *this = *this * other; return *this; } } inline QMatrix4x4& QMatrix4x4::operator*=(qreal factor) { m[0][0] *= factor; m[0][1] *= factor; m[0][2] *= factor; m[0][3] *= factor; m[1][0] *= factor; m[1][1] *= factor; m[1][2] *= factor; m[1][3] *= factor; m[2][0] *= factor; m[2][1] *= factor; m[2][2] *= factor; m[2][3] *= factor; m[3][0] *= factor; m[3][1] *= factor; m[3][2] *= factor; m[3][3] *= factor; flagBits = General; return *this; } inline bool QMatrix4x4::operator==(const QMatrix4x4& other) const { return m[0][0] == other.m[0][0] && m[0][1] == other.m[0][1] && m[0][2] == other.m[0][2] && m[0][3] == other.m[0][3] && m[1][0] == other.m[1][0] && m[1][1] == other.m[1][1] && m[1][2] == other.m[1][2] && m[1][3] == other.m[1][3] && m[2][0] == other.m[2][0] && m[2][1] == other.m[2][1] && m[2][2] == other.m[2][2] && m[2][3] == other.m[2][3] && m[3][0] == other.m[3][0] && m[3][1] == other.m[3][1] && m[3][2] == other.m[3][2] && m[3][3] == other.m[3][3]; } inline bool QMatrix4x4::operator!=(const QMatrix4x4& other) const { return m[0][0] != other.m[0][0] || m[0][1] != other.m[0][1] || m[0][2] != other.m[0][2] || m[0][3] != other.m[0][3] || m[1][0] != other.m[1][0] || m[1][1] != other.m[1][1] || m[1][2] != other.m[1][2] || m[1][3] != other.m[1][3] || m[2][0] != other.m[2][0] || m[2][1] != other.m[2][1] || m[2][2] != other.m[2][2] || m[2][3] != other.m[2][3] || m[3][0] != other.m[3][0] || m[3][1] != other.m[3][1] || m[3][2] != other.m[3][2] || m[3][3] != other.m[3][3]; } inline QMatrix4x4 operator+(const QMatrix4x4& m1, const QMatrix4x4& m2) { QMatrix4x4 m(1); m.m[0][0] = m1.m[0][0] + m2.m[0][0]; m.m[0][1] = m1.m[0][1] + m2.m[0][1]; m.m[0][2] = m1.m[0][2] + m2.m[0][2]; m.m[0][3] = m1.m[0][3] + m2.m[0][3]; m.m[1][0] = m1.m[1][0] + m2.m[1][0]; m.m[1][1] = m1.m[1][1] + m2.m[1][1]; m.m[1][2] = m1.m[1][2] + m2.m[1][2]; m.m[1][3] = m1.m[1][3] + m2.m[1][3]; m.m[2][0] = m1.m[2][0] + m2.m[2][0]; m.m[2][1] = m1.m[2][1] + m2.m[2][1]; m.m[2][2] = m1.m[2][2] + m2.m[2][2]; m.m[2][3] = m1.m[2][3] + m2.m[2][3]; m.m[3][0] = m1.m[3][0] + m2.m[3][0]; m.m[3][1] = m1.m[3][1] + m2.m[3][1]; m.m[3][2] = m1.m[3][2] + m2.m[3][2]; m.m[3][3] = m1.m[3][3] + m2.m[3][3]; return m; } inline QMatrix4x4 operator-(const QMatrix4x4& m1, const QMatrix4x4& m2) { QMatrix4x4 m(1); m.m[0][0] = m1.m[0][0] - m2.m[0][0]; m.m[0][1] = m1.m[0][1] - m2.m[0][1]; m.m[0][2] = m1.m[0][2] - m2.m[0][2]; m.m[0][3] = m1.m[0][3] - m2.m[0][3]; m.m[1][0] = m1.m[1][0] - m2.m[1][0]; m.m[1][1] = m1.m[1][1] - m2.m[1][1]; m.m[1][2] = m1.m[1][2] - m2.m[1][2]; m.m[1][3] = m1.m[1][3] - m2.m[1][3]; m.m[2][0] = m1.m[2][0] - m2.m[2][0]; m.m[2][1] = m1.m[2][1] - m2.m[2][1]; m.m[2][2] = m1.m[2][2] - m2.m[2][2]; m.m[2][3] = m1.m[2][3] - m2.m[2][3]; m.m[3][0] = m1.m[3][0] - m2.m[3][0]; m.m[3][1] = m1.m[3][1] - m2.m[3][1]; m.m[3][2] = m1.m[3][2] - m2.m[3][2]; m.m[3][3] = m1.m[3][3] - m2.m[3][3]; return m; } inline QMatrix4x4 operator*(const QMatrix4x4& m1, const QMatrix4x4& m2) { if (m1.flagBits == QMatrix4x4::Identity) return m2; else if (m2.flagBits == QMatrix4x4::Identity) return m1; QMatrix4x4 m(1); m.m[0][0] = m1.m[0][0] * m2.m[0][0] + m1.m[1][0] * m2.m[0][1] + m1.m[2][0] * m2.m[0][2] + m1.m[3][0] * m2.m[0][3]; m.m[0][1] = m1.m[0][1] * m2.m[0][0] + m1.m[1][1] * m2.m[0][1] + m1.m[2][1] * m2.m[0][2] + m1.m[3][1] * m2.m[0][3]; m.m[0][2] = m1.m[0][2] * m2.m[0][0] + m1.m[1][2] * m2.m[0][1] + m1.m[2][2] * m2.m[0][2] + m1.m[3][2] * m2.m[0][3]; m.m[0][3] = m1.m[0][3] * m2.m[0][0] + m1.m[1][3] * m2.m[0][1] + m1.m[2][3] * m2.m[0][2] + m1.m[3][3] * m2.m[0][3]; m.m[1][0] = m1.m[0][0] * m2.m[1][0] + m1.m[1][0] * m2.m[1][1] + m1.m[2][0] * m2.m[1][2] + m1.m[3][0] * m2.m[1][3]; m.m[1][1] = m1.m[0][1] * m2.m[1][0] + m1.m[1][1] * m2.m[1][1] + m1.m[2][1] * m2.m[1][2] + m1.m[3][1] * m2.m[1][3]; m.m[1][2] = m1.m[0][2] * m2.m[1][0] + m1.m[1][2] * m2.m[1][1] + m1.m[2][2] * m2.m[1][2] + m1.m[3][2] * m2.m[1][3]; m.m[1][3] = m1.m[0][3] * m2.m[1][0] + m1.m[1][3] * m2.m[1][1] + m1.m[2][3] * m2.m[1][2] + m1.m[3][3] * m2.m[1][3]; m.m[2][0] = m1.m[0][0] * m2.m[2][0] + m1.m[1][0] * m2.m[2][1] + m1.m[2][0] * m2.m[2][2] + m1.m[3][0] * m2.m[2][3]; m.m[2][1] = m1.m[0][1] * m2.m[2][0] + m1.m[1][1] * m2.m[2][1] + m1.m[2][1] * m2.m[2][2] + m1.m[3][1] * m2.m[2][3]; m.m[2][2] = m1.m[0][2] * m2.m[2][0] + m1.m[1][2] * m2.m[2][1] + m1.m[2][2] * m2.m[2][2] + m1.m[3][2] * m2.m[2][3]; m.m[2][3] = m1.m[0][3] * m2.m[2][0] + m1.m[1][3] * m2.m[2][1] + m1.m[2][3] * m2.m[2][2] + m1.m[3][3] * m2.m[2][3]; m.m[3][0] = m1.m[0][0] * m2.m[3][0] + m1.m[1][0] * m2.m[3][1] + m1.m[2][0] * m2.m[3][2] + m1.m[3][0] * m2.m[3][3]; m.m[3][1] = m1.m[0][1] * m2.m[3][0] + m1.m[1][1] * m2.m[3][1] + m1.m[2][1] * m2.m[3][2] + m1.m[3][1] * m2.m[3][3]; m.m[3][2] = m1.m[0][2] * m2.m[3][0] + m1.m[1][2] * m2.m[3][1] + m1.m[2][2] * m2.m[3][2] + m1.m[3][2] * m2.m[3][3]; m.m[3][3] = m1.m[0][3] * m2.m[3][0] + m1.m[1][3] * m2.m[3][1] + m1.m[2][3] * m2.m[3][2] + m1.m[3][3] * m2.m[3][3]; return m; } #ifndef QT_NO_VECTOR3D inline QVector3D operator*(const QVector3D& vector, const QMatrix4x4& matrix) { qreal x, y, z, w; x = vector.x() * matrix.m[0][0] + vector.y() * matrix.m[0][1] + vector.z() * matrix.m[0][2] + matrix.m[0][3]; y = vector.x() * matrix.m[1][0] + vector.y() * matrix.m[1][1] + vector.z() * matrix.m[1][2] + matrix.m[1][3]; z = vector.x() * matrix.m[2][0] + vector.y() * matrix.m[2][1] + vector.z() * matrix.m[2][2] + matrix.m[2][3]; w = vector.x() * matrix.m[3][0] + vector.y() * matrix.m[3][1] + vector.z() * matrix.m[3][2] + matrix.m[3][3]; if (w == 1.0f) return QVector3D(x, y, z); else return QVector3D(x / w, y / w, z / w); } inline QVector3D operator*(const QMatrix4x4& matrix, const QVector3D& vector) { qreal x, y, z, w; if (matrix.flagBits == QMatrix4x4::Identity) { return vector; } else if (matrix.flagBits == QMatrix4x4::Translation) { return QVector3D(vector.x() + matrix.m[3][0], vector.y() + matrix.m[3][1], vector.z() + matrix.m[3][2]); } else if (matrix.flagBits == (QMatrix4x4::Translation | QMatrix4x4::Scale)) { return QVector3D(vector.x() * matrix.m[0][0] + matrix.m[3][0], vector.y() * matrix.m[1][1] + matrix.m[3][1], vector.z() * matrix.m[2][2] + matrix.m[3][2]); } else if (matrix.flagBits == QMatrix4x4::Scale) { return QVector3D(vector.x() * matrix.m[0][0], vector.y() * matrix.m[1][1], vector.z() * matrix.m[2][2]); } else { x = vector.x() * matrix.m[0][0] + vector.y() * matrix.m[1][0] + vector.z() * matrix.m[2][0] + matrix.m[3][0]; y = vector.x() * matrix.m[0][1] + vector.y() * matrix.m[1][1] + vector.z() * matrix.m[2][1] + matrix.m[3][1]; z = vector.x() * matrix.m[0][2] + vector.y() * matrix.m[1][2] + vector.z() * matrix.m[2][2] + matrix.m[3][2]; w = vector.x() * matrix.m[0][3] + vector.y() * matrix.m[1][3] + vector.z() * matrix.m[2][3] + matrix.m[3][3]; if (w == 1.0f) return QVector3D(x, y, z); else return QVector3D(x / w, y / w, z / w); } } #endif #ifndef QT_NO_VECTOR4D inline QVector4D operator*(const QVector4D& vector, const QMatrix4x4& matrix) { qreal x, y, z, w; x = vector.x() * matrix.m[0][0] + vector.y() * matrix.m[0][1] + vector.z() * matrix.m[0][2] + vector.w() * matrix.m[0][3]; y = vector.x() * matrix.m[1][0] + vector.y() * matrix.m[1][1] + vector.z() * matrix.m[1][2] + vector.w() * matrix.m[1][3]; z = vector.x() * matrix.m[2][0] + vector.y() * matrix.m[2][1] + vector.z() * matrix.m[2][2] + vector.w() * matrix.m[2][3]; w = vector.x() * matrix.m[3][0] + vector.y() * matrix.m[3][1] + vector.z() * matrix.m[3][2] + vector.w() * matrix.m[3][3]; return QVector4D(x, y, z, w); } inline QVector4D operator*(const QMatrix4x4& matrix, const QVector4D& vector) { qreal x, y, z, w; x = vector.x() * matrix.m[0][0] + vector.y() * matrix.m[1][0] + vector.z() * matrix.m[2][0] + vector.w() * matrix.m[3][0]; y = vector.x() * matrix.m[0][1] + vector.y() * matrix.m[1][1] + vector.z() * matrix.m[2][1] + vector.w() * matrix.m[3][1]; z = vector.x() * matrix.m[0][2] + vector.y() * matrix.m[1][2] + vector.z() * matrix.m[2][2] + vector.w() * matrix.m[3][2]; w = vector.x() * matrix.m[0][3] + vector.y() * matrix.m[1][3] + vector.z() * matrix.m[2][3] + vector.w() * matrix.m[3][3]; return QVector4D(x, y, z, w); } #endif inline QPoint operator*(const QPoint& point, const QMatrix4x4& matrix) { qreal xin, yin; qreal x, y, w; xin = point.x(); yin = point.y(); x = xin * matrix.m[0][0] + yin * matrix.m[0][1] + matrix.m[0][3]; y = xin * matrix.m[1][0] + yin * matrix.m[1][1] + matrix.m[1][3]; w = xin * matrix.m[3][0] + yin * matrix.m[3][1] + matrix.m[3][3]; if (w == 1.0f) return QPoint(qRound(x), qRound(y)); else return QPoint(qRound(x / w), qRound(y / w)); } inline QPointF operator*(const QPointF& point, const QMatrix4x4& matrix) { qreal xin, yin; qreal x, y, w; xin = point.x(); yin = point.y(); x = xin * matrix.m[0][0] + yin * matrix.m[0][1] + matrix.m[0][3]; y = xin * matrix.m[1][0] + yin * matrix.m[1][1] + matrix.m[1][3]; w = xin * matrix.m[3][0] + yin * matrix.m[3][1] + matrix.m[3][3]; if (w == 1.0f) { return QPointF(qreal(x), qreal(y)); } else { return QPointF(qreal(x / w), qreal(y / w)); } } inline QPoint operator*(const QMatrix4x4& matrix, const QPoint& point) { qreal xin, yin; qreal x, y, w; xin = point.x(); yin = point.y(); if (matrix.flagBits == QMatrix4x4::Identity) { return point; } else if (matrix.flagBits == QMatrix4x4::Translation) { return QPoint(qRound(xin + matrix.m[3][0]), qRound(yin + matrix.m[3][1])); } else if (matrix.flagBits == (QMatrix4x4::Translation | QMatrix4x4::Scale)) { return QPoint(qRound(xin * matrix.m[0][0] + matrix.m[3][0]), qRound(yin * matrix.m[1][1] + matrix.m[3][1])); } else if (matrix.flagBits == QMatrix4x4::Scale) { return QPoint(qRound(xin * matrix.m[0][0]), qRound(yin * matrix.m[1][1])); } else { x = xin * matrix.m[0][0] + yin * matrix.m[1][0] + matrix.m[3][0]; y = xin * matrix.m[0][1] + yin * matrix.m[1][1] + matrix.m[3][1]; w = xin * matrix.m[0][3] + yin * matrix.m[1][3] + matrix.m[3][3]; if (w == 1.0f) return QPoint(qRound(x), qRound(y)); else return QPoint(qRound(x / w), qRound(y / w)); } } inline QPointF operator*(const QMatrix4x4& matrix, const QPointF& point) { qreal xin, yin; qreal x, y, w; xin = point.x(); yin = point.y(); if (matrix.flagBits == QMatrix4x4::Identity) { return point; } else if (matrix.flagBits == QMatrix4x4::Translation) { return QPointF(xin + matrix.m[3][0], yin + matrix.m[3][1]); } else if (matrix.flagBits == (QMatrix4x4::Translation | QMatrix4x4::Scale)) { return QPointF(xin * matrix.m[0][0] + matrix.m[3][0], yin * matrix.m[1][1] + matrix.m[3][1]); } else if (matrix.flagBits == QMatrix4x4::Scale) { return QPointF(xin * matrix.m[0][0], yin * matrix.m[1][1]); } else { x = xin * matrix.m[0][0] + yin * matrix.m[1][0] + matrix.m[3][0]; y = xin * matrix.m[0][1] + yin * matrix.m[1][1] + matrix.m[3][1]; w = xin * matrix.m[0][3] + yin * matrix.m[1][3] + matrix.m[3][3]; if (w == 1.0f) { return QPointF(qreal(x), qreal(y)); } else { return QPointF(qreal(x / w), qreal(y / w)); } } } inline QMatrix4x4 operator-(const QMatrix4x4& matrix) { QMatrix4x4 m(1); m.m[0][0] = -matrix.m[0][0]; m.m[0][1] = -matrix.m[0][1]; m.m[0][2] = -matrix.m[0][2]; m.m[0][3] = -matrix.m[0][3]; m.m[1][0] = -matrix.m[1][0]; m.m[1][1] = -matrix.m[1][1]; m.m[1][2] = -matrix.m[1][2]; m.m[1][3] = -matrix.m[1][3]; m.m[2][0] = -matrix.m[2][0]; m.m[2][1] = -matrix.m[2][1]; m.m[2][2] = -matrix.m[2][2]; m.m[2][3] = -matrix.m[2][3]; m.m[3][0] = -matrix.m[3][0]; m.m[3][1] = -matrix.m[3][1]; m.m[3][2] = -matrix.m[3][2]; m.m[3][3] = -matrix.m[3][3]; return m; } inline QMatrix4x4 operator*(qreal factor, const QMatrix4x4& matrix) { QMatrix4x4 m(1); m.m[0][0] = matrix.m[0][0] * factor; m.m[0][1] = matrix.m[0][1] * factor; m.m[0][2] = matrix.m[0][2] * factor; m.m[0][3] = matrix.m[0][3] * factor; m.m[1][0] = matrix.m[1][0] * factor; m.m[1][1] = matrix.m[1][1] * factor; m.m[1][2] = matrix.m[1][2] * factor; m.m[1][3] = matrix.m[1][3] * factor; m.m[2][0] = matrix.m[2][0] * factor; m.m[2][1] = matrix.m[2][1] * factor; m.m[2][2] = matrix.m[2][2] * factor; m.m[2][3] = matrix.m[2][3] * factor; m.m[3][0] = matrix.m[3][0] * factor; m.m[3][1] = matrix.m[3][1] * factor; m.m[3][2] = matrix.m[3][2] * factor; m.m[3][3] = matrix.m[3][3] * factor; return m; } inline QMatrix4x4 operator*(const QMatrix4x4& matrix, qreal factor) { QMatrix4x4 m(1); m.m[0][0] = matrix.m[0][0] * factor; m.m[0][1] = matrix.m[0][1] * factor; m.m[0][2] = matrix.m[0][2] * factor; m.m[0][3] = matrix.m[0][3] * factor; m.m[1][0] = matrix.m[1][0] * factor; m.m[1][1] = matrix.m[1][1] * factor; m.m[1][2] = matrix.m[1][2] * factor; m.m[1][3] = matrix.m[1][3] * factor; m.m[2][0] = matrix.m[2][0] * factor; m.m[2][1] = matrix.m[2][1] * factor; m.m[2][2] = matrix.m[2][2] * factor; m.m[2][3] = matrix.m[2][3] * factor; m.m[3][0] = matrix.m[3][0] * factor; m.m[3][1] = matrix.m[3][1] * factor; m.m[3][2] = matrix.m[3][2] * factor; m.m[3][3] = matrix.m[3][3] * factor; return m; } inline bool qFuzzyCompare(const QMatrix4x4& m1, const QMatrix4x4& m2) { return qFuzzyCompare(m1.m[0][0], m2.m[0][0]) && qFuzzyCompare(m1.m[0][1], m2.m[0][1]) && qFuzzyCompare(m1.m[0][2], m2.m[0][2]) && qFuzzyCompare(m1.m[0][3], m2.m[0][3]) && qFuzzyCompare(m1.m[1][0], m2.m[1][0]) && qFuzzyCompare(m1.m[1][1], m2.m[1][1]) && qFuzzyCompare(m1.m[1][2], m2.m[1][2]) && qFuzzyCompare(m1.m[1][3], m2.m[1][3]) && qFuzzyCompare(m1.m[2][0], m2.m[2][0]) && qFuzzyCompare(m1.m[2][1], m2.m[2][1]) && qFuzzyCompare(m1.m[2][2], m2.m[2][2]) && qFuzzyCompare(m1.m[2][3], m2.m[2][3]) && qFuzzyCompare(m1.m[3][0], m2.m[3][0]) && qFuzzyCompare(m1.m[3][1], m2.m[3][1]) && qFuzzyCompare(m1.m[3][2], m2.m[3][2]) && qFuzzyCompare(m1.m[3][3], m2.m[3][3]); } inline QPoint QMatrix4x4::map(const QPoint& point) const { return *this * point; } inline QPointF QMatrix4x4::map(const QPointF& point) const { return *this * point; } #ifndef QT_NO_VECTOR3D inline QVector3D QMatrix4x4::map(const QVector3D& point) const { return *this * point; } inline QVector3D QMatrix4x4::mapVector(const QVector3D& vector) const { if (flagBits == Identity || flagBits == Translation) { return vector; } else if (flagBits == Scale || flagBits == (Translation | Scale)) { return QVector3D(vector.x() * m[0][0], vector.y() * m[1][1], vector.z() * m[2][2]); } else { return QVector3D(vector.x() * m[0][0] + vector.y() * m[1][0] + vector.z() * m[2][0], vector.x() * m[0][1] + vector.y() * m[1][1] + vector.z() * m[2][1], vector.x() * m[0][2] + vector.y() * m[1][2] + vector.z() * m[2][2]); } } #endif #ifndef QT_NO_VECTOR4D inline QVector4D QMatrix4x4::map(const QVector4D& point) const { return *this * point; } #endif inline qreal *QMatrix4x4::data() { // We have to assume that the caller will modify the matrix elements, // so we flip it over to "General" mode. flagBits = General; return m[0]; } #ifndef QT_NO_DEBUG_STREAM Q_GUI_EXPORT QDebug operator<<(QDebug dbg, const QMatrix4x4 &m); #endif #ifndef QT_NO_DATASTREAM Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QMatrix4x4 &); Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QMatrix4x4 &); #endif template <int N, int M> QMatrix4x4 qGenericMatrixToMatrix4x4(const QGenericMatrix<N, M, qreal>& matrix) { return QMatrix4x4(matrix.constData(), N, M); } template <int N, int M> QGenericMatrix<N, M, qreal> qGenericMatrixFromMatrix4x4(const QMatrix4x4& matrix) { QGenericMatrix<N, M, qreal> result; const qreal *m = matrix.constData(); qreal *values = result.data(); for (int col = 0; col < N; ++col) { for (int row = 0; row < M; ++row) { if (col < 4 && row < 4) values[col * M + row] = m[col * 4 + row]; else if (col == row) values[col * M + row] = 1.0f; else values[col * M + row] = 0.0f; } } return result; } #endif QT_END_NAMESPACE QT_END_HEADER #endif
[ "ulmonkey1987@7c5ce3f8-edad-37de-be84-b98c484540b5" ]
[ [ [ 1, 1024 ] ] ]
1426fbd5d689f179ff7275d9832a1add60895d86
335783c9e5837a1b626073d1288b492f9f6b057f
/source/fbxcmd/daolib/Model/MAO/MAOFile.h
83a3e95d430b283b4fc8d2fb960d01a19bd59cc6
[ "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
802
h
/********************************************************************** *< FILE: MAOFile.h DESCRIPTION: MAO File Format HISTORY: *> Copyright (c) 2009, All Rights Reserved. **********************************************************************/ #pragma once #include "MAOCommon.h" #include "MAO/MaterialObject.h" namespace DAO { namespace MAO { class MAOFile { class Impl; ValuePtr<Impl> pimpl; public: MAOFile(); ~MAOFile(); virtual void open(const _tstring& filename); virtual void open(IDAOStream& stream); virtual void save(const _tstring& filename); virtual void save(IDAOStream& stream); virtual void dump(); virtual void dump(const _tstring& filename); MaterialObjectRef get_Object() ; MaterialObjectRef get_Object() const; }; } }
[ "tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792" ]
[ [ [ 1, 42 ] ] ]
ca320c3ea97e06eeff4334e6f236269299190074
59ce53af7ad5a1f9b12a69aadbfc7abc4c4bfc02
/src/SkinResEditor_Old/SkinStrResDoc.h
cd5d85a191a71ba94d2e1d1015f3d691c675ec8c
[]
no_license
fingomajom/skinengine
444a89955046a6f2c7be49012ff501dc465f019e
6bb26a46a7edac88b613ea9a124abeb8a1694868
refs/heads/master
2021-01-10T11:30:51.541442
2008-07-30T07:13:11
2008-07-30T07:13:11
47,892,418
0
0
null
null
null
null
UTF-8
C++
false
false
2,784
h
/******************************************************************** * CreatedOn: 2008-2-17 12:25 * FileName: SkinStrResDoc.h * CreatedBy: lidengwang <[email protected]> * $LastChangedDate$ * $LastChangedRevision$ * $LastChangedBy$ * $HeadURL: $ * Purpose: *********************************************************************/ #pragma once class SkinStrResDoc : public KSGUI::skinstrres { public: SkinStrResDoc() { } ~SkinStrResDoc(void) { } typedef struct _StrResItemInfo { KSGUI::CString strIDName; KSGUI::CString strValue; }STRRESITEMINFO; BOOL NewResDoc() { BOOL bResult = TRUE; m_vtItemList.clear(); return bResult; } BOOL OpenResDoc(KSGUI::SkinXmlDocument& doc) { BOOL bResult = FALSE; NewResDoc(); KSGUI::SkinXmlElement root = doc.RootElement(); if (!root.IsValid()) return bResult; KSGUI::SkinXmlElement strnode = root.FirstChildElement(KSGUI::skinstrresbase::GetResKeyName()); if (!strnode.IsValid()) return bResult; KSGUI::SkinXmlElement node = strnode.FirstChildElement(); while ( node.IsValid() ) { SkinStrResDoc::STRRESITEMINFO itemInfo; node.Name(itemInfo.strIDName); node.GetValue(KSGUI::skinstrresbase::GetValueAttName(), itemInfo.strValue); m_vtItemList.push_back(itemInfo); node = node.NextSiblingElement(); } bResult = TRUE; return bResult; } BOOL SaveResDoc(KSGUI::SkinXmlDocument& doc) { BOOL bResult = FALSE; KSGUI::SkinXmlElement root = doc.RootElement(); if (!root.IsValid()) return bResult; KSGUI::SkinXmlElement strnode = root.FirstChildElement(KSGUI::skinstrresbase::GetResKeyName()); if (strnode.IsValid()) { root.RemoveElement(strnode); } strnode = root.AppendElement(KSGUI::skinstrresbase::GetResKeyName()); for (size_t i = 0; i < m_vtItemList.size(); i++) { KSGUI::SkinXmlElement node = strnode.AppendElement(m_vtItemList[i].strIDName); node.SetValue(skinstrresbase::GetValueAttName(), m_vtItemList[i].strValue); } bResult = TRUE; return bResult; } ////////////////////////////////////////////////////////////////////////// std::vector<SkinStrResDoc::STRRESITEMINFO>& GetStrTableList() { m_vtItemList; } public: std::vector<SkinStrResDoc::STRRESITEMINFO> m_vtItemList; };
[ [ [ 1, 118 ] ] ]
57de44697d54a3237ca19c9355e6e80796ffeee8
9ad9345e116ead00be7b3bd147a0f43144a2e402
/Integration_WAH_&_Extraction/SMDataExtraction/Algorithm/C45TreeNominal.h
cf5735b4bbc94dfc65d5890791dcc6ac5713beb0
[]
no_license
asankaf/scalable-data-mining-framework
e46999670a2317ee8d7814a4bd21f62d8f9f5c8f
811fddd97f52a203fdacd14c5753c3923d3a6498
refs/heads/master
2020-04-02T08:14:39.589079
2010-07-18T16:44:56
2010-07-18T16:44:56
33,870,353
0
0
null
null
null
null
UTF-8
C++
false
false
2,622
h
#pragma once #include "classifier.h" #include "modelselection.h" #include "classifiertree.h" #include "ewah.h" #include "boost/dynamic_bitset.hpp" #include "WAHStructure.h" #include "smalgorithmexceptions.h" using namespace CompressedStructure; /************************************************************************ * Class :C45TreeNominal * Author :Amila De Silva * Subj : * Class for generating a pruned or unpruned C4.5 decision tree. * * Version: 1 ************************************************************************/ class C45TreeNominal : public Classifier { public: /*** * Constructor */ _declspec(dllexport) C45TreeNominal(void); /*** * Destructor */ _declspec(dllexport) virtual ~C45TreeNominal(void); /** * Generates a C45 classifier. Method overridden from Classifier. * * _data set of instances serving as training data */ _declspec(dllexport) virtual void buildClassifier(WrapDataSource * _data) throw (invalid_parameter_exception); /*** * Gets the string representation of the tree* */ _declspec(dllexport) string toString(); /*** * Gets the graph of the tree* */ _declspec(dllexport) string toGraph(); /** Public Getters and Setters*/ /*** * Returns the existence bitmap for the current tree. */ BitStreamInfo * Existence_map() const { return m_existence_map; } /*** * Sets the existence bitmap for the current tree. */ void Existence_map(BitStreamInfo * val) { m_existence_map = val; } /*** * Returns the class index to be used. */ int ClassIndex() const { return m_classIndex; } /*** * Sets the class index to be used. */ void ClassIndex(int val) { m_classIndex = val; } private: /** The decision tree */ ClassifierTree * m_root; /** Unpruned tree */ boolean m_unpruned; /** Collapse tree */ boolean m_collapseTree; /** Confidence level */ float m_CF; /** Minimum number of instances */ int m_minNumObj; /** Use MDL correction? */ bool m_useMDLcorrection; /** Binary splits on nominal attributes? */ bool m_binarySplits; /** Subtree raising to be performed? */ bool m_subtreeRaising; /** Cleanup after the tree has been built. */ bool m_noCleanup; /** Stores the generated data source*/ DataSource * m_source; /** Existence bitmap for the current source*/ BitStreamInfo * m_existence_map; /** Class index of the Data source*/ int m_classIndex; /*** * Creates a dummy existence bitmap */ void CreateExistenceBitMap() throw(empty_data_source_exception); };
[ "jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1" ]
[ [ [ 1, 114 ] ] ]
f87d9f3b4fd7578bcd9d4bb5a451555b1545b732
d609fb08e21c8583e5ad1453df04a70573fdd531
/trunk/DiskMonitor/TimeTrace.h
1aa841bb473f465c1b2dc599ade258443c899bff
[]
no_license
svn2github/openxp
d68b991301eaddb7582b8a5efd30bc40e87f2ac3
56db08136bcf6be6c4f199f4ac2a0850cd9c7327
refs/heads/master
2021-01-19T10:29:42.455818
2011-09-17T10:27:15
2011-09-17T10:27:15
21,675,919
0
1
null
null
null
null
GB18030
C++
false
false
2,989
h
#ifndef __TIMETRACE__H__ #define __TIMETRACE__H__ #pragma once #include <time.h> #include <fstream> #ifdef _WINDOWS //็ช—ๅฃ้กน็›ฎ #include <Shlwapi.h> #else //ๆŽงๅˆถๅฐ้กน็›ฎ #include <atlpath.h> #endif using namespace std; #define MAX_HTML_BUFFER 1024 enum enHTML { HTML_COLOR_NORMAL=0, //ๆญฃๅธธไฟกๆฏ HTML_COLOR_ERROR, //้”™่ฏฏไฟกๆฏ HTML_COLOR_WARNING, //่ญฆๅ‘Šไฟกๆฏ }; static TCHAR g_szHTMLSavePath[MAX_HTML_BUFFER] = {0}; static void ClearLog() { if (PathFileExists("trace.log")) DeleteFile("trace.log"); if (PathFileExists("trace.htm")) DeleteFile("trace.htm"); } static void HTrace(LPCTSTR lpsz,...) { #ifdef _DEBUG time_t curtime = time(0); tm tim = *localtime(&curtime); int day,mon,year,hour,min,sec; sec = tim.tm_sec; min = tim.tm_min; hour = tim.tm_hour; day = tim.tm_mday; mon = tim.tm_mon+1; year = tim.tm_year+1900; #define BUFFER_MAX_LOG 2048 va_list arglist; TCHAR szTrace[BUFFER_MAX_LOG] = {0}; size_t nTimeLength = 0; sprintf(szTrace,"[%.4d-%.2d-%.2d %.2d:%.2d:%.2d]๏ผš",year,mon,day,hour,min,sec); nTimeLength = strlen(szTrace); va_start(arglist, lpsz); _vsnprintf(szTrace+nTimeLength,BUFFER_MAX_LOG-nTimeLength-1,lpsz,arglist); #ifdef _CONSOLE printf(szTrace); printf("\n") #else TRACE(szTrace); TRACE("\n"); #endif ofstream outFile("trace.log",ios::app); outFile << szTrace; outFile << "\r\n"; outFile.flush(); outFile.close(); #endif } static void HTraceHtml(enHTML enType,LPCTSTR lpsz,...) { //#ifdef _DEBUG time_t curtime = time(0); tm tim = *localtime(&curtime); int day,mon,year,hour,min,sec; sec = tim.tm_sec; min = tim.tm_min; hour = tim.tm_hour; day = tim.tm_mday; mon = tim.tm_mon+1; year = tim.tm_year+1900; #define BUFFER_MAX_LOG 2048 va_list arglist; TCHAR szTrace[BUFFER_MAX_LOG] = {0}; TCHAR szFileName[BUFFER_MAX_LOG] = {0}; size_t nTimeLength = 0; sprintf(szTrace,"[%.4d-%.2d-%.2d %.2d:%.2d:%.2d]๏ผš",year,mon,day,hour,min,sec); sprintf(szFileName,".\\%.4d-%.2d-%.2d",year,mon,day); strcat(szFileName,".htm"); switch(enType) { case HTML_COLOR_NORMAL: { strcat(szTrace,"<font color=#000000>"); break; } case HTML_COLOR_ERROR: { strcat(szTrace,"<font color=#ff0000>"); break; } case HTML_COLOR_WARNING: { strcat(szTrace,"<font color=#0000ff>"); break; } default: break; } nTimeLength = strlen(szTrace); va_start(arglist, lpsz); _vsnprintf(szTrace+nTimeLength,BUFFER_MAX_LOG-nTimeLength-1,lpsz,arglist); strcat(szTrace,"</font><br>"); #ifdef _CONSOLE printf(szTrace); printf("\n") #else TRACE(szTrace); TRACE("\n"); #endif ofstream outFile(szFileName,ios::app); outFile << szTrace; outFile.flush(); outFile.close(); //#endif } #ifdef _DEBUG #define HTRACE HTrace #define HTRACEHTML HTraceHtml #else #define HTRACE #define HTRACEHTML #endif #endif
[ "[email protected]@f92b348d-55a1-4afa-8193-148a6675784b" ]
[ [ [ 1, 143 ] ] ]
dd07329a912a660bcd5667a42f24724c0e08c852
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/GUIComboBox.cpp
862b950f1504b53d491818a450ddee9145ed8762
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
3,835
cpp
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: GUIComboBox.cpp Version: 0.01 --------------------------------------------------------------------------- */ #include "PrecompiledHeaders.h" #include "GUIComboBox.h" #include "GUIFont.h" #include "GUIManager.h" #include "GUIWindow.h" #include "ScreenOverlay.h" namespace nGENE { GUIComboBox::GUIComboBox(): m_bOpened(false) { m_VerticalScrollbar.setVisible(false); } //---------------------------------------------------------------------- GUIComboBox::~GUIComboBox() { } //---------------------------------------------------------------------- void GUIComboBox::render(ScreenOverlay* _overlay, Vector2& _position) { Colour clr = m_Colour; clr.setAlpha(clr.getAlpha() * m_fOpacity); _overlay->render(_position, m_fWidth, 28.0f, SRect<Real>(0.0f, 0.0625f, 0.0625, 0.125f), m_Colour); if(m_vSelectedItems.size()) { clr = Colour::COLOUR_BLACK; clr.setAlpha(clr.getAlpha() * m_fOpacity); GUIManager::getSingleton().getFont()->drawText(m_vSelectedItems[0]->text, _position.x, _position.y, 24, clr); } if(m_bOpened) { m_fHeight -= 28.0; Vector2 pos = _position; pos.y += 28.0f; GUIListBox::render(_overlay, pos); m_fHeight += 28.0; } } //---------------------------------------------------------------------- void GUIComboBox::mouseClick(uint _x, uint _y) { if(m_bOpened) { GUIListBox::mouseClick(_x, _y - 28.0f); if(_x < getAbsolutePosition().x + m_fWidth) { m_bOpened = false; m_VerticalScrollbar.setVisible(false); } } else { if(_x < getAbsolutePosition().x + m_fWidth && _y < getAbsolutePosition().y + 28.0f) { m_bOpened = true; m_VerticalScrollbar.setVisible(true); } } } //---------------------------------------------------------------------- void GUIComboBox::loosingFocus() { GUIListBox::loosingFocus(); m_bOpened = false; m_VerticalScrollbar.setVisible(false); } //---------------------------------------------------------------------- void GUIComboBox::setHeight(Real _height) { GUIListBox::setHeight(_height); m_VerticalScrollbar.setHeight(m_fHeight - 28.0f); } //---------------------------------------------------------------------- void GUIComboBox::setPosition(const Vector2& _position) { GUIListBox::setPosition(_position); m_VerticalScrollbar.setPosition(m_VerticalScrollbar.getPosition().x, m_VerticalScrollbar.getPosition().y + 28.0f); } //---------------------------------------------------------------------- void GUIComboBox::setPosition(Real _x, Real _y) { GUIListBox::setPosition(_x, _y); m_VerticalScrollbar.setPosition(m_VerticalScrollbar.getPosition().x, m_VerticalScrollbar.getPosition().y + 28.0f); } //---------------------------------------------------------------------- void GUIComboBox::keyboardDown(const KeyboardEvent& _evt) { if(m_bOpened) { GUIListBox::keyboardDown(_evt); if(_evt.isKeyPressed(KC_RETURN)) { m_bOpened = false; m_VerticalScrollbar.setVisible(false); } } else { if(m_vSelectedIndices.size()) { int i = m_vSelectedIndices[0]; if(_evt.isKeyPressed(KC_DOWN)) ++i; else if(_evt.isKeyPressed(KC_UP)) --i; Maths::clamp_roll <int>(i, 0, m_vItems.size() - 1); selectItem(i); } else { if(m_vItems.size()) selectItem(0); } } } //---------------------------------------------------------------------- }
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 148 ] ] ]
29c6fde43e7636566f29c290a52103ed1c3bee82
299a1b0fca9e1de3858a5ebeaf63be6dc3a02b48
/tags/ic2005demo/dingus/dingus/resource/CubeTextureBundle.cpp
1fd62852a6a642890bffb2e609255b5a35928d27
[]
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
3,934
cpp
// -------------------------------------------------------------------------- // Dingus project - a collection of subsystems for game/graphics applications // -------------------------------------------------------------------------- #include "stdafx.h" #include "CubeTextureBundle.h" #include "../utils/Errors.h" #include "../kernel/D3DDevice.h" using namespace dingus; CCubeTextureBundle::CCubeTextureBundle() { addExtension( ".dds" ); addExtension( ".png" ); addExtension( ".jpg" ); addExtension( ".tga" ); addExtension( ".bmp" ); }; IDirect3DCubeTexture9* CCubeTextureBundle::loadTexture( const CResourceId& id, const CResourceId& fullName ) const { IDirect3DCubeTexture9* texture = NULL; // try to load from native cube texture format HRESULT hres = D3DXCreateCubeTextureFromFileEx( &CD3DDevice::getInstance().getDevice(), fullName.getUniqueName().c_str(), D3DX_DEFAULT, 0, // mipLevels 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, &texture ); if( !SUCCEEDED( hres ) ) { // now, if we didn't load, and last thing before file extension is // "_px", then load "_px", "_nx", "_py", "_ny", "_pz" and "_nz" into // corresponding faces. int dotIdx = fullName.getUniqueName().find_last_of( '.' ); if( dotIdx >= 3 ) { // fit "_px" std::string beforeExt = fullName.getUniqueName().substr( dotIdx-3, 3 ); if( beforeExt == std::string("_px") ) { D3DXIMAGE_INFO info; hres = D3DXGetImageInfoFromFile( fullName.getUniqueName().c_str(), &info ); if( !SUCCEEDED(hres) ) goto _fail; hres = D3DXCreateCubeTexture( &CD3DDevice::getInstance().getDevice(), info.Width, 0, 0, info.Format, D3DPOOL_MANAGED, &texture ); if( !SUCCEEDED(hres) ) goto _fail; static const char* CHAR1 = "pnpnpn"; static const char* CHAR2 = "xxyyzz"; std::string fileName = fullName.getUniqueName(); int charIdx = dotIdx-2; for( int i = 0; i < 6; ++i ) { IDirect3DSurface9* surface = NULL; hres = texture->GetCubeMapSurface( (D3DCUBEMAP_FACES)i, 0, &surface ); if( !SUCCEEDED(hres) ) goto _fail; fileName[charIdx] = CHAR1[i]; fileName[charIdx+1] = CHAR2[i]; hres = D3DXLoadSurfaceFromFile( surface, NULL, NULL, fileName.c_str(), NULL, D3DX_DEFAULT, 0, NULL ); surface->Release(); // don't fail, just the cubemap faces will contain garbage //if( !SUCCEEDED(hres) ) goto _fail; } // gen mipmaps D3DXFilterTexture( texture, NULL, 0, D3DX_DEFAULT ); goto _ok; } } _fail: std::string msg = "failed to load cubemap '" + fullName.getUniqueName() + "'"; CConsole::CON_ERROR.write(msg); THROW_DXERROR( hres, msg ); } _ok: assert( texture ); CONSOLE.write( "cubemap loaded '" + id.getUniqueName() + "'" ); return texture; } CD3DCubeTexture* CCubeTextureBundle::loadResourceById( const CResourceId& id, const CResourceId& fullName ) { IDirect3DCubeTexture9* texture = loadTexture( id, fullName ); if( !texture ) return NULL; return new CD3DCubeTexture( texture ); } void CCubeTextureBundle::createResource() { // reload all objects TResourceMap::iterator it; for( it = mResourceMap.begin(); it != mResourceMap.end(); ++it ) { CD3DCubeTexture& res = *it->second; assert( res.isNull() ); CD3DCubeTexture* n = tryLoadResourceById( it->first ); assert( n ); res.setObject( n->getObject() ); delete n; assert( !res.isNull() ); } } void CCubeTextureBundle::activateResource() { } void CCubeTextureBundle::passivateResource() { } void CCubeTextureBundle::deleteResource() { // unload all objects TResourceMap::iterator it; for( it = mResourceMap.begin(); it != mResourceMap.end(); ++it ) { CD3DCubeTexture& res = *it->second; assert( !res.isNull() ); res.getObject()->Release(); res.setObject( NULL ); } }
[ "nearaz@73827abb-88f4-0310-91e6-a2b8c1a3e93d" ]
[ [ [ 1, 130 ] ] ]
2d377f42140b34e4dceca40a8dba2df73e337222
9773c3304eecc308671bcfa16b5390c81ef3b23a
/MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/InfoCtrl.h
322bad652c40538915e6e1b53517db61174464a9
[]
no_license
15831944/AiPI-1
2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4
9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8
refs/heads/master
2021-12-02T20:34:03.136125
2011-10-27T00:07:54
2011-10-27T00:07:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,554
h
#if !defined(AFX_INFOCTRL_H__52FA5733_7D5E_4752_B2CF_BA3BC8FBE5DD__INCLUDED_) #define AFX_INFOCTRL_H__52FA5733_7D5E_4752_B2CF_BA3BC8FBE5DD__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // InfoCtrl.h : header file // #include "OXSizeCtrlBar.h" #include "OXEdit.h" ///////////////////////////////////////////////////////////////////////////// // CInfoCtrl window class CInfoCtrl : public COXSizeControlBar { DECLARE_DYNAMIC(CInfoCtrl); public: BOOL Create(CWnd * pParentWnd, const CString& sTitle = _T("InfoCtrl"), const UINT nID=IDC_STATIC_EX); // Construction CInfoCtrl(); // Attributes public: COXEdit m_staticCtrl; COLORREF m_clrBack; COLORREF m_clrText; CFont m_font; // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CInfoCtrl) //}}AFX_VIRTUAL // Implementation public: virtual ~CInfoCtrl(); // Generated message map functions protected: virtual void OnSizedOrDocked(int cx, int cy, BOOL bFloating, int flags); protected: //{{AFX_MSG(CInfoCtrl) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnContextMenu(CWnd* pWnd, CPoint point); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_INFOCTRL_H__52FA5733_7D5E_4752_B2CF_BA3BC8FBE5DD__INCLUDED_)
[ [ [ 1, 61 ] ] ]
9c048c0a1c039409ace8bb3d158c68ffcb32625a
c86338cfb9a65230aa7773639eb8f0a3ce9d34fd
/KernelDefs.h
ac779e4879c2be3cd95a0f77d7f51266bc5f591a
[]
no_license
jonike/mnrt
2319fb48d544d58984d40d63dc0b349ffcbfd1dd
99b41c3deb75aad52afd0c315635f1ca9b9923ec
refs/heads/master
2021-08-24T05:52:41.056070
2010-12-03T18:31:24
2010-12-03T18:31:24
113,554,148
0
0
null
null
null
null
UTF-8
C++
false
false
41,041
h
//////////////////////////////////////////////////////////////////////////////////////////////////// // MNRT License //////////////////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2010 Mathias Neumann, www.maneumann.com. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name Mathias Neumann, nor the names of 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. //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// /// \file MNRT\KernelDefs.h /// /// \brief Declares appropriate structures to pass data to CUDA kernels. /// \author Mathias Neumann /// \date 31.01.2010 /// \ingroup globalillum //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// /// \defgroup globalillum GPU-based Global Illumination /// /// \brief GPU-based components of MNRT for global illumination. //////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef __MN_KERNELDEFS_H__ #define __MN_KERNELDEFS_H__ #pragma once #include <cuda_runtime.h> // for cudaArray #include <vector_types.h> #include <vector> #include <string> class BasicScene; /// \brief Unsigned 32-bit integer type. /// /// It is important that this is 32-bit wide as some operations, e.g. CUDPP primitives, do /// not support wider types. typedef unsigned __int32 uint; /// Unsigned char type. typedef unsigned char uchar; /// Maximum number of materials allowed. The number is restricted to ensure constant structure size for /// GPU's constant memory. #define MAX_MATERIALS 64 /// Number of texture types. It is restricted by material flag array. See MaterialProperties. #define NUM_TEX_TYPES 2 //////////////////////////////////////////////////////////////////////////////////////////////////// /// \enum LightType /// /// \brief Light types supported by MNRT. /// /// As MNRT uses a GPU-based implementation, support for area light sources with custom /// shapes to define the area is not available. This is basically a simplification to /// avoid searching for parallel techniques to support custom shapes. /// /// \author Mathias Neumann /// \date 31.01.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// enum LightType { /// Point light source. Emitting uniformly in all directions of the surrounding sphere. Light_Point = 0, /// Directional light source. Placed infinitely far away from the scene and emits in a single direction. Light_Directional = 1, /// Area light source with disc as area. The disc is defined using the light's position as center, /// the light's direction and a radius. Light_AreaDisc = 2, /// Area light source with rectangle as area. The rectangle is defined using the light's position /// as one rectangle vertex and two edge vectors for the adjacent edges. Light_AreaRect = 3 }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// \enum TextureType /// /// \brief Texture types supported by MNRT. /// /// \author Mathias Neumann /// \date 03.04.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// enum TextureType { /// Diffuse material texture. Can be used instead of the material's diffuse color. Tex_Diffuse = 0, /// Bump map (height map) to provide more geometric detail by adapting the surface normal /// according to the bump map. Currently this texture type support is not that sophisticated /// as ray differentials are not tracked in MNRT. These would be required to determine correct /// offsets for fetching adjacent texels from the bump map. Tex_Bump = 1 }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// \struct TextureHost /// /// \brief Temporary structure for texture information read into host memory. /// /// Used to transfer textures into device memory. /// /// \author Mathias Neumann /// \date 03.04.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// struct TextureHost { /// Host memory texture data. \c float array for bump maps and \c uchar4 array (RGBA) for diffuse textures. void* h_texture; /// Two-dimensional size (width, height). uint2 size; }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// \struct ShadingPoints /// /// \brief Structure to hold the shading points determined during a ray tracing pass. /// /// The ray \em tracing kernel fills this structure with intersection information that /// describes the found hits for rays traced. Not all rays have to hit something. Therefore /// the #d_idxTris contains -1 for rays that hit nothing. /// /// All data is stored in global GPU memory since we generate the rays on the GPU. A /// structure of arrays (SoA) is used instead of an array of structures (AoS) to allow /// coalesced memory access. Each thread handles a single ray. The global thread index /// \c tid is the index of the shading point to write. Hence the shading point arrays /// have to be at least as large as the RayChunk that is traced. /// /// \note The member functions are only for the C++ CPU side. Device code cannot use them. /// /// \author Mathias Neumann /// \date 31.01.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// struct ShadingPoints { #ifdef __cplusplus public: //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn bool Initialize(uint _maxPoints) /// /// \brief Initializes the shading point structure. /// /// Requests device memory of the given maximum number of shading points. /// /// \author Mathias Neumann /// \date 31.01.2010 /// /// \param _maxPoints The maximum number of shading points to store. /// /// \return \c true if it succeeds, \c false if it fails. //////////////////////////////////////////////////////////////////////////////////////////////////// bool Initialize(uint _maxPoints); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void Clear() /// /// \brief Sets the number of shading points to zero. /// /// \author Mathias Neumann /// \date 31.01.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// void Clear() { numPoints = 0; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void Destroy() /// /// \brief Frees allocated memory. /// /// \author Mathias Neumann /// \date 31.01.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// void Destroy(); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void CompactSrcAddr(uint* d_srcAddr, uint countNew) /// /// \brief Compacts this shading point structure using the given source address array. /// /// This operation assumes that the source addresses were generated before, e.g. using /// ::mncudaGenCompactAddresses(). The latter also returns the required new number of /// shading points. Basically, this was done to allow compacting multiple structures /// using the same source addresses. /// /// \author Mathias Neumann /// \date April 2010 /// \see ::mncudaGenCompactAddresses(), PhotonData::CompactSrcAddr() /// /// \param [in] d_srcAddr The source addresses (device memory). \a d_srcAddr[i] defines at /// which original index the new value for the i-th shading point /// can be found. /// \param countNew The new number of shading points. //////////////////////////////////////////////////////////////////////////////////////////////////// void CompactSrcAddr(uint* d_srcAddr, uint countNew); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void Add(const ShadingPoints& other) /// /// \brief Adds other shading point list to this list. /// /// \author Mathias Neumann /// \date October 2010 /// /// \param other Shading points to add. //////////////////////////////////////////////////////////////////////////////////////////////////// void Add(const ShadingPoints& other); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn uint Merge(const ShadingPoints& other, uint* d_isValid) /// /// \brief Merges given shading point data into this shading point data. /// /// The merge process is controlled using the given \a d_isValid "binary" array. If /// \a d_isValid[i] = 1, then the i-th element of \a other is merged into this object. /// Else, if \a d_isValid[i] = 0, the i-th element of \a other is ignored. /// /// \author Mathias Neumann /// \date April 2010 /// \see ::mncudaGenCompactAddresses(), ::mncudaSetFromAddress() /// /// \param other Shading points to merge into this object. /// \param [in] d_isValid "Binary" device array that contains as many elements as \a other /// has shading points. Element values have to be 0 and 1. /// /// \return Returns number of merged points. //////////////////////////////////////////////////////////////////////////////////////////////////// uint Merge(const ShadingPoints& other, uint* d_isValid); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void SetFrom(const ShadingPoints& other, uint* d_srcAddr, uint numSrcAddr) /// /// \brief Sets this shading points based on other shading points. /// /// The process of copying the \a other shading points into this object is guided by /// the source addresses \a d_srcAddr in the following way: /// /// \code d_pixels[i] = other.d_pixels[d_srcAddr[i]]; // Same for other members \endcode /// /// \author Mathias Neumann /// \date July 2010 /// \see ::mncudaSetFromAddress(), CompactSrcAddr() /// /// \param other Shading points to set this object from. /// \param [in] d_srcAddr The source addresses (device memory). \a d_srcAddr[i] defines at /// which original index the new value for the i-th shading point /// can be found. /// \param numSrcAddr Number of source address. This is also the new number of shading /// points in this object. //////////////////////////////////////////////////////////////////////////////////////////////////// void SetFrom(const ShadingPoints& other, uint* d_srcAddr, uint numSrcAddr); public: #endif // __cplusplus /// Number of shading points stored. uint numPoints; /// Maximum number of shading points that can be stored. uint maxPoints; /// Index of the corresponding pixel (device array). uint* d_pixels; /// Index of the intersected triangle or -1, if no intersection (device array). int* d_idxTris; /// Point of intersection coordinates (device array). float4* d_ptInter; /// Geometric normal at intersection point (device array). float4* d_normalsG; /// Shading normal at intersection point (device array). float4* d_normalsS; /// Barycentric hit coordinates (device array). float2* d_baryHit; }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// \struct LightData /// /// \brief Holds information about the primary light source for use in kernels. /// /// This structure is loaded into GPU's constant memory. Therefore no host/device memory /// pointers are allowed. Currently I only allow one single light source for simplicity. /// Extension to more light sources would be possible by allowing a maximum number of /// light sources, just as with the MaterialProperties structure. /// /// \author Mathias Neumann /// \date 31.01.2010 /// \see LightType, BasicLight //////////////////////////////////////////////////////////////////////////////////////////////////// struct LightData { /// Type of light source. LightType type; /// Light source position. Invalid for directional light sources. float3 position; /// Light direction. Invalid for point light sources. float3 direction; /// Emitted radiance of light source. This is the intensity for point lights. float3 L_emit; /// Vector that spans first side of the rectangle for rectangle area lights. float3 areaV1; /// Vector that spans second side of the rectangle for rectangle area lights. float3 areaV2; /// Area light radius for disc area lights. float areaRadius; }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// \struct MaterialProperties /// /// \brief Material properties structure for use in kernels. /// /// This structure represents the material data for CUDA kernels. It is copied into /// GPU's constant memory and therefore has to have a constant size. Hence there is an /// limit (::MAX_MATERIALS) for the total number of materials allowed. /// /// \author Mathias Neumann /// \date 31.01.2010 /// \see BasicMaterial /// /// \todo Check if area light material flag is correcly used. /// //////////////////////////////////////////////////////////////////////////////////////////////////// struct MaterialProperties { /// \brief Texture flags. /// /// Bits as follows: /// \li \c x: Diffuse texture index. -1 if no texture. /// \li \c y: Bump map texture index. -1 if no texture. /// \li \c w0: Area light flag (bit 0). Set to 1 for an area light material. char4 flags[MAX_MATERIALS]; /// Diffuse material color. float3 clrDiff[MAX_MATERIALS]; /// Specular material color. float3 clrSpec[MAX_MATERIALS]; /// Specular exponent (shininess). float specExp[MAX_MATERIALS]; /// Transparency alpha (opaque = 1, completely transparent = 0). float transAlpha[MAX_MATERIALS]; /// Index of refraction (1 = vacuum; 1.333 = water; 1.5-1.6 = glass;...). float indexRefrac[MAX_MATERIALS]; }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// \class MaterialData /// /// \brief Manages material data and loads texture images. /// /// Creates the MaterialProperties structure from a given BasicScene and loads all /// diffuse and bump map textures from specified files. Textures are internally stored /// as \c cudaArray objects to benefit from improved cache performance for 2D locality. /// /// \author Mathias Neumann /// \date March 2010 /// \see MaterialProperties /// /// \todo Hide public members as this is no longer a struct for kernels. //////////////////////////////////////////////////////////////////////////////////////////////////// class MaterialData { public: //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn bool Initialize(BasicScene* pScene) /// /// \brief Initialization from BasicScene object. /// /// \author Mathias Neumann /// \date March 2010 /// /// \param [in] pScene Scene to load the materials for. /// /// \return \c true if it succeeds, \c false if it fails. //////////////////////////////////////////////////////////////////////////////////////////////////// bool Initialize(BasicScene* pScene); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void Destroy() /// /// \brief Releases requested memory. /// /// \author Mathias Neumann /// \date March 2010 //////////////////////////////////////////////////////////////////////////////////////////////////// void Destroy(); public: //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn static void* LoadImageFromFile(const std::string& strImage, bool isBumpMap, /// uint2* outImgSize) /// /// \brief Loads image from file using DevIL. /// /// This method uses the Developer's Image Library (DevIL) to load and convert images /// from lots of file formats. Check http://openil.sourceforge.net/ for more information /// about DevIL. /// /// \author Mathias Neumann /// \date 03.04.2010 /// /// \param strImage The image file path. /// \param isBumpMap \c true if is a bump map texture. /// \param [out] outImgSize In this parameter the image size is stored. /// /// \return Returns the loaded image in host memory. This is an \c float array for bump maps and /// a \c uchar4 array (RGBA) for diffuse textures. Might return \c NULL in case loading /// failed. //////////////////////////////////////////////////////////////////////////////////////////////////// static void* LoadImageFromFile(const std::string& strImage, bool isBumpMap, uint2* outImgSize); private: void LoadTextures(BasicScene* pScene, uint texType, std::vector<TextureHost>* outHostTextures); public: /// Number of materials. Maximum is ::MAX_MATERIALS. uint numMaterials; /// Material properties for GPU's constant memory. MaterialProperties matProps; /// Textures as \c cudaArray objects. One vector for each texture type. std::vector<cudaArray*> vecTexArrays[NUM_TEX_TYPES]; }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// \struct TriangleData /// /// \brief Triangle data structure for kernel use. /// /// Holds triangle data from a BasicScene in form of a structure of arrays for /// coalescing. \c float4 is used instead of \c float3 to ensure alignment and improve /// performance. /// /// \note It seems that the texture fetcher can only fetch from a texture once per thread /// without using too many registers (observed on a GTS 250, CUDA 2.3). Also there seems /// to be a limit of fetches that can be done without using too many registers and having /// the performance dropping. Also note that we use linear device memory instead of cuda /// arrays since cuda arrays can only hold up to 8k elements when one dimensional, while /// linear device memory can have up to 2^27 elements (observed on a GTS 250). /// /// \todo Add way to handle dynamic geometry. /// /// \author Mathias Neumann /// \date 31.01.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// struct TriangleData { #ifdef __cplusplus public: //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn bool Initialize(BasicScene* pScene) /// /// \brief Initializes this object from a given scene. /// /// Requests all required memory so that all triangle information can be stored in /// global memory. /// /// \author Mathias Neumann /// \date 31.01.2010 /// /// \param [in] pScene The scene. /// /// \return \c true if it succeeds, \c false if it fails. //////////////////////////////////////////////////////////////////////////////////////////////////// bool Initialize(BasicScene* pScene); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void Destroy() /// /// \brief Releases requested memory. /// /// \author Mathias Neumann /// \date 31.01.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// void Destroy(); private: // Allocates auxiliary memory (e.g. for bounding boxes). bool InitAuxillary(); public: #endif // __cplusplus /// Number of triangles. uint numTris; /// Scene AABB minimum. Stored for kd-tree initial node. float3 aabbMin; /// Scene AABB maximum. Stored for kd-tree initial node. float3 aabbMax; /// Vertices, 3 per triangle (device memory). float4 *d_verts[3]; /// Normals, 3 per triangle (device memory). float4* d_normals[3]; /// Material indices, 1 per triangle (device memory). uint* d_idxMaterial; /// Texture coordinates (UV), 3 per triangle (device memory). float2* d_texCoords[3]; }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// \struct PhotonData /// /// \brief GPU-based photon array representation. /// /// Used to represent photons on the GPU-side, e.g. for photon spawning. Furthermore this /// structure is used for the final photon array. The photons are stored as structure of /// arrays to improve memory performance. \c float4 is used for both position and power /// to achieve some compression and to reduce the number of texture fetches within kernels. /// /// The structure has a maximum for storable photons, so that we can only work on a limited /// number of photons within one kernel. This is unproblematic in most cases: Usually one /// photon is assigned to one thread, and the thread number cannot change during kernel /// execution. /// /// \author Mathias Neumann /// \date 07.04.2010 /// \see PhotonMap /// /// \todo Increase compression, see e.g. \ref lit_jensen "[Jensen 2001]". //////////////////////////////////////////////////////////////////////////////////////////////////// struct PhotonData { #ifdef __cplusplus public: //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn bool Initialize(uint _maxPhotons) /// /// \brief Initializes this object by requesting device memory. /// /// \author Mathias Neumann /// \date 07.04.2010 /// /// \param _maxPhotons The maximum number of photons that should be stored. /// /// \return \c true if it succeeds, \c false if it fails. //////////////////////////////////////////////////////////////////////////////////////////////////// bool Initialize(uint _maxPhotons); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void Clear() /// /// \author Mathias Neumann /// \date 07.04.2010 /// /// \brief Clears this data structure by resetting the photon count to zero. //////////////////////////////////////////////////////////////////////////////////////////////////// void Clear(); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void Destroy() /// /// \author Mathias Neumann /// \date 07.04.2010 /// /// \brief Releases device memory. //////////////////////////////////////////////////////////////////////////////////////////////////// void Destroy(); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void CompactSrcAddr(uint* d_srcAddr, uint countNew) /// /// \brief Compacts this photon structure using the given source address array. /// /// See ShadingPoints::CompactSrcAddr() for more information. /// /// \author Mathias Neumann /// \date 07.04.2010 /// \see ShadingPoints::CompactSrcAddr(), ::mncudaGenCompactAddresses() /// /// \param [in] d_srcAddr The source addresses (device memory). \a d_srcAddr[i] defines at /// which original index the new value for the i-th element /// can be found. /// \param countNew The new number of photons. //////////////////////////////////////////////////////////////////////////////////////////////////// void CompactSrcAddr(uint* d_srcAddr, uint countNew); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn uint Merge(const PhotonData& other, uint* d_isValid) /// /// \brief Merges given photon data into this photon data. /// /// The merge process is controlled using the given \a d_isValid "binary" array. If /// \a d_isValid[i] = 1, then the i-th element of \a other is merged into this object. /// Else, if \a d_isValid[i] = 0, the i-th element of \a other is ignored. /// /// \author Mathias Neumann /// \date July 2010 /// \see ShadingPoints::Merge(), ::mncudaGenCompactAddresses() /// /// \param other Photons to merge into this object. /// \param [in] d_isValid "Binary" device array that contains as many elements as \a other /// has photons. Element values have to be 0 and 1. /// /// \return Returns number of merged photons. //////////////////////////////////////////////////////////////////////////////////////////////////// uint Merge(const PhotonData& other, uint* d_isValid); public: #endif // __cplusplus /// Number of photons. uint numPhotons; /// Maximum number of photons. uint maxPhotons; /// \brief 3D positions of the stored photons and azimuthal angle. /// /// \li \c xyz: Position of photon. /// \li \c w: Azimuthal angle phi (spherical coordinates first angle) of indicent direction (radians). float4* d_positions; /// \brief Transported power (flux) for each photon and polar angle. /// /// \li \c xyz: Power, stored for R, G and B color bands. /// \li \c w: Polar angle theta (spherical coordinates second angle) of indicent direction (radians). float4* d_powers; }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// \struct PairList /// /// \brief Stores pairs of unsigned 32-bit integers and allows sorting them by the first pair /// component. /// /// The sorting by first component can be usefull to organize the pairs in a segmented /// reduction compatible way. Once done, pairs with identical first pair element lie /// contiguously. Hence on all elements with identical first element a reduction can be /// performed by calling ::mncudaSegmentedReduce with first elements as owner array and /// second elements as data array. /// /// \author Mathias Neumann /// \date 15.04.2010 /// \see ::mncudaSegmentedReduce //////////////////////////////////////////////////////////////////////////////////////////////////// struct PairList { #ifdef __cplusplus public: //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn bool Initialize(uint _maxPairs) /// /// \brief Initializes this object by requesting device memory. /// /// \author Mathias Neumann /// \date 15.04.2010 /// /// \param _maxPairs The maximum number of pairs to store. /// /// \return \c true if it succeeds, \c false if it fails. //////////////////////////////////////////////////////////////////////////////////////////////////// bool Initialize(uint _maxPairs); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void Clear() /// /// \brief Resets the pair number to zero. /// /// \author Mathias Neumann /// \date 15.04.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// void Clear() { numPairs = 0; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void Destroy() /// /// \brief Releases device memory. /// /// \author Mathias Neumann /// \date 15.04.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// void Destroy(); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void SortByFirst(uint firstValueMax, uint sortSegmentSize = 0, uint* d_outSrcAddr = NULL) /// /// \brief Sorts the pair list by first element values. /// /// Pass maximum for first value so we can compute the number of least significant bits /// we use for radix sort. /// /// \todo Check why \c cudppSort has problems with sorting arrays starting from /// unaligned addresses. Currently I avoid this by copying the input data into /// temporary buffers before sorting. /// /// \author Mathias Neumann. /// \date 15.04.2010. /// /// \param firstValueMax The first value maximum. Can be used to restrict number of /// significant bits for radix sort. /// \param sortSegmentSize Size of a sort segment. If non-zero, this parameter divides /// sorting into chunks of size \a sortSegmentSize that are /// sorted individually. /// \param [out] d_outSrcAddr If not \c NULL, the source addresses to sort further arrays /// (exaclty as the second element values were sorted) is /// returned. In this case, the array should have #numPairs /// elements. Further sorting can then be done using the /// ::mncudaSetFromAddress() method. //////////////////////////////////////////////////////////////////////////////////////////////////// void SortByFirst(uint firstValueMax, uint sortSegmentSize = 0, uint* d_outSrcAddr = NULL); public: #endif // __cplusplus /// Number of pairs. uint numPairs; /// Maximum number of pairs. uint maxPairs; /// First pair values. uint* d_first; /// Second pair values. uint* d_second; }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// \struct QuadTreeSP /// /// \brief Quadtree used to organize shading points in screen space. For use within kernels. /// /// This is used for adaptive sample seeding using the geometric variation of the quadtree /// nodes. A shading point can be classified using it's pixel coordinate in screen space. /// So we can, on each tree level, find exactly one quadtree node for the shading point. /// Using segmented reduction we can compute the average position, normal and geometric /// variation of a quadtree node center. The geometric variation is given as sum of /// the variations between the averaged node center and all quadtree node shading points. /// /// The quadtree is constructed down to the pixel level where each quadtree node /// represents exactly one screen pixel. Note that this structure does \em not record /// the association between shading points and quadtree nodes. It only provides the frame /// for the tree. /// /// \par Order of Nodes /// Kernels constructing the quad tree should create the following order of nodes: Nodes /// of one tree level are stored contiguously, and all nodes of level i appear before /// all deeper nodes of level i+1. Hence the root node is in element 0 and its children are /// in elements 1-4. The child in 1 is the top-left child, 2 is the top-right child, 3 /// the bottom-left and 4 the bottom-right child. The order of the children of these /// children stays the same, i.e 5-8 will contain the children of element 1, 9-12 those /// of element 2 and so forth. Keeping this order is important as many kernels rely on it. /// /// \author Mathias Neumann /// \date 16.04.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// struct QuadTreeSP { #ifdef __cplusplus public: //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn bool Initialize(uint sizeScreen) /// /// \brief Initialization from given screen size. /// /// Requests required memory to store a quadtree for the given screen size. /// /// \author Mathias Neumann /// \date 16.04.2010 /// /// \param sizeScreen The size of the screen. Has to be power of 2. It is assumed that the /// screen is quadratic, e.g. 512 times 512 pixels. /// /// \return \c true if it succeeds, \c false if it fails. //////////////////////////////////////////////////////////////////////////////////////////////////// bool Initialize(uint sizeScreen); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void Destroy() /// /// \brief Releases all device memory and therefore destroys the quadtree. /// /// \author Mathias Neumann /// \date 16.04.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// void Destroy(); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn uint GetLevel(uint idxNode) const /// /// \brief Gets the level for the given node index. /// /// Avoids storing the level for each node. /// /// \author Mathias Neumann /// \date 16.04.2010 /// /// \param idxNode The node index. /// /// \return The level. Level starts from 0 for root and goes to log(sizeScreen) for leafs. //////////////////////////////////////////////////////////////////////////////////////////////////// uint GetLevel(uint idxNode) const; public: #endif // __cplusplus /// Number of quadtree nodes. uint numNodes; /// Maximum number of nodes. uint maxNodes; /// Number of levels of the constructed tree. uint numLevels; /// Average position for nodes. float4* d_positions; /// Average normal for nodes. Might not always be normalized. float4* d_normals; /// Geometric variation for nodes. Defined as the sum of the geometric variation to all contained shading points. float* d_geoVars; }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// \struct ClusterList /// /// \brief List of clusters for use within kernels. /// /// Keeps track of cluster information, mainly position and normal. Used during adaptive /// sample seeding. For convenience, the arrays have one additional entry that can be /// used for a virtual cluster, e.g. a cluster of unclassified points. It is \e not /// taken into account by all methods of this structure besides Initialize(), which /// allocates one more entry than #maxClusters. /// /// \author Mathias Neumann /// \date 17.04.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// struct ClusterList { #ifdef __cplusplus public: //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn bool Initialize(uint _maxClusters) /// /// \brief Initializes the list by requesting device memory. /// /// \author Mathias Neumann /// \date 17.04.2010 /// /// \param _maxClusters The maximum number of clusters to store. /// /// \return \c true if it succeeds, \c false if it fails. //////////////////////////////////////////////////////////////////////////////////////////////////// bool Initialize(uint _maxClusters); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void Clear() /// /// \brief Resets the clusters number to zero. /// /// \author Mathias Neumann /// \date 17.04.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// void Clear() { numClusters = 0; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void CompactSrcAddr(uint* d_srcAddr, uint countNew) /// /// \brief Compacts this cluster list using the given source address array. /// /// This operation assumes that the source addresses were generated before, e.g. using /// ::mncudaGenCompactAddresses(). The latter also returns the required new number of /// new clusters. Basically, this was done to allow compacting multiple structures /// using the same source addresses. /// /// \author Mathias Neumann /// \date April 2010 /// \see ::mncudaGenCompactAddresses(), PhotonData::CompactSrcAddr() /// /// \param [in] d_srcAddr The source addresses (device memory). \a d_srcAddr[i] defines at /// which original index the new value for the i-th cluster /// can be found. /// \param countNew The new number of clusters. //////////////////////////////////////////////////////////////////////////////////////////////////// void CompactSrcAddr(uint* d_srcAddr, uint countNew); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void Add(const ClusterList& other) /// /// \brief Adds other cluster list to this list. /// /// \author Mathias Neumann. /// \date October 2010. /// /// \param other Clusters to add. //////////////////////////////////////////////////////////////////////////////////////////////////// void Add(const ClusterList& other); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn uint Merge(const ClusterList& other, uint* d_isValid) /// /// \brief Merges given clusters into this cluster list. /// /// The merge process is controlled using the given \a d_isValid "binary" array. If \a /// d_isValid[i] = 1, then the i-th element of \a other is merged into this object. Else, /// if \a d_isValid[i] = 0, the i-th element of \a other is ignored. /// /// \author Mathias Neumann. /// \date April 2010 \see ::mncudaGenCompactAddresses(), ::mncudaSetFromAddress() /// /// \param other Clusters to merge into this object. /// \param [in] d_isValid "Binary" device array that contains as many elements as \a other /// has clusters. Element values have to be 0 and 1. /// /// \return Returns number of merged clusters. //////////////////////////////////////////////////////////////////////////////////////////////////// uint Merge(const ClusterList& other, uint* d_isValid); //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void Destroy() /// /// \brief Releases all device memory and therefore destroys the list. /// /// \author Mathias Neumann /// \date 17.04.2010 //////////////////////////////////////////////////////////////////////////////////////////////////// void Destroy(); public: #endif // __cplusplus /// \brief Number of clusters. /// /// This does not include the virtual cluster at the end of the cluster list. uint numClusters; /// \brief Maximum number of clusters. /// /// This does not include the virtual cluster at the end of the cluster list. uint maxClusters; /// Cluster center positions. float4* d_positions; /// Cluster center normals. float4* d_normals; /// \brief Stores which shading point is used as cluster center (index). /// /// Only valid after final irradiance samples are generated. uint* d_idxShadingPt; /// \brief Maximum geometric variation of all shading points assigned to a cluster (for each cluster). /// /// Stored from generation of last frame. Will be used to classify new frame's shading points /// according to old clusters to retain some of the latter for temporal coherence. Only valid /// after final irradiance samples are generated. float* d_geoVarMax; }; #endif // __MN_KERNELDEFS_H__
[ [ [ 1, 953 ] ] ]
29aecbda949f6ffc5bb74a2495159e8ef82fd0bd
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/dom/deprecated/NamedNodeMapImpl.hpp
a06be573ff3013d277afed63bfa950175d5ecbe2
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
3,135
hpp
#ifndef NamedNodeMapImpl_HEADER_GUARD_ #define NamedNodeMapImpl_HEADER_GUARD_ /* * Copyright 1999-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: NamedNodeMapImpl.hpp,v 1.6 2004/09/08 13:55:43 peiyongz Exp $ */ // // This file is part of the internal implementation of the C++ XML DOM. // It should NOT be included or used directly by application programs. // // Applications should include the file <xercesc/dom/deprecated/DOM.hpp> for the entire // DOM API, or DOM_*.hpp for individual DOM classes, where the class // name is substituded for the *. // #include <xercesc/util/XMemory.hpp> #include "NodeImpl.hpp" XERCES_CPP_NAMESPACE_BEGIN class NodeVector; class DocumentImpl; class NodeImpl; class DEPRECATED_DOM_EXPORT NamedNodeMapImpl: public XMemory { protected: NodeVector *nodes; NodeImpl *ownerNode; // the node this map belongs to bool readOnly; int refCount; static int gLiveNamedNodeMaps; static int gTotalNamedNodeMaps; friend class DOM_NamedNodeMap; friend class DomMemDebug; friend class ElementImpl; friend class DocumentImpl; virtual void cloneContent(NamedNodeMapImpl *srcmap); public: NamedNodeMapImpl(NodeImpl *ownerNode); virtual ~NamedNodeMapImpl(); virtual NamedNodeMapImpl *cloneMap(NodeImpl *ownerNode); static void addRef(NamedNodeMapImpl *); virtual int findNamePoint(const DOMString &name); virtual unsigned int getLength(); virtual NodeImpl *getNamedItem(const DOMString &name); virtual NodeImpl *item(unsigned int index); virtual void removeAll(); virtual NodeImpl *removeNamedItem(const DOMString &name); static void removeRef(NamedNodeMapImpl *); virtual NodeImpl *setNamedItem(NodeImpl *arg); virtual void setReadOnly(bool readOnly, bool deep); //Introduced in DOM Level 2 virtual int findNamePoint(const DOMString &namespaceURI, const DOMString &localName); virtual NodeImpl *getNamedItemNS(const DOMString &namespaceURI, const DOMString &localName); virtual NodeImpl *setNamedItemNS(NodeImpl *arg); virtual NodeImpl *removeNamedItemNS(const DOMString &namespaceURI, const DOMString &localName); virtual void setOwnerDocument(DocumentImpl *doc); }; XERCES_CPP_NAMESPACE_END #endif
[ [ [ 1, 91 ] ] ]
13718114793b3c4ccfcc05c16f66c6939b43680a
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Shared/symbian-r7/Thread.cpp
4e6678a1d43366617b08884be34f72bb1266aef3
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,578
cpp
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "../symbian-r6/Thread.cpp"
[ [ [ 1, 13 ] ] ]
51465c079364f4dc694525722de0fed67354395c
804e416433c8025d08829a08b5e79fe9443b9889
/src/argss/classes/atable.h
4d29d6284103519621e9a9f01672f1fbde2fe815
[ "BSD-2-Clause" ]
permissive
cstrahan/argss
e77de08db335d809a482463c761fb8d614e11ba4
cc595bd9a1e4a2c079ea181ff26bdd58d9e65ace
refs/heads/master
2020-05-20T05:30:48.876372
2010-10-03T23:21:59
2010-10-03T23:21:59
1,682,890
1
0
null
null
null
null
UTF-8
C++
false
false
3,109
h
///////////////////////////////////////////////////////////////////////////// // ARGSS - Copyright (c) 2009 - 2010, Alejandro Marzini (vgvgf) // 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. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ///////////////////////////////////////////////////////////////////////////// #ifndef _ARGSS_TABLE_H_ #define _ARGSS_TABLE_H_ /////////////////////////////////////////////////////////// // Headers /////////////////////////////////////////////////////////// #include "aruby.h" namespace ARGSS { /////////////////////////////////////////////////////// /// ARGSS::Table namespace /////////////////////////////////////////////////////// namespace ATable { /////////////////////////////////////////////////// /// Initialize Table class. /////////////////////////////////////////////////// void Init(); /////////////////////////////////////////////////// /// Create Table instance. /////////////////////////////////////////////////// //@{ VALUE New(int xsize); VALUE New(int xsize, int ysize); VALUE New(int xsize, int ysize, int zsize); //@} /// Table class id. extern VALUE id; /////////////////////////////////////////////////// /// Table instance methods. /////////////////////////////////////////////////// //@{ VALUE rinitialize(int argc, VALUE* argv, VALUE self); VALUE rresize(int argc, VALUE* argv, VALUE self); VALUE rxsize(VALUE self); VALUE rysize(VALUE self); VALUE rzsize(VALUE self); VALUE raref(int argc, VALUE* argv, VALUE self); VALUE raset(int argc, VALUE* argv, VALUE self); VALUE rdump(int argc, VALUE* argv, VALUE self); //@} /////////////////////////////////////////////////// /// Table class methods. /////////////////////////////////////////////////// //@{ VALUE rload(VALUE self, VALUE str); //@} }; }; #endif
[ "vgvgf@a70b67f4-0116-4799-9eb2-a6e6dfe7dbda" ]
[ [ [ 1, 86 ] ] ]
7eb00352ca88fba8ebfc2a7c7400bc1be49f9fe3
699401c51bd407f32c4984faec2e4807fede97be
/Fractal.h
e2b41764acfcca5609edb3e819b8f9770a486e05
[]
no_license
NIA/Fractal
9c7d817d62b6f20a8309814a001f23bf90623d7c
c8b0eb622284d7ccbf3478422bc0a21ad6ee2a75
refs/heads/master
2021-04-26T16:48:07.242246
2009-12-17T19:30:40
2009-12-17T19:30:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
514
h
// Fractal.h : main header file for the PROJECT_NAME application // #pragma once #ifndef __AFXWIN_H__ #error "include 'stdafx.h' before including this file for PCH" #endif #include "resource.h" // main symbols // CFractalApp: // See Fractal.cpp for the implementation of this class // class CFractalApp : public CWinAppEx { public: CFractalApp(); // Overrides public: virtual BOOL InitInstance(); // Implementation DECLARE_MESSAGE_MAP() }; extern CFractalApp theApp;
[ [ [ 1, 32 ] ] ]
5a8d4ab69ccb28c1097064d9a270685341a17d18
22d9640edca14b31280fae414f188739a82733e4
/Code/VTK/include/vtk-5.2/vtkInformationDataObjectKey.h
ba86e2687d60cb6549624ef7149e650b795d0d8d
[]
no_license
tack1/Casam
ad0a98febdb566c411adfe6983fcf63442b5eed5
3914de9d34c830d4a23a785768579bea80342f41
refs/heads/master
2020-04-06T03:45:40.734355
2009-06-10T14:54:07
2009-06-10T14:54:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,308
h
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkInformationDataObjectKey.h,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkInformationDataObjectKey - Key for vtkDataObject values. // .SECTION Description // vtkInformationDataObjectKey is used to represent keys in // vtkInformation for values that are vtkDataObject instances. #ifndef __vtkInformationDataObjectKey_h #define __vtkInformationDataObjectKey_h #include "vtkInformationKey.h" #include "vtkCommonInformationKeyManager.h" // Manage instances of this type. class vtkDataObject; class VTK_COMMON_EXPORT vtkInformationDataObjectKey : public vtkInformationKey { public: vtkTypeRevisionMacro(vtkInformationDataObjectKey,vtkInformationKey); void PrintSelf(ostream& os, vtkIndent indent); vtkInformationDataObjectKey(const char* name, const char* location); ~vtkInformationDataObjectKey(); // Description: // Get/Set the value associated with this key in the given // information object. //BTX void Set(vtkInformation* info, vtkDataObject*); vtkDataObject* Get(vtkInformation* info); //ETX int Has(vtkInformation* info); // Description: // Copy the entry associated with this key from one information // object to another. If there is no entry in the first information // object for this key, the value is removed from the second. virtual void ShallowCopy(vtkInformation* from, vtkInformation* to); // Description: // Report a reference this key has in the given information object. virtual void Report(vtkInformation* info, vtkGarbageCollector* collector); private: vtkInformationDataObjectKey(const vtkInformationDataObjectKey&); // Not implemented. void operator=(const vtkInformationDataObjectKey&); // Not implemented. }; #endif
[ "nnsmit@9b22acdf-97ab-464f-81e2-08fcc4a6931f" ]
[ [ [ 1, 62 ] ] ]
661c6ac8fce30bd4c7c9ed7f4288cf4d796b91e4
50f94444677eb6363f2965bc2a29c09f8da7e20d
/Src/EmptyProject/WorldStateManager.h
5a85a27a2af435c1e1fdf98a520e4c8c5c24c6ed
[]
no_license
gasbank/poolg
efd426db847150536eaa176d17dcddcf35e74e5d
e73221494c4a9fd29c3d75fb823c6fb1983d30e5
refs/heads/master
2020-04-10T11:56:52.033568
2010-11-04T19:31:00
2010-11-04T19:31:00
1,051,621
1
0
null
null
null
null
UTF-8
C++
false
false
924
h
๏ปฟ#pragma once #include "StateManager.h" /** @brief PlayState ์˜ ์„ธ๋ถ€ ์ƒํƒœ๋ฅผ ๊ด€๋ฆฌํ•˜๋Š” ํด๋ž˜์Šค PlayState ๋Š” ํŠน๋ณ„ํžˆ ๊ฒŒ์ž„์„ ํ”Œ๋ ˆ์ดํ•˜๊ณ  ์žˆ๋Š” ์ƒํƒœ๋กœ์„œ ์„ธ๋ถ€์ ์ธ ์ƒํƒœ๋กœ ๋‚˜๋ˆŒ ํ•„์š”๊ฐ€ ์žˆ๋‹ค. ์ด๋Ÿฌํ•œ ์„ธ๋ถ€ ์ƒํƒœ๋ฅผ WorldState๋ผ๊ณ  ๋ถ€๋ฅด๋ฉฐ ์ด๋Ÿฌํ•œ State ๋กœ๋Š” BattleState ๋‚˜ FieldState ๋“ฑ์ด ์žˆ๋‹ค. */ class WorldStateManager : public StateManager, public Singleton<WorldStateManager> { public: WorldStateManager(void); ~WorldStateManager(void); virtual void init(); virtual HRESULT onCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); HRESULT onResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); void onLostDevice(); }; inline WorldStateManager& GetWorldStateManager() { return WorldStateManager::getSingleton(); }
[ [ [ 1, 1 ], [ 4, 11 ], [ 17, 26 ] ], [ [ 2, 3 ], [ 12, 16 ] ] ]
53a86a2a981a349da534707287934bffb7384abd
3eae8bea68fd2eb7965cca5afca717b86700adb5
/Engine/Project/Core/GnMesh/Source/GForcesController.cpp
3d2ac6245e48d587b24b9d8fee883c98ea25296e
[]
no_license
mujige77/WebGame
c0a218ee7d23609076859e634e10e29c92bb595b
73d36f9d8bfbeaa944c851e8a1cfa5408ce1d3dd
refs/heads/master
2021-01-01T15:51:20.045414
2011-10-03T01:02:59
2011-10-03T01:02:59
455,950
3
1
null
null
null
null
UTF-8
C++
false
false
2,609
cpp
#include "GnMeshPCH.h" #include "GnGamePCH.h" #include "GForcesController.h" #include "GInfoForcesBasic.h" #include "GCollectComponentHeader.h" #include "GActionStand.h" #include "GActionAttack.h" #include "GActionDamage.h" #include "GActionAttackCheck.h" #include "GActorInfoDatabase.h" #include "GActionFollows.h" GForcesController::GForcesController() { } GForcesController* GForcesController::Create(const gchar* pcID, guint32 uiLevel) { gstring fullPath; GetFullActorFilePath( pcID, fullPath ); GForcesController* controller = GnNew GForcesController(); if( controller->Init( fullPath.c_str(), pcID, uiLevel ) == false ) { GnDelete controller; return NULL; } return controller; } bool GForcesController::InitController() { mCallbackActorEventSlot.Initialize( this, &GForcesController::ActorCallbackFunc ); GetActor()->SetCallbackEvent( &mCallbackActorEventSlot ); return true; } bool GForcesController::InitInfoCompenent(const gchar* pcID, guint32 uiLevel) { GInfoForcesBasic* pInfo = GnNew GInfoForcesBasic(); if( pInfo->LoadDataFromSql( pcID, uiLevel, GetActorInfoDatabase()->GetSql() ) == false ) { GnDelete pInfo; return false; } SetInfoComponent( pInfo->GetInfoType(), pInfo ); return true; } bool GForcesController::InitActionComponents() { GActorController::InitActionComponents(); GInfoForcesBasic* info = (GInfoForcesBasic*)GetInfoComponent( GInfo::INFO_BASIC ); GMainGameMove* moveAction = GnNew GMainGameMove( this ); SetActionComponent( moveAction->GetActionType(), moveAction ); moveAction->SetMoveRangeX( info->GetMoveSpeed() ); moveAction->SetMoveRight( true ); GActionDamage* damageAction = (GActionDamage*)GetActionComponent( GAction::ACTION_DAMAGE ); damageAction->SetIsPushDamage( info->GetPush() == 1 ); damageAction->SetPushDelta( GnVector2( -1.0f, 0.0f) ); GActionFollows* follows = (GActionFollows*)GetActionComponent( GAction::ACTION_FOLLOWS ); follows->CreateFollow( GActionFollows::eShadow ); return true; } void GForcesController::ActorCallbackFunc(Gn2DActor::TimeEvent* pEvent) { GnAssert( pEvent ); if( pEvent == NULL ) return; if( pEvent->GetEventType() == Gn2DActor::TimeEvent::ANIKEY ) { if( pEvent->GetSequenceID() == GAction::ANI_ATTACK ) SetAttack( pEvent->GetSequenceID() ); return; } else if( pEvent->GetEventType() == Gn2DActor::TimeEvent::END_SEQUENCE ) { if( pEvent->GetSequenceID() == GAction::ANI_ATTACK ) SetEndAttack(); if( pEvent->GetSequenceID() == GAction::ANI_DIE ) SetEndDie(); } }
[ [ [ 1, 90 ] ] ]
396598e90ef166ba25783b22a42cd2f846df421e
9a6a9d17dde3e8888d8183618a02863e46f072f1
/Area.cpp
15649a51e01878c9f3db0c58181ca29b74f9a16a
[]
no_license
pritykovskaya/max-visualization
34266c449fb2c03bed6fd695e0b54f144d78e123
a3c0879a8030970bb1fee95d2bfc6ccf689972ea
refs/heads/master
2021-01-21T12:23:01.436525
2011-07-06T18:23:38
2011-07-06T18:23:38
2,006,225
0
0
null
null
null
null
UTF-8
C++
false
false
486
cpp
#include "stdafx.h" #include "Area.h" #include <vector> Area:: Area(){ my_dim = 2; my_area.reserve(2*my_dim); for (int i = 0; i < my_dim; ++i) { my_area.push_back(-10); my_area.push_back(10); } }; int Area::get_dim() {return my_dim;} Area::~Area() {}; bool Area::contain_point(vector<double> point){ for (int i = 0; i < my_dim ; ++i) { if (point[i] < my_area[2 * i] || point[i] > my_area[2 * i + 1]) { return false; } } return true; };
[ [ [ 1, 27 ] ] ]
d653390582189bfe66e7687fdbb793c1a083c10b
3eae8bea68fd2eb7965cca5afca717b86700adb5
/Engine/Project/Core/GnMesh/Source/GnIInputEvent.h
cda1186a833c443589a6747356e7e5e870cba5d5
[]
no_license
mujige77/WebGame
c0a218ee7d23609076859e634e10e29c92bb595b
73d36f9d8bfbeaa944c851e8a1cfa5408ce1d3dd
refs/heads/master
2021-01-01T15:51:20.045414
2011-10-03T01:02:59
2011-10-03T01:02:59
455,950
3
1
null
null
null
null
UTF-8
C++
false
false
574
h
#ifndef __Core__GnIInputEvent__ #define __Core__GnIInputEvent__ class GnIInputEvent { public: enum eEventType { PUSH, PUSHUP, HOVER, MOVE, }; private: eEventType mEventType; float mPointX; float mPointY; public: GnIInputEvent(eEventType eType, float fPointX, float fPointY) : mEventType( eType ) , mPointX( fPointX ), mPointY( fPointY ) { } inline eEventType GetEventType() { return mEventType; } inline float GetPointX() { return mPointX; } inline float GetPointY() { return mPointY; } }; #endif
[ [ [ 1, 36 ] ] ]
f0239ed23bb30b7ea29c26c1134d7f4d92f3b0b7
41371839eaa16ada179d580f7b2c1878600b718e
/SELETIVA/IME-USP2008-1/koch.cpp
7ee70d1d7531e0a445a8bc63023d547600fdd9be
[]
no_license
marinvhs/SMAS
5481aecaaea859d123077417c9ee9f90e36cc721
2241dc612a653a885cf9c1565d3ca2010a6201b0
refs/heads/master
2021-01-22T16:31:03.431389
2009-10-01T02:33:01
2009-10-01T02:33:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
755
cpp
#include <cstdio> #include <cstring> #define NN 1500 int f[NN]; char k[1000024]; /* Bignum {{{ */ void rev(char v[]) { int l = strlen(v); int i; char cc; for(i = 0; i < l-1-i; i++) { cc = v[i]; v[i] = v[l-1-i]; v[l-i-1] = cc; } } int div(char v[], int q) { int i, l = strlen(v); int c = 0, d; for(i = l - 1; i >= 0; i--) { d = c*10 + (v[i] - '0'); c = d%q; d /= q; v[i] = '0'+d; } i = l - 1; while(i > 0 && v[i] == '0') i--; v[i+1] = '\0'; return c; } /* }}} */ int main(void) { int i; f[0] = 0, f[1] = 1; for(i = 2; i < NN; i++) f[i] = (f[i-1] + f[i-2]) % 1000; scanf("%d", &i); while(i--) { scanf("%s", k); rev(k); printf("%03d\n", f[div(k, NN)]); } return 0; }
[ [ [ 1, 48 ] ] ]
9ab6745ff858b700b7e51358d776b47d4c8bf541
4d39427e647851791cbd2be2f7b7e14428b983de
/case.h
cf07736927933cc2a5ba08e6a2b6f90bbaccd047
[]
no_license
elfumelfu/sandbox
dff76aa5f42659d08ad532e9c2dd17dbb453306a
8688489e14711234111abf858054ca0b332d8d0d
refs/heads/master
2021-01-22T09:26:49.570550
2011-12-06T19:11:18
2011-12-06T19:11:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,770
h
//--------------------------------------------------------------------------- #ifndef caseH #define caseH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include "ButtonWithColor.hpp" #include <CheckLst.hpp> #include <ComCtrls.hpp> #include <DB.hpp> #include <DBTables.hpp> #include <Dialogs.hpp> #include <ExtCtrls.hpp> #include <ExtDlgs.hpp> #include <jpeg.hpp> #include "JvCheckListBox.hpp" #include "JvExCheckLst.hpp" //--------------------------------------------------------------------------- class TfrmCase : public TForm { __published: // IDE-managed Components TImage *imgPoza1; TImage *imgPoza2; TImage *imgPoza3; TImage *imgPoza4; TLabel *Label7; TLabel *Label8; TImage *imgFaraPoza; TRadioGroup *rgMobilat; TButton *btnSalveaza; TGroupBox *GroupBox1; TLabel *Label1; TLabel *Label4; TLabel *Label6; TLabel *Label9; TLabel *Label10; TLabel *Label11; TLabeledEdit *txtStrada; TLabeledEdit *txtGs; TLabeledEdit *txtPret; TMemo *memAltele; TComboBox *txtMoneda; TComboBox *txtNrcam; TComboBox *txtZona; TComboBox *txtJudet; TComboBox *txtLocalitate; TButton *btnLocalitate; TButton *btnZona; TGroupBox *GroupBox2; TGroupBox *GroupBox3; TLabel *Label3; TLabeledEdit *txtNume; TMemo *memInfo; TLabeledEdit *txtTel; TButton *btnStergeTot; TButton *btnRenunta; TRadioGroup *rgUtilat; TBitBtnWithColor *btnInchiriat; TUpdateSQL *SQL; TOpenPictureDialog *OpenPictureDialog1; TQuery *getID; TUpdateSQL *insertQuery; TLabeledEdit *txtSpTeren; TLabeledEdit *txtSpConstruita; TLabel *Label2; TDateTimePicker *txtDataExpirarii; TJvCheckListBox *CheckListBox1; void __fastcall btnStergeTotClick(TObject *Sender); void __fastcall btnRenuntaClick(TObject *Sender); void __fastcall FormShow(TObject *Sender); void __fastcall btnInchiriatClick(TObject *Sender); void __fastcall txtGsKeyPress(TObject *Sender, wchar_t &Key); void __fastcall txtJudetChange(TObject *Sender); void __fastcall txtLocalitateChange(TObject *Sender); void __fastcall btnLocalitateClick(TObject *Sender); void __fastcall btnZonaClick(TObject *Sender); void __fastcall btnSalveazaClick(TObject *Sender); void __fastcall txtSpTerenKeyPress(TObject *Sender, wchar_t &Key); private: // User declarations public: // User declarations __fastcall TfrmCase(TComponent* Owner); UnicodeString operatie; int id; int inchiriat; }; //--------------------------------------------------------------------------- extern PACKAGE TfrmCase *frmCase; //--------------------------------------------------------------------------- #endif
[ "Elfu@.(none)", "[email protected]" ]
[ [ [ 1, 18 ], [ 21, 69 ], [ 71, 92 ] ], [ [ 19, 20 ], [ 70, 70 ] ] ]
208b4906951c8c0eac19b9d8660b990029468d7a
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/plugins/uavtalk/uavtalkplugin.h
0781fadea431a41b860451eb2eee17901dc10883
[]
no_license
caichunyang2007/my_OpenPilot_mods
8e91f061dc209a38c9049bf6a1c80dfccb26cce4
0ca472f4da7da7d5f53aa688f632b1f5c6102671
refs/heads/master
2023-06-06T03:17:37.587838
2011-02-28T10:25:56
2011-02-28T10:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,951
h
/** ****************************************************************************** * * @file uavtalkplugin.h * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * @addtogroup GCSPlugins GCS Plugins * @{ * @addtogroup UAVTalkPlugin UAVTalk Plugin * @{ * @brief The UAVTalk protocol plugin *****************************************************************************/ /* * 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, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef UAVTALKPLUGIN_H #define UAVTALKPLUGIN_H #include <extensionsystem/iplugin.h> #include <extensionsystem/pluginmanager.h> #include <QtPlugin> #include "telemetrymonitor.h" #include "telemetry.h" #include "uavtalk.h" #include "telemetrymanager.h" #include "uavobjects/uavobjectmanager.h" class UAVTALK_EXPORT UAVTalkPlugin: public ExtensionSystem::IPlugin { Q_OBJECT public: UAVTalkPlugin(); ~UAVTalkPlugin(); void extensionsInitialized(); bool initialize(const QStringList & arguments, QString * errorString); void shutdown(); protected slots: void onDeviceConnect(QIODevice *dev); void onDeviceDisconnect(); private: UAVObjectManager* objMngr; TelemetryManager* telMngr; }; #endif // UAVTALKPLUGIN_H
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 60 ] ] ]
554dd25213228033a022af58ae3aea47ab9dd2b1
99d3989754840d95b316a36759097646916a15ea
/trunk/2011_09_07_to_baoxin_gpd/ferrylibs/src/ferry/ground_detection/VLinesBasedREstimator.h
66392ebcd5219b1d9e780ba1094835f1cd6fc422
[]
no_license
svn2github/ferryzhouprojects
5d75b3421a9cb8065a2de424c6c45d194aeee09c
482ef1e6070c75f7b2c230617afe8a8df6936f30
refs/heads/master
2021-01-02T09:20:01.983370
2011-10-20T11:39:38
2011-10-20T11:39:38
11,786,263
1
0
null
null
null
null
UTF-8
C++
false
false
4,666
h
#pragma once #include <algorithm> #include <iostream> #include <ferry/cv_geometry/CvMatUtil.h> using namespace std; using namespace ferry::cv_mat; //ztheta -> x = 0 //xtheta -> z = 0 class ToVerticalR { public: ToVerticalR(CvMat* vp) { double x0 = cvmGet(vp, 0, 0); double y0 = cvmGet(vp, 1, 0); double z0 = cvmGet(vp, 2, 0); ztheta = -atan(x0/y0); double y1 = -sin(ztheta) * x0 + cos(ztheta) * y0; xtheta = atan(z0 / y1); cout<<"n vp: "<<matMul(getR(), vp)<<endl; } ToVerticalR(float xtheta, float ztheta) { this->xtheta = xtheta; this->ztheta = ztheta; } CvMat* getR() { double zr[] = {cos(ztheta), sin(ztheta), 0, -sin(ztheta), cos(ztheta), 0, 0, 0, 1}; CvMat ZR = cvMat(3, 3, CV_64FC1, zr); double xr[] = {1, 0, 0, 0, cos(xtheta), sin(xtheta), 0, -sin(xtheta), cos(xtheta)}; CvMat XR = cvMat(3, 3, CV_64FC1, xr); return matMul(&XR, &ZR); } static CvMat* getZR(float ztheta) { double zr[] = {cos(ztheta), sin(ztheta), 0, -sin(ztheta), cos(ztheta), 0, 0, 0, 1}; CvMat ZR = cvMat(3, 3, CV_64FC1, zr); return cloneMat(&ZR); } static CvMat* getXR(float xtheta) { double xr[] = {1, 0, 0, 0, cos(xtheta), sin(xtheta), 0, -sin(xtheta), cos(xtheta)}; CvMat XR = cvMat(3, 3, CV_64FC1, xr); return cloneMat(&XR); } public: float xtheta; float ztheta; }; /** * K, lines * lines -> normalized. nline = Kt * line * nlines -> vanishing points -> theta, vy * theta,vy -> error estimation -> best theta, vy -> best R */ class VLinesBasedREstimator { public: VLinesBasedREstimator(void) { } ~VLinesBasedREstimator(void) {} public: CvMat* compute(CvMat* K, vector<CvMat*> lines) { ToVerticalR vr = computeVR(K, lines); return vr.getR(); } ToVerticalR computeVR(CvMat* K, vector<CvMat*> lines) { CvMat* Kt = transpose(K); cout<<"Kt: "<<Kt<<endl; //normalize vector<CvMat*> nlines; for (int i = 0; i < lines.size(); i++) { cout<<"line: "<<lines[i]<<endl; cout<<"nline: "<<matMul(Kt, lines[i])<<endl; nlines.push_back(matMul(Kt, lines[i])); } vector<CvMat*> crossPoints = getAllCrossPoints(nlines); vector<ToVerticalR> vrs = estimateVRs(crossPoints); vector<CvMat*> rs = vrsToMats(vrs); vector<double> errors = estimateErrors(rs, nlines); int index = min_element(errors.begin(), errors.end()) - errors.begin(); //return vrs[index]; ///// float xtheta0 = vrs[index].xtheta; float ztheta0 = vrs[index].ztheta; double minError = errors[index]; const int RANGE_N = 5; const double PRECISION_THETA = CV_PI / 180 * 0.05; ToVerticalR bestVR(xtheta0, ztheta0); for (int i = -RANGE_N; i <= RANGE_N; i++) { for (int j = -RANGE_N; j <= RANGE_N; j++) { ToVerticalR vr(xtheta0 + i * PRECISION_THETA, ztheta0 + j * PRECISION_THETA); double error = estimateErrors(vr.getR(), nlines); if (error < minError) { bestVR = vr; minError = error; } } } cout<<"initial min error: "<<errors[index]<<endl; cout<<"min error: "<<minError<<endl; return bestVR; } public: vector<CvMat*> getAllCrossPoints(vector<CvMat*>& nlines) { vector<CvMat*> pts; for (int i = 0; i < nlines.size() - 1; i++) { cout<<"line: "<<i<<" "<<nlines[i]<<endl; for (int j = i + 1; j < nlines.size(); j++) { CvMat* pt = cvCreateMat(3, 1, CV_64FC1); cvCrossProduct(nlines[i], nlines[j], pt); pts.push_back(pt); } } return pts; } vector<ToVerticalR> estimateVRs(vector<CvMat*>& pts) { vector<ToVerticalR> vrs; for (int i = 0; i < pts.size(); i++) { vrs.push_back(ToVerticalR(pts[i])); } return vrs; } vector<CvMat*> vrsToMats(vector<ToVerticalR>& vrs) { vector<CvMat*> rs; for (int i = 0; i < vrs.size(); i++) { rs.push_back(vrs[i].getR()); } return rs; } static double estimateError(CvMat* R, CvMat* nline) { CvMat* newline = matMul(R, nline); cout<<"nline: "<<nline<<endl; cout<<"newline: "<<newline<<endl; double e = abs(cvmGet(newline, 1, 0) / cvmGet(newline, 0, 0)); cvReleaseMat(&newline); return e; } static double estimateErrors(CvMat* R, vector<CvMat*> nlines) { double es = 0; for (int i = 0; i < nlines.size(); i++) { es += estimateError(R, nlines[i]); } return es; } vector<double> estimateErrors(vector<CvMat*> rs, vector<CvMat*> nlines) { vector<double> ess; for (int i = 0; i < rs.size(); i++) { ess.push_back(estimateErrors(rs[i], nlines)); } return ess; } private: CvMat* K; vector<CvMat*> lines; CvMat* Kt; CvMat* R; };
[ "ferryzhou@b6adba56-547e-11de-b413-c5e99dc0a8e2" ]
[ [ [ 1, 195 ] ] ]
8f4af20961a807d94a361146d4916628d257ac48
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
/KylinSdk/Engine/Source/EffectManager.h
3d095c914acf684210ef9fe44a0cab1e88b57212
[]
no_license
dzw/kylin001v
5cca7318301931bbb9ede9a06a24a6adfe5a8d48
6cec2ed2e44cea42957301ec5013d264be03ea3e
refs/heads/master
2021-01-10T12:27:26.074650
2011-05-30T07:11:36
2011-05-30T07:11:36
46,501,473
0
0
null
null
null
null
GB18030
C++
false
false
3,965
h
#pragma once #include "Singleton.h" //#include "ParticleUniverseSystem.h" #include "Property.h" namespace Kylin { // ็‰นๆ•ˆ็ฑปๅž‹ enum EffectType { ET_NONE, ET_PARTICLE, ET_COMPOSITOR, ET_CUSTROM, }; ////////////////////////////////////////////////////////////////////////// // ็‰นๆ•ˆๆŽฅๅฃ class EffectObject { public: EffectObject(KSTR sName) : m_sName(sName) , m_pClocking(NULL) , m_uType(ET_NONE) , m_bAutoRemove(false) {} virtual ~EffectObject(){} // ๅˆๅง‹ๅŒ– virtual KBOOL Initialize() = 0; // render virtual KVOID Render(KFLOAT fElapsed){} // ้”€ๆฏ virtual KVOID Destroy() = 0; // ๆŒ‚่ฝฝๅˆฐๆŸ็‚น virtual KVOID Attach(Ogre::SceneNode* pNode, KFLOAT fScale = 1.0f){} // ๆฟ€ๆดป็‰นๆ•ˆ virtual KVOID Activate(KBOOL bFlag) = 0; // ่Žทๅพ—็‰นๆ•ˆๅ็งฐ virtual KSTR GetName() { return m_sName; } // virtual KVOID SetScale(KFLOAT fScale){} // ๆ˜ฏๅฆๅฏ่ง virtual KBOOL IsVisible(){ return false; } // ่ฎพ็ฝฎๅ›ž่ฐƒๅฏน่ฑก virtual KVOID SetCallbackObj(ClockingCallback* pObj); // ่ฎพ็ฝฎ็”จๆˆทๆ•ฐๆฎ virtual KVOID SetUserData(KANY aData) { m_kUserData = aData; } // virtual KVOID SetAutoRemove(KBOOL bFlag) { m_bAutoRemove = bFlag; } // virtual KVOID SetPosition(const KPoint3& pt){} protected: KSTR m_sName; // ็‰นๆ•ˆๅ็งฐ KUINT m_uType; // ็‰นๆ•ˆ็ฑปๅž‹ KBOOL m_bAutoRemove; // ่‡ชๅŠจๅˆ ้™ค ClockingCallback* m_pClocking; // ๅฎšๆ—ถๅ›ž่ฐƒ KANY m_kUserData; }; ////////////////////////////////////////////////////////////////////////// // ็ฒ’ๅญ็‰นๆ•ˆ class EffectParticle : public EffectObject { public: EffectParticle(KSTR sName, KSTR sTemplate, KFLOAT fLifeTime); virtual ~EffectParticle(); virtual KBOOL Initialize(); // render virtual KVOID Render(KFLOAT fElapsed); virtual KVOID Destroy(); virtual KVOID Activate(KBOOL bFlag); virtual KVOID Attach(Ogre::SceneNode* pNode, KFLOAT fScale = 1.0f); virtual KVOID SetScale(KFLOAT fScale); // ๆ˜ฏๅฆๅฏ่ง virtual KBOOL IsVisible(); virtual KVOID SetPosition(const KPoint3& pt); protected: //ParticleUniverse::ParticleSystem* m_pParticleSystemEx; // ๆ‰ฉๅฑ•็ฒ’ๅญ็‰นๆ•ˆๅฅๆŸ„ Ogre::ParticleSystem* m_pParticleHandle; // Ogre::SceneNode* m_pRoot; KSTR m_sTemplate; // ็‰นๆ•ˆๆจกๆฟ KFLOAT m_fLifeTime; // ๅญ˜ๅœจๆ—ถ้—ด๏ผŒ <= 0 ไธบๆ— ้™ๆ—ถ }; ////////////////////////////////////////////////////////////////////////// // ๅˆๆˆๅ™จ็‰นๆ•ˆ class EffectCompositor : public EffectObject { public: EffectCompositor(KSTR sName); virtual ~EffectCompositor(); virtual KBOOL Initialize(); virtual KVOID Destroy(); virtual KVOID Activate(KBOOL bFlag); virtual KBOOL IsEnabled(); protected: Ogre::CompositorInstance* m_pCompositor; }; ////////////////////////////////////////////////////////////////////////// // Bloom็‰นๆ•ˆ // class EffectBloom : public EffectCompositor // { // public: // EffectBloom():EffectCompositor("Bloom"){} // virtual KBOOL Initialize(); // }; ////////////////////////////////////////////////////////////////////////// // ็‰นๆ•ˆ็ฎก็†ๅ™จ class EffectManager : public Singleton<EffectManager> { public: // ๅˆๅง‹ๅŒ– KBOOL Initialize(); // render KVOID Render(KFLOAT fElapsed); // ้”€ๆฏ KVOID Destroy(); // ้”€ๆฏๆŸไธช็‰นๆ•ˆ KVOID DestroyEffect(KSTR sName); // ไบง็”Ÿ็‰นๆ•ˆ EffectObject* Generate(EffectObject* pEffect); EffectObject* Generate(const KSTR& sName, const KSTR& sTemplate, KFLOAT fLifeTime = -1.0f, KUINT uType = ET_PARTICLE); // ๆฟ€ๆดป็‰นๆ•ˆ KVOID Activate(KSTR sName, KBOOL bFlag); protected: typedef KMAP<KSTR,EffectObject*> EffectMap; typedef KVEC<KSTR> WaitList; EffectMap m_kEffectMap; // ็‰นๆ•ˆๅˆ—่กจ WaitList m_kWaitList; // ็ญ‰ๅพ…ๅˆ—่กจ }; }
[ "[email protected]", "apayaccount@5fe9e158-c84b-58b7-3744-914c3a81fc4f" ]
[ [ [ 1, 9 ], [ 19, 25 ], [ 28, 39 ], [ 41, 48 ], [ 55, 60 ], [ 63, 64 ], [ 67, 73 ], [ 75, 77 ], [ 80, 84 ], [ 86, 87 ], [ 91, 98 ], [ 100, 136 ], [ 138, 146 ], [ 149, 159 ] ], [ [ 10, 18 ], [ 26, 27 ], [ 40, 40 ], [ 49, 54 ], [ 61, 62 ], [ 65, 66 ], [ 74, 74 ], [ 78, 79 ], [ 85, 85 ], [ 88, 90 ], [ 99, 99 ], [ 137, 137 ], [ 147, 148 ] ] ]
8bcc917c95a465cc92055e266b9a110beb4e4296
2f72d621e6ec03b9ea243a96e8dd947a952da087
/lol4edit/include/EditGameLogic.h
797247aaabd9b945b6f400cd9cb9891e8ef455a2
[]
no_license
gspu/lol4fg
752358c3c3431026ed025e8cb8777e4807eed7a0
12a08f3ef1126ce679ea05293fe35525065ab253
refs/heads/master
2023-04-30T05:32:03.826238
2011-07-23T23:35:14
2011-07-23T23:35:14
364,193,504
0
0
null
null
null
null
ISO-8859-1
C++
false
false
16,379
h
#ifndef TESTGAMELOGIC_H_ #define TESTGAMELOGIC_H_ /* This class pretty much replaces the old EditFrameListener */ //#include "ChooseMeshWidget.h" #include "GameLogic.h" //#include "MainMenu.h" #include "Application.h" #include <OgrePrerequisites.h> #include "FwDec.h" #include <QtCore/QHash> #include "Ogre.h" #include <QtCore/QTime> #include "data.h" #include "UniKey.h" //#include "DecalCursor.h" #include <OgreTerrain.h> #include <OgreTerrainGroup.h> #include <OgreTerrainPaging.h> #include "EditorHelperObjects.h" namespace QtOgre { enum KeyStates { KS_RELEASED, KS_PRESSED }; class EditGameLogic : public GameLogic { friend class QtEditorApp; friend class EditorApp; public: EditGameLogic(void); void initialise(void); //THIS IS PRETTY MUCH FrameStarted void update(void); void shutdown(void); void onKeyPress(QKeyEvent* event); void onKeyRelease(QKeyEvent* event); void onMouseMove(QMouseEvent* event); void onMousePress(QMouseEvent* event); void onMouseRelease(QMouseEvent* event); void onMouseDoubleClick(QMouseEvent* event); void onWheel(QWheelEvent* event); void showDebugLines(bool show); QtOgre::Log* demoLog(void); void processTerrainEditing(Ogre::Real time); void doTerrainModify(Ogre::Terrain* terrain, const Ogre::Vector3& centrepos, Ogre::Real timeElapsed); //gets the value how much of a certain layer is visible when it has layers above it //blendValue of the point * this coverage value = should be the final value Ogre::Real getCoverageAboveLayer(Ogre::Terrain *terrain, Ogre::uint8 layer, size_t x, size_t y); void setCoverageAboveLayer(Ogre::Terrain *terrain, Ogre::uint8 layer, size_t x, size_t y, Ogre::Real val); Ogre::Real getCombinedBlendValue(Ogre::Terrain *terrain, Ogre::uint8 layer, size_t x, size_t y); void setCombinedBlendValue(Ogre::Terrain *terrain, Ogre::uint8 layer, size_t x, size_t y, Ogre::Real val); //void paintOntoTerrain(Ogre::Terrain *terrain, int const Ogre::Vector3& centrepos, Ogre::Real timeElapsed); void createDecal(); //ENTFERNEN! //void loadScene(QString filename); //***BEGIN vom FrameListener klauen enum transformMode { tmMove, tmRotate, tmScale }; enum TransformAxis { //nix tNone, //alles gleichzeitig, nur bei scale relevant tAll, //X-Achse tAxisX, //Y-achse tAxisY, //Z-Achse tAxisZ, //XY-ebene tPlaneXY, //XZ-ebene tPlaneXZ, //YZ-ebene tPlaneYZ }; //hilfsklasse class MyRenderQueueListener: public Ogre::RenderQueueListener { public: void renderQueueStarted(Ogre::uint8 queueGroupId, const Ogre::String& invocation, bool& skipThisInvocation) { if(queueGroupId == Ogre::RENDER_QUEUE_9) { //aha Ogre::Root::getSingletonPtr()->getRenderSystem()->clearFrameBuffer(Ogre::FBT_DEPTH); // mDebugText("jetzt"); } } void renderQueueEnded(Ogre::uint8 queueGroupId, const Ogre::String& invocation, bool& repeatThisInvocation) { } private: //Ogre::SceneManager *mSceneMgr; }; MyRenderQueueListener *rqListener; TransformAxis curTransform; transformMode mTMode; //TerrainDecal *mTerrainDecal; SelectionBorder *selBorder; void requestShutdown(); void uniKeyPressed(UniKey key); void uniKeyReleased(UniKey key); //terrain bearbeiten void processTerrainEditing(const Ogre::FrameEvent &evt); //to notify the FL that the level has been changed //this is called as soon as the new level is constructed, but the old one still exists void levelChangeBegin(Level *newLevel); //this is called when everything is finished void levelChangeEnd(); bool isKeyDown(UniKey k); void setSelected(GameObject *obj); GameObject *getSelected() { return selectedObject; } /*void setDecalPosition(Ogre::Vector3 pos) { if(decal) decal->setPosition(pos); }*/ //objekt von oben zeigen void showObjectFromTop(GameObject *obj); //auswahl sperren void setSelectionLocked(bool set); //***END vom FrameListener klauen //funktionen, die nach und nach von EditGameLogic geklaut werden //void loadLevel(Ogre::String filename); // //VOM ALTEN EDITORAPP // friend class Level; //friend class EditFrameListener; //void go(); // void log(Ogre::String txt); // Ogre::Real sensibility_x; // Ogre::Real sensibility_y; // //editormodus. ob man das level, das terrain, oder die objekte bearbeitet // enum EditorMode // { // //das level bearbeiten, also die objekte dort rumschieben // emLevel, // //das terrain bearbeiten, die heightmap deformieren und bemalen // emTerrain, // //einzelne objekte bearbeiten // emObjects // }; // // // //ContCallback *cc_static_char; // //GameChar *player, *playerBackup; // Ogre::Real conf_lookspeed; // // int menuMode; // bool paused, // shutDown, // cursorMode; // //lvlLoaded; // //Ogre::SceneNode *CamNode, *CamHeadNode; // //well, faking drag&drop... // ObjType dragItemType; // Ogre::String dragItemID; // // // //hier das configzeug. ERSTMAL // Ogre::Real gridSnap; // Ogre::Real angleSnap; // Ogre::Real scaleSnap; // bool snapOnGrid; // bool snapOnAngle; // bool snapOnScale; // // //bool dotSceneMode; // // // Ogre::Real axesScaleFactor; // Ogre::String windowName; // Ogre::Vector3 camStartPos; // //Ogre::Quaternion camStartOrient; // // Ogre::StringVector paramList; // bool showConfigDialog; // // Ogre::Vector3 oldHitpoint;//das ist fรผr objectScale // //es speichert hier den vorherigen Punkt, // //an dem die ebene durchgestoรŸen wurde // // Ogre::SceneNode *axesNode; // Ogre::SceneNode *axe_X; // Ogre::SceneNode *axe_Y; // Ogre::SceneNode *axe_Z; // Ogre::SceneNode *plane_XZ; // Ogre::SceneNode *plane_XY; // Ogre::SceneNode *plane_YZ; // Ogre::SceneNode *boxAll; // Ogre::SceneNode *rotateMoveNode;//diese node wird benutzt, um die cam um ein obj zu drehen // // //StandardApplication *app;//hm. oder erbe ich selbst davon? // // //bool loadTerrainCollision; // //configzeug ENDE // // //fรผr das material-fenster //// CEGUI::Window *materialSelectTarget; // // //fรผr particlesystem //// CEGUI::Window *psSelectTarget; // void setEditorMode(EditGameLogic::EditorMode mode); // void hideAxes(); // //ENDE //drops currently holding item - TO BE REPLACED with Qt's drag&drop-function void dropItem(); //drops item using type and string-id //this function can also drop lights, entrances or statics void dropItem(ObjType objectType,Ogre::String objectID,WorldArtType staticType = WT_NONE); //drops item using it's gamedata void dropItem(gamedata *data); //drops item by id void dropItem(Ogre::String id); //gets position for dropping Ogre::Vector3 getDropPosition(); void setTransformModeDirect(transformMode mod); void setTransformMode(transformMode mod); private: //input events QKeyEvent *lastKeyEvent; QMouseEvent *lastMouseEvent; // //in erster Linie dazu, um festzustellen, wann die collision neu erzeugt werden muss // bool terrainDeformed; // //ob man sich im EditTerrain-Modus befindet // EditorMode editingMode; // bool editingTerrain; // // //bool paintingHoles; // //bool paintingTextures; // //bool terrainFlattening; // //bool flatteningToClick; // Ogre::Real terrainIntensity; // bool intensityChangeInProgress; // unsigned int currentTexture; // //CEGUI::OgreCEGUIRenderer* mGUIRenderer; // //CEGUI::System* mGUISystem; // //CEGUI::Window* mEditorGuiSheet; // //CEGUI::UVector2 barDimensions; // //CEGUI::FrameWindow *detailswnd; //could be used more often // //CEGUI::FrameWindow *editorsettings; // //CEGUI::FrameWindow *levelsettings; // //CEGUI::FrameWindow *inputdialog; // //CEGUI::Window *selectionBorder; // //CEGUI::UVector2 selBorderFirst; // //CEGUI::Window *fpsBox; // //CEGUI::Window *objInfo; // // //das Objekt, zu dem grad das detailfenster offen ist // GameObject *curEditing; // // void (EditGameLogic::*inputDialogReturn)(Ogre::String value); // //ENDE GEKLAUT // //// bool paused; // Level *currentLevel; QHash<int, KeyStates> mKeyStates; QPoint mLastFrameMousePos; QPoint mCurrentMousePos; int mLastFrameWheelPos; int mCurrentWheelPos; QTime* mTime; int mLastFrameTime; int mCurrentTime; bool mIsFirstFrame; float mCameraSpeed; // ChooseMeshWidget* mChooseMeshWidget; // MainMenu* mMainMenu; Ogre::Camera* mCamera; Ogre::SceneManager* mSceneManager; QtOgre::Log* mDemoLog; QtEditorApp *mRealApp; //*** BEGIN vom FrameListener klauen //die hรถhe, zu der hin abgeflacht wird //-1 = nicht festgelegt, es wird bei mouseUp auf -1 gesetzt Ogre::Real flattenHeight; //ob die auswahl gesperrt ist bool selectionLocked; //DecalCursor *decal; /* void createDecal(); void deleteDecal() { if(!decal) return; decal->hide(); delete decal; decal = NULL; }*/ void setDecalScale(Ogre::ushort scale); Ogre::Vector3 deformPosition; EditorApp *app; // CEGUI::Renderer* mGUIRenderer; UniKey key_modeMove, key_modeRotate, key_modeScale, key_viewRotate, key_viewMove, key_viewRotateMove, key_showLines, key_screenShot, key_delete, key_showDetails, key_objMove, key_clone, key_group, key_copy, key_paste, key_cut, key_movedown, key_savemap, key_viewtop; //short moveMode; bool wasOverGui; //ob davor รผber der GUI war. "hebt" maustasten beim gui-betreten bool lastMouseDownOnGui; //wenn ja, wird das nรคchste mouseUp รผber Nichtgui nur so weit verarbeitet, dass man items droppt bool mousePosChanged; //fรผrs Selektieren //das ist wg cegui. eine funktion wird den cursor anzeigen/ausblenden, dabei diese var รคndern //wenn sie falsch ist, kriegt cegui keine mausbewegungen bool cursorShown; //die var hรคlt nur solange, wie man irgendwas am terrain macht //wird beim loslassen der maus auf false gesetzt bool mustUpdateLightmap; //ob ich beenden muss bool shutDown; //ob OgreNewt debuglinien angezeigt werden bool linesShown; bool view_rotate; bool view_move; bool view_rotatemove; bool rotateStartDoOnce; Ogre::Vector3 holdingOffset; //difference between obj position and intersection point Ogre::Vector3 intersectionPoint; Ogre::Vector3 oldIntersectionPoint;//das ist fรผr rotation. Ogre::Vector3 lastSnapVector; Ogre::Vector3 prevCamPos; //alte cam-position, um die achsen nicht unnรถtig zu skalieren Ogre::Vector3 startPosition; Ogre::Vector3 startScale; Ogre::Quaternion startOrientation; Ogre::Vector3 unSnappedScale; //scale, ohne durch scalesnap betroffen zu sein //Ogre::Quaternion rotatedOrientation; /* OIS::InputManager* mInputManager; OIS::Mouse* mMouse; OIS::Keyboard* mKeyboard;*/ Ogre::Real lastFrameTime; Ogre::Real mRotate; Ogre::Real mMove; Ogre::Real mMoveKeyboard; Ogre::Real mScroll; GameObject *nextSelected; GameObject *selectedObject; GameObject *prevSelected; //das "vorher selektierte" //beim mouseUp wird selectedObject damit verglichen //bei nichtรผbereinstimmung werden sie gleichgesetzt //wenn sie im mouseDragged nicht รผbereinstimmen, wird //kein movement zugelassen void updatePositionInfoBox(Ogre::Vector3 pos); //1=x 2=y 3=z void updateRotationInfoBox(Ogre::Real deg,short axis); //1=x 2=y 3=z void objectRotate(); void objectMove(); void objectScale(); void objectMoveDown(); //aktualisiert die auswahl. prรผft nicht mehrs elber, ob die group-taste gedrรผckt ist, muss nun รผbergeben werden void updateSelection(bool grouping = false); void updateObjectInfo(); bool selBoxDrawing; // CEGUI::Point selBoxStart, selBoxEnd; //damn.... selektion muss nun iwie anders laufen... Ogre::Vector2 selBoxStart, selBoxEnd; void drawSelectionBox(); void finishSelectionBox(); void showMouseCursor(bool show); Ogre::Ray getMouseRay(); GameObject* doObjectRaycast(); bool scaleDoOnce; //einmal-var fรผrs skalieren Ogre::Vector3 oldHitpoint;//das ist fรผr objectScale //es speichert hier den vorherigen Punkt, //an dem die ebene durchgestoรŸen wurde Ogre::SceneNode *axesNode; Ogre::SceneNode *axe_X; Ogre::SceneNode *axe_Y; Ogre::SceneNode *axe_Z; Ogre::SceneNode *plane_XZ; Ogre::SceneNode *plane_XY; Ogre::SceneNode *plane_YZ; Ogre::SceneNode *boxAll; Ogre::SceneNode *rotateMoveNode;//diese node wird benutzt, um die cam um ein obj zu drehen void showAxes(GameObject *obj); void hideAxes(); void updateAxes(); void copyObjects(); void pasteObjects(); void deleteSelected(); //void processTextKey(UniKey key); //initiiert rotatemove (um ein objekt herumdrehen) //das ist etwas komplizierter, da es die camera an die axesnode hรคngt void initRotatemove(); //lรถscht das rotatemove. es ist danach mit dem normalen Umschauen identisch void cancelRotatemove(); //das "rastet" einen Vektor ein, //dh sucht das um ein Vielfaches von `angle` an `axis` gedrehtes `base`, dass //dem src am nรคchsten ist. Das `base`wird jetzt automatisch bestimmt Ogre::Vector3 snapVector(Ogre::Degree angle,Ogre::Vector3 src,Ogre::Vector3 axis); //*** END vom FrameListener klauen // bool isKeyPressed(UniKey key); protected: // Ogre::String listboxTypeText;//wenn man im listbox tippt // Ogre::Real timeSinceLastLBDown; //zeit seit letztem keydown auf ein listbox // //CEGUI::Window *lastLB; // //Ogre::Root *mRoot; // Ogre::Camera* mDefaultCam; //Ogre::SceneNode *mDefaultCamNode; // Ogre::SceneManager* mDefaultSceneMgr; // EditFrameListener *mFrameListener; //CEGUI::WindowManager *wmgr; //EventProcessor *mEventProcessor; Ogre::RenderWindow* mWindow; /*OgreNewt::World* mWorld;*/ //*** BEGIN vom FrameListener klauen int desired_framerate; Ogre::Real m_update, m_elapsed; //*** END vom FrameListener klauen /** * this functions will emulate the old FrameListner behaviour... or not?! */ //void frameEnded(Ogre::Real time); bool frameStarted(Ogre::Real time); /*Ogre::String levelPath, currentLvl;*/ /*void createTerrainBrushes(); void updateBrushesWindow(); void updateTexturesList();*/ //void fillMaterialComboBox(CEGUI::Combobox *cb); }; } #endif /*DEMOGAMELOGIC_H_*/
[ "praecipitator@bd7a9385-7eed-4fd6-88b1-0096df50a1ac" ]
[ [ [ 1, 557 ] ] ]
2ef1b052dff6f3a7124e776aaa1cc9f601e8a024
69eed80ee7eb670d957d2fe86e3044cab51e517a
/src/main/cpp/vision/finder.cpp
6d45150253a06c4cee5eaf7031a19f07c6dd2f3f
[]
no_license
lineCode/libsikuli
9a6e4a883362002be18741fdecb0e5fc0c32ec6d
b0e2f381375456561a2b4d87b1b2241c7e085b17
refs/heads/master
2021-01-16T07:19:19.254683
2011-01-04T01:34:15
2011-01-04T01:34:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,152
cpp
#include <stdio.h> #include <iostream> #include <fstream> #include "finder.h" #include "pyramid-template-matcher.h" #include "TimingBlock.h" using namespace cv; using namespace std; #define PYRAMID_MIM_TARGET_DIMENSION 6 #define PYRAMID_MIM_TARGET_DIMENSION_ALL 50 #define REMATCH_THRESHOLD 0.9 #define CENTER_REMATCH_THRESHOLD 0.99 #define BORDER_MARGIN 0.2 #ifdef DEBUG #define dout std::cerr #else #define dout if(0) std::cerr #endif BaseFinder::BaseFinder(Mat _source) : source(_source){ roi = Rect(0,0,source.cols,source.rows); } BaseFinder::BaseFinder(const char* source_image_filename){ source = imread(source_image_filename,1); roi = Rect(0,0,source.cols,source.rows); } // somwhow after changing it to false works!! BaseFinder::BaseFinder(IplImage* _source) : source(Mat(_source, false)){ roi = Rect(0,0,source.cols,source.rows); } BaseFinder::~BaseFinder(){ } void BaseFinder::setROI(int x, int y, int w, int h){ roi = Rect(x,y,w,h); } void BaseFinder::find(){ // create an ROI image to work on roiSource.create(roi.size(),source.type()); Mat(source,roi).copyTo(roiSource); } //======================================================================================= bool sort_by_score(FindResult m1, FindResult m2){ return m1.score > m2.score; } TemplateFinder::TemplateFinder(Mat _source) : BaseFinder(_source){ matcher = NULL; } TemplateFinder::TemplateFinder(IplImage* _source) : BaseFinder(_source){ matcher = NULL; } TemplateFinder::TemplateFinder(const char* source_image_filename) : BaseFinder(source_image_filename){ matcher = NULL; } TemplateFinder::~TemplateFinder(){ if (matcher) delete matcher; } void TemplateFinder::find(const char *target_image_filename, double min_similarity){ Mat target = imread(target_image_filename, 1); if (target.data == NULL) throw cv::Exception(); find(target, min_similarity); } void TemplateFinder::find(IplImage* target, double min_similarity){ find(Mat(target, false), min_similarity); } void TemplateFinder::find_all(const char *target_image_filename, double min_similarity){ Mat target = imread(target_image_filename, 1); if (target.data == NULL) throw cv::Exception(); find_all(target, min_similarity); } void TemplateFinder::find_all(IplImage* target, double min_similarity){ find_all(Mat(target, true), min_similarity); } void TemplateFinder::find_all(Mat target, double min_similarity){ this->min_similarity = min_similarity; BaseFinder::find(); if (roiSource.cols < target.cols || roiSource.rows < target.rows){ current_match.score = -1; return; } float factor = 2.0; int levels=-1; int w = target.rows; int h = target.cols; while (w >= PYRAMID_MIM_TARGET_DIMENSION_ALL && h >= PYRAMID_MIM_TARGET_DIMENSION_ALL){ w = w / factor; h = h / factor; levels++; } Mat roiSourceGray; Mat targetGray; // convert image from RGB to grayscale cvtColor(roiSource, roiSourceGray, CV_RGB2GRAY); cvtColor(target, targetGray, CV_RGB2GRAY); create_matcher(roiSourceGray, targetGray, levels, factor); add_matches_to_buffer(5); if (top_score_in_buffer() >= max(min_similarity,REMATCH_THRESHOLD)) return; dout << "[find_all] matching (original resolution: color) ... " << endl; create_matcher(roiSource, target, 0, 1); add_matches_to_buffer(5); } float TemplateFinder::top_score_in_buffer(){ if (buffered_matches.empty()) return -1; else return buffered_matches[0].score; } void TemplateFinder::create_matcher(Mat& source, Mat& target, int level, float ratio){ if (matcher) delete matcher; matcher = new PyramidTemplateMatcher(source,target,level,ratio); } void TemplateFinder::add_matches_to_buffer(int num_matches_to_add){ buffered_matches.clear(); for (int i=0;i<num_matches_to_add;++i){ FindResult next_match = matcher->next(); buffered_matches.push_back(next_match); } sort(buffered_matches,sort_by_score); } void TemplateFinder::find(Mat target, double min_similarity){ this->min_similarity = min_similarity; BaseFinder::find(); if (roiSource.cols < target.cols || roiSource.rows < target.rows){ current_match.score = -1; return; } float ratio; ratio = min(target.rows * 1.0 / PYRAMID_MIM_TARGET_DIMENSION, target.cols * 1.0 / PYRAMID_MIM_TARGET_DIMENSION); Mat roiSourceGray; Mat targetGray; // convert image from RGB to grayscale cvtColor(roiSource, roiSourceGray, CV_RGB2GRAY); cvtColor(target, targetGray, CV_RGB2GRAY); TimingBlock tb("NEW METHOD"); dout << "matching (center) ... " << endl; Mat roiSourceGrayCenter = Mat(roiSourceGray, Range(roiSourceGray.rows*BORDER_MARGIN, roiSourceGray.rows*(1-BORDER_MARGIN)), Range(roiSourceGray.cols*BORDER_MARGIN, roiSourceGray.cols*(1-BORDER_MARGIN))); create_matcher(roiSourceGrayCenter, targetGray, 1, ratio); add_matches_to_buffer(5); if (top_score_in_buffer() >= max(min_similarity,CENTER_REMATCH_THRESHOLD)){ roi.x += roiSourceGray.cols*BORDER_MARGIN; roi.y += roiSourceGray.rows*BORDER_MARGIN; return; } dout << "matching (whole) ... " << endl; create_matcher(roiSourceGray, targetGray, 1, ratio); add_matches_to_buffer(5); if (top_score_in_buffer() >= max(min_similarity,REMATCH_THRESHOLD)){ return; } dout << "matching (0.75) ..." << endl; create_matcher(roiSourceGray, targetGray, 1, ratio*0.75); add_matches_to_buffer(5); if (top_score_in_buffer() >= max(min_similarity,REMATCH_THRESHOLD)) return; if (ratio > 2){ dout << "matching (0.5) ..." << endl; create_matcher(roiSourceGray, targetGray, 1, ratio*0.5); add_matches_to_buffer(5); if (top_score_in_buffer() >= max(min_similarity,REMATCH_THRESHOLD)) return; } if (ratio > 4){ dout << "matching (0.25) ..." << endl; create_matcher(roiSourceGray, targetGray, 1, ratio*0.25); add_matches_to_buffer(5); if (top_score_in_buffer() >= max(min_similarity,REMATCH_THRESHOLD)) return; } dout << "matching (original resolution) ... " << endl; create_matcher(roiSourceGray, targetGray, 0, 1); add_matches_to_buffer(5); if (top_score_in_buffer() >= max(min_similarity,REMATCH_THRESHOLD)) return; dout << "matching (original resolution: color) ... " << endl; create_matcher(roiSource, target, 0, 1); add_matches_to_buffer(5); } bool TemplateFinder::hasNext(){ return top_score_in_buffer() >= (min_similarity-0.0000001); } FindResult TemplateFinder::next(){ if (!hasNext()) return FindResult(0,0,0,0,-1); FindResult top_match = buffered_matches.front(); top_match.x += roi.x; top_match.y += roi.y; FindResult next_match = matcher->next(); buffered_matches[0] = next_match; sort(buffered_matches,sort_by_score); return top_match; } //========================================================================================= static const char* cascade_name = "haarcascade_frontalface_alt.xml"; CvHaarClassifierCascade* FaceFinder::cascade = 0; FaceFinder::FaceFinder(const char* screen_image_name) : BaseFinder(screen_image_name){ // cascade = 0; storage = 0; if (!cascade){ cascade = (CvHaarClassifierCascade*)cvLoad(cascade_name, 0, 0, 0); } if (!cascade) { cerr << "can't load the face cascade"; return; } } FaceFinder::~FaceFinder(){ //cvReleaseImage(&img); if (cascade) cvReleaseHaarClassifierCascade(&cascade); if (storage) cvReleaseMemStorage(&storage); } void FaceFinder::find(){ BaseFinder::find(); storage = cvCreateMemStorage(0); //faces = cvHaarDetectObjects(roi_img, cascade, storage, 1.1, 2, CV_HAAR_DO_CANNY_PRUNING, cvSize(40,40)); face_i = 0; // [DEBUG] reset the debug image to the content of the input image } bool FaceFinder::hasNext(){ return faces && face_i < faces->total; } FindResult FaceFinder::next(){ CvRect* r = (CvRect*)cvGetSeqElem(faces ,face_i); face_i++; FindResult match; match.x = r->x + roi.x; match.y = r->y + roi.y; match.w = r->width; match.h = r->height; return match; } //===================================================================================== #define PIXEL_DIFF_THRESHOLD 50 #define IMAGE_DIFF_THRESHOLD 20 ChangeFinder::ChangeFinder(const char* screen_image_filename) : BaseFinder(screen_image_filename){ is_identical = false; storage = 0; } ChangeFinder::ChangeFinder(const IplImage* screen_image) : BaseFinder(screen_image){ is_identical = false; storage = 0; } ChangeFinder::ChangeFinder(const Mat screen_image) : BaseFinder(screen_image){ is_identical = false; storage = 0; } ChangeFinder::~ChangeFinder(){ if (storage) cvReleaseMemStorage(&storage); } void ChangeFinder::find(const char* new_screen_image_filename){ find(imread(new_screen_image_filename,1)); } void ChangeFinder::find(IplImage* new_screen_image){ find(Mat(new_screen_image, false)); } void ChangeFinder::find(Mat new_screen_image){ BaseFinder::find(); // set ROI Mat im1 = roiSource; Mat im2 = Mat(new_screen_image,roi); Mat gray1; Mat gray2; // convert image from RGB to grayscale cvtColor(im1, gray1, CV_RGB2GRAY); cvtColor(im2, gray2, CV_RGB2GRAY); Mat diff1; absdiff(gray1,gray2,diff1); typedef float T; Size size = diff1.size(); int diff_cnt = 0; for( int i = 0; i < size.height; i++ ) { const T* ptr1 = diff1.ptr<T>(i); for( int j = 0; j < size.width; j += 4 ) { if (ptr1[j] > PIXEL_DIFF_THRESHOLD) diff_cnt++; } } // quickly check if two images are nearly identical if (diff_cnt < IMAGE_DIFF_THRESHOLD){ is_identical = true; return; } threshold(diff1,diff1,PIXEL_DIFF_THRESHOLD,255,CV_THRESH_BINARY); dilate(diff1,diff1,Mat()); // close operation Mat se = getStructuringElement(MORPH_ELLIPSE, Size(5,5)); morphologyEx(diff1, diff1, MORPH_CLOSE, se); /* namedWindow("matches", CV_WINDOW_AUTOSIZE); imshow("matches", diff1); waitKey(); */ vector< vector<Point> > contours; vector< Vec4i> hierarchy; //findContours(diff1, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE, Point()); storage = cvCreateMemStorage(); CvSeq* first_contour = NULL; CvMat mat = (CvMat) diff1; cvFindContours( &mat, storage, &first_contour, sizeof(CvContour), CV_RETR_EXTERNAL); c = first_contour; } bool ChangeFinder::hasNext(){ return !is_identical && c !=NULL; } FindResult ChangeFinder::next(){ // find bounding boxes int x1=source.cols; int x2=0; int y1=source.rows; int y2=0; for( int i=0; i < c->total; ++i ){ CvPoint* p = CV_GET_SEQ_ELEM( CvPoint, c, i ); if (p->x > x2) x2 = p->x; if (p->x < x1) x1 = p->x; if (p->y > y2) y2 = p->y; if (p->y < y1) y1 = p->y; } FindResult m; m.x = x1 + roi.x; m.y = y1 + roi.y; m.w = x2 - x1 + 1; m.h = y2 - y1 + 1; c = c->h_next; return m; } //===================================================================================== #include "tessocr.h" TextFinder::TextFinder(Mat inputImage) : BaseFinder(inputImage){ }; void TextFinder::train(Mat& trainingImage){ // train_by_image(trainingImage); } // Code copied from // http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html static void Tokenize(const string& str, vector<string>& tokens, const string& delimiters = " ") { // Skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". string::size_type pos = str.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } } void TextFinder::find(const char* text, double _min_similarity){ vector<string> words; Tokenize(text, words, " "); return find(words, _min_similarity); } void TextFinder::find_all(const char* text, double _min_similarity){ vector<string> words; Tokenize(text, words, " "); return find_all(words, _min_similarity); } void TextFinder::find(vector<string> words, double _min_similarity){ this->min_similarity = _min_similarity; BaseFinder::find(); TimingBlock tb("TextFinder::find"); matches = OCR::find_phrase(roiSource, words); matches_iterator = matches.begin(); } void TextFinder::find_all(vector<string> words, double _min_similarity){ this->min_similarity = _min_similarity; BaseFinder::find(); TimingBlock tb("TextFinder::find_all"); matches = OCR::find_phrase(roiSource, words, false); matches_iterator = matches.begin(); } bool TextFinder::hasNext(){ // dout << "[TextFinder] " << matches_iterator->score << endl; return (matches_iterator != matches.end()) && (matches_iterator->score >= min_similarity); } FindResult TextFinder::next(){ FindResult ret; if (hasNext()){ ret = *matches_iterator; ++matches_iterator; return ret; }else { return FindResult(0,0,0,0,-1); } } vector<string> TextFinder::recognize(const Mat& inputImage){ return vector<string>();//recognize_words(inputImage); } //===================================================================================== Finder::Finder(Mat source) : _source(source){ _finder = NULL; _roi = Rect(-1,-1,-1,-1); } Finder::Finder(IplImage* source) : _source(Mat(source)){ _finder = NULL; _roi = Rect(-1,-1,-1,-1); } Finder::Finder(const char* source){ _source = imread(source,1); _finder = NULL; _roi = Rect(-1,-1,-1,-1); } Finder::~Finder(){ if (_finder) delete _finder; } void Finder::find(IplImage* target, double min_similarity){ dout << "[Finder::find]" << endl; if (abs(min_similarity - 100)< 0.00001){ cout << "training.." << endl; Mat im(target); TextFinder::train(im); }else{ TemplateFinder* tf = new TemplateFinder(_source); if(_roi.width>0) tf->setROI(_roi.x, _roi.y, _roi.width, _roi.height); tf->find(target, min_similarity); _finder = tf; } } void Finder::find(const char *target, double min_similarity){ dout << "[Finder::find]" << endl; const char* p = target; const char* ext = p + strlen(p) - 3; if (abs(min_similarity - 100)< 0.00001){ Mat im = imread(target,1); TextFinder::train(im); }else if (strncmp(ext,"png",3) != 0){ TextFinder* wf = new TextFinder(_source); if(_roi.width>0) wf->setROI(_roi.x, _roi.y, _roi.width, _roi.height); // get name after bundle path, which is // assumed to be the query word int j; for (j = (strlen(p)-1); j >=0; j--){ if (p[j]=='/') break; } const char* q = p + j + 1; wf->find(q,0.6); _finder = wf; }else { TemplateFinder* tf = new TemplateFinder(_source); if(_roi.width>0) tf->setROI(_roi.x, _roi.y, _roi.width, _roi.height); tf->find(target, min_similarity); _finder = tf; } } void Finder::find_all(IplImage* target, double min_similarity){ TemplateFinder* tf = new TemplateFinder(_source); if(_roi.width>0) tf->setROI(_roi.x, _roi.y, _roi.width, _roi.height); tf->find_all(target, min_similarity); _finder = tf; } void Finder::find_all(const char *target, double min_similarity){ const char* p = target; const char* ext = p + strlen(p) - 3; if (strncmp(ext,"png",3) != 0){ TextFinder* wf = new TextFinder(_source); if(_roi.width>0) wf->setROI(_roi.x, _roi.y, _roi.width, _roi.height); // get name after bundle path, which is // assumed to be the query word int j; for (j = (strlen(p)-1); j >=0; j--){ if (p[j]=='/') break; } const char* q = p + j + 1; wf->find(q,0.6); _finder = wf; }else { TemplateFinder* tf = new TemplateFinder(_source); if(_roi.width>0) tf->setROI(_roi.x, _roi.y, _roi.width, _roi.height); tf->find_all(target, min_similarity); _finder = tf; } } bool Finder::hasNext(){ return _finder->hasNext(); } FindResult Finder::next(){ return _finder->next(); } void Finder::setROI(int x, int y, int w, int h){ _roi = Rect(x, y, w, h); }
[ [ [ 1, 593 ], [ 595, 599 ], [ 601, 605 ], [ 607, 626 ], [ 628, 647 ], [ 649, 665 ], [ 667, 674 ], [ 676, 687 ], [ 689, 704 ], [ 706, 720 ] ], [ [ 594, 594 ], [ 600, 600 ], [ 606, 606 ], [ 627, 627 ], [ 648, 648 ], [ 666, 666 ], [ 675, 675 ], [ 688, 688 ], [ 705, 705 ], [ 721, 724 ] ] ]
48829587b0017279034d4e485b170375419a145d
075043812c30c1914e012b52c60bc3be2cfe49cc
/src/ShokoRocket++lib/Animation.h
512d996e03dc06a6cf3c23dda6cfafc362ccb08d
[]
no_license
Luke-Vulpa/Shoko-Rocket
8a916d70bf777032e945c711716123f692004829
6f727a2cf2f072db11493b739cc3736aec40d4cb
refs/heads/master
2020-12-28T12:03:14.055572
2010-02-28T11:58:26
2010-02-28T11:58:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
962
h
#pragma once #include <vector> #include <string> using std::vector; using std::string; class AnimationFrame; class Animation { private: float total_length_; float frame_time_; AnimationFrame* current_frame_; int current_frame_index_; vector<AnimationFrame*> frames_; string name_; static int count_; public: Animation(); ~Animation(); /* Directly access a frame by time */ AnimationFrame* GetFrame(float _time); int GetFrameID(float _time); /* Add a frame to animation */ void AddFrame(AnimationFrame* _frame); /* Get the current frame. Animation stores time */ AnimationFrame* GetCurrentFrame(){return current_frame_;} /* Gets the frame at this index. If index out of bounds then returns frame at mod of _index */ AnimationFrame* GetFrameByIndex(int _index); int GetCurrentFrameID(); void Tick(float _timespan); string GetName(){return name_;} void SetName(string _name){name_ = _name;} };
[ [ [ 1, 41 ] ] ]
bf6d34ace4a6da9772905c9d6591a1ca36d79092
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/validators/common/ContentLeafNameTypeVector.cpp
41e006535617d5583679569ba92f3977c60c344b
[ "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,546
cpp
/* * Copyright 2001,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Log: ContentLeafNameTypeVector.cpp,v $ * Revision 1.5 2004/09/08 13:56:51 peiyongz * Apache License Version 2.0 * * Revision 1.4 2003/12/17 00:18:38 cargilld * Update to memory management so that the static memory manager (one used to call Initialize) is only for static data. * * Revision 1.3 2003/05/15 18:48:27 knoaman * Partial implementation of the configurable memory manager. * * Revision 1.2 2002/11/04 14:54:58 tng * C++ Namespace Support. * * Revision 1.1.1.1 2002/02/01 22:22:38 peiyongz * sane_include * * Revision 1.3 2001/05/11 13:27:17 tng * Copyright update. * * Revision 1.2 2001/04/19 18:17:28 tng * Schema: SchemaValidator update, and use QName in Content Model * * Revision 1.1 2001/02/27 14:48:49 tng * Schema: Add CMAny and ContentLeafNameTypeVector, by Pei Yong Zhang * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/validators/common/ContentLeafNameTypeVector.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // ContentLeafNameTypeVector: Constructors and Destructor // --------------------------------------------------------------------------- ContentLeafNameTypeVector::ContentLeafNameTypeVector ( MemoryManager* const manager ) : fMemoryManager(manager) , fLeafNames(0) , fLeafTypes(0) , fLeafCount(0) { } ContentLeafNameTypeVector::ContentLeafNameTypeVector ( QName** const names , ContentSpecNode::NodeTypes* const types , const unsigned int count , MemoryManager* const manager ) : fMemoryManager(manager) , fLeafNames(0) , fLeafTypes(0) , fLeafCount(0) { setValues(names, types, count); } /*** copy ctor ***/ ContentLeafNameTypeVector::ContentLeafNameTypeVector ( const ContentLeafNameTypeVector& toCopy ) : fMemoryManager(toCopy.fMemoryManager) , fLeafNames(0) , fLeafTypes(0) , fLeafCount(0) { fLeafCount=toCopy.getLeafCount(); init(fLeafCount); for (unsigned int i=0; i<this->fLeafCount; i++) { fLeafNames[i] = toCopy.getLeafNameAt(i); fLeafTypes[i] = toCopy.getLeafTypeAt(i); } } ContentLeafNameTypeVector::~ContentLeafNameTypeVector() { cleanUp(); } // --------------------------------------------------------------------------- // ContentSpecType: Setter methods // --------------------------------------------------------------------------- void ContentLeafNameTypeVector::setValues ( QName** const names , ContentSpecNode::NodeTypes* const types , const unsigned int count ) { cleanUp(); init(count); for (unsigned int i=0; i<count; i++) { fLeafNames[i] = names[i]; fLeafTypes[i] = types[i]; } } // --------------------------------------------------------------------------- // ContentLeafNameTypeVector: Getter methods // --------------------------------------------------------------------------- QName* ContentLeafNameTypeVector::getLeafNameAt(const unsigned int pos) const { if (pos >= fLeafCount) ThrowXMLwithMemMgr(ArrayIndexOutOfBoundsException, XMLExcepts::Vector_BadIndex, fMemoryManager); return fLeafNames[pos]; } const ContentSpecNode::NodeTypes ContentLeafNameTypeVector::getLeafTypeAt (const unsigned int pos) const { if (pos >= fLeafCount) ThrowXMLwithMemMgr(ArrayIndexOutOfBoundsException, XMLExcepts::Vector_BadIndex, fMemoryManager); return fLeafTypes[pos]; } const unsigned int ContentLeafNameTypeVector::getLeafCount() const { return fLeafCount; } XERCES_CPP_NAMESPACE_END
[ [ [ 1, 154 ] ] ]
8c796ba952d21809f4d2964b9e3dfcb1e6e0742d
2c1e5a69ca68fe185cc04c5904aa104b0ba42e32
/src/game/BackLayer.cpp
dc1ea11a5662a855d29c532ab0af431d92b17c30
[]
no_license
dogtwelve/newsiderpg
e3f8284a7cd9938156ef8d683dca7bcbd928c593
303566a034dca3e66cf0f29cf9eaea1d54d63e4a
refs/heads/master
2021-01-10T13:03:31.986204
2010-06-27T05:36:33
2010-06-27T05:36:33
46,550,247
0
1
null
null
null
null
UHC
C++
false
false
6,554
cpp
#include "BackLayer.h" //-------------------------------------------------------------------------- BackLayer::BackLayer() //-------------------------------------------------------------------------- { pObjectList = GL_NEW List2<BackLayerObject*>(); m_nLayerSizeX = 0; m_nBaseYLine = 0; } //-------------------------------------------------------------------------- BackLayer::~BackLayer() //-------------------------------------------------------------------------- { InitList(pObjectList); while(NotEndList(pObjectList)) { SUTIL_FreeSpriteInstance(GetData(pObjectList)->pAsIns); SAFE_DELETE(GetData(pObjectList)); pObjectList->Delete(); } SAFE_DELETE(pObjectList); } //-------------------------------------------------------------------------- void BackLayer::InsertObject(BackLayerObject* pBackObject) // ์˜ค๋ธŒ์ ํŠธ๋ฅผ ์ถ”๊ฐ€์‹œํ‚จ๋‹ค. //-------------------------------------------------------------------------- { /* InitList(pObjectList); if(0 == GetNodeCount(pObjectList)) { pObjectList->Insert_prev(pBackObject); return; } while(NotEndList(pObjectList)) { if(GetData(pObjectList)->x > pBackObject->x) { pObjectList->Insert_prev(pBackObject); return; } MoveNext(pObjectList); } pObjectList->Insert_prev(pBackObject); */ MoveTail(pObjectList); pObjectList->Insert_prev(pBackObject); } //-------------------------------------------------------------------------- void BackLayer::Process() //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- void BackLayer::Paint() //-------------------------------------------------------------------------- { int nTmpXAddAngle = m_nMyAngleX; nTmpXAddAngle %= m_nLayerSizeX; nTmpXAddAngle *= (-1); while(1) { InitList(pObjectList); while(NotEndList(pObjectList)) { // ํƒ€์ž…์€ ๊ณ ์œ  ์ธ๋ฑ์Šค์ด๋‹ค. // if() // ์ด๋ฏธ์ง€๊ฐ€ ํ™”๋ฉด์˜ ์™ผ์ชฝ๋ณด๋‹ค ์ž‘์œผ๋ฉด ๊ทธ๋ฆฌ์ง€ ์•Š๋Š”๋‹ค. if(0 < (GetData(pObjectList)->endx + nTmpXAddAngle)) //if(0 < (GetData(pObjectList)->x + nTmpXAddAngle + GetData(pObjectList)->width)) { // ์ด๋ฏธ์ง€๊ฐ€ ํ™”๋ฉด์˜ ์˜ค๋ฅธ์ชฝ๋ณด๋‹ค ํฌ๋ฉด ๊ทธ๋ฆฌ์ง€ ์•Š๋Š”๋‹ค. if(SCREEN_WIDTH > (GetData(pObjectList)->startx + nTmpXAddAngle)) { if(1 == GetData(pObjectList)->drawtype) {SUTIL_UpdateTimeAsprite(GetData(pObjectList)->pAsIns);} SUTIL_SetXPosAsprite(GetData(pObjectList)->pAsIns, GetData(pObjectList)->x); SUTIL_SetYPosAsprite(GetData(pObjectList)->pAsIns, GetData(pObjectList)->y); SUTIL_SetZPosAsprite(GetData(pObjectList)->pAsIns, GetData(pObjectList)->z); GetData(pObjectList)->pAsIns->CameraX = nTmpXAddAngle; SUTIL_PaintAsprite(GetData(pObjectList)->pAsIns,S_NOT_INCLUDE_SORT); } } MoveNext(pObjectList); } nTmpXAddAngle += m_nLayerSizeX; if(SCREEN_WIDTH < nTmpXAddAngle){return;} } } //-------------------------------------------------------------------------- void BackLayer::SetAngle(int xAngle) //-------------------------------------------------------------------------- { m_nMyAngleX = xAngle * m_nMoveRate / 100; } //-------------------------------------------------------------------------- void BackLayer::LoadMapLayer(ASprite** pASprite, char* packName, int packIndex) //-------------------------------------------------------------------------- { BackLayerObject* pBackObject = NULL; int tmpsprid = 0; SUTIL_Data_init(packName); SUTIL_Data_open(packIndex); int AsframeNum = 0; int tmpId = 0; ASprite* tmpASprite; while(1) { SUTIL_Data_readU8(); // 0x08 ์ฝ๊ณ  ๋ฒ„๋ฆฐ๋‹ค. tmpId = (short)SUTIL_Data_readU16(); if(1 == tmpId) // ๋งˆ์ง€๋ง‰ ๋ฐ์ดํƒ€ { m_nLayerSizeX += (short)SUTIL_Data_readU16(); break; } else if(2 == tmpId || 3 == tmpId) // ์ž„์‹œ๊ฐ’ ๊ทธ๋ƒฅ ํ˜๋Ÿฌ๊ฐ„๋‹ค. { } else if(11 == tmpId) // ๋ž™ํŠธ๋ฅผ ๊ทธ๋ ค์•ผ ํ•œ๋‹ค. { (short)SUTIL_Data_readU16(); // x (short)SUTIL_Data_readU16(); // y (short)SUTIL_Data_readU16(); // ๊ณ ์œ  ํƒ€์ž… (short)SUTIL_Data_readU16(); // draw type // 0์ด๋ฉด frame, 1์ด๋ฉด animation (short)SUTIL_Data_readU16(); // draw num (short)SUTIL_Data_readU16(); // ์ž„์‹œ3 ์ฝ๊ณ  ๋ฒ„๋ฆฐ๋‹ค. (short)SUTIL_Data_readU16(); // ์ž„์‹œ3 ์ฝ๊ณ  ๋ฒ„๋ฆฐ๋‹ค. continue; } else { if(100 <= tmpId) //ํ˜„์žฌ ์˜ค๋ธŒ์ ํŠธ์˜ ์Šคํ”„๋ผ์ดํŠธ ๋„˜๋ฒ„๊ฐ’์„ ์•Œ๋ ค์ค€๋‹ค. { tmpsprid = (tmpId-100)/100; tmpASprite = pASprite[tmpsprid]; } } pBackObject = GL_NEW BackLayerObject(); pBackObject->x = (short)SUTIL_Data_readU16(); // x pBackObject->y = (short)SUTIL_Data_readU16(); // y (short)SUTIL_Data_readU16(); // ์ฝ๊ณ  ๋ฒ„๋ฆฐ๋‹ค. pBackObject->type = (short)SUTIL_Data_readU16(); // ๊ณ ์œ  ํƒ€์ž… pBackObject->drawtype = (short)SUTIL_Data_readU16(); // draw type // 0์ด๋ฉด frame, 1์ด๋ฉด animation AsframeNum = (short)SUTIL_Data_readU16(); // draw num (short)SUTIL_Data_readU16(); // ์ž„์‹œ3 ์ฝ๊ณ  ๋ฒ„๋ฆฐ๋‹ค. pBackObject->spridx = tmpsprid; pBackObject->pAsIns = GL_NEW ASpriteInstance(tmpASprite, 0, 0, NULL); pBackObject->pAsIns->SetAniMoveLock(true); if(0 == pBackObject->drawtype) {SUTIL_SetTypeFrameAsprite(pBackObject->pAsIns, AsframeNum);} else if(1 == pBackObject->drawtype) { SUTIL_SetTypeAniAsprite(pBackObject->pAsIns, AsframeNum); SUTIL_SetLoopAsprite(pBackObject->pAsIns, true); } // pBackObject->adjustx = tmpASprite->GetFrameX(AsframeNum); // pBackObject->width = tmpASprite->GetFrameWidth(AsframeNum); pBackObject->x += m_nLayerSizeX; pBackObject->y += m_nBaseYLine; // pBackObject->x += pBackObject->adjustx; pBackObject->z = 0; pBackObject->startx = pBackObject->x + tmpASprite->GetFrameX(AsframeNum); pBackObject->endx = pBackObject->startx + tmpASprite->GetFrameWidth(AsframeNum); InsertObject(pBackObject); } SUTIL_Data_free(); } //-------------------------------------------------------------------------- void BackLayer::RematchImage(class ASprite** pAsprite) //-------------------------------------------------------------------------- { for(InitList(pObjectList);NotEndList(pObjectList);MoveNext(pObjectList)) { GetData(pObjectList)->pAsIns->m_sprite = pAsprite[GetData(pObjectList)->spridx]; } }
[ [ [ 1, 209 ] ] ]
ddeb16fba2af66d939b5c79df8c78e237ecbcae5
6e563096253fe45a51956dde69e96c73c5ed3c18
/os/AX_Thread_Guard.h
65ec7d11071d150765209e759a22dd3b406d6432
[]
no_license
15831944/phoebemail
0931b76a5c52324669f902176c8477e3bd69f9b1
e10140c36153aa00d0251f94bde576c16cab61bd
refs/heads/master
2023-03-16T00:47:40.484758
2010-10-11T02:31:02
2010-10-11T02:31:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,897
h
#ifndef _AX_THREAD_GUARD #define _AX_THREAD_GUARD #include "AX_OS.h" template <class AX_LOCK> class AX_Guard { public: // = Initialization and termination methods. AX_Guard (AX_LOCK &l); /// Implicitly and automatically acquire (or try to acquire) the /// lock. If @a block is non-0 then <acquire> the <ACE_LOCK>, else /// <tryacquire> it. AX_Guard (AX_LOCK &l, int block); /// Initialise the guard without implicitly acquiring the lock. The /// <become_owner> parameter indicates whether the guard should release /// the lock implicitly on destruction. The <block> parameter is /// ignored and is used here to disambiguate with the preceding /// constructor. AX_Guard (AX_LOCK &l, int block, int become_owner); /// Implicitly release the lock. ~AX_Guard (void); // = Lock accessors. /// Explicitly acquire the lock. int acquire (void); /// Conditionally acquire the lock (i.e., won't block). int tryacquire (void); /// Explicitly release the lock, but only if it is held! int release (void); /// Relinquish ownership of the lock so that it is not released /// implicitly in the destructor. void disown (void); // = Utility methods. /// 1 if locked, 0 if couldn't acquire the lock /// (errno will contain the reason for this). int locked (void) const; /// Explicitly remove the lock. int remove (void); /// Dump the state of an object. void dump (void) const; // ACE_ALLOC_HOOK_DECLARE; // Declare the dynamic allocation hooks. protected: /// Helper, meant for subclass only. AX_Guard (AX_LOCK *lock): lock_ (lock) {} /// Pointer to the ACE_LOCK we're guarding. AX_LOCK *lock_; /// Keeps track of whether we acquired the lock or failed. int owner_; private: // = Prevent assignment and initialization. void operator= (const AX_Guard<AX_LOCK> &); AX_Guard (const AX_Guard<AX_LOCK> &); }; /** * @class ACE_Write_Guard * * @brief This class is similar to class ACE_Guard, though it * acquires/releases a write lock automatically (naturally, the * <ACE_LOCK> it is instantiated with must support the appropriate * API). */ template <class AX_LOCK> class AX_Write_Guard : public AX_Guard<AX_LOCK> { public: // = Initialization method. /// Implicitly and automatically acquire a write lock. AX_Write_Guard (AX_LOCK &m); /// Implicitly and automatically acquire (or try to acquire) a write /// lock. AX_Write_Guard (AX_LOCK &m, int block); // = Lock accessors. /// Explicitly acquire the write lock. int acquire_write (void); /// Explicitly acquire the write lock. int acquire (void); /// Conditionally acquire the write lock (i.e., won't block). int tryacquire_write (void); /// Conditionally acquire the write lock (i.e., won't block). int tryacquire (void); // = Utility methods. /// Dump the state of an object. void dump (void) const; // ACE_ALLOC_HOOK_DECLARE; // Declare the dynamic allocation hooks. }; template <class AX_LOCK> class AX_Read_Guard : public AX_Guard<AX_LOCK> { public: // = Initialization methods. /// Implicitly and automatically acquire a read lock. AX_Read_Guard (AX_LOCK& m); /// Implicitly and automatically acquire (or try to acquire) a read /// lock. AX_Read_Guard (AX_LOCK &m, int block); // = Lock accessors. /// Explicitly acquire the read lock. int acquire_read (void); /// Explicitly acquire the read lock. int acquire (void); /// Conditionally acquire the read lock (i.e., won't block). int tryacquire_read (void); /// Conditionally acquire the read lock (i.e., won't block). int tryacquire (void); // = Utility methods. /// Dump the state of an object. void dump (void) const; // ACE_ALLOC_HOOK_DECLARE; // Declare the dynamic allocation hooks. }; #include "AX_Thread_Guard.inl" #endif
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 154 ] ] ]
699fcf34f002f43e3f0afeb1fdde1288c61cf353
744e9a2bf1d0aee245c42ee145392d1f6a6f65c9
/tags/0.11.1-alpha/gui/ttcutccrwnd.cpp
3c7da97990adad46750d13c6fb68af416907ebcf
[]
no_license
BackupTheBerlios/ttcut-svn
2b5d00c3c6d16aa118b4a58c7d0702cfcc0b051a
958032e74e8bb144a96b6eb7e1d63bc8ae762096
refs/heads/master
2020-04-22T12:08:57.640316
2009-02-08T16:14:00
2009-02-08T16:14:00
40,747,642
0
0
null
null
null
null
UTF-8
C++
false
false
12,681
cpp
/*----------------------------------------------------------------------------*/ /* COPYRIGHT: TriTime (c) 2003/2005 / www.tritime.org */ /*----------------------------------------------------------------------------*/ /* PROJEKT : TTCUT 2005 */ /* FILE : ttcutchaptertab.cpp */ /*----------------------------------------------------------------------------*/ /* AUTHOR : b. altendorf (E-Mail: [email protected]) DATE: 03/10/2005 */ /* MODIFIED: b. altendorf DATE: 06/22/2005 */ /* MODIFIED: DATE: */ /*----------------------------------------------------------------------------*/ // ---------------------------------------------------------------------------- // TTCUTCHAPTERTAB // ---------------------------------------------------------------------------- /*----------------------------------------------------------------------------*/ /* 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 "ttcutccrwnd.h" #include "../common/ttmessagelogger.h" //Added by qt3to4: #include <QLabel> #include <QVBoxLayout> #include <QHBoxLayout> #include <QGridLayout> // ///////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // Tab widget for cut-, chapter- and result-tab // ----------------------------------------------------------------------------- // ///////////////////////////////////////////////////////////////////////////// // Constructor TTCutCCRWnd::TTCutCCRWnd( QWidget* parent, const char* name, Qt::WFlags fl ) :QTabWidget( parent, name, fl ) { // create the widget for the single tabs cutTab = new TTCutCutTab( 0, "CUT_TAB" ); chapterTab = new TTCutChapterTab( 0, "CHAPTER_TAB" ); resultTab = new TTCutResultTab( 0, "RESULT_TAB" ); // insert the tabs insertTab( cutTab, tr( "Cut list" ) ); insertTab( chapterTab, tr( "Chapter list" ) ); insertTab( resultTab, tr( "Result list" ) ); setTabIconSet( cutTab, QIcon( *(TTCut::imgCutAV) ) ); setTabIconSet( chapterTab, QIcon( *(TTCut::imgChapter) ) ); setTabIconSet( resultTab, QIcon( *(TTCut::imgClock) ) ); } // Destructor TTCutCCRWnd::~TTCutCCRWnd() { } // public methods // ----------------------------------------------------------------------------- TTCutCutTab* TTCutCCRWnd::getCutTab() { return cutTab; } TTCutListView* TTCutCCRWnd::getCutListView() { return cutTab->cutListView; } TTCutChapterTab* TTCutCCRWnd::getChapterTab() { return chapterTab; } TTCutResultTab* TTCutCCRWnd::getResultTab() { return resultTab; } // ///////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // Cut tab // ----------------------------------------------------------------------------- // ///////////////////////////////////////////////////////////////////////////// // Constructor TTCutCutTab::TTCutCutTab( QWidget* parent, const char* name, Qt::WFlags fl ) :QWidget( parent, name, fl ) { parentWnd = (TTCutCCRWnd*)parent; // images // -------------------------------------------------------------------------- // Grid-layout for the entire widget tabLayout = new QGridLayout( this ); tabLayout->setSpacing( 6 ); tabLayout->setMargin( 11 ); // HBox-layout for buttons and listview layoutH1 = new QHBoxLayout( 0, 0, 6, "layout32"); // VBox-layout for buttons layoutV1 = new QVBoxLayout( 0, 0, 6, "layout20"); // button cut "up" pbCutUp = new QPushButton( this, "pbCutUp" ); pbCutUp->setMinimumSize( QSize( 30, 20 ) ); pbCutUp->setMaximumSize( QSize( 30, 20 ) ); pbCutUp->setPixmap( *(TTCut::imgUpArrow) ); layoutV1->addWidget( pbCutUp ); // button cut "delete" pbCutDelete = new QPushButton( this, "pbCutDelete" ); pbCutDelete->setMinimumSize( QSize( 30, 20 ) ); pbCutDelete->setMaximumSize( QSize( 30, 20 ) ); pbCutDelete->setPixmap( *(TTCut::imgDelete) ); layoutV1->addWidget( pbCutDelete ); // button cut "down" pbCutDown = new QPushButton( this, "pbCutDown" ); pbCutDown->setMinimumSize( QSize( 30, 20 ) ); pbCutDown->setMaximumSize( QSize( 30, 20 ) ); pbCutDown->setPixmap( *(TTCut::imgDownArrow) ); layoutV1->addWidget( pbCutDown ); layoutH1->addLayout( layoutV1 ); // cut list-view cutListView = new TTCutListView( this, "listView2" ); cutListView->addColumn( tr( "Videofile" ) ); cutListView->addColumn( tr( "Start" ) ); cutListView->addColumn( tr( "End" ) ); layoutH1->addWidget( cutListView ); tabLayout->addLayout( layoutH1, 0, 0 ); } // Destructor TTCutCutTab::~TTCutCutTab() { } // ///////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // Chapter tab // ----------------------------------------------------------------------------- // ///////////////////////////////////////////////////////////////////////////// // Constructor TTCutChapterTab::TTCutChapterTab( QWidget* parent, const char* name, Qt::WFlags fl ) :QWidget( parent, name, fl ) { parentWnd = (TTCutCCRWnd*)parent; video_stream = (TTVideoStream*)NULL; // Grid-layout for the entire widget tabLayout = new QGridLayout( this ); tabLayout->setSpacing( 4 ); tabLayout->setMargin( 8 ); // listview for temporary chapters lvTempChapter = new Q3ListView( this, "lvTempChapter" ); lvTempChapter->addColumn( tr( "Temporal chapter" ) ); tabLayout->addMultiCellWidget( lvTempChapter, 0, 1, 1, 1 ); // listview for destiantion time-stamps lvDestTimeStamp = new Q3ListView( this, "lvDestTimeStamp" ); lvDestTimeStamp->addColumn( tr( "Destination time stamp" ) ); lvDestTimeStamp->addColumn( tr( "Source time stamp" ) ); lvDestTimeStamp->addColumn( tr( "Source videostream" ) ); tabLayout->addMultiCellWidget( lvDestTimeStamp, 0, 1, 3, 3 ); Layout5 = new QVBoxLayout; Layout5->setSpacing( 4 ); Layout5->setMargin( 0 ); // auto-create chapter laAutoCreate = new QLabel( this, "laAutoCreate" ); laAutoCreate->setText( tr( "Auto create \nchapters each" ) ); Layout5->addWidget( laAutoCreate ); Layout2 = new QHBoxLayout; Layout2->setSpacing( 6 ); Layout2->setMargin( 0 ); sbMinutes = new QSpinBox( this, "sbMinutes" ); Layout2->addWidget( sbMinutes ); laMinutes = new QLabel( this, "laMinutes" ); laMinutes->setText( tr( "minutes" ) ); Layout2->addWidget( laMinutes ); Layout5->addLayout( Layout2 ); btnApplyAutoCreate = new QPushButton( this, "btnApplyAutoCreate" ); btnApplyAutoCreate->setText( tr( "apply" ) ); btnApplyAutoCreate->setIconSet( QIcon( *(TTCut::imgApply) ) ); Layout5->addWidget( btnApplyAutoCreate ); tabLayout->addLayout( Layout5, 1, 4 ); Layout7 = new QVBoxLayout; Layout7->setSpacing( 6 ); Layout7->setMargin( 0 ); QSpacerItem* spacer_2 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Minimum ); Layout7->addItem( spacer_2 ); pbDelTimeStamp = new QPushButton( this, "pbDelTimeStamp" ); pbDelTimeStamp->setMaximumSize( QSize( 24, 24 ) ); pbDelTimeStamp->setText( tr( "PushButton8" ) ); pbDelTimeStamp->setIconSet( QIcon( *(TTCut::imgDelete) ) ); Layout7->addWidget( pbDelTimeStamp ); tabLayout->addMultiCellLayout( Layout7, 0, 1, 2, 2 ); Layout6 = new QVBoxLayout; Layout6->setSpacing( 6 ); Layout6->setMargin( 0 ); QSpacerItem* spacer_3 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding ); Layout6->addItem( spacer_3 ); pbDelTempChapter = new QPushButton( this, "pbDelTempChapter" ); pbDelTempChapter->setMaximumSize( QSize( 24, 24 ) ); pbDelTempChapter->setText( tr( "PushButton8" ) ); pbDelTempChapter->setIconSet( QIcon( *(TTCut::imgDelete) ) ); Layout6->addWidget( pbDelTempChapter ); tabLayout->addMultiCellLayout( Layout6, 0, 1, 0, 0 ); QSpacerItem* spacer_4 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding ); tabLayout->addItem( spacer_4, 0, 4 ); } // Destructor TTCutChapterTab::~TTCutChapterTab() { } void TTCutChapterTab::setVideoStream( TTVideoStream* v_stream ) { video_stream = v_stream; } // ///////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // Result tab // ----------------------------------------------------------------------------- // ///////////////////////////////////////////////////////////////////////////// // Constructor TTCutResultTab::TTCutResultTab( QWidget* parent, const char* name, Qt::WFlags fl ) :QWidget( parent, name, fl ) { parentWnd = (TTCutCCRWnd*)parent; video_stream = (TTVideoStream*)NULL; // main tab layout tabLayout = new QGridLayout( this ); tabLayout->setSpacing( 6 ); tabLayout->setMargin( 11 ); // result cut length listview lvResultLength = new Q3ListView( this, "lvResultLength" ); lvResultLength->addColumn( tr( "Stream type" ) ); lvResultLength->addColumn( tr( "Length" ) ); lvResultLength->addColumn( tr( "Size" ) ); tabLayout->addWidget( lvResultLength, 0, 0 ); QSpacerItem* spacer_5 = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum ); tabLayout->addItem( spacer_5, 0, 1 ); } // Destructor TTCutResultTab::~TTCutResultTab() { } void TTCutResultTab::setVideoStream( TTVideoStream* v_stream ) { video_stream = v_stream; } void TTCutResultTab::refreshCutVideoLength( uint v_length, off64_t v_size ) { QString stream_type; QString length_time; QString length_size; QString sz_temp; double res_size; clearList(); if ( ttAssigned( video_stream ) ) { stream_type = "video"; length_time = ttFramesToTime( v_length, video_stream->frameRate() ).toString("hh:mm:ss"); sz_temp.sprintf( "(%d)",v_length ); length_time += sz_temp; res_size = 0.0; length_size = "n.n"; // size in bytes if ( v_size < (off64_t)1024 ) { res_size = (double)v_size; length_size.sprintf( "%6.2lf bytes", res_size ); } // size in kb else if ( v_size >= (off64_t)1024 && v_size < (off64_t)(1024*1024) ) { res_size = (double)v_size / (double)1024.0; length_size.sprintf( "%6.2lf kb", res_size ); } // size in mb else { res_size = (double)v_size / (double)(1024.0*1024.0); length_size.sprintf( "%6.2lf mb", res_size ); } // TODO: why is this here ???? TTMessageLogger* log = TTMessageLogger::getInstance(); log->debugMsg("TTCUTCCRWND", "unused listItem ????"); //Q3ListViewItem* listItem = new Q3ListViewItem( lvResultLength, lvResultLength->lastItem(), // stream_type, // length_time, // length_size ); } } void TTCutResultTab::clearList() { //list-view iterator Q3ListViewItemIterator cutIt( lvResultLength ); // iterate trough the list while ( cutIt.current() ) { delete cutIt.current(); } }
[ "tritime@7763a927-590e-0410-8f7f-dbc853b76eaa" ]
[ [ [ 1, 377 ] ] ]
56abbb0d8c28e7ab168c0f32e36f969c02908444
6477cf9ac119fe17d2c410ff3d8da60656179e3b
/Projects/MotoDesk/BaseDlg.cpp
22f5f4aa71f4fb000d964dee05d88a2ff4f5d4a9
[]
no_license
crutchwalkfactory/motocakerteam
1cce9f850d2c84faebfc87d0adbfdd23472d9f08
0747624a575fb41db53506379692973e5998f8fe
refs/heads/master
2021-01-10T12:41:59.321840
2010-12-13T18:19:27
2010-12-13T18:19:27
46,494,539
0
0
null
null
null
null
UTF-8
C++
false
false
967
cpp
// // C++ Implementation: BaseDlg // // Description: // // // Author: root <root@andLinux>, (C) 2008 // // Copyright: See COPYING file that comes with this distribution // // #include "BaseDlg.h" #include <ZApplication.h> #include <ZSoftKey.h> #include <ezxres.h> MyBaseDlg::MyBaseDlg() :ZKbMainWidget( ZHeader::FULL_TYPE, NULL, "ZMainWidget", WType_Modal | WType_TopLevel ) { myInLoop = false; } MyBaseDlg::~MyBaseDlg() { } int MyBaseDlg::exec() { setResult(0); //RES_ICON_Reader iconReader; //QPixmap f1; //f1 = QPixmap( iconReader.getIcon("fsba01_bg", false)); //setScreenFSBA( f1 , 100, (PIXMAP_STRETCH_POLICY_E)0); show(); myInLoop = TRUE; qApp->enter_loop(); return result(); } void MyBaseDlg::done( int r ) { hide(); if (myInLoop) { qApp->exit_loop(); } setResult(r); if ( qApp->mainWidget() == this ) qApp->quit(); } void MyBaseDlg::accept() { done(Accepted); } void MyBaseDlg::reject() { done(Rejected); }
[ [ [ 1, 60 ] ] ]
af14f2acd1b9953936c0d7fd43ba799bcf5bdec8
3bf3c2da2fd334599a80aa09420dbe4c187e71a0
/textures.cpp
0eefeea2b265f273e703082243b4951fce3340d4
[]
no_license
xiongchiamiov/virus-td
31b88f6a5d156a7b7ee076df55ddce4e1c65ca4f
a7b24ce50d07388018f82d00469cb331275f429b
refs/heads/master
2020-12-24T16:50:11.991795
2010-06-10T05:05:48
2010-06-10T05:05:48
668,821
1
0
null
null
null
null
UTF-8
C++
false
false
7,146
cpp
#include "textures.h" Image *TextureImage; GLuint curTexId = 1; GLuint LoadMipMapTexture(char* image_file) { TextureImage = (Image *) malloc(sizeof(Image)); if (TextureImage == NULL) { printf("Error allocating space for image"); //exit(1); } cout << "trying to load " << image_file << endl; if (!ImageLoad(image_file, TextureImage)) { //exit(1); } /* 2d texture, level of detail 0 (normal), 3 components (red, green, blue), */ /* x size from image, y size from image, */ /* border 0 (normal), rgb color data, unsigned byte data, data */ glBindTexture(GL_TEXTURE_2D, curTexId); gluBuild2DMipmaps(GL_TEXTURE_2D, 3, TextureImage->sizeX, TextureImage->sizeY, GL_RGB, GL_UNSIGNED_BYTE, TextureImage->data); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR_MIPMAP_NEAREST); /* cheap scaling when image bigger than texture */ glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); /* cheap scaling when image smalled than texture*/ return curTexId++; } GLuint LoadRepeatMipMapTexture(char* image_file) { TextureImage = (Image *) malloc(sizeof(Image)); if (TextureImage == NULL) { printf("Error allocating space for image"); //exit(1); } cout << "trying to load " << image_file << endl; if (!ImageLoad(image_file, TextureImage)) { //exit(1); } /* 2d texture, level of detail 0 (normal), 3 components (red, green, blue), */ /* x size from image, y size from image, */ /* border 0 (normal), rgb color data, unsigned byte data, data */ glBindTexture(GL_TEXTURE_2D, curTexId); gluBuild2DMipmaps(GL_TEXTURE_2D, 3, TextureImage->sizeX, TextureImage->sizeY, GL_RGB, GL_UNSIGNED_BYTE, TextureImage->data); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR_MIPMAP_NEAREST); /* cheap scaling when image bigger than texture */ glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); /* cheap scaling when image smalled than texture*/ glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); return curTexId++; } GLuint LoadTexture(char* image_file) { TextureImage = (Image *) malloc(sizeof(Image)); if (TextureImage == NULL) { printf("Error allocating space for image"); //exit(1); } cout << "trying to load " << image_file << endl; if (!ImageLoad(image_file, TextureImage)) { //exit(1); } /* 2d texture, level of detail 0 (normal), 3 components (red, green, blue), */ /* x size from image, y size from image, */ /* border 0 (normal), rgb color data, unsigned byte data, data */ glBindTexture(GL_TEXTURE_2D, curTexId); glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage->sizeX, TextureImage->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage->data); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); /* cheap scaling when image bigger than texture */ glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); /* cheap scaling when image smalled than texture*/ return curTexId++; } GLuint LoadHQTexture(char* image_file) { TextureImage = (Image *) malloc(sizeof(Image)); if (TextureImage == NULL) { printf("Error allocating space for image"); //exit(1); } cout << "trying to load " << image_file << endl; if (!ImageLoad(image_file, TextureImage)) { //exit(1); } /* 2d texture, level of detail 0 (normal), 3 components (red, green, blue), */ /* x size from image, y size from image, */ /* border 0 (normal), rgb color data, unsigned byte data, data */ glBindTexture(GL_TEXTURE_2D, curTexId); glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage->sizeX, TextureImage->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage->data); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); /* cheap scaling when image bigger than texture */ glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); /* cheap scaling when image smalled than texture*/ return curTexId++; } /* BMP file loader loads a 24-bit bmp file only */ /* * getint and getshort are help functions to load the bitmap byte by byte */ static unsigned int getint(FILE *fp) { int c, c1, c2, c3; /* get 4 bytes */ c = getc(fp); c1 = getc(fp); c2 = getc(fp); c3 = getc(fp); return ((unsigned int) c) + (((unsigned int) c1) << 8) + (((unsigned int) c2) << 16) + (((unsigned int) c3) << 24); } static unsigned int getshort(FILE *fp){ int c, c1; /* get 2 bytes*/ c = getc(fp); c1 = getc(fp); return ((unsigned int) c) + (((unsigned int) c1) << 8); } /* quick and dirty bitmap loader...for 24 bit bitmaps with 1 plane only. */ int ImageLoad(char *filename, Image *image) { FILE *file; unsigned long size; /* size of the image in bytes. */ unsigned long i; /* standard counter. */ unsigned short int planes; /* number of planes in image (must be 1) */ unsigned short int bpp; /* number of bits per pixel (must be 24) */ char temp; /* used to convert bgr to rgb color. */ /* make sure the file is there. */ if ((file = fopen(filename, "rb"))==NULL) { printf("File Not Found : %s\n",filename); return 0; } /* seek through the bmp header, up to the width height: */ fseek(file, 18, SEEK_CUR); /* No 100% errorchecking anymore!!! */ /* read the width */ image->sizeX = getint (file); /* read the height */ image->sizeY = getint (file); /* calculate the size (assuming 24 bits or 3 bytes per pixel). */ size = image->sizeX * image->sizeY * 3; /* read the planes */ planes = getshort(file); if (planes != 1) { printf("Planes from %s is not 1: %u\n", filename, planes); return 0; } /* read the bpp */ bpp = getshort(file); if (bpp != 24) { printf("Bpp from %s is not 24: %u\n", filename, bpp); return 0; } /* seek past the rest of the bitmap header. */ fseek(file, 24, SEEK_CUR); /* read the data. */ image->data = (char *) malloc(size); if (image->data == NULL) { printf("Error allocating memory for color-corrected image data"); return 0; } if ((i = fread(image->data, size, 1, file)) != 1) { printf("Error reading image data from %s.\n", filename); return 0; } for (i=0;i<size;i+=3) { /* reverse all of the colors. (bgr -> rgb) */ temp = image->data[i]; image->data[i] = image->data[i+2]; image->data[i+2] = temp; } fclose(file); /* Close the file and release the filedes */ /* we're done. */ return 1; }
[ "tcasella@05766cc9-4f33-4ba7-801d-bd015708efd9", "jlangloi@05766cc9-4f33-4ba7-801d-bd015708efd9" ]
[ [ [ 1, 56 ], [ 58, 60 ], [ 62, 197 ] ], [ [ 57, 57 ], [ 61, 61 ] ] ]
47c402ac9df43fb9ee25b55cfe858a16739bf97e
b8ac0bb1d1731d074b7a3cbebccc283529b750d4
/Code/controllers/OdometryCalibration/robotapi/webts/WebotsTrashBin.cpp
d89bb8001ed0f696647818880280ec69cded9ec8
[]
no_license
dh-04/tpf-robotica
5efbac38d59fda0271ac4639ea7b3b4129c28d82
10a7f4113d5a38dc0568996edebba91f672786e9
refs/heads/master
2022-12-10T18:19:22.428435
2010-11-05T02:42:29
2010-11-05T02:42:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
549
cpp
#include "WebotsTrashBin.h" namespace robotapi { namespace webts { WebotsTrashBin::WebotsTrashBin( webots::TouchSensor & ts ) : WebotsDevice ( ts ){ this->myts = &ts; } int WebotsTrashBin::enable(int ms){ return 0; } int WebotsTrashBin::disable(){ return 0; } int WebotsTrashBin::getValue(){ return 0; } bool WebotsTrashBin::isFull(){ return false; } void WebotsTrashBin::setFullBias(double bias){ return; } } /* End of namespace robotapi::webts */ } /* End of namespace robotapi */
[ "guicamest@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a" ]
[ [ [ 1, 31 ] ] ]
5ce227e79d4acd31bc854b825ed242d59ed0f0b6
ca2395f4eec7e941d0d91d7e2913f8cc66b14472
/Net.cpp
6475f165856736d2e591046c55ca15dfb92b51cd
[]
no_license
EmilHernvall/chatclient
21a27de2e44bb25dd2acb34a8d75a79d8e7bd46a
47e16866992e4dd4ce3e5538b32b09ed2dfaef06
refs/heads/master
2021-01-15T22:28:44.465662
2008-04-16T16:12:48
2008-04-16T16:12:48
1,697,523
0
0
null
null
null
null
UTF-8
C++
false
false
3,095
cpp
#include "stdafx.h" #include "Chatclient.h" #include "String.h" #include "Net.h" BOOL Net::Initialize() { // Winsock variables WORD wVersionRequested; WSADATA wsaData; INT nErr; // Initialize winsock wVersionRequested = MAKEWORD(2, 2); nErr = WSAStartup(wVersionRequested, &wsaData); if (nErr != 0) { MessageBox(NULL, TEXT("Your system doesn't support the required Winsock Version!"), TEXT("Winsock Error!"), MB_ICONEXCLAMATION); return FALSE; } if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { WSACleanup(); MessageBox(NULL, TEXT("Your system doesn't support the required Winsock Version!"), TEXT("Winsock Error!"), MB_ICONEXCLAMATION); return FALSE; } return TRUE; } VOID Net::CleanUp() { WSACleanup(); } Net::Net() { m_bConnected = FALSE; m_bConnected = FALSE; } BOOL Net::Connect(LPTSTR szHost, WORD wPort) { struct sockaddr_in ClientSAddr; INT nConVal; CHAR szAsciiHost[50]; m_szHost = szHost; m_wPort = wPort; WideCharToMultiByte(CP_ACP, 0, szHost, -1, szAsciiHost, sizeof(szAsciiHost)-1, NULL, NULL); m_sock = socket(AF_INET, SOCK_STREAM, 0); // Do a dns lookup for the provided address. struct addrinfo* info; if (getaddrinfo(szAsciiHost, NULL, NULL, &info) != 0) { return FALSE; } memset (&ClientSAddr, 0, sizeof(struct sockaddr)); ClientSAddr.sin_family = AF_INET; ClientSAddr.sin_addr.s_addr = ((struct sockaddr_in*)info->ai_addr)->sin_addr.s_addr; //inet_addr(host); ClientSAddr.sin_port = htons((u_short)wPort); nConVal = connect(m_sock, (struct sockaddr*)&ClientSAddr, sizeof(struct sockaddr)); if (nConVal != 0) { return false; } m_bConnected = TRUE; return TRUE; } VOID Net::Disconnect() { shutdown(m_sock, SD_BOTH); closesocket(m_sock); m_bConnected = FALSE; } INT Net::Write(LPTSTR szData) { int sent; LPCSTR szBuffer = wcToMb(szData); sent = send(m_sock, szBuffer, strlen(szBuffer), 0); send(m_sock, "\r\n", 2, 0); free((VOID*)szBuffer); return sent; } INT Net::Read(LPTSTR* ret) { CHAR byte = 0, lastbyte = 0; PCHAR buf; INT buf_size = (32 * sizeof(CHAR)), r = 0, totalread = 0, wcLen; LPWSTR szOut; buf = (PCHAR)malloc(buf_size); memset(buf, 0, buf_size); while (TRUE) { if (totalread + sizeof(CHAR) >= buf_size) { buf_size *= 2; buf = (PCHAR)realloc(buf, buf_size); } r = recv(m_sock, &byte, sizeof(CHAR), 0); if (r == 0 || r == -1) { break; } if (byte == 10 && lastbyte == 13) { buf[totalread-1] = 0; break; } else { buf[totalread] = byte; } totalread += r; lastbyte = byte; //Sleep(10); } wcLen = MultiByteToWideChar(CP_ACP, 0, buf, strlen(buf)+1, NULL, 0); szOut = (LPWSTR)malloc((wcLen+1) * sizeof(WCHAR)); MultiByteToWideChar(CP_ACP, 0, buf, strlen(buf)+1, szOut, wcLen); *ret = szOut; return wcLen; }
[ "emil@2d89dd5f-9cc0-461d-8d4c-555c0e271dc8" ]
[ [ [ 1, 144 ] ] ]
8cde57ab437a1cf59cff513864cfd4a08641d868
2b80036db6f86012afcc7bc55431355fc3234058
/src/cube/BrowseView.cpp
bd0bb27db4e304a0f8c7e45f14b4c46cab30fd39
[ "BSD-3-Clause" ]
permissive
leezhongshan/musikcube
d1e09cf263854bb16acbde707cb6c18b09a0189f
e7ca6a5515a5f5e8e499bbdd158e5cb406fda948
refs/heads/master
2021-01-15T11:45:29.512171
2011-02-25T14:09:21
2011-02-25T14:09:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,218
cpp
////////////////////////////////////////////////////////////////////////////// // // License Agreement: // // The following are Copyright 2007, Casey Langen // // Sources and Binaries of: mC2, win32cpp // // 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 other 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 "pch.hpp" #include <cube/BrowseView.hpp> #include <cube/TracklistView.hpp> #include <win32cpp/ListView.hpp> #include <win32cpp/Splitter.hpp> #include <win32cpp/LinearLayout.hpp> ////////////////////////////////////////////////////////////////////////////// using namespace musik::cube; ////////////////////////////////////////////////////////////////////////////// /*ctor*/ BrowseView::BrowseView() { } void BrowseView::OnCreated() { this->filterViewLayout = new LinearLayout(win32cpp::HorizontalLayout,win32cpp::LayoutFillFill); this->tracklistView = new TracklistView(); mainVSplitter = new Splitter( SplitRow, this->filterViewLayout, this->tracklistView); this->AddMetadataFilter(_T("genre")); this->AddMetadataFilter(_T("artist")); this->AddMetadataFilter(_T("album")); this->AddChild(mainVSplitter); mainVSplitter->SetAnchor(AnchorTop); mainVSplitter->SetAnchorSize(100); } void BrowseView::AddMetadataFilter(const uistring& metadataKey) { ListView* listView = new ListView(); listView->SetLayoutFlags(win32cpp::LayoutFillFill); this->filterViews.push_back(listView); this->filterKeyMap[listView] = metadataKey; this->filterViewLayout->AddChild(listView); }
[ "onnerby@6a861d04-ae47-0410-a6da-2d49beace72e", "[email protected]@6a861d04-ae47-0410-a6da-2d49beace72e", "[email protected]@6a861d04-ae47-0410-a6da-2d49beace72e" ]
[ [ [ 1, 4 ], [ 6, 44 ], [ 46, 58 ], [ 60, 66 ], [ 70, 78 ], [ 80, 84 ] ], [ [ 5, 5 ], [ 45, 45 ], [ 59, 59 ], [ 79, 79 ] ], [ [ 67, 69 ] ] ]
e15772ad44c3f9c3ed8402dac405c16ff0baf3f1
48ab31a0a6a8605d57b5e140309c910f46eb5b35
/Root/Implementation/BerkeleyDatabase/BerkeleyDatabase.h
9f6fc1f2e77d484518ea61a553647f98916ee428
[]
no_license
firebreath/indexeddb
4c3106027a70e233eb0f91c6e0b5d60847d75800
50136d2fadced369788a42d249157b8a0d06eb88
refs/heads/master
2023-08-31T11:28:42.664028
2011-01-03T23:29:46
2011-01-03T23:29:46
1,218,008
2
1
null
null
null
null
UTF-8
C++
false
false
2,433
h
/**********************************************************\ Copyright Brandon Haynes http://code.google.com/p/indexeddb GNU Lesser General Public License \**********************************************************/ #ifndef BRANDONHAYNES_INDEXEDDB_IMPLEMENTATION_BERKELEYDB_BERKELEYDATABASE_H #define BRANDONHAYNES_INDEXEDDB_IMPLEMENTATION_BERKELEYDB_BERKELEYDATABASE_H #include <string> #include <db_cxx.h> #include "../Database.h" #include "../Transaction.h" namespace BrandonHaynes { namespace IndexedDB { namespace Implementation { class ObjectStore; class Key; class Data; namespace BerkeleyDB { class BerkeleyDeadlockDetection; ///<summary> /// This class represents a Indexed Database API database implementation (which is represented, confusingly, /// by a Berkeley DB environment). ///</summary> class BerkeleyDatabase : public Database { public: BerkeleyDatabase(const std::string& origin, const std::string& name, const std::string& description, const bool modifyDatabase); virtual ~BerkeleyDatabase(void); virtual void removeObjectStore(const std::string& objectStoreName, TransactionContext& transactionContext); virtual ObjectStore& getMetadata() { return *metadata; } // Utility methods to convert between the implementation-exposing Data/Key objects and underlying // BerkeleyDB Dbts. Used by most of the other Berkeley DB implementation classes. static Dbt ToDbt(const Data& data); static Data ToData(const Dbt& dbt); static Key ToKey(const Dbt& key); // Not a fan of exposing the environment in this way, but otherwise we'd need several friends. DbEnv& getEnvironment() { return environment; } private: DbEnv environment; // Managed thread associated with this environment to detect lock and transaction timeouts std::auto_ptr<BerkeleyDeadlockDetection> deadlockDetection; // An object store containing metdata for this environment std::auto_ptr<ObjectStore> metadata; const std::string origin; const std::string name; // An fixed suffix for metadatabase naming (e.g. "__metadata") static const std::string metadataDatabaseSuffix; // Empty implementation; set a breakpoint here for debugging. static void errorHandler(const DbEnv *environment, const char *errpfx, const char *message); }; } } } } #endif
[ [ [ 1, 72 ] ] ]
087971935bbefe710a12bf0116b339c51d28e1a5
2d212a074917aad8c57ed585e6ce8e2073aa06c6
/cgworkshop/src/fe/FeatureExtraction.h
47c675ad61b5774c05116d5cf1e23c060a178217
[]
no_license
morsela/cgworkshop
b31c9ec39419edcedfaed81468c923436528e538
cdf9ef2a9b2d9c389279fe0e38fb9c8bc1d86d89
refs/heads/master
2021-07-29T01:37:24.739450
2007-09-09T13:44:54
2007-09-09T13:44:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,833
h
#ifndef __FEATURE_EXTRACTION_H__ #define __FEATURE_EXTRACTION_H__ #include <stdio.h> #include <cv.h> #include <cxcore.h> #include <highgui.h> #define COLOR_CHANNEL_NUM 3 #define TEXTURE_CHANNEL_NUM 3 class CFeatureExtraction { public: CFeatureExtraction(IplImage * pSrcImg); virtual ~CFeatureExtraction(); bool Run(); public: CvMat ** GetColorChannelsArr() { return m_pColorChannelsArr; } CvMat ** GetTextureChannelsArr() { return m_pTextureChannelsArr; } CvMat * GetColorChannels() { return m_pColorChannels; } CvMat * GetTextureChannels() { return m_pTextureChannels; } CvMat * GetPrincipalChannels() { return m_pPrincipalChannels; } protected: bool GetColorChannels(CvMat * pChannels, CvMat * pColorChannelsArr[]); bool GetTextureChannels(CvMat * pChannels, CvMat * pTextureChannelsArr[]); bool GetGaborResponse(CvMat * pGaborMat); bool GetGaborResponse(IplImage *pGrayImg, IplImage *pResImg, float orientation, float freq, float sx, float sy); void CalcHistogram(IplImage * pImg, CvMat * pHistogram); bool GetChannels(CvMat * pMergedMat, CvMat * pChannels[], int nTotalChans, int nExtractChans); bool DoPCA(CvMat * pMat, CvMat * pResultMat, int nSize, int nExpectedSize); bool CFeatureExtraction::MergeMatrices(CvMat * pMatrix1, CvMat * pMatrix2, CvMat * pMatrix3, CvMat * pResultMat); bool MergeMatrices(CvMat * pMatrix1, CvMat * pMatrix2, CvMat * pResultMat); protected: IplImage * m_pSrcImg; IplImage * m_pSrcImgFloat; int m_nWidth; int m_nHeight; int m_nChannels; CvMat * m_pColorChannelsArr[COLOR_CHANNEL_NUM]; CvMat * m_pTextureChannelsArr[TEXTURE_CHANNEL_NUM]; CvMat * m_pColorChannels; CvMat * m_pTextureChannels; CvMat * m_pPrincipalChannels; }; #endif // __FEATURE_EXTRACTION_H__
[ "ikirsh@60b542fb-872c-0410-bfbb-43802cb78f6e", "morsela@60b542fb-872c-0410-bfbb-43802cb78f6e" ]
[ [ [ 1, 7 ], [ 11, 15 ], [ 18, 18 ], [ 21, 27 ], [ 31, 43 ], [ 46, 52 ], [ 54, 64 ] ], [ [ 8, 10 ], [ 16, 17 ], [ 19, 20 ], [ 28, 30 ], [ 44, 45 ], [ 53, 53 ] ] ]
91ed26b26979e675debc33c74a1f3ad145d81a87
8b3186e126ac2d19675dc19dd473785de97068d2
/bmt_prod/core/texturehandler.cpp
a6d23c09c787b9077574bff3e505c83f97b94c0e
[]
no_license
leavittx/revenge
e1fd7d6cd1f4a1fb1f7a98de5d16817a0c93da47
3389148f82e6434f0619df47c076c60c8647ed86
refs/heads/master
2021-01-01T17:28:26.539974
2011-08-25T20:25:14
2011-08-25T20:25:14
618,159
2
0
null
null
null
null
UTF-8
C++
false
false
13,141
cpp
#include "texturehandler.h" #ifndef _WIN32 #include <libgen.h> #endif TextureHandler::TextureHandler() { } TextureHandler::~TextureHandler() { } void TextureHandler::init() { g_debug << "starting up FBO manager" << endl; m_FBO = new FBOManager(); m_FBO->init(); for (int i = 0; i < MAX_TEXTURES; i++) { m_lastBoundTexture[i] = "no texture"; } } void TextureHandler::clear() { map<string, Image*>::iterator it; for (it = m_images.begin(); it != m_images.end(); it++) { Image *i = (*it).second; i->releaseData(); delete i; } m_images.clear(); m_textures.clear(); for (int i = 0; i < MAX_TEXTURES; i++) { m_lastBoundTexture[i] = "no texture"; } } void TextureHandler::addTextureParameters(string name, TextureParameters* params) { m_textureParameters[name] = params; } void TextureHandler::addImage(string name, Image *image) { m_images[name] = image; } void TextureHandler::bindTexture(string name, int texunit) { glDisable(GL_COLOR_MATERIAL); glDisable(GL_LIGHTING); // glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); glDisable(GL_ALPHA_TEST); glDisable(GL_STENCIL_TEST); glColor3f(1,1,1); #if 0 if (name == "0.png") { int width = 512, height = 512; static unsigned int textureID; static unsigned int *data = new unsigned int[width*height]; if (data[0] != 4278418111) { for (int i = 0; i < width*height; i++) { unsigned int val = (rand()%255) + ((rand()%255) << 8) + ((rand()%255) << 16) + (0xFF << 24); data[i] = val; } data[0] = 4278418111; glGenTextures(1, &textureID); // glBindTexture(GL_TEXTURE_2D, textureID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); // glGenTextures(1, &textureID); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glActiveTexture(textureID); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, textureID); } return; } #endif int texunitoffset = texunit - GL_TEXTURE0_ARB; if (texunitoffset < 0 || texunitoffset > MAX_TEXTURES) { g_debug << "trying to bind texture " << name << " to an invalid texture unit << " << texunitoffset << "!" << endl; return; } if (m_textures.find(name) != m_textures.end()) { //g_debug << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << "\n"; TextureParameters &oldparams = *m_textureParameters[m_lastBoundTexture[texunitoffset]]; TextureParameters &newparams = *m_textureParameters[name]; /* g_debug << "old texture name = " << m_lastBoundTexture[texunitoffset] << "\n"; g_debug << "oldparams.repeat = " << oldparams.m_repeat << "\n"; g_debug << "oldparams.linear = " << oldparams.m_linear << "\n\n"; g_debug << "new texture name = " << name << "\n"; g_debug << "newparams.repeat = " << newparams.m_repeat << "\n"; g_debug << "newparams.linear = " << newparams.m_linear << "\n"; GLint wrap_s, wrap_t; glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, &wrap_s); glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, &wrap_t); if (wrap_s == GL_REPEAT) g_debug << "wrap_s = GL_REPEAT\n"; else if (wrap_s == GL_CLAMP_TO_EDGE) g_debug << "wrap_s = GL_CLAMP_TO_EDGE\n"; else if (wrap_s == GL_CLAMP) g_debug << "wrap_s = GL_CLAMP\n"; else g_debug << "wrap_s = " << wrap_s << " (unknown!)\n"; if (wrap_t == GL_REPEAT) g_debug << "wrap_t = GL_REPEAT\n"; else if (wrap_t == GL_CLAMP_TO_EDGE) g_debug << "wrap_t = GL_CLAMP_TO_EDGE\n"; else if (wrap_t == GL_CLAMP) g_debug << "wrap_t = GL_CLAMP\n"; else g_debug << "wrap_t = " << wrap_t << " (unknown!)\n"; */ //glActiveTexture(texunit); //we need to change the linear/nearest settings /* if (name == "kohina1.png" || name == "kohina2.png" || name == "kohina3.png" || name == "noise1.jpg" || name == "noise2.jpg" || name == "noise3.jpg") { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } else*/ { if (newparams.m_linear != oldparams.m_linear) { //g_debug << "set texture " << name << " to linear filter mode " << newparams.m_linear << "\n"; glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, newparams.m_linear ? GL_LINEAR : GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, newparams.m_linear ? GL_LINEAR : GL_NEAREST); } if (newparams.m_repeat != oldparams.m_repeat) { int wrap = newparams.m_repeat ? GL_REPEAT : GL_CLAMP_TO_EDGE; glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, wrap); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, wrap); } } //there is a bug here // glTexParameteri(GL_TEXTURE_2D, // GL_TEXTURE_WRAP_S, // GL_CLAMP_TO_EDGE); // glTexParameteri(GL_TEXTURE_2D, // GL_TEXTURE_WRAP_T, // GL_CLAMP_TO_EDGE); m_textures[name]->bind(texunit); m_lastBoundTexture[texunitoffset] = name; } else { g_debug << "trying to bind texture " << name << " that does not exist!" << endl; } } void TextureHandler::clearTextureUnits() { //this is slow but what the hell... glActiveTexture(GL_TEXTURE7_ARB); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_REPEAT); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE6_ARB); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_REPEAT); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE5_ARB); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_REPEAT); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE4_ARB); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_REPEAT); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE3_ARB); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_REPEAT); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE2_ARB); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_REPEAT); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE1_ARB); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE0_ARB); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_REPEAT); glDisable(GL_TEXTURE_2D); } void TextureHandler::loadImages() { vector<string> filenames; #ifdef _WIN32 string directory = "data\\graphics\\"; StringUtils::iterateDirectory(directory, filenames); #else string directory = "data/graphics/"; StringUtils::iterateDirectory(directory, filenames, false); #endif //add steps, one for uploading and one for loading g_system.addLoadingScreenSteps(filenames.size() * 2); vector<string>::iterator it; for (it = filenames.begin(); it < filenames.end(); it++) { string filename = *it; string path = directory + filename; string suffix = filename.substr(filename.length()-3, filename.length()); if (suffix == "jpg") { Image *image = ImageFactory::loadJPG(path); if (image != 0) { addImage(filename, image); } g_system.advanceLoadingScreen(1); } else if (suffix == "png") { Image *image = ImageFactory::loadPNG(path); if (image != 0) { addImage(filename, image); } g_system.advanceLoadingScreen(1); } else { g_debug << "non-image file " << filename << " found in graphics directory!" << endl; // string tmp(basename("data/graphics/")); // g_debug << "basename: " << tmp << endl; } g_system.drawLoadingScreen(); } } void TextureHandler::uploadImages() { g_debug << "uploading textures to OpenGL" << endl; int videoMemoryConsumption = 0; int count = 0; map<string, Image*>::iterator it; //add extra texture parameters for default "no texture" image TextureParameters *tempparams = new TextureParameters(); addTextureParameters("no texture", tempparams); glEnable(GL_TEXTURE_2D); //loop through all images and upload the ones that need to be uploaded for (it = m_images.begin(); it != m_images.end(); it++) { const string& name = (*it).first; Image *image = (*it).second; TextureParameters params; //try to find corresponding texture parameters map<string, TextureParameters*>::iterator paramiterator; paramiterator = m_textureParameters.find(name); if (paramiterator != m_textureParameters.end()) { params = *paramiterator->second; } else { //upload new default texturaparameters for this image TextureParameters *temp = new TextureParameters(); temp->setDefaults(); m_textureParameters[name] = temp; params = *temp; } //create the texture and upload it if (params.m_upload) { Texture *texture = new Texture(); texture->upload(*image, params); m_textures[name] = texture; videoMemoryConsumption += image->getWidth() * image->getHeight() * 4; count++; } //release data on images after uploading if (!params.m_retain) { image->releaseData(); } //update and draw loading screen g_system.advanceLoadingScreen(1); g_system.drawLoadingScreen(); } g_debug << "uploaded " << count << " textures, total video memory usage: " << (videoMemoryConsumption/1000) << "k" << endl; } Image& TextureHandler::image(string name) { return *m_images[name]; } void TextureHandler::dumpUnusedImages() { g_debug << "" << endl; g_debug << "TextureHandler::dumpUnusedImages()" << endl; g_debug << "-------------------" << endl; map<string, Texture*>::iterator it; for (it = m_textures.begin(); it != m_textures.end(); it++) { Texture *t = (*it).second; if (!t->hasBeenUsed()) { g_debug << " unused texture: " << (*it).first << endl; } } g_debug << "" << endl; } void TextureHandler::bindDepthFBO() { m_FBO->bindDepthFBO(); } void TextureHandler::bindTextureFBO(string name) { //find texture data Image& i = *m_images[name]; Texture &t = *m_textures[name]; int width = i.getWidth(); int height = i.getHeight(); int ID = t.getID(); //select the correct FBO to bind it to if (width == 32 && height == 32) { m_FBO->bindTextureFBO32(ID); } else if (width == 64 && height == 64) { m_FBO->bindTextureFBO64(ID); } else if (width == 128 && height == 128) { m_FBO->bindTextureFBO128(ID); } else if (width == 256 && height == 256) { m_FBO->bindTextureFBO256(ID); } else if (width == 512 && height == 512) { m_FBO->bindTextureFBO512(ID); } else if (width == 1024 && height == 1024) { m_FBO->bindTextureFBO1024(ID); } else if (width == 2048 && height == 2048) { m_FBO->bindTextureFBO2048(ID); } else { g_debug << "Trying to bind texture " << name << " to a FBO but there is no suitable FBO available!" << endl; } } void TextureHandler::unbindFBO() { m_FBO->unbindFBO(); }
[ [ [ 1, 59 ], [ 61, 103 ], [ 105, 427 ] ], [ [ 60, 60 ], [ 104, 104 ] ] ]
5cfb5b206db35ad86dd6d2e663cabbd16c4e05f3
6ee200c9dba87a5d622c2bd525b50680e92b8dab
/Walkyrie Dx9/DoomeRX/Scenes/SceneTerrain.h
955f15c6da78fed7f59bd8f30bbc1ed6c059a66a
[]
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
ISO-8859-1
C++
false
false
2,025
h
// Classe pour la gestion d'une scรจne 3D #pragma once #include "..\..\Valkyrie\Moteur\Scene.h" #include "..\MiniGames\InterfacesBattlefly.h" #include "..\..\Valkyrie\Moteur\CameraVolLibre.h" #include "..\Objects\CameraPremierePersonneTerrain.h" #include "..\..\Valkyrie\Moteur\MeshCollision.h" #include "..\..\Valkyrie\Moteur\Panorama.h" #include "..\..\Valkyrie\Moteur\Terrain.h" #include "..\..\Valkyrie\Moteur\ModelEau.h" #include "..\..\Valkyrie\Moteur\Vegetation.h" class CSceneTerrain : public CScene { public: enum ESound { ANIMAUX1 = 0, ANIMAUX2, ANIMAUX3, ANIMAUX4, ANIMAUX5, MOTEUR_AVION }; CMesh* m_pAvion; // Avion CPanorama* m_pCiel; // SkyBox CTerrain* m_pTerrain; // Terrain CModelEau* m_pModelEau; // ModelEau CVegetation* m_pVegetation; // Vegetation CInterfaceBattleFly* m_pInterface; // Pointeur sur l'Interface D3DXMATRIXA16 m_MatTransAvion; // Matrice de transformation pour l'avion D3DXMATRIXA16 m_MatriceGeneral; // Matrice de transformation CCamera* m_pCamera1; // Camera au sol CCamera* m_pCamera2; // Camera sur l'aile de l'avion CCamera* m_pCamera3; // Camera derriรจre l'avion CLumiere m_Lumiere; // Lumiรจre pour รฉclairer l'avion float m_Rotation; // Angle de rotation de l'avion float m_Px; // Postion X par rapport ร  la rotation float m_Pz; // Postion Z par rapport ร  la rotation int m_FiltreTexture; // Type de filtrage de texture bool m_bRenduFilDeFer; // Si rendu en fil de fer float m_fIntervalleAnimaux; float m_fIntervalleMoteur; CSceneTerrain(CMoteur* pMoteur); ~CSceneTerrain(); bool Initialisation(); bool CreationObjet(); void Destruction(); void DestructionObjet(); void Rendu3D(); void RenduInterface(); void Aquisition(BYTE EtatClavier[], DIMOUSESTATE* pEtatSouris,DIJOYSTATE2* pEtatJoystick); void Animation(double TempsEcouler, double DeltaTemps); void SetFiltreTexture(); };
[ "Colas.Vincent@ab19582e-f48f-11de-8f43-4547254af6c6" ]
[ [ [ 1, 71 ] ] ]
811d8eaab676d1a85a4a54540f6f3b35e7fa81c6
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Targets/MapLib/Shared/src/TileImportanceTable.cpp
2fd24ac3055e3d6378774925d12986613fcdb224
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,563
cpp
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "TileImportanceTable.h" #include "BitBuffer.h" //using namespace std; TileImportanceNotice::TileImportanceNotice( float64 detailLevel, uint16 maxScale, uint16 type, uint32 threshold ) : m_detailLevel( detailLevel ), m_maxScale( maxScale ), m_type( type ), m_threshold( threshold ) { } void TileImportanceNotice::load( BitBuffer& buf ) { m_threshold = buf.readNextBALong(); m_maxScale = buf.readNextBAShort(); m_type = buf.readNextBAShort(); m_detailLevel = buf.readNextBAByte() / 20.0 ; } void TileImportanceNotice::save( BitBuffer& buf ) const { buf.writeNextBALong( m_threshold ); buf.writeNextBAShort( m_maxScale ); buf.writeNextBAShort( m_type ); buf.writeNextBAByte( uint32( m_detailLevel * 20 ) ); } void TileImportanceNotice::dump( ostream& stream ) const { stream << "TileImportanceNotice: detailLevel = " << m_detailLevel << ", type = " << m_type << ", threshold = " << m_threshold << ", maxScale = " << m_maxScale << endl; } // ----------------------- TileImportanceTable ---------------------------- TileImportanceTable::~TileImportanceTable() { // Delete the stuff in the matrix. for ( uint32 i = 0; i < m_importanceMatrix.size(); ++i ) { delete m_importanceMatrix[ i ]; } } void TileImportanceTable::load( BitBuffer& buf ) { clear(); uint16 nbrElems = buf.readNextBAShort(); for ( uint16 i = 0; i < nbrElems; ++i ) { TileImportanceNotice notice; notice.load( buf ); insert( std::make_pair( notice.getMaxScale(), notice ) ); } // Build the matrix. buildMatrix(); } void TileImportanceTable::save( BitBuffer& buf ) const { buf.writeNextBAShort( size() ); for ( const_iterator it = begin(); it != end(); ++it ) { it->second.save( buf ); } } void TileImportanceTable::getInterestingScales( std::vector<uint32>& scales ) const { for ( const_iterator it = begin(); it != end(); ++it ) { scales.push_back( it->first ); } } int TileImportanceTable::getNbrImportanceNbrs( uint16 scale, int detailLevel ) const { int nbrImportance = 0; for ( const_reverse_iterator it = rbegin(); it != rend(); ++it ) { if ( (*it).first >= scale ) { if ( (*it).second.getDetailLevel() == detailLevel || (*it).second.getThreshold() == MAX_UINT32 ) { ++nbrImportance; } } else { return nbrImportance; } } return nbrImportance; } const TileImportanceNotice* TileImportanceTable::getImportanceNbrSlow( int importanceNbr, int detailLevel ) const { const_reverse_iterator it = rbegin(); int count = -1; while ( it != rend() ) { if ( ( (*it).second.getDetailLevel() == detailLevel ) || ( (*it).second.getThreshold() == MAX_UINT32 ) ) { ++count; if ( count == importanceNbr ) { return &((*it).second); } } ++it; } // If we get here, we didn't find the importance notice. return NULL; } const TileImportanceNotice* TileImportanceTable::getImportanceNbr( int importanceNbr, int detailLevel ) const { // Indata must not be incorrect now! return (*(m_importanceMatrix[ detailLevel ]))[ importanceNbr ]; } void TileImportanceTable::buildMatrix() { if ( empty() ) { return; } int nbrDetailLevels = int((*rbegin()).second.getDetailLevel()) + 1; m_importanceMatrix.resize( nbrDetailLevels ); for ( int i = 0; i < nbrDetailLevels; ++i ) { int nbrImportances = getNbrImportanceNbrs( 0, i ); std::vector<const TileImportanceNotice*>* vecPtr = new std::vector<const TileImportanceNotice*>(); vecPtr->resize( nbrImportances ); m_importanceMatrix[ i ] = vecPtr; for ( int j = 0; j < nbrImportances; ++j ) { // Use the slow method. (*vecPtr)[ j ] = getImportanceNbrSlow( j, i ); } } } const TileImportanceNotice* TileImportanceTable::getFirstOfType( uint16 type ) const { const_reverse_iterator it = rbegin(); while ( it != rend() ) { if ( (*it).second.getType() == type ) { return &((*it).second); } ++it; } // If we get here, we didn't find the importance notice. return NULL; } void TileImportanceTable::dump( ostream& stream ) const { stream << "TileImportanceTable::dump" << endl; for ( TileImportanceTable::const_iterator it = begin(); it != end(); ++it ) { stream << "ScaleLevel = " << (*it).first << ", "; (*it).second.dump( stream ); } }
[ [ [ 1, 200 ] ] ]
d78c97432d91aa45b202650decd18feeedaef445
b4d726a0321649f907923cc57323942a1e45915b
/CODE/ImpED/ModifyVariableDlg.h
abe848c248b6312b533601c0877a3d89371d379f
[]
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
2,724
h
/* * 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. * */ #if !defined(AFX_MODIFYVARIABLEDLG_H__710D45F1_ABBF_11D2_A89A_0060088FAE88__INCLUDED_) #define AFX_MODIFYVARIABLEDLG_H__710D45F1_ABBF_11D2_A89A_0060088FAE88__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // ModifyVariableDlg.h : header file // #include "parse/sexp.h" ///////////////////////////////////////////////////////////////////////////// // CModifyVariableDlg dialog class CModifyVariableDlg : public CDialog { // Construction public: CModifyVariableDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CModifyVariableDlg) enum { IDD = IDD_MODIFY_VARIABLE }; CString m_cur_variable_name; CString m_default_value; CString m_old_var_name; bool m_type_number; bool m_type_player_persistent; bool m_type_campaign_persistent; bool m_modified_name; bool m_modified_value; bool m_modified_type; bool m_modified_persistence; bool m_deleted; bool m_data_validated; bool m_var_name_validated; bool m_do_modify; int m_combo_last_modified_index; int m_translate_combo_to_sexp[MAX_SEXP_VARIABLES]; int m_start_index; // index of sexp_variables which is right clicked to get this menu sexp_tree *m_p_sexp_tree; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CModifyVariableDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CModifyVariableDlg) afx_msg void OnDeleteVariable(); afx_msg void OnTypeString(); afx_msg void OnTypeNumber(); afx_msg void OnTypePlayerPersistent(); afx_msg void OnTypeCampaignPersistent(); afx_msg void OnSelchangeModifyVariableName(); afx_msg void OnEditchangeModifyVariableName(); virtual BOOL OnInitDialog(); virtual void OnOK(); afx_msg void OnKillfocusModifyDefaultValue(); afx_msg void set_variable_type(); afx_msg void validate_data(CString &temp_data, int set_focus); afx_msg void validate_var_name(int set_focus); afx_msg int get_sexp_var_index(); afx_msg void OnDropdownModifyVariableName(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_MODIFYVARIABLEDLG_H__710D45F1_ABBF_11D2_A89A_0060088FAE88__INCLUDED_)
[ [ [ 1, 88 ] ] ]
92d76dd0b83b63cb968751bb2786384179e2a3c3
65a392af0450708ed4fa26f66393e12bdf387634
/Package/Polynomial/ExternUnisolve.cpp
99a28cd13de67569fd6c9ee6ce36b4ee420850e0
[]
no_license
zhouxs1023/mU
d5abea6e883cb746aa28ff6ee2b3902babb053d8
c9ecc5f0a4fd13567b3c9ca24ff05ba149af743e
refs/heads/master
2021-05-27T11:37:59.464639
2011-06-17T22:39:25
2011-06-17T22:39:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,507
cpp
#include <mU/Kernel.h> #include "common.h" #include <fstream> namespace mU { ////////////////////////////////////// namespace { var ca,cb,cc,cd,ce; var solution1,solution2,solution3,solution4; var expr_minus,expr_root_of_uint; uint gcd_uint(uint a,uint b) { uint u=a,v=b,r; while(v!=0) { r=u%v; u=v;v=r; } return u; } void root_of_unit(var & root, uint i, uint n, map_t & current) { uint h=gcd_uint(i,n); uint ii=i/h,nn=n/h; ii=ii%nn; if(2*ii==nn) { root=Int();mpz_set_si(CInt(root),-1); return ; } if(ii==0) { root=Int();mpz_set_ui(CInt(root),1); return ; } if(2*ii<nn) { var a=Int(); mpz_set_ui(CInt(a),1); current[ca]=a; a=Rat(); mpq_set_ui(CRat(a),2*ii,nn); current[cb]=a; root=Eval(Subs(current,expr_root_of_uint)); return ; } else { var a=Int(); mpz_set_si(CInt(a),-1); current[ca]=a; a=Rat(); mpq_set_ui(CRat(a),2*ii-nn,nn); current[cb]=a; root=Eval(Subs(current,expr_root_of_uint)); return ; } } } void UniSolveInitialize() { var In=ParseFile(Path() + L"Package/Polynomial/UniSolve.u"); ca=At(In,0); cb=At(In,1); cc=At(In,2); cd=At(In,3); ce=At(In,4); solution1=At(In,5); solution2=At(In,6); solution3=At(In,7); solution4=At(In,8); expr_minus=At(In,9); expr_root_of_uint=At(In,10); return ; } void UniSolve_Decomposition_Stage(var & rootlist, const poly_z & f) { static mpq_t l; var a,b,c,d,e; var temp; var rootlist1,rootlist2; map_t new_e; mpq_init(l); std::vector<poly_z> partlist; rootlist=Vec(); if(f.size()>5) { UniFuncionalDecompositionZ(l,partlist,f); } else { partlist.resize(1); copy_poly_z(partlist[0],f); } uint deg_deal,oldsize; poly_z & deal=partlist[0]; deg_deal=deal.size()-1; //first cyclotomic-testing uint n; poly_z g; var root; if(deg_deal>3)n=UniShiftedCyclotomicZQ(g,deal); else n=0; rootlist=Vec(); if(n>0) { for(uint i=0;i<n;++i) { if(gcd_uint(i,n)==1) { root_of_unit(root,i,n,new_e); if(mpz_cmp_ui(g[0],0)!=0||mpz_cmp_ui(g[1],1)!=0) { a=Int(); mpz_set(CInt(a),g[0]); new_e[ca]=a; new_e[cb]=root; root=Eval(Subs(new_e,expr_minus)); a=Int(); mpz_set(CInt(a),g[1]); new_e[ca]=a; new_e[cb]=root; root=Eval(Subs(new_e,solution1)); } Push(rootlist,root); } } } else { switch(deg_deal) { case 1: a=Int();b=Int(); mpz_set(CInt(a),deal[1]);mpz_set(CInt(b),deal[0]); new_e[ca]=a;new_e[cb]=b; rootlist=Eval(Subs(new_e,solution1)); break; case 2: a=Int();b=Int();c=Int(); mpz_set(CInt(a),deal[2]);mpz_set(CInt(b),deal[1]);mpz_set(CInt(c),deal[0]); new_e[ca]=a;new_e[cb]=b;new_e[cc]=c; rootlist=Eval(Subs(new_e,solution2)); break; case 3: a=Int();b=Int();c=Int();d=Int(); mpz_set(CInt(a),deal[3]);mpz_set(CInt(b),deal[2]);mpz_set(CInt(c),deal[1]);mpz_set(CInt(d),deal[0]); new_e[ca]=a;new_e[cb]=b;new_e[cc]=c;new_e[cd]=d; rootlist=Eval(Subs(new_e,solution3)); break; case 4: a=Int();b=Int();c=Int();d=Int();e=Int(); mpz_set(CInt(a),deal[4]);mpz_set(CInt(b),deal[3]);mpz_set(CInt(c),deal[2]);mpz_set(CInt(d),deal[1]);mpz_set(CInt(e),deal[0]); new_e[ca]=a;new_e[cb]=b;new_e[cc]=c;new_e[cd]=d;new_e[ce]=e; rootlist=Eval(Subs(new_e,solution4)); break; default: var fc; from_poly_z(fc,f); rootlist=Vec(); for(uint i=1;i<f.size();++i) { Push(rootlist,Ex(tag_root,Vec(fc,Int(i)))); } mpq_clear(l); return ; break; } } g.resize(0); for(uint i=1;i<partlist.size();++i) { oldsize=Size(rootlist); deal=partlist[i]; rootlist1=Vec(); for(uint j=0;j<oldsize;++j) { deg_deal=deal.size()-1; switch(deg_deal) { case 1: a=Int();b=Int(); mpz_set(CInt(b),deal[0]); new_e[ca]=b; new_e[cb]=At(rootlist,j); temp=Eval(Subs(new_e,expr_minus)); mpz_set(CInt(a),deal[1]); new_e[ca]=a;new_e[cb]=temp; rootlist2=Eval(Subs(new_e,solution1)); break; case 2: a=Int();b=Int();c=Int(); mpz_set(CInt(c),deal[0]); new_e[ca]=c; new_e[cb]=At(rootlist,j); temp=Eval(Subs(new_e,expr_minus)); mpz_set(CInt(a),deal[2]);mpz_set(CInt(b),deal[1]); new_e[ca]=a;new_e[cb]=b;new_e[cc]=temp; rootlist2=Eval(Subs(new_e,solution2)); break; case 3: a=Int();b=Int();c=Int();d=Int(); mpz_set(CInt(d),deal[0]); new_e[ca]=d; new_e[cb]=At(rootlist,j); temp=Eval(Subs(new_e,expr_minus)); mpz_set(CInt(a),deal[3]);mpz_set(CInt(b),deal[2]);mpz_set(CInt(c),deal[1]); new_e[ca]=a;new_e[cb]=b;new_e[cc]=c;new_e[cd]=temp; rootlist2=Eval(Subs(new_e,solution3)); break; case 4: a=Int();b=Int();c=Int();d=Int();e=Int(); mpz_set(CInt(e),deal[0]); new_e[ca]=e; new_e[cb]=At(rootlist,j); temp=Eval(Subs(new_e,expr_minus)); mpz_set(CInt(a),deal[4]);mpz_set(CInt(b),deal[3]);mpz_set(CInt(c),deal[2]);mpz_set(CInt(d),deal[1]); new_e[ca]=a;new_e[cb]=b;new_e[cc]=c;new_e[cd]=d;new_e[ce]=temp; rootlist2=Eval(Subs(new_e,solution4)); break; default: //x^n if(is_x_power_z(deal)) { rootlist2=Vec(); for(uint i=0;i<deg_deal;++i) { var root; root_of_unit(root,i,deg_deal,new_e); temp=Ex(TAG(Power),Vec(At(rootlist,j),Rat(1L,deg_deal))); root=Ex(TAG(Times),Vec(root,temp)); Push(rootlist2,root); } } else { var fc; from_poly_z(fc,f); rootlist=Vec(); for(uint i=1;i<f.size();++i) { Push(rootlist,Ex(tag_root,Vec(fc,Int(i)))); } mpq_clear(l); return ; } break; } for(uint k=0;k<Size(rootlist2);++k)Push(rootlist1,At(rootlist2,k)); } rootlist=rootlist1; } mpq_clear(l); return ; } void UniSolve_Factorization_Stage(var & rootlist, const poly_z & f) { static mpz_t a; mpz_init(a); std::vector<poly_z> faclist; std::vector<uint> deglist; UniFacZ(f,a,faclist,deglist); var rootlist1; rootlist=Vec(); uint size=faclist.size(); for(uint i=0;i<size;++i) { UniSolve_Decomposition_Stage(rootlist1,faclist[i]); uint size1=Size(rootlist1); for(uint j=0;j<size1;++j) { for(uint k=0;k<deglist[i];++k)Push(rootlist,At(rootlist1,j)); } } mpz_clear(a); clear_poly_z_list(faclist); return ; } ////////////////////////////////////// }
[ [ [ 1, 289 ] ] ]
eb93ef484ce72c4b0d8ec6b7116d2604c7d38eba
b5ab57edece8c14a67cc98e745c7d51449defcff
/Captain's Log/MainGame/Source/GameObjects/CMarine.h
c70a5e4e75621b18974d91478da73fbd6c5441c0
[]
no_license
tabu34/tht-captainslog
c648c6515424a6fcdb628320bc28fc7e5f23baba
72d72a45e7ea44bdb8c1ffc5c960a0a3845557a2
refs/heads/master
2020-05-30T15:09:24.514919
2010-07-30T17:05:11
2010-07-30T17:05:11
32,187,254
0
0
null
null
null
null
UTF-8
C++
false
false
254
h
#ifndef CMarine_h__ #define CMarine_h__ #include "CPlayerUnit.h" class CMarine : public CPlayerUnit { int m_nCurFrame; public: CMarine(); void Update(float fElapsedTime); void Render(); void Initialize(); }; #endif // CMarine_h__
[ "notserp007@34577012-8437-c882-6fb8-056151eb068d" ]
[ [ [ 1, 17 ] ] ]
98aa6ea80af0891c9ca4871d276fdf266b9ccaed
5b6830ee6a50a80388b42c1ed3e857e02e08c672
/Source/FERmula_1/voziloInputDeviceStateType.h
1304442d3e8d519a330341f8d91400ae6d185119
[]
no_license
MarioVolarevic/projekt-irg-2011
930f7eb1e10a7c0784fec76b336d887b49fff442
c2c2724b7581e2f08b8f745ce886cdff75aa7a40
refs/heads/master
2021-01-02T08:57:34.512092
2011-11-29T17:43:22
2011-11-29T17:43:22
32,448,049
0
0
null
null
null
null
UTF-8
C++
false
false
324
h
class VoziloInputDeviceStateType { public: VoziloInputDeviceStateType::VoziloInputDeviceStateType() : moveFwdRequest(false),moveBcwRequest(false), rotLReq(false), rotRReq(false), resetReq(false), promijeniModel(0){} bool moveFwdRequest,moveBcwRequest,rotLReq,rotRReq,resetReq; int promijeniModel; };
[ "mario.volarevic@86cc4e84-eea2-baa8-f4a2-eb7baa844040" ]
[ [ [ 1, 9 ] ] ]
27c28c9e9a9ebeea17e9ee08c08c11cbb5c538c1
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/audio/ndsound_query.cc
eaad318b88f7750e39c0b46177b11810326eebca
[]
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
6,395
cc
#define N_IMPLEMENTS nDSoundServer //------------------------------------------------------------------- // ndsound_query.cc // (C) 2000 RadonLabs GmbH -- A.Weissflog //------------------------------------------------------------------- #include "kernel/nenv.h" #include "misc/nblob.h" #include "audio/ndsoundserver.h" extern const char *ndsound_Error(HRESULT hr); //------------------------------------------------------------------- /** Callback function for DirectSound device enumeration. Each device gets a numbered entry under @c '/sys/share/audio'. 15-May-00 floh created 28-Sep-00 floh PushCwd()/PopCwd() */ //------------------------------------------------------------------- BOOL CALLBACK ndsound_EnumDevicesCB(LPGUID lpGuid, LPCSTR lpcstrDescription, LPCSTR lpcstrModule, LPVOID lpContext) { nDSoundServer *dsound = (nDSoundServer *) lpContext; nKernelServer *ks = nDSoundServer::ks; HRESULT hr; nRoot *root; nEnv *env; nBlob *blob; char buf[N_MAXPATH]; // generate a new device database entry sprintf(buf,"%d",dsound->act_device++); root = ks->New("nroot",buf); ks->PushCwd(root); // export device data into database env = (nEnv *) ks->New("nenv","desc"); env->SetS(lpcstrDescription); env = (nEnv *) ks->New("nenv","module"); env->SetS(lpcstrModule); blob = (nBlob *) ks->New("nblob","guid"); blob->Set(lpGuid,sizeof(GUID)); // open device and ask for caps bits, close device IDirectSound *tmp_ds; hr = DirectSoundCreate(lpGuid,&tmp_ds,NULL); if (FAILED(hr)) { n_printf("ndsound_EnumDevicesCB(): DirectSoundCreate() failed with '%s'\n",ndsound_Error(hr)); dsound->enum_failed = true; return FALSE; } tmp_ds->SetCooperativeLevel(dsound->hwnd,DSSCL_EXCLUSIVE); DSCAPS ds_caps; memset(&ds_caps,0,sizeof(ds_caps)); ds_caps.dwSize = sizeof(ds_caps); hr = tmp_ds->GetCaps(&ds_caps); if (FAILED(hr)) { n_printf("ndsound_EnumDevicesCB(): GetCaps() failed with '%s'\n",ndsound_Error(hr)); dsound->enum_failed = true; return FALSE; } tmp_ds->Release(); // export caps into filesystem blob = (nBlob *) ks->New("nblob","caps_blob"); blob->Set(&ds_caps,sizeof(ds_caps)); env = (nEnv *) ks->New("nenv","flags"); DWORD f = ds_caps.dwFlags; buf[0] = 0; if (f & DSCAPS_CERTIFIED) n_strcat(buf,"certified ",sizeof(buf)); if (f & DSCAPS_CONTINUOUSRATE) n_strcat(buf,"continuousrate ",sizeof(buf)); if (f & DSCAPS_EMULDRIVER) n_strcat(buf,"emuldriver ",sizeof(buf)); if (f & DSCAPS_PRIMARY16BIT) n_strcat(buf,"primary16bit ",sizeof(buf)); if (f & DSCAPS_PRIMARY8BIT) n_strcat(buf,"primary8bit ",sizeof(buf)); if (f & DSCAPS_PRIMARYMONO) n_strcat(buf,"primarymono ",sizeof(buf)); if (f & DSCAPS_PRIMARYSTEREO) n_strcat(buf,"primarystereo ",sizeof(buf)); if (f & DSCAPS_SECONDARY16BIT) n_strcat(buf,"secondary16bit ",sizeof(buf)); if (f & DSCAPS_SECONDARY8BIT) n_strcat(buf,"secondary8bit ",sizeof(buf)); if (f & DSCAPS_SECONDARYMONO) n_strcat(buf,"secondarymono ",sizeof(buf)); if (f & DSCAPS_SECONDARYSTEREO) n_strcat(buf,"secondarystereo ",sizeof(buf)); env->SetS(buf); env = (nEnv *) ks->New("nenv","min_sec_rate"); env->SetI(ds_caps.dwMinSecondarySampleRate); env = (nEnv *) ks->New("nenv","max_sec_rate"); env->SetI(ds_caps.dwMaxSecondarySampleRate); env = (nEnv *) ks->New("nenv","max_hwmixing_all_buffers"); env->SetI(ds_caps.dwMaxHwMixingAllBuffers); env = (nEnv *) ks->New("nenv","max_hwmixing_static_buffers"); env->SetI(ds_caps.dwMaxHwMixingStaticBuffers); env = (nEnv *) ks->New("nenv","max_hwmixing_streaming_buffers"); env->SetI(ds_caps.dwMaxHwMixingStreamingBuffers); env = (nEnv *) ks->New("nenv","max_hw3d_all_buffers"); env->SetI(ds_caps.dwMaxHw3DAllBuffers); env = (nEnv *) ks->New("nenv","max_hw3d_static_buffers"); env->SetI(ds_caps.dwMaxHw3DStaticBuffers); env = (nEnv *) ks->New("nenv","max_hw3d_streaming_buffers"); env->SetI(ds_caps.dwMaxHw3DStreamingBuffers); env = (nEnv *) ks->New("nenv","total_hwmem_bytes"); env->SetI(ds_caps.dwTotalHwMemBytes); env = (nEnv *) ks->New("nenv","unlock_transferrate_hwbuffers"); env->SetI(ds_caps.dwUnlockTransferRateHwBuffers); env = (nEnv *) ks->New("nenv","play_cpuoverhead_swbuffers"); env->SetI(ds_caps.dwPlayCpuOverheadSwBuffers); // everything done, next please... ks->PopCwd(); return TRUE; } //------------------------------------------------------------------- /** Enumerate all DirectSound devices in the system and create a database under @c '/sys/share/audio'. 15-May-00 floh created 28-Sep-00 floh PushCwd()/PopCwd() */ //------------------------------------------------------------------- bool nDSoundServer::queryDevices(void) { HRESULT hr; this->query_called = true; this->act_device = 0; this->enum_failed = false; // throw away old database and allocate new one this->ref_devdir->Release(); this->ref_devdir = ks->New("nroot","/sys/share/audio"); // enumerate dsound devices... ks->PushCwd(ref_devdir.get()); hr = DirectSoundEnumerate(ndsound_EnumDevicesCB,this); ks->PopCwd(); if (hr != DD_OK) { n_printf("DirectSoundEnumerate() failed with '%s'!\n",ndsound_Error(hr)); return false; } return !(this->enum_failed); } //------------------------------------------------------------------- /** After queryDevice() has been called to build the database, call selectDevice() to select one from the database. This device will then be used with the next call to OpenAudio(). The following members will be initialized: @verbatim this->ref_seldevice this->sel_guid this->sel_caps @endverbatim 15-May-00 floh created */ //------------------------------------------------------------------- bool nDSoundServer::selectDevice(int n) { n_assert(this->query_called); return true; }
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 168 ] ] ]
21b65166d383162a33c17ac672d5bf0351a807e6
66581a883c3eab4c6c7b7c1d5850892485a5cab8
/Action Bros Now/Enemy.cpp
5a8c1227acfdae2a7f4e212dffbcf8ec6ce024c5
[]
no_license
nrolando/d-m-seniorprojectgsp
9457841f43697a73d956b202541064022dd4a189
503f311142bf4995f3e5c6fc6110317babde08f9
refs/heads/master
2021-01-10T05:49:14.926897
2010-02-17T03:29:10
2010-02-17T03:29:10
49,738,324
0
0
null
null
null
null
UTF-8
C++
false
false
8,357
cpp
#include <cassert> #include <iostream> #include "EnemyOwnedStates.h" #include "Player.h" #include "Enemy.h" Enemy::Enemy(int ID):BaseGameEntity(ID), status(InRange), CurrentState(Idle::Instance()) { faceRight = false; miss = false; } //possible bug: idk if passing a char array will get the c-str that its supposed to Enemy::Enemy(int ID, char KEY, D3DXVECTOR3 pos, spriteSheet *ptr) :BaseGameEntity(ID, KEY, pos, ptr), status(InRange), CurrentState(Idle::Instance()) { miss = false; if(KEY == SOLDIER1) faceRight = false; else faceRight = false; } void Enemy::UpdateState(Player *p,std::vector<BaseGameEntity*> e) { if(state != E_STUN && state != E_FALL) CurrentState->Execute(this,p,e); //temp code: IM USING STATE/ANIM FROM BGE FOR RIGHT NOW. clock_t now = clock(); switch(state) { case E_IDLE: if(now - aniFStart >= IDLEANIMATION) { if(anim < IDLEFRAME-1) { anim++; } else { anim = 0; } aniFStart = now; } break; case E_WALK: if(now - aniFStart >= WALKFRAMETIME) { if(anim < CSWALKFRAME-1) { anim++; } else { anim = 0; } aniFStart = now; } break; case E_ATTACK1: setHitFrames(2, -1, -1); setPower(5); if(now - aniFStart >= ANIMATIONGAP) { if(anim < ATTACKFRAME-1) { anim++; } else { lastAttFrame = -1; anim = 0; } aniFStart = now; } break; case E_FALL: if(now - aniFStart >= DEATHFRAMETIME) { if(health > 0) { if(anim < FALLFRAME-1) anim++; else anim = 0; } else { if(anim < FALLFRAME-2) anim++; else alive = false; } aniFStart = now; } break; case E_STUN: //if has been long enough if(now - stunStart >= stunTime) { //switch to first frame of idle state state = E_IDLE; anim = 0; aniFStart = now; } //if still stunned and time to switch frame of animation else if(now - aniFStart >= ANIMATIONGAP) { //loop to the beginning of the animation if(anim >= STUNFRAME-1) anim = 0; //advance 1 frame else anim++; aniFStart = now; } break; } calcDrawRECT(); } void Enemy::ChangeState(State<Enemy, Player>* pNewState) { CurrentState->Exit(this); CurrentState = pNewState; CurrentState->Enter(this); } void Enemy::UpdateStat(int stat, int val) { switch(stat) { case 0: health += val; if(health < 0) { health = 0; } break; default: printf("Sorry incorrect stat addition"); break; } } void Enemy::calcDrawRECT() { int state_frame; switch(this->key) { case SOLDIER1: if(faceRight) state_frame = state; else state_frame = state + SOLDIER1STATES; break; default: state_frame = state; }; //source rect to be drawn sprInfo.drawRect.left = anim * sprInfo.width; sprInfo.drawRect.right = sprInfo.drawRect.left + sprInfo.width; sprInfo.drawRect.top = state_frame * sprInfo.height; sprInfo.drawRect.bottom = sprInfo.drawRect.top + sprInfo.height; //ENEMY HITBOX FOR DAMAGE VERIFICATION switch(this->key) { case SOLDIER1: sprInfo.hitBox.top = long(sprInfo.POS.y - 170); sprInfo.hitBox.left = long(sprInfo.POS.x + 102); sprInfo.hitBox.right = sprInfo.hitBox.left + 48; sprInfo.hitBox.bottom = sprInfo.hitBox.top - 86; break; default: break; }; //Enemy's threatBox for dmg verification //while in DEBUG this will be shown //PLEASE NOTE: THIS IS ALL FOR RIGHT FACING ONLY! LEFT FACE IS NOT SET UP YET. ALSO, IM NOT SURE //IF DONNIE PLANS ON SHARING THE CURRENT ENEMY STATES BETWEEN ALL ENEMY TYPES, OR EACH ENEMY HAVING ITS //OWN SET OF STATES, SO IM PUTTING THIS INSIDE A SWITCH TO BE SAFE switch(this->key) { case SOLDIER1: if(state == E_ATTACK1) { if(faceRight) { sprInfo.threatBox.top = long(sprInfo.POS.y - 192); sprInfo.threatBox.left = long(sprInfo.POS.x + 145); sprInfo.threatBox.right = sprInfo.threatBox.left + 56; sprInfo.threatBox.bottom = sprInfo.threatBox.top - 21; } else { sprInfo.threatBox.top = long(sprInfo.POS.y - 192); sprInfo.threatBox.left = long(sprInfo.POS.x + 55); sprInfo.threatBox.right = sprInfo.threatBox.left + 56; sprInfo.threatBox.bottom = sprInfo.threatBox.top - 21; } } else { //make threatbox off world sprInfo.threatBox.top = -8880; sprInfo.threatBox.left = -8880; sprInfo.threatBox.right = -8880; sprInfo.threatBox.bottom = -8880; } break; default: break; }; } bool Enemy::MovementPossible(std::vector<BaseGameEntity*> EMgr) { for(unsigned int i=0;i<EMgr.size();++i) { if(this != EMgr[i] && EMgr[i]->isAlive()) { if (getDrawInfo().hitBox.top >= EMgr[i]->getDrawInfo().hitBox.bottom-20 && getDrawInfo().hitBox.top <= EMgr[i]->getDrawInfo().hitBox.top+20 && getDrawInfo().hitBox.left >= EMgr[i]->getDrawInfo().hitBox.left+20 && getDrawInfo().hitBox.left <= EMgr[i]->getDrawInfo().hitBox.right-20) {return false;} if (getDrawInfo().hitBox.right >= EMgr[i]->getDrawInfo().hitBox.left+20 && getDrawInfo().hitBox.right <= EMgr[i]->getDrawInfo().hitBox.right-20 && getDrawInfo().hitBox.bottom <= EMgr[i]->getDrawInfo().hitBox.top+20 && getDrawInfo().hitBox.bottom >= EMgr[i]->getDrawInfo().hitBox.bottom-20) {return false;} } } return true; } void Enemy::AvoidEntity(Player* p,std::vector<BaseGameEntity*> EMgr) { //Zeroes out everything since movement possible failed //movement('n',p,EMgr); for(unsigned int i= 0;i<EMgr.size();i++) { //If the entity being checked is not itself, within sight range, and has not been tagged to stand still if(this != EMgr[i] && getDistance(this,EMgr[i]->getDrawInfo().hitBox) < AVOID_RANGE) { if(getDrawInfo().hitBox.right <= EMgr[i]->getDrawInfo().hitBox.right-5.0f) vel.x = -speed; if(getDrawInfo().hitBox.left >= EMgr[i]->getDrawInfo().hitBox.left+5.0f) vel.x = speed; if(getDrawInfo().hitBox.bottom >= EMgr[i]->getDrawInfo().hitBox.bottom-YRANGE_OFFSET) vel.y = speed; if(getDrawInfo().hitBox.top <= EMgr[i]->getDrawInfo().hitBox.top+YRANGE_OFFSET) vel.y = -speed; } } } void Enemy::movement(char dir,Player* p,std::vector<BaseGameEntity*> EMgr) { clock_t now = clock(); switch(dir) { case 'l': faceRight = false; vel.x = -speed; if(!MovementPossible(EMgr)) AvoidEntity(p,EMgr); break; case 'd': vel.y = -speed; if(!MovementPossible(EMgr)) AvoidEntity(p,EMgr); break; case 'r': faceRight = true; vel.x = speed; if(!MovementPossible(EMgr)) AvoidEntity(p,EMgr); break; case 'u': vel.y = speed; if(!MovementPossible(EMgr)) AvoidEntity(p,EMgr); break; default: vel.x = vel.y = vel.z = 0; break; } } void Enemy::stun() { //min + rand() % max - min + 1 stunTime = 200 + rand() % 301; stunStart = clock(); state = E_STUN; anim = 0; aniFStart = clock(); this->setVel(D3DXVECTOR3(0.0f, 0.0f, 0.0f)); } void Enemy::stun(int num) { //min + rand() % max - min + 1 stunTime = (200 + rand() % 301) + num; stunStart = clock(); state = E_STUN; anim = 0; aniFStart = clock(); this->setVel(D3DXVECTOR3(0.0f, 0.0f, 0.0f)); } int Enemy::getDistance(Enemy* e,Player* p) { D3DXVECTOR3 ePos,pPos; ePos.x = float(e->getDrawInfo().hitBox.left); ePos.y = float(e->getDrawInfo().hitBox.top); pPos.x = float(p->getDrawInfo().hitBox.left); pPos.y = float(p->getDrawInfo().hitBox.top); double distance = sqrt(pow((ePos.x - pPos.x),2)+pow((ePos.y - pPos.y),2)); return int(distance); } int Enemy::getDistance(Enemy* e, RECT eMgr) { D3DXVECTOR3 ePos,mgrPos; ePos.x = float(e->getDrawInfo().hitBox.left); ePos.y = float(e->getDrawInfo().hitBox.top); mgrPos.x = float(eMgr.left); mgrPos.y = float(eMgr.top); double distance = sqrt(pow((ePos.x - mgrPos.x),2)+pow((ePos.y - mgrPos.y),2)); return int(distance); } void Enemy::die() { //note the alive variable doesn't get set until animation is over, then enemy gets deleted in EntMgr->update() state = E_FALL; anim = 0; aniFStart = clock(); this->setVel(D3DXVECTOR3(0.0f, 0.0f, 0.0f)); }
[ "nicklamort@2c89e556-c775-11de-bfbd-4d0f0f27293a", "DHeardjr@2c89e556-c775-11de-bfbd-4d0f0f27293a", "dheardjr@2c89e556-c775-11de-bfbd-4d0f0f27293a" ]
[ [ [ 1, 3 ], [ 5, 11 ], [ 13, 15 ], [ 18, 18 ], [ 20, 25 ], [ 27, 28 ], [ 30, 30 ], [ 32, 34 ], [ 51, 52 ], [ 55, 55 ], [ 57, 57 ], [ 59, 59 ], [ 61, 64 ], [ 75, 76 ], [ 78, 78 ], [ 82, 90 ], [ 92, 106 ], [ 108, 123 ], [ 125, 125 ], [ 127, 135 ], [ 141, 142 ], [ 153, 223 ], [ 297, 320 ], [ 343, 350 ] ], [ [ 4, 4 ], [ 12, 12 ], [ 19, 19 ], [ 44, 44 ], [ 46, 47 ], [ 49, 50 ], [ 230, 230 ], [ 232, 240 ], [ 246, 246 ], [ 248, 264 ], [ 266, 266 ], [ 272, 272 ], [ 274, 275 ], [ 279, 280 ], [ 283, 283 ], [ 285, 286 ], [ 290, 291 ], [ 321, 342 ] ], [ [ 16, 17 ], [ 26, 26 ], [ 29, 29 ], [ 31, 31 ], [ 35, 43 ], [ 45, 45 ], [ 48, 48 ], [ 53, 54 ], [ 56, 56 ], [ 58, 58 ], [ 60, 60 ], [ 65, 74 ], [ 77, 77 ], [ 79, 81 ], [ 91, 91 ], [ 107, 107 ], [ 124, 124 ], [ 126, 126 ], [ 136, 140 ], [ 143, 152 ], [ 224, 229 ], [ 231, 231 ], [ 241, 245 ], [ 247, 247 ], [ 265, 265 ], [ 267, 271 ], [ 273, 273 ], [ 276, 278 ], [ 281, 282 ], [ 284, 284 ], [ 287, 289 ], [ 292, 296 ] ] ]
1efa149e48676c9a41048a02a1c5420e2c9211c4
04fec4cbb69789d44717aace6c8c5490f2cdfa47
/include/wx/generic/splash.h
e7cf5cd22ab4ed66f74078777995abbb51174e75
[]
no_license
aaryanapps/whiteTiger
04f39b00946376c273bcbd323414f0a0b675d49d
65ed8ffd530f20198280b8a9ea79cb22a6a47acd
refs/heads/master
2021-01-17T12:07:15.264788
2010-10-11T20:20:26
2010-10-11T20:20:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,701
h
///////////////////////////////////////////////////////////////////////////// // Name: splash.h // Purpose: Splash screen class // Author: Julian Smart // Modified by: // Created: 28/6/2000 // RCS-ID: $Id: splash.h 41020 2006-09-05 20:47:48Z VZ $ // Copyright: (c) Julian Smart // Licence: wxWindows Licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_SPLASH_H_ #define _WX_SPLASH_H_ #include "wx/bitmap.h" #include "wx/timer.h" #include "wx/frame.h" /* * A window for displaying a splash screen */ #define wxSPLASH_CENTRE_ON_PARENT 0x01 #define wxSPLASH_CENTRE_ON_SCREEN 0x02 #define wxSPLASH_NO_CENTRE 0x00 #define wxSPLASH_TIMEOUT 0x04 #define wxSPLASH_NO_TIMEOUT 0x00 class WXDLLIMPEXP_ADV wxSplashScreenWindow; /* * wxSplashScreen */ class WXDLLIMPEXP_ADV wxSplashScreen: public wxFrame { public: // for RTTI macros only wxSplashScreen() {} wxSplashScreen(const wxBitmap& bitmap, long splashStyle, int milliseconds, wxWindow* parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxSIMPLE_BORDER|wxFRAME_NO_TASKBAR|wxSTAY_ON_TOP); virtual ~wxSplashScreen(); void OnCloseWindow(wxCloseEvent& event); void OnNotify(wxTimerEvent& event); long GetSplashStyle() const { return m_splashStyle; } wxSplashScreenWindow* GetSplashWindow() const { return m_window; } int GetTimeout() const { return m_milliseconds; } protected: wxSplashScreenWindow* m_window; long m_splashStyle; int m_milliseconds; wxTimer m_timer; DECLARE_DYNAMIC_CLASS(wxSplashScreen) DECLARE_EVENT_TABLE() DECLARE_NO_COPY_CLASS(wxSplashScreen) }; /* * wxSplashScreenWindow */ class WXDLLIMPEXP_ADV wxSplashScreenWindow: public wxWindow { public: wxSplashScreenWindow(const wxBitmap& bitmap, wxWindow* parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxNO_BORDER); void OnPaint(wxPaintEvent& event); void OnEraseBackground(wxEraseEvent& event); void OnMouseEvent(wxMouseEvent& event); void OnChar(wxKeyEvent& event); void SetBitmap(const wxBitmap& bitmap) { m_bitmap = bitmap; } wxBitmap& GetBitmap() { return m_bitmap; } protected: wxBitmap m_bitmap; DECLARE_EVENT_TABLE() DECLARE_NO_COPY_CLASS(wxSplashScreenWindow) }; #endif // _WX_SPLASH_H_
[ [ [ 1, 92 ] ] ]
72010a97342ce5861be92a977275be30df55d2e0
16d6176d43bf822ad8d86d4363c3fee863ac26f9
/Submission/Submission/Source code/rayTracer/Camera.cpp
af7729c0027831e7819a798f343fbabc70e0099a
[]
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
1,314
cpp
#include "StdAfx.h" #include "Camera.h" bool Camera::setArgs(char **args) { if( !args ) return false; for(int i=0; i<10; i++) { if(!args[i]) return false; } eye = vec3((float)atof(args[0]),(float)atof(args[1]),(float)atof(args[2])); center = vec3((float)atof(args[3]),(float)atof(args[4]),(float)atof(args[5])); up = vec3((float)atof(args[6]),(float)atof(args[7]),(float)atof(args[8])); fov = atof(args[9]); initCoordinates(); return true; } /* calc 'u', 'v', 'w' given eye, center and up */ void Camera::initCoordinates() { w = eye - center; w.normalize(); u = cross(u,up,w); u.normalize(); v = cross(v,w,u); } vec3 Camera::calcRays(int i, int j) { vec3 delta,ray; float alpha; float beta; float fovy=fov; float fovx=fovy*float(float(width)/float(height)); //float fovx=fov; //float fovy=fovx*width/height; alpha = tanf(degToRad * (fovx/2.0)) * ((j - (width/2.0))/(width/2.0)); beta = tanf(degToRad * (fovy/2.0)) * ((height/2.0) - i)/ (height/2.0); delta = (alpha * u) + (beta * v) - w; delta.normalize(); ray = delta; return ray; } void Camera::setImageParameters(int width, int height) { this->width = width; this->height = height; } Camera::Camera(void) { } Camera::~Camera(void) { }
[ "[email protected]@074c0a88-b503-11dd-858c-a3a1ac847323" ]
[ [ [ 1, 71 ] ] ]
975a5112c5058014691552cb99ec80e56d2f9edc
c58f258a699cc866ce889dc81af046cf3bff6530
/include/qmlib/corelib/templates/patterns.hpp
2eb72c85e471ea96ce760ee37e7c02b99dea2561
[]
no_license
KoWunnaKo/qmlib
db03e6227d4fff4ad90b19275cc03e35d6d10d0b
b874501b6f9e537035cabe3a19d61eed7196174c
refs/heads/master
2021-05-27T21:59:56.698613
2010-02-18T08:27:51
2010-02-18T08:27:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,250
hpp
// /// @defgroup patterns /// \file /// \brief Definition of some generic Patterns /// \ingroup patterns // // #ifndef __PATTERNS_QM_H__ #define __PATTERNS_QM_H__ #include <qmlib/definitions.hpp> QM_NAMESPACE /** \brief The Curiously Recurring Template Pattern (CRTP). * * A class T has, as a base class, a template specialization of CRTP, taking T itself * as an argument. * \ingroup patterns */ template<typename T> class CRTP { public: CRTP() { } CRTP(const CRTP<T>&) { } T& unwrap() { return static_cast<T&>(*this); } const T& unwrap() const { return static_cast<const T&>(*this); } }; /** * \ingroup patterns */ template<class T> class singleton : private boost::noncopyable { public: /// \brief access to the unique instance static T& instance(); protected: singleton() {} static QM_SMART_PTR(T) m_instance; }; template <class T> QM_SMART_PTR(T) singleton<T>::m_instance; template <class T> T& singleton<T>::instance() { if(!m_instance) m_instance = QM_SMART_PTR(T)(new T); return *m_instance; } /// \brief Visitor for a specific class T /// \ingroup patterns template <class T> class visitor { public: virtual ~visitor() {}; // /// \brief Visit the "visited" class T /// @param pointer to T virtual void visit(T&) const {} }; /// \brief Reference counter class template<class T> class refCount : public T { public: refCount():m_references(0){} int reference() const { return m_references;} int addReference() {++m_references; return m_references;} int removeReference() { --m_references; return m_references; } T& cast() { return static_cast<T&>(*this); } const T& cast() const { return static_cast<const T&>(*this); } private: int m_references; }; template<class S> class simple_smart { typedef S elementtype; simple_smart():m_ptr(0){} private: refCount<S>* m_ptr; }; /* // class acyclicVisitor { public: virtual ~acyclicVisitor() {} }; // // # include<qmlib/impl/patterns_impl.hpp> // */ QM_NAMESPACE_END // #endif // __PATTERNS_QM_H__ //
[ [ [ 1, 120 ] ] ]
9aac8d5ad5539a04667d358dc2f4172c2ae25d47
bef7d0477a5cac485b4b3921a718394d5c2cf700
/nanobots/src/demo/map/TriangleMesh.cpp
f8cd29fb3895be81f16611a183c06a28c5d9f0d2
[ "MIT" ]
permissive
TomLeeLive/aras-p-dingus
ed91127790a604e0813cd4704acba742d3485400
22ef90c2bf01afd53c0b5b045f4dd0b59fe83009
refs/heads/master
2023-04-19T20:45:14.410448
2011-10-04T10:51:13
2011-10-04T10:51:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,029
cpp
#include "stdafx.h" #include "TriangleMesh.h" #include <dingus/math/Plane.h> // -------------------------------------------------------------------------- void CTriangleMesh::initFromSubdivMesh( const CSubdivMesh& sm ) { int i, n; // copy verts mVerts.resize( sm.getVerts().size() ); n = sm.getVerts().size(); for( i = 0; i < n; ++i ) { mVerts[i].pos = sm.getVerts()[i].pos; mVerts[i].normal = sm.getVerts()[i].normal; const SVector3& d = sm.getVerts()[i].data; mVerts[i].data.set( d.x, d.y, d.z, 0.0f ); } // create faces - each quad into two tris mFaces.resize( sm.getFaces().size() * 2 ); n = sm.getFaces().size(); for( i = 0; i < n; ++i ) { const CSubdivMesh::SFace& f = sm.getFaces()[i]; SFace& fa = mFaces[i*2+0]; fa.verts[0] = f.verts[0]; fa.verts[1] = f.verts[1]; fa.verts[2] = f.verts[2]; SFace& fb = mFaces[i*2+1]; fb.verts[0] = f.verts[0]; fb.verts[1] = f.verts[2]; fb.verts[2] = f.verts[3]; } // fill topology fillHalfEdges(); //checkValidity(); } void CTriangleMesh::optimize( float tolerance ) { int i; srand(0); int nverts = mVerts.size(); for( i = 0; i < nverts; ++i ) mVerts[i].data.w = 0.0f; // go thru hedges CONS << "optimize start: verts=" << (int)mVerts.size() << " tris=" << (int)mFaces.size() << endl; int collsDone = 0; for( int pass = 0; pass < 2; ++pass ) { int degenTriCount = 0; for( i = 0; i < mHEdges.size(); ) { const SHEdge& he = mHEdges[i]; int vIdxTo = he.vert; int vIdxFrom = mHEdges[he.other].vert; SVertex& vto = mVerts[vIdxTo]; const SVertex& vfrom = mVerts[vIdxFrom]; // go through "from" vertex adjacent faces, project "to" vertex // onto them, calc error float hedgeError = vfrom.data.w + vto.data.w; // cheesy fix: if "from" vert is on 0.0 height, and "to" is not, OR // vert heights are of different signs // then try to prevent this edge collapse if( fabsf(vfrom.pos.y) < 0.1f && fabsf(vto.pos.y) > 0.1f ) hedgeError = tolerance; else if( vfrom.pos.y * vto.pos.y < -0.1f ) hedgeError = tolerance; // can we collapse the hedge? if( hedgeError >= tolerance ) { ++i; continue; } int adjhe = vfrom.hedge; do { const SHEdge& he1 = mHEdges[adjhe]; const SHEdge& he2 = mHEdges[he1.next]; // just skip collapsing this if( he1.vert != vIdxTo && he2.vert != vIdxTo ) { // get verts const SVertex& vert1 = mVerts[he1.vert]; const SVertex& vert2 = mVerts[he2.vert]; // penalize long thin triangles SVector3 vecSide1 = vert1.pos - vto.pos; SVector3 vecSide2 = vert2.pos - vto.pos; vecSide1.normalize(); vecSide2.normalize(); float sideDot = vecSide1.dot( vecSide2 ); const float SKINNY = 0.99f; const float VERYSKINNY = 0.998f; if( sideDot < -VERYSKINNY || sideDot > VERYSKINNY ) hedgeError += tolerance; else if( sideDot < -SKINNY || sideDot > SKINNY ) hedgeError += tolerance * 0.2f; else { // check if this tri is degenerate // TBD: why there are degenerates in the first place??? vecSide1 = vert1.pos - vfrom.pos; vecSide2 = vert2.pos - vfrom.pos; vecSide1.normalize(); vecSide2.normalize(); sideDot = vecSide1.dot( vecSide2 ); if( sideDot < -VERYSKINNY || sideDot > VERYSKINNY ) { hedgeError += tolerance; ++degenTriCount; } else { // calc plane SPlane plane( vfrom.pos, vert1.pos, vert2.pos ); /* if( plane.a < -100 || plane.a > 100 ) assert( false ); if( plane.b < -100 || plane.b > 100 ) assert( false ); if( plane.c < -100 || plane.c > 100 ) assert( false ); if( plane.d < -1000 || plane.d > 1000 ) assert( false );*/ // distance of "to" to plane - error float errPos = fabsf( plane.distance( vto.pos ) ); //if( errPos < -1.0e6f || errPos > 1.0e6f ) // assert( false ); hedgeError += errPos; } } } adjhe = mHEdges[he1.other].next; } while( adjhe != vfrom.hedge && hedgeError < tolerance ); // can we collapse the hedge? if( hedgeError >= tolerance ) { ++i; continue; } assert( hedgeError >= 0.0f ); vto.data.w = hedgeError; bool ok = collapseHEdge( i ); if( ok ) { ++collsDone; } else { ++i; } } CONS << " degenerate tris: " << degenTriCount << endl; //CONS << "optimize pass " << pass << " collapses=" << collsDone << endl; } CONS << "optimize ended: verts=" << (int)mVerts.size() << " tris=" << (int)mFaces.size() << " collapses=" << collsDone << endl; fillFaceVerts(); checkValidity(); // DEBUG nverts = mVerts.size(); int* vcounts = new int[nverts]; memset( vcounts, 0, nverts*sizeof(vcounts[0]) ); int nfaces = mFaces.size(); for( i = 0; i < nfaces; ++i ) { const SFace& f = mFaces[i]; ++vcounts[f.verts[0]]; ++vcounts[f.verts[1]]; ++vcounts[f.verts[2]]; } for( i = 0; i < nverts; ++i ) { if( vcounts[i] >= 16 ) { CONS << "vert " << i << " in " << vcounts[i] << " at " << mVerts[i].pos << endl; } } delete[] vcounts; } bool CTriangleMesh::collapseHEdge( int hedge ) { // collapse removes: // 1 vertex (starting vert of this hedge) // 2 tris (bordering this hedge pair) // 6 half-edges (from the removed two tris) int he1idx = hedge; const SHEdge& he1 = mHEdges[he1idx]; int he2idx = he1.other; const SHEdge& he2 = mHEdges[he2idx]; int vIdxFrom = he2.vert; int vIdxTo = he1.vert; int fidx1 = he1.face; int fidx2 = he2.face; int colHedge1a = he1.next; const SHEdge& colHe1a = mHEdges[colHedge1a]; int colHedge1b = colHe1a.next; const SHEdge& colHe1b = mHEdges[colHedge1b]; int colHedge2a = he2.next; const SHEdge& colHe2a = mHEdges[colHedge2a]; int colHedge2b = colHe2a.next; const SHEdge& colHe2b = mHEdges[colHedge2b]; // check if hedge can be collapsed // side verts the same - no collapse int vIdxSide1 = colHe1a.vert; int vIdxSide2 = colHe2a.vert; if( vIdxSide1 == vIdxSide2 ) return false; const SVertex& vFrom = mVerts[vIdxFrom]; SVertex& vTo = mVerts[vIdxTo]; // if hedge vertices have common neighbors (excluding side verts), // then no collapse possible { int vhe1 = vFrom.hedge; do { const SHEdge& he = mHEdges[vhe1]; int hvertTo1 = he.vert; if( hvertTo1 != vIdxSide1 && hvertTo1 != vIdxSide2 ) { int vhe2 = vTo.hedge; do { const SHEdge& hhe = mHEdges[vhe2]; int hvertTo2 = hhe.vert; if( hvertTo2 == hvertTo1 ) return false; // no collapse vhe2 = mHEdges[hhe.other].next; } while( vhe2 != vTo.hedge ); } vhe1 = mHEdges[he.other].next; } while( vhe1 != vFrom.hedge ); } // go through "from" vertex hedges and update them to point to "to" vertex { int vhe = vFrom.hedge; do { SHEdge& he = mHEdges[ mHEdges[vhe].other ]; assert( he.vert == vIdxFrom ); he.vert = vIdxTo; vhe = he.next; } while( vhe != vFrom.hedge ); } // collapsing tris: pair their outer hedges mHEdges[colHe1a.other].other = colHe1b.other; mHEdges[colHe1b.other].other = colHe1a.other; mHEdges[colHe2a.other].other = colHe2b.other; mHEdges[colHe2b.other].other = colHe2a.other; // update the side verts' hedge indices mVerts[vIdxSide1].hedge = colHe1a.other; mVerts[vIdxSide2].hedge = colHe2a.other; vTo.hedge = colHe2b.other; // now, actually remove the things // hedges const int colHeCount = 6; int colHedges[colHeCount]; colHedges[0] = he1idx; colHedges[1] = he2idx; colHedges[2] = colHedge1a; colHedges[3] = colHedge1b; colHedges[4] = colHedge2a; colHedges[5] = colHedge2b; removeHEdges( colHeCount, colHedges ); // faces removeFace( fidx1, (fidx2==mFaces.size()-1) ); if( fidx2 == mFaces.size() ) fidx2 = fidx1; removeFace( fidx2, false ); // vertex removeVert( vIdxFrom ); return true; } void CTriangleMesh::removeHEdges( int count, int* hedges ) { for( int i = 0; i < count; ++i ) { int j; bool last4remove = false; for( j = i; j < count; ++j ) { if( hedges[j] == mHEdges.size()-1 ) { last4remove = true; break; } } removeHEdge( hedges[i], last4remove ); for( j = i+1; j < count; ++j ) { if( hedges[j] == mHEdges.size() ) hedges[j] = hedges[i]; } } } void CTriangleMesh::removeHEdge( int hedge, bool dontFixLast ) { // remove half-edge: place last one in place of it int lastHIdx = mHEdges.size()-1; SHEdge& he = mHEdges[hedge]; he = mHEdges[lastHIdx]; mHEdges.pop_back(); assert( dontFixLast || (hedge!=lastHIdx) ); if( dontFixLast ) return; // update it's paired hedge index mHEdges[he.other].other = hedge; // update it's face hedge index mFaces[he.face].hedge = hedge; // update it's previous hedge to point to new index, and update the vertex hedge SHEdge* hhe = &mHEdges[he.next]; do { hhe = &mHEdges[hhe->next]; } while( hhe->next != lastHIdx ); hhe->next = hedge; SVertex& v = mVerts[hhe->vert]; if( v.hedge == lastHIdx ) v.hedge = hedge; } void CTriangleMesh::removeVert( int vert ) { // remove vertex: place last one in place of it int lastVIdx = mVerts.size()-1; SVertex& v = mVerts[vert]; v = mVerts[lastVIdx]; mVerts.pop_back(); if( vert == lastVIdx ) return; // go through adjacent half-edges and update the vertex index int hedge = v.hedge; do { SHEdge& he = mHEdges[ mHEdges[hedge].other ]; assert( he.vert == lastVIdx ); he.vert = vert; hedge = he.next; } while( hedge != v.hedge ); } void CTriangleMesh::removeFace( int face, bool dontFixLast ) { // remove face: place last one in place of it int lastFIdx = mFaces.size()-1; if( lastFIdx == face ) dontFixLast = true; SFace& f = mFaces[face]; f = mFaces[lastFIdx]; mFaces.pop_back(); if( dontFixLast ) return; // go through border half-edges and update the face index int hedge = f.hedge; do { SHEdge& he = mHEdges[hedge]; assert( he.face == lastFIdx ); he.face = face; hedge = he.next; } while( hedge != f.hedge ); } /* void CTriangleMesh::collapseEdge( int vidx, int vedge ) { int i, j; const SVertex& cv = mVerts[vidx]; int colEdgeIdx = cv.edges[vedge]; const SEdge& cedge = mEdges[colEdgeIdx]; int newVertIdx = cedge.getOtherVert( vidx ); // collapse removes: // 1 vertex [i] // 2 faces [bordering edge colEdgeIdx] // 3 edges [colEdgeIdx, and two more that go from collapsed vertex and border the collapsed faces] for( i = 0; i < 2; ++i ) { // collapsing face int colFaceIdx = cedge.faces[i]; const SFace& colFace = mFaces[colFaceIdx]; // find collapsing edge int colEdgeSideIdx = -1; for( j = 0; j < cv.edgeCount; ++j ) { int ei = cv.edges[j]; if( ei == colEdgeIdx ) continue; if( mEdges[ei].findFace( colFaceIdx ) >= 0 ) { colEdgeSideIdx = ei; break; } } assert( colEdgeSideIdx >= 0 ); // find non-collapsed edge in the collapsing face // (one edge is the main collapse edge, other is "side edge") int noColEdgeIdx = -1; if( colFace.edges[0]!=colEdgeIdx && colFace.edges[0]!=colEdgeSideIdx ) noColEdgeIdx = colFace.edges[0]; else if( colFace.edges[1]!=colEdgeIdx && colFace.edges[1]!=colEdgeSideIdx ) noColEdgeIdx = colFace.edges[1]; else if( colFace.edges[2]!=colEdgeIdx && colFace.edges[2]!=colEdgeSideIdx ) noColEdgeIdx = colFace.edges[2]; assert( noColEdgeIdx >= 0 ); // now, update the topology: // collapsed face's non-collapsed edge: // update it's one face index int sideFaceIdx = mEdges[colEdgeSideIdx].getOtherFace( colFaceIdx ); SEdge& noColEdge = mEdges[noColEdgeIdx]; int cfaceIdxNoColEdge = noColEdge.findFace( colFaceIdx ); assert( cfaceIdxNoColEdge >= 0 ); noColEdge.faces[cfaceIdxNoColEdge^1] = sideFaceIdx; // } } */
[ [ [ 1, 412 ] ] ]
902c2c6241267acb6391f3daa873ab7812f08417
36d0ddb69764f39c440089ecebd10d7df14f75f3
/ใƒ—ใƒญใ‚ฐใƒฉใƒ /Framework/OpenGL/GraphicDeviceNglGL.h
cdf6afdfc9adbd36e21259582cb866c0e953934f
[]
no_license
weimingtom/tanuki-mo-issyo
3f57518b4e59f684db642bf064a30fc5cc4715b3
ab57362f3228354179927f58b14fa76b3d334472
refs/heads/master
2021-01-10T01:36:32.162752
2009-04-19T10:37:37
2009-04-19T10:37:37
48,733,344
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,453
h
/*******************************************************************************/ /** * @file GraphicDeviceNglGL.h.<br> * * @brief NGLใƒฉใ‚คใƒ–ใƒฉใƒชOpenGLใ‚ฐใƒฉใƒ•ใ‚ฃใƒƒใ‚ฏใƒ‡ใƒใ‚คใ‚นใ‚ฏใƒฉใ‚นใƒ˜ใƒƒใƒ€ใƒ•ใ‚กใ‚คใƒซ.<br> * * @date 2008/10/27.<br> * * @version 1.00. * * @author Kentarou Nishimura. */ /******************************************************************************/ #ifndef _GRAPHICDEVICENGLGL_H_ #define _GRAPHICDEVICENGLGL_H_ #include "GraphicDeviceBase.h" #include <Ngl/OpenGL/FrameWorkGLUT.h> /** * @brief NGLใƒฉใ‚คใƒ–ใƒฉใƒชOpenGLใ‚ฐใƒฉใƒ•ใ‚ฃใƒƒใ‚ฏใƒ‡ใƒใ‚คใ‚นใ‚ฏใƒฉใ‚น. */ class GraphicDeviceNglGL : public GraphicDeviceBase { public: /*=========================================================================*/ /** * ใ‚ณใƒณใ‚นใƒˆใƒฉใ‚ฏใ‚ฟ<br> * * @param[in] frame ใƒ•ใƒฌใƒผใƒ ใƒฏใƒผใ‚ฏ. */ GraphicDeviceNglGL( Ngl::OpenGL::FrameWorkGLUT& frame ); /*=========================================================================*/ /** * ใƒ‡ใ‚นใƒˆใƒฉใ‚ฏใ‚ฟ<br> * * @param[in] ใชใ—. */ virtual ~GraphicDeviceNglGL(); /*=========================================================================*/ /** * ไฝœๆˆๅ‡ฆ็†<br> * * @param[in] frame ใƒ•ใƒฌใƒผใƒ ใƒฏใƒผใ‚ฏ. * @return ใชใ—. */ void Create( Ngl::IFrameWork* frame ); }; #endif /*===== EOF ==================================================================*/
[ "rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33" ]
[ [ [ 1, 59 ] ] ]
f0261f91afaefca5417a07f705f7c8d6896fca3b
414125a8704145430a08fcd1a75016ecedbd2c70
/src/AMF3.h
9527be426995a54af96d09d3259fcac903b13791
[]
no_license
qykings/amf3cplusplus
0bfda6907b596d02900f374fcb4e1e607d59131d
7ad0adf0f7a87a4a3eff2e4290d9d6af1ef3d34c
refs/heads/master
2021-01-10T04:50:42.343277
2010-09-25T01:47:00
2010-09-25T01:47:00
43,055,238
1
0
null
null
null
null
UTF-8
C++
false
false
5,258
h
๏ปฟ/* Copyright (c) 2010 , 6spring 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 [email protected] 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. */ //---------------------------------------------- //Name๏ผšAMF3 Protocol //About๏ผšAMF3ๅ่ฎฎ๏ผˆ้ƒจๅˆ†๏ผ‰๏ผŒๆš‚ๆ—ถไป…ๆ”ฏๆŒwinๅนณๅฐ //Author๏ผš6Spring //Time: 2010/04/07 //EMail: [email protected] //---------------------------------------------- #pragma once #ifndef __AMF3_H__ #define __AMF3_H__ #include <Windows.h> #include <string> #include <vector> namespace AMF3 { //้ฟๅ…่งฃๆž้”™่ฏฏๅ‡บ่ฟ‡ๅคงobject๏ผŒๆœ€ๅคงๆ”ฏๆŒ็š„ๅŠจๆ€ๅญๅ…ƒ็ด ไธชๆ•ฐ #define DYNAMIC_OBJ_MAX_PROPERTY 512 //ๅผ•็”จๆ ‡ๅฟ—ไฝ #define REFERENCE_BIT 0x01 //็ฉบไธฒ #define EMPTY_STRING 0x01 //IO ่ฏปๅ†™ๅ‡ฝๆ•ฐ typedef int (*READ_FUNC)(void* file,size_t size,unsigned char* buf); typedef void (*WRITE_FUNC)(void* file,const unsigned char* buf,size_t size); //ๆ•ฐๆฎ็ฑปๅž‹ๅฎšไน‰ enum DataType { DT_UNDEFINED = 0x00, //unsupport DT_NULL = 0x01, DT_FALSE = 0x02, DT_TRUE = 0x03, DT_INTEGER = 0x04, DT_DOUBLE = 0x05, DT_STRING = 0x06, DT_XMLDOC = 0x07, //unsupport DT_DATE = 0x08, DT_ARRAY = 0x09, DT_OBJECT = 0x0A, DT_XML = 0x0B, //unsupport DT_BYTEARRAY = 0x0C }; class amf_object; /////////////////////////////////////////////////////////////////////////////// //obj handle ็”จไบŽobject็š„ๅผ•็”จ่ฎกๆ•ฐ่‡ชๅŠจๅŠ ๅ‡ // /////////////////////////////////////////////////////////////////////////////// class amf_object_handle { public: amf_object_handle(); amf_object_handle(const amf_object_handle &rhs); amf_object_handle(amf_object* obj); ~amf_object_handle(void); public: bool isnull(); void release(); public: amf_object_handle& operator = (const amf_object_handle &rhs); amf_object_handle& operator = (amf_object* obj); amf_object* operator -> () const; bool operator == (const amf_object_handle &rhs) const; private: amf_object* pobj; }; typedef std::vector<amf_object_handle> type_amf_ref_tab; /////////////////////////////////////////////////////////////////////////////// //object ๅ…ƒ็ด ๆ•ฐๆฎๅฏน่ฑก // /////////////////////////////////////////////////////////////////////////////// class amf_object { friend class amf_object_handle; public: static amf_object_handle Alloc(); protected: amf_object(); ~amf_object(void); public: void clear_value(); public: double get_time_seed(); void set_time_seed(double t); public: void set_as_unsigned_number(unsigned int num); void set_as_number(int num); public: void add_ref(); void release(); public: void add_child(amf_object_handle obj); bool has_child(const char* name); amf_object_handle get_child(const char* name); private: long ref; public: std::string classname; std::string name; DataType type; bool boolValue; int intValue; double doubleValue; std::string strValue; SYSTEMTIME dateValue; int bytearrayLen; unsigned char* bytearrayValue; std::vector<amf_object_handle> childrens; }; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// typedef struct _context { void* m_IFileHandle; void* m_OFileHandle; READ_FUNC m_ReadFunc; WRITE_FUNC m_WriteFunc; unsigned char* s_ReadBuf; int s_ReadBufSize; type_amf_ref_tab m_szReadObjRefTab; type_amf_ref_tab m_szReadStrRefTab; }context; /////////////////////////////////////////////////////////////////////////////// void init_context(context* ctx,READ_FUNC pRFunc,WRITE_FUNC pWFunc); void clear_context(context* ctx); amf_object_handle decode(context* ctx,void* file_handle); void encode(context* ctx,void* file_handle,amf_object_handle obj); }//end namespace AMF3 #endif
[ "6spring@9f2118ee-182d-f051-378b-c06e471c1d7c" ]
[ [ [ 1, 197 ] ] ]
45ed0f14d73bdfb589a6ab0e6581bc4f8ad87dde
5d3c1be292f6153480f3a372befea4172c683180
/trunk/Event Heap/c++/Mac OS X/include/eh2_EventHeapProtocolException.h
d67ce59e19afa2691b39e277b1dbf5ae956e7e4e
[ "Artistic-2.0" ]
permissive
BackupTheBerlios/istuff-svn
5f47aa73dd74ecf5c55f83765a5c50daa28fa508
d0bb9963b899259695553ccd2b01b35be5fb83db
refs/heads/master
2016-09-06T04:54:24.129060
2008-05-02T22:33:26
2008-05-02T22:33:26
40,820,013
0
0
null
null
null
null
UTF-8
C++
false
false
934
h
/* Copyright (c) 2003 The Board of Trustees of The Leland Stanford Junior * University. All Rights Reserved. * * See the file LICENSE.txt for information on redistributing this software. */ /* $Id: eh2_EventHeapProtocolException.h,v 1.2 2003/06/02 08:02:05 tomoto Exp $ */ #ifndef _EH2_EVENTHEAPPROTOCOLEXCEPTION_H_ #define _EH2_EVENTHEAPPROTOCOLEXCEPTION_H_ /** @file Definition of eh2_EventHeapProtocolException class. @internal This header belongs to the eh2i_cl component. */ #include <eh2_Base.h> #include <eh2_EventHeapException.h> /** Thrown when an protocol error occured. In the current implementation, this exception is thrown when protocol version mismatch was detected during connecting to the server. */ class EH2_DECL eh2_EventHeapProtocolException : public eh2_EventHeapException { IDK_UT_EXCEPTION_DECL(eh2_EventHeapProtocolException, eh2_EventHeapException); }; #endif
[ "ballagas@2a53cb5c-8ff1-0310-8b75-b3ec22923d26" ]
[ [ [ 1, 29 ] ] ]
87d35654f35584501e748b52e4e28edcb5392276
be2e23022d2eadb59a3ac3932180a1d9c9dee9c2
/GameServer/MapGroupKernel/WeatherRegion.h
1e6877ee7b974a9b5caed28b1284da97aa18ad4a
[]
no_license
cronoszeu/revresyksgpr
78fa60d375718ef789042c452cca1c77c8fa098e
5a8f637e78f7d9e3e52acdd7abee63404de27e78
refs/heads/master
2020-04-16T17:33:10.793895
2010-06-16T12:52:45
2010-06-16T12:52:45
35,539,807
0
2
null
null
null
null
UTF-8
C++
false
false
854
h
#pragma once #include "Weather.h" class CWeatherRegion : IWeatherOwner { protected: CWeatherRegion(); virtual ~CWeatherRegion(); public: static CWeatherRegion* CreateNew() { return new CWeatherRegion; } void ReleaseByOwner() { delete this; } OBJID GetID() { return m_pData->GetID(); } bool Create(CRegionData* pData, PROCESS_ID idProcess); CWeather* QueryWeather() { CHECKF(m_pWeather); return m_pWeather; } CRegionData* QueryRegion() { CHECKF(m_pData); return m_pData; } public: // interface virtual void BroadcastMsg(Msg* pMsg, CUser* pExclude=NULL); protected: CWeather* m_pWeather; CRegionData* m_pData; protected: // ctrl PROCESS_ID m_idProcess; MYHEAP_DECLARATION(s_heap) }; typedef IGameObjSet<CWeatherRegion> IWeatherSet; typedef CGameObjSet<CWeatherRegion> CWeatherSet;
[ "rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1" ]
[ [ [ 1, 35 ] ] ]
267af10a0045e512c99d61e1ee0196be95aa33e0
8cf9b251e0f4a23a6ef979c33ee96ff4bdb829ab
/src-ginga-editing/wac-editing-cpp/include/IFormatterAdapter.h
8ccbc2dd9700a486b19506c139b5b80be31fe6a5
[]
no_license
BrunoSSts/ginga-wac
7436a9815427a74032c9d58028394ccaac45cbf9
ea4c5ab349b971bd7f4f2b0940f2f595e6475d6c
refs/heads/master
2020-05-20T22:21:33.645904
2011-10-17T12:34:32
2011-10-17T12:34:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,622
h
/****************************************************************************** Este arquivo eh parte da implementacao do ambiente declarativo do middleware Ginga (Ginga-NCL). Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados. Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob os termos da Licenca Publica Geral GNU versao 2 conforme publicada pela Free Software Foundation. Este programa eh distribuido na expectativa de que seja util, porem, SEM NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do GNU versao 2 para mais detalhes. Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto com este programa; se nao, escreva para a Free Software Foundation, Inc., no endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. Para maiores informacoes: [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br ****************************************************************************** This file is part of the declarative environment of middleware Ginga (Ginga-NCL) Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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 version 2 for more details. You should have received a copy of the GNU General Public License version 2 along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA For further information contact: [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br *******************************************************************************/ /** * @file IFormatterAdapter.h * @author Caio Viel * @date 29-01-10 */ #ifndef IFORMATTERADAPTER_H #define IFORMATTERADAPTER_H #include "ncl/components/ContextNode.h" #include "ncl/components/CompositeNode.h" #include "ncl/components/ContentNode.h" #include "ncl/components/Node.h" #include "ncl/components/NodeEntity.h" using namespace ::br::pucrio::telemidia::ncl::components; #include "ncl/interfaces/Anchor.h" #include "ncl/interfaces/PropertyAnchor.h" #include "ncl/interfaces/Port.h" #include "ncl/interfaces/SwitchPort.h" #include "ncl/interfaces/InterfacePoint.h" using namespace ::br::pucrio::telemidia::ncl::interfaces; #include "ncl/switches/Rule.h" using namespace ::br::pucrio::telemidia::ncl::switches; #include "ncl/descriptor/GenericDescriptor.h" using namespace ::br::pucrio::telemidia::ncl::descriptor; #include "ncl/link/Bind.h" #include "ncl/link/CausalLink.h" #include "ncl/link/Link.h" #include "ncl/link/LinkComposition.h" using namespace ::br::pucrio::telemidia::ncl::link; #include "ncl/connectors/EventUtil.h" #include "ncl/connectors/SimpleAction.h" #include "ncl/connectors/Connector.h" using namespace ::br::pucrio::telemidia::ncl::connectors; #include "ncl/layout/LayoutRegion.h" using namespace ::br::pucrio::telemidia::ncl::layout; #include "ncl/reuse/ReferNode.h" using namespace ::br::pucrio::telemidia::ncl::reuse; #include "util/functions.h" using namespace ::br::pucrio::telemidia::util; #include "ncl/Base.h" #include "ncl/connectors/ConnectorBase.h" #include "ncl/descriptor/DescriptorBase.h" #include "ncl/layout/RegionBase.h" #include "ncl/switches/RuleBase.h" using namespace ::br::pucrio::telemidia::ncl; #include "ncl/transition/Transition.h" #include "ncl/transition/TransitionBase.h" using namespace ::br::pucrio::telemidia::ncl::transition; #include "ncl/NclDocument.h" using namespace ::br::pucrio::telemidia::ncl; #include <cstdlib> #include <string> using namespace std; namespace br { namespace ufscar { namespace lince { namespace ginga { namespace wac { namespace editing { /** * Interface que permite que as classes do mรณdulo Wac-Editing enviem mensagem a classe Formatter do mรณdulo Formatter. * Esta interface basicamente possuรญ todos os mรฉtodos de ediรงรฃo ao vivo (que pertencem ao formatter) e outros mรฉtodos * que sรฃo necessรกrios da classe Formatter para a execuรงรฃo do Ginga-Wac. */ class IFormatterAdapter { public: /** * Destrรณi IFormatterAdapter. */ virtual ~IFormatterAdapter() {}; /// Constante que indica ediรงรตes do cliente. static const int CLIENT_EDITING = 1; /// Constante que indica ediรงรตes da emissora. static const int BROADCASTER_EDITING =0; //Mรฉtodos de ediรงรฃo ao vivo do formatter. virtual LayoutRegion* addRegion( string compositeDocumentId, string regionId, string xmlRegion, int=BROADCASTER_EDITING)=0; virtual LayoutRegion* removeRegion(string compositeDocumentId, string regionId,int=BROADCASTER_EDITING)=0; virtual RegionBase* addRegionBase(string compositeDocumentId, string xmlRegionBase, int=BROADCASTER_EDITING)=0; virtual RegionBase* removeRegionBase(string compositeDocumentId, string regionBaseId, int=BROADCASTER_EDITING)=0; virtual Rule* addRule(string compositeDocumentId, string xmlRule, int=BROADCASTER_EDITING)=0; virtual Rule* removeRule(string compositeDocumentId, string ruleId, int=BROADCASTER_EDITING)=0; virtual RuleBase* addRuleBase(string compositeDocumentId, string xmlRuleBase, int=BROADCASTER_EDITING)=0; virtual RuleBase* removeRuleBase(string compositeDocumentId, string ruleBaseId, int=BROADCASTER_EDITING)=0; virtual Transition* addTransition(string compositeDocumentId, string xmlTransition, int=BROADCASTER_EDITING)=0; virtual Transition* removeTransition(string compositeDocumentId, string transitionId, int=BROADCASTER_EDITING)=0; virtual TransitionBase* addTransitionBase( string compositeDocumentId, string xmlTransitionBase, int=BROADCASTER_EDITING)=0; virtual TransitionBase* removeTransitionBase(string documentId, string transitionBaseId, int=BROADCASTER_EDITING)=0; virtual Connector* addConnector(string compositeDocumentId, string xmlConnector, int=BROADCASTER_EDITING)=0; virtual Connector* removeConnector(string compositeDocumentId, string connectorId, int=BROADCASTER_EDITING)=0; virtual ConnectorBase* addConnectorBase( string compositeDocumentId, string xmlConnectorBasem, int=BROADCASTER_EDITING)=0; virtual ConnectorBase* removeConnectorBase( string compositeDocumentId, string connectorBaseId, int=BROADCASTER_EDITING)=0; virtual GenericDescriptor* addDescriptor( string compositeDocumentId, string xmlDescriptor, int=BROADCASTER_EDITING)=0; virtual GenericDescriptor* removeDescriptor( string compositeDocumentId, string descriptorId, int=BROADCASTER_EDITING)=0; virtual DescriptorBase* addDescriptorBase( string compositeDocumentId, string xmlDescriptorBase, int=BROADCASTER_EDITING)=0; virtual DescriptorBase* removeDescriptorBase( string compositeDocumentId, string descriptorBaseId, int=BROADCASTER_EDITING)=0; virtual Base* addImportBase(string compositeDocumentId, string docBaseId, string xmlImportBase, int=BROADCASTER_EDITING)=0; virtual Base* removeImportBase(string compositeDocumentId, string docBaseId, string documentURI, int=BROADCASTER_EDITING)=0; virtual NclDocument* addImportedDocumentBase(string compositeDocumentId, string xmlImportedDocumentBase, int=BROADCASTER_EDITING)=0; virtual NclDocument* removeImportedDocumentBase( string compositeDocumentId, string importedDocumentBaseId, int=BROADCASTER_EDITING)=0; virtual NclDocument* addImportNCL(string compositeDocumentId, string xmlImportNCL, int=BROADCASTER_EDITING)=0; virtual NclDocument* removeImportNCL(string compositeDocumentId, string documentURI, int=BROADCASTER_EDITING)=0; virtual Node* addNode( string compositeDocumentId, string compositeId, string xmlNode, int=BROADCASTER_EDITING)=0; virtual Node* removeNode( string compositeDocumentId, string compositeId, string nodeId, int=BROADCASTER_EDITING)=0; virtual InterfacePoint* addInterface( string compositeDocumentId, string nodeId, string xmlInterface, int=BROADCASTER_EDITING)=0; virtual InterfacePoint* removeInterface( string compositeDocumentId, string nodeId, string interfaceId, int=BROADCASTER_EDITING)=0; virtual Link* addLink( string compositeDocumentId, string compositeId, string xmlLink, int=BROADCASTER_EDITING)=0; virtual Link* removeLink( string compositeDocumentId, string compositeId, string linkId, int=BROADCASTER_EDITING)=0; virtual bool setPropertyValue( string compositeDocumentId, string nodeId, string propertyId, string value)=0; /*virtual bool startDocument(string documentId, string interfaceId)=0; virtual bool stopDocument(string documentId)=0; virtual bool pauseDocument(string documentId)=0; virtual bool resumeDocument(string documentId)=0; virtual void addFormatterListener(IFormatterListener* listener)=0; virtual void removeFormatterListener(IFormatterListener* listener)=0; virtual void presentationCompleted(IFormatterEvent* documentEvent)=0;*/ }; } } } } } } #endif //IFORMATTERADAPTER_H
[ [ [ 1, 282 ] ] ]
87f7b82c7041dea05c5b64821eb4dc5443a04539
2eda21938786de13a565903d8b2feab25ac9ccb8
/LevelManager.h
088d39538306764067305e31bb2fe1e49ba1a96b
[]
no_license
gbougard/NBK
d2ed27fc825a8919c716e7011e1a7631a6bc3be1
e8155adec2da3f333230b050fccc164e1e3c04fe
refs/heads/master
2021-01-15T21:39:58.541842
2011-11-21T20:36:38
2011-11-21T20:36:38
3,157,757
0
0
null
null
null
null
UTF-8
C++
false
false
4,453
h
#ifndef LEVEL_MANAGER_H #define LEVEL_MANAGER_H #include "Block.h" #include "Manager.h" #include "ConsoleListener.h" /* Level represents a logical brother to the level written on the disk. It gets loaded from a file. Then it gets in charge of drawing blocks, water, lava, ceiling in FPS mode, terrain effects... */ namespace game_utils { namespace managers { class CLevelManager: public CManager, public control::CConsoleListener { public: CLevelManager(); ~CLevelManager(); // from CManager virtual bool init(); virtual bool update(); virtual bool shutdown(); // from CConsoleListener virtual std::string onAction(std::string keyword, std::string params); /* Checks is all necessary level files are present. */ bool levelExists(std::string levelFileName); /* Returns block if x&y are in normal bounds else NULL. */ game_objects::CBlock *getBlock(GLint x, GLint y); game_objects::CBlock *getBlockOld(GLint x, GLint y); game_objects::CBlock *getBlock(cml::vector2i pos); GLint getBlockType(GLint x, GLint y); GLint getBlockTypeOld(GLint x, GLint y); // for being able to use old code bool isBlockTypeNear(GLint blockType, GLint x, GLint y, bool diagonal, GLubyte owner, std::vector<game_objects::CBlock*> *blocks = NULL); bool isBlockTypeNear(GLint blockType, cml::vector2i logicalPos, bool diagonal, GLubyte owner, std::vector<game_objects::CBlock*> *blocks = NULL); bool isBlockClaimable(GLint x, GLint y, GLubyte owner, std::vector<game_objects::CBlock*> *blocks = NULL); bool isBlockClaimable(cml::vector2i logicalPos, GLubyte owner, std::vector<game_objects::CBlock*> *blocks = NULL); game_objects::CBlock *getUnclaimedBlock(GLubyte owner, cml::vector2i position); void getUnclaimedBlock(GLubyte owner, std::vector<game_objects::CBlock*> *blocks); game_objects::CBlock *getMarkedBlock(GLubyte owner, cml::vector2i position); game_objects::CBlock *getUnfortifiedBlock(GLubyte owner, cml::vector2i position); std::map<game_objects::CBlock*,game_objects::CBlock*> *getUnclaimedBlocksList(); GLvoid addUnclaimedBlock(game_objects::CBlock *block); GLvoid removeUnclaimedBlock(game_objects::CBlock *block); GLvoid addMarkedBlock(game_objects::CBlock *block); GLvoid removeMarkedBlock(game_objects::CBlock *block); GLvoid addUnfortifiedBlock(game_objects::CBlock *block); GLvoid removeUnfortifiedBlock(game_objects::CBlock *block); // returns true if this block is full type, bool isFullBlock(game_objects::CBlock *block); /* Some utility methods. */ /* Returns true if block on targetX, targetY is same type and owner as sourceBlock. */ bool isNotSameTypeAndOwnerAndNotRockOrEarth(GLint targetX, GLint targetY, game_objects::CBlock *sourceBlock); bool isSameTypeAndOwner(GLint targetX, GLint targetY, game_objects::CBlock *sourceBlock); bool isSameOwner(GLint targetX, GLint targetY, game_objects::CBlock *sourceBlock); bool isSameType(GLint targetX, GLint targetY, game_objects::CBlock *sourceBlock); /* Calculates ceiling hieght fo a specific block. Must be called: 1. all blocks init 2. all block ceiling height 3. all blocks finalize */ GLvoid calculateBlockCeilingHeight(game_objects::CBlock *block); private: game_objects::CBlock *levelMap[85][85]; /* Most important info about level is stored in: - OWN tells ownership of the map blocks - SLB what type are the map blocks - TNG items on the map */ bool loadSLB(std::string fileName); bool loadOWN(std::string fileName); bool loadTNG(std::string fileName); bool saveSLB(std::string fileName); bool saveOWN(std::string fileName); bool saveTNG(std::string fileName); /* A list of playable levels stored in data\resources\levels.conf. */ std::vector<std::string> levelFileNames; /* The block lists used for imps */ std::map<game_objects::CBlock*,game_objects::CBlock*> unclaimedBlocksList; std::map<game_objects::CBlock*,game_objects::CBlock*> markedBlocksList; std::map<game_objects::CBlock*,game_objects::CBlock*> unfortifiedBlocksList; /* A currently playing level; */ GLint currentLevel; std::string levelFileName; }; }; }; #endif // LEVEL_MANAGER_H
[ [ [ 1, 35 ], [ 37, 47 ], [ 67, 104 ], [ 108, 112 ], [ 120, 130 ] ], [ [ 36, 36 ], [ 48, 49 ], [ 53, 53 ], [ 56, 60 ], [ 113, 116 ], [ 119, 119 ] ], [ [ 50, 52 ], [ 54, 55 ], [ 61, 66 ], [ 105, 107 ], [ 117, 118 ] ] ]
9f9e97c56b96d1dd10998daffc96e652bab3ca92
4dd44d686f1b96f8e6edae3769369a89013f6bc1
/ocass/libocs/cs_core.cpp
8686af87d3b8ad59c70d52249734adef597cff21
[]
no_license
bactq/ocass
e1975533a69adbd1b4d1f9fd1bd88647039fff82
116565ea7c554b11b0a696f185d3a6376e0161dc
refs/heads/master
2021-01-10T14:04:02.179429
2007-07-14T16:03:23
2007-07-14T16:03:23
45,017,357
0
0
null
null
null
null
UTF-8
C++
false
false
3,565
cpp
/* * OCASS - Microsoft Office Communicator Assistant * (http://code.google.com/p/ocass/) * * Copyright (C) 2007 Le Xiongjia * * 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, see <http://www.gnu.org/licenses/>. * * Le Xiongjia ([email protected] [email protected]) * */ #include "liboca.h" #include "ca_ofc.h" #include "ca_cfg.h" #include "cs_core.h" #include "cs_wrk.h" #include "cs_misc.h" #include "cs_nti.h" #include "cs_log.h" #include "cs_inner.h" typedef struct _CS_CORE { CSWrk *pCoreWrk; } CSCore; static CSCore g_csCore = {0}; static CSCore *g_pCSCore = NULL; const CSWrk* CS_CoreGetWrkPtr(void) { if (NULL == g_pCSCore) { return NULL; } return g_pCSCore->pCoreWrk; } void CS_CoreOnDllLoad(HINSTANCE hInst) { } void CS_CoreOnDllUnload(HINSTANCE hInst) { if (NULL == g_pCSCore) { return; } CA_RTLog(CA_SRC_MARK, CA_RTLOG_INFO, TEXT("Start end spy work thread.")); /* close spy core thread */ CS_WrkStop(g_pCSCore->pCoreWrk); CA_RTSetLog(NULL, NULL); CA_RTSetLogFilter(NULL, NULL); CS_LogCleanup(); CA_Cleanup(); } CA_DECLARE_DYL(CAErrno) CS_Entry(HMODULE hLib, CACfgDatum *pCfgDatum) { CSLogCfg caLogCfg; CAErrno caErr; BOOL bResult; if (NULL != g_pCSCore) { /* already startup */ return CA_ERR_BAD_SEQ; } bResult = CS_IsRawOFCLoad(CS_GetDllInst()); if (!bResult) { /* not communicate proc */ return CA_ERR_BAD_SEQ; } caErr = CA_Startup(); if (CA_ERR_SUCCESS != caErr) { /* startup failed */ return caErr; } caErr = CA_CfgSetRT(pCfgDatum); if (CA_ERR_SUCCESS != caErr) { CA_Cleanup(); return caErr; } CA_RTSetLog(NULL, CS_RTLog); CA_RTSetLogFilter(NULL, CS_RTLogFilter); bResult = CA_OFCIsCommunicatorMod(NULL); if (!bResult) { /* not communicate proc */ CA_Cleanup(); return CA_ERR_BAD_SEQ; } /* startup log */ caLogCfg.pszSpyLogFName = pCfgDatum->szSpyLog; caLogCfg.dwSpyLogTSize = pCfgDatum->dwSpyLogTSize; caLogCfg.pszNtDumpLogFName = pCfgDatum->szSpyNtDump; caLogCfg.dwNtDumpLogTSize = pCfgDatum->dwSpyNtDumpTSize; caLogCfg.spyLogMask = pCfgDatum->spyLogMask; CS_LogStartup(&caLogCfg); caErr = CS_WrkStart(hLib, pCfgDatum, &g_csCore.pCoreWrk); if (CA_ERR_SUCCESS != caErr) { /* start wrk thread failed */ CA_RTLog(CA_SRC_MARK, CA_RTLOG_ERR, TEXT("Start spy work thread failed. error %u"), caErr); CA_Cleanup(); return caErr; } CA_RTLog(CA_SRC_MARK, CA_RTLOG_INFO, TEXT("Start spy work thread successed.")); /* attach network api */ CS_NtWrkApiAttach(); g_pCSCore = &g_csCore; return CA_ERR_SUCCESS; }
[ "lexiongjia@4b591cd5-a833-0410-8603-c1928dc92378" ]
[ [ [ 1, 145 ] ] ]
6dd9ad30bdf8fdd911a67562eb38f3e05731127c
43ba63c6de0dcfefab3bdc0bef7914b498f90eeb
/vrf/include/cThread.h
a11303f2e4cc99ad702f33f3363ddec3531604b5
[]
no_license
axelerator/Fluid
b074766c8820abdd56205903589c42aa0b02ab50
a23650142d2987a195f9ac86157e774023aaec3f
refs/heads/master
2021-01-20T09:01:49.865832
2010-12-28T20:19:41
2010-12-28T20:19:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
499
h
#ifndef CTHREAD_H #define CTHREAD_H #ifdef WIN32 #include <windows.h> #else #include <pthread.h> #endif class cThread { private: #ifdef WIN32 HANDLE pThread; static DWORD WINAPI pProc(LPVOID pPtr); #else pthread_t pThread; static void* pProc(void* pPtr); #endif private: virtual void run() = 0; public: virtual ~cThread() {}; void start(); void join(); }; #endif
[ [ [ 1, 27 ] ] ]
19f93af0673cdba11c2d73ed8fc3cb36341f7a78
3a577d02f876776b22e2bf1c0db12a083f49086d
/vba2/gba2/cartridgeinfo.cpp
e3bf0fc216558774eaeacfcd8c93980bb3b91db8
[]
no_license
xiaoluoyuan/VisualBoyAdvance-2
d19565617b26e1771f437842dba5f0131d774e73
cadd2193ba48e1846b45f87ff7c36246cd61b6ee
refs/heads/master
2021-01-10T01:19:23.884491
2010-05-12T09:59:37
2010-05-12T09:59:37
46,539,728
0
0
null
null
null
null
UTF-8
C++
false
false
4,783
cpp
/* VisualBoyAdvance 2 Copyright (C) 2009-2010 VBA development team 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/>. */ #include "cartridgeinfo.h" #include <assert.h> #include "backupmedia.h" CartridgeInfo::CartridgeInfo() { gameTitle[0] = '\0'; gameCode[0] = '\0'; makerCode[0] = '\0'; gameVersion = 0; debuggingEnabled = false; checksumOK = false; backupType = NONE; usesRTC = false; m_backupMedia = NULL; } inline void copyMemory( const u8 *from, u8 *to, u8 length ) { while( length-- ) { *to++ = *from++; } } bool CartridgeInfo::load( IChipMemory &rom ) { const u8 *romData = (const u8 *)rom.getData(); // read cartridge header from ROM copyMemory( romData + 0xA0, (u8*)gameTitle, 12 ); gameTitle[12] = 0; copyMemory( romData + 0xAC, (u8*)gameCode, 4 ); gameCode[4] = 0; copyMemory( romData + 0xB0, (u8*)makerCode, 2 ); makerCode[2] = 0; gameVersion = romData[0xBC]; // handle undefined instructions if bit 2 and 7 are set debuggingEnabled = romData[0x9C] & 0x84; // calculate checksum u8 chk = 0; for( u8 i = 0xA0; i <= 0xBC; i++ ) { chk -= romData[i]; } chk = ( chk - 0x19 ) & 0xFF; checksumOK = ( romData[0xBD] == chk ); scanChips( (const u32 *)romData, rom.getSize() ); if( m_backupMedia != NULL ) { // tell backup media what chip to emulate m_backupMedia->setType( backupType ); } return true; } void CartridgeInfo::connectBackupMedia( BackupMedia *backupMedia ) { m_backupMedia = backupMedia; } u32 stringToValue( const char s[5] ) { // maximum string length: 4 characters + zero byte u64 result = 0; for( int i = 0; i < 4; i++ ) { if( s[i] == 0 ) break; result |= ( s[i] << (i*8) ); } return result; } void CartridgeInfo::scanChips( const u32 *romData, u32 romSize ) { assert( (romData != NULL) && (romSize > 192) ); /* possible strings are: backup media: - "EEPROM_V" - "SRAM_V" - "SRAM_F_V" - "FLASH_V" - "FLASH512_V" - "FLASH1M_V" real-time clock: - "SIIRTC_V" It is assumed, that all strings are word-aligned. */ // first part const u32 _EEPR = stringToValue( "EEPR" ); // EEPROM const u32 _SRAM = stringToValue( "SRAM" ); // SRAM const u32 _FLAS = stringToValue( "FLAS" ); // FLASH const u32 _SIIR = stringToValue( "SIIR" ); // RTC // following parts const u32 _OM_V = stringToValue( "OM_V" ); // EEPROM const u32 __Vxx = stringToValue( "_V" ); // SRAM const u32 __F_V = stringToValue( "_F_V" ); // SRAM const u32 _H_Vx = stringToValue( "H_V" ); // FLASH 64 KiB const u32 _H512 = stringToValue( "H512" ); // FLASH 64 KiB const u32 _H1M_ = stringToValue( "H1M_" ); // FLASH 128 KiB const u32 _TC_V = stringToValue( "TC_V" ); // RTC const u32 endAdress = ( romSize / 4 ) - 2; bool saveTypeFound = false; bool rtcFound = false; BACKUPMEDIATYPE result = NONE; for( u32 a/*ddress*/ = 0; a < endAdress; a++ ) { const u32 block = romData[a]; if( block == _EEPR ) { // EEPROM if( romData[a+1] == _OM_V ) { result = EEPROM; saveTypeFound = true; } } else if( block == _SRAM ) { // SRAM const u32 next32 = romData[a+1]; const u32 next16 = next32 & 0xFFFF; if( ( next32 == __F_V ) || ( next16 == __Vxx ) ) { result = SRAM; saveTypeFound = true; } } else if( block == _FLAS ) { // FLASH const u32 next32 = romData[a+1]; const u32 next24 = next32 & 0xFFFFFF; if( next32 == _H1M_ ) { result = FLASH128KiB; saveTypeFound = true; } else if( ( next32 == _H512 ) || ( next24 == _H_Vx ) ) { result = FLASH64KiB; saveTypeFound = true; } } else if( block == _SIIR ) { // RTC const u32 next32 = romData[a+1]; if( next32 == _TC_V ) { rtcFound = true; } } if( saveTypeFound && rtcFound ) break; // finished } backupType = result; usesRTC = rtcFound; }
[ "spacy51@5a53c671-dd2d-0410-9261-3f5c817b7aa0" ]
[ [ [ 1, 179 ] ] ]
17183318fb0fdf0af636254f0859dfdb596e01be
4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4
/src/nvimage/DirectDrawSurface.cpp
e5fdb10da0194fcd830ab76e0a231294687fd34d
[]
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
37,773
cpp
// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <[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. #include <nvimage/DirectDrawSurface.h> #include <nvimage/ColorBlock.h> #include <nvimage/Image.h> #include <nvimage/BlockDXT.h> #include <nvimage/PixelFormat.h> #include <nvcore/Debug.h> #include <nvcore/Containers.h> // max #include <nvcore/StdStream.h> #include <string.h> // memset using namespace nv; #if !defined(MAKEFOURCC) # define MAKEFOURCC(ch0, ch1, ch2, ch3) \ (uint(uint8(ch0)) | (uint(uint8(ch1)) << 8) | \ (uint(uint8(ch2)) << 16) | (uint(uint8(ch3)) << 24 )) #endif namespace { static const uint FOURCC_DDS = MAKEFOURCC('D', 'D', 'S', ' '); static const uint FOURCC_DXT1 = MAKEFOURCC('D', 'X', 'T', '1'); static const uint FOURCC_DXT2 = MAKEFOURCC('D', 'X', 'T', '2'); static const uint FOURCC_DXT3 = MAKEFOURCC('D', 'X', 'T', '3'); static const uint FOURCC_DXT4 = MAKEFOURCC('D', 'X', 'T', '4'); static const uint FOURCC_DXT5 = MAKEFOURCC('D', 'X', 'T', '5'); static const uint FOURCC_RXGB = MAKEFOURCC('R', 'X', 'G', 'B'); static const uint FOURCC_ATI1 = MAKEFOURCC('A', 'T', 'I', '1'); static const uint FOURCC_ATI2 = MAKEFOURCC('A', 'T', 'I', '2'); static const uint FOURCC_A2XY = MAKEFOURCC('A', '2', 'X', 'Y'); static const uint FOURCC_DX10 = MAKEFOURCC('D', 'X', '1', '0'); // 32 bit RGB formats. static const uint D3DFMT_R8G8B8 = 20; static const uint D3DFMT_A8R8G8B8 = 21; static const uint D3DFMT_X8R8G8B8 = 22; static const uint D3DFMT_R5G6B5 = 23; static const uint D3DFMT_X1R5G5B5 = 24; static const uint D3DFMT_A1R5G5B5 = 25; static const uint D3DFMT_A4R4G4B4 = 26; static const uint D3DFMT_R3G3B2 = 27; static const uint D3DFMT_A8 = 28; static const uint D3DFMT_A8R3G3B2 = 29; static const uint D3DFMT_X4R4G4B4 = 30; static const uint D3DFMT_A2B10G10R10 = 31; static const uint D3DFMT_A8B8G8R8 = 32; static const uint D3DFMT_X8B8G8R8 = 33; static const uint D3DFMT_G16R16 = 34; static const uint D3DFMT_A2R10G10B10 = 35; static const uint D3DFMT_A16B16G16R16 = 36; // Palette formats. static const uint D3DFMT_A8P8 = 40; static const uint D3DFMT_P8 = 41; // Luminance formats. static const uint D3DFMT_L8 = 50; static const uint D3DFMT_A8L8 = 51; static const uint D3DFMT_A4L4 = 52; static const uint D3DFMT_L16 = 81; // Floating point formats static const uint D3DFMT_R16F = 111; static const uint D3DFMT_G16R16F = 112; static const uint D3DFMT_A16B16G16R16F = 113; static const uint D3DFMT_R32F = 114; static const uint D3DFMT_G32R32F = 115; static const uint D3DFMT_A32B32G32R32F = 116; static const uint DDSD_CAPS = 0x00000001U; static const uint DDSD_PIXELFORMAT = 0x00001000U; static const uint DDSD_WIDTH = 0x00000004U; static const uint DDSD_HEIGHT = 0x00000002U; static const uint DDSD_PITCH = 0x00000008U; static const uint DDSD_MIPMAPCOUNT = 0x00020000U; static const uint DDSD_LINEARSIZE = 0x00080000U; static const uint DDSD_DEPTH = 0x00800000U; static const uint DDSCAPS_COMPLEX = 0x00000008U; static const uint DDSCAPS_TEXTURE = 0x00001000U; static const uint DDSCAPS_MIPMAP = 0x00400000U; static const uint DDSCAPS2_VOLUME = 0x00200000U; static const uint DDSCAPS2_CUBEMAP = 0x00000200U; static const uint DDSCAPS2_CUBEMAP_POSITIVEX = 0x00000400U; static const uint DDSCAPS2_CUBEMAP_NEGATIVEX = 0x00000800U; static const uint DDSCAPS2_CUBEMAP_POSITIVEY = 0x00001000U; static const uint DDSCAPS2_CUBEMAP_NEGATIVEY = 0x00002000U; static const uint DDSCAPS2_CUBEMAP_POSITIVEZ = 0x00004000U; static const uint DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x00008000U; static const uint DDSCAPS2_CUBEMAP_ALL_FACES = 0x0000FC00U; static const uint DDPF_ALPHAPIXELS = 0x00000001U; static const uint DDPF_ALPHA = 0x00000002U; static const uint DDPF_FOURCC = 0x00000004U; static const uint DDPF_RGB = 0x00000040U; static const uint DDPF_PALETTEINDEXED1 = 0x00000800U; static const uint DDPF_PALETTEINDEXED2 = 0x00001000U; static const uint DDPF_PALETTEINDEXED4 = 0x00000008U; static const uint DDPF_PALETTEINDEXED8 = 0x00000020U; static const uint DDPF_LUMINANCE = 0x00020000U; static const uint DDPF_ALPHAPREMULT = 0x00008000U; static const uint DDPF_NORMAL = 0x80000000U; // @@ Custom nv flag. // DX10 formats. enum DXGI_FORMAT { DXGI_FORMAT_UNKNOWN = 0, DXGI_FORMAT_R32G32B32A32_TYPELESS = 1, DXGI_FORMAT_R32G32B32A32_FLOAT = 2, DXGI_FORMAT_R32G32B32A32_UINT = 3, DXGI_FORMAT_R32G32B32A32_SINT = 4, DXGI_FORMAT_R32G32B32_TYPELESS = 5, DXGI_FORMAT_R32G32B32_FLOAT = 6, DXGI_FORMAT_R32G32B32_UINT = 7, DXGI_FORMAT_R32G32B32_SINT = 8, DXGI_FORMAT_R16G16B16A16_TYPELESS = 9, DXGI_FORMAT_R16G16B16A16_FLOAT = 10, DXGI_FORMAT_R16G16B16A16_UNORM = 11, DXGI_FORMAT_R16G16B16A16_UINT = 12, DXGI_FORMAT_R16G16B16A16_SNORM = 13, DXGI_FORMAT_R16G16B16A16_SINT = 14, DXGI_FORMAT_R32G32_TYPELESS = 15, DXGI_FORMAT_R32G32_FLOAT = 16, DXGI_FORMAT_R32G32_UINT = 17, DXGI_FORMAT_R32G32_SINT = 18, DXGI_FORMAT_R32G8X24_TYPELESS = 19, DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 20, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21, DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 22, DXGI_FORMAT_R10G10B10A2_TYPELESS = 23, DXGI_FORMAT_R10G10B10A2_UNORM = 24, DXGI_FORMAT_R10G10B10A2_UINT = 25, DXGI_FORMAT_R11G11B10_FLOAT = 26, DXGI_FORMAT_R8G8B8A8_TYPELESS = 27, DXGI_FORMAT_R8G8B8A8_UNORM = 28, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29, DXGI_FORMAT_R8G8B8A8_UINT = 30, DXGI_FORMAT_R8G8B8A8_SNORM = 31, DXGI_FORMAT_R8G8B8A8_SINT = 32, DXGI_FORMAT_R16G16_TYPELESS = 33, DXGI_FORMAT_R16G16_FLOAT = 34, DXGI_FORMAT_R16G16_UNORM = 35, DXGI_FORMAT_R16G16_UINT = 36, DXGI_FORMAT_R16G16_SNORM = 37, DXGI_FORMAT_R16G16_SINT = 38, DXGI_FORMAT_R32_TYPELESS = 39, DXGI_FORMAT_D32_FLOAT = 40, DXGI_FORMAT_R32_FLOAT = 41, DXGI_FORMAT_R32_UINT = 42, DXGI_FORMAT_R32_SINT = 43, DXGI_FORMAT_R24G8_TYPELESS = 44, DXGI_FORMAT_D24_UNORM_S8_UINT = 45, DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 46, DXGI_FORMAT_X24_TYPELESS_G8_UINT = 47, DXGI_FORMAT_R8G8_TYPELESS = 48, DXGI_FORMAT_R8G8_UNORM = 49, DXGI_FORMAT_R8G8_UINT = 50, DXGI_FORMAT_R8G8_SNORM = 51, DXGI_FORMAT_R8G8_SINT = 52, DXGI_FORMAT_R16_TYPELESS = 53, DXGI_FORMAT_R16_FLOAT = 54, DXGI_FORMAT_D16_UNORM = 55, DXGI_FORMAT_R16_UNORM = 56, DXGI_FORMAT_R16_UINT = 57, DXGI_FORMAT_R16_SNORM = 58, DXGI_FORMAT_R16_SINT = 59, DXGI_FORMAT_R8_TYPELESS = 60, DXGI_FORMAT_R8_UNORM = 61, DXGI_FORMAT_R8_UINT = 62, DXGI_FORMAT_R8_SNORM = 63, DXGI_FORMAT_R8_SINT = 64, DXGI_FORMAT_A8_UNORM = 65, DXGI_FORMAT_R1_UNORM = 66, DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 67, DXGI_FORMAT_R8G8_B8G8_UNORM = 68, DXGI_FORMAT_G8R8_G8B8_UNORM = 69, DXGI_FORMAT_BC1_TYPELESS = 70, DXGI_FORMAT_BC1_UNORM = 71, DXGI_FORMAT_BC1_UNORM_SRGB = 72, DXGI_FORMAT_BC2_TYPELESS = 73, DXGI_FORMAT_BC2_UNORM = 74, DXGI_FORMAT_BC2_UNORM_SRGB = 75, DXGI_FORMAT_BC3_TYPELESS = 76, DXGI_FORMAT_BC3_UNORM = 77, DXGI_FORMAT_BC3_UNORM_SRGB = 78, DXGI_FORMAT_BC4_TYPELESS = 79, DXGI_FORMAT_BC4_UNORM = 80, DXGI_FORMAT_BC4_SNORM = 81, DXGI_FORMAT_BC5_TYPELESS = 82, DXGI_FORMAT_BC5_UNORM = 83, DXGI_FORMAT_BC5_SNORM = 84, DXGI_FORMAT_B5G6R5_UNORM = 85, DXGI_FORMAT_B5G5R5A1_UNORM = 86, DXGI_FORMAT_B8G8R8A8_UNORM = 87, DXGI_FORMAT_B8G8R8X8_UNORM = 88, }; enum D3D10_RESOURCE_DIMENSION { D3D10_RESOURCE_DIMENSION_UNKNOWN = 0, D3D10_RESOURCE_DIMENSION_BUFFER = 1, D3D10_RESOURCE_DIMENSION_TEXTURE1D = 2, D3D10_RESOURCE_DIMENSION_TEXTURE2D = 3, D3D10_RESOURCE_DIMENSION_TEXTURE3D = 4, }; const char * getDxgiFormatString(DXGI_FORMAT dxgiFormat) { #define CASE(format) case DXGI_FORMAT_##format: return #format switch(dxgiFormat) { CASE(UNKNOWN); CASE(R32G32B32A32_TYPELESS); CASE(R32G32B32A32_FLOAT); CASE(R32G32B32A32_UINT); CASE(R32G32B32A32_SINT); CASE(R32G32B32_TYPELESS); CASE(R32G32B32_FLOAT); CASE(R32G32B32_UINT); CASE(R32G32B32_SINT); CASE(R16G16B16A16_TYPELESS); CASE(R16G16B16A16_FLOAT); CASE(R16G16B16A16_UNORM); CASE(R16G16B16A16_UINT); CASE(R16G16B16A16_SNORM); CASE(R16G16B16A16_SINT); CASE(R32G32_TYPELESS); CASE(R32G32_FLOAT); CASE(R32G32_UINT); CASE(R32G32_SINT); CASE(R32G8X24_TYPELESS); CASE(D32_FLOAT_S8X24_UINT); CASE(R32_FLOAT_X8X24_TYPELESS); CASE(X32_TYPELESS_G8X24_UINT); CASE(R10G10B10A2_TYPELESS); CASE(R10G10B10A2_UNORM); CASE(R10G10B10A2_UINT); CASE(R11G11B10_FLOAT); CASE(R8G8B8A8_TYPELESS); CASE(R8G8B8A8_UNORM); CASE(R8G8B8A8_UNORM_SRGB); CASE(R8G8B8A8_UINT); CASE(R8G8B8A8_SNORM); CASE(R8G8B8A8_SINT); CASE(R16G16_TYPELESS); CASE(R16G16_FLOAT); CASE(R16G16_UNORM); CASE(R16G16_UINT); CASE(R16G16_SNORM); CASE(R16G16_SINT); CASE(R32_TYPELESS); CASE(D32_FLOAT); CASE(R32_FLOAT); CASE(R32_UINT); CASE(R32_SINT); CASE(R24G8_TYPELESS); CASE(D24_UNORM_S8_UINT); CASE(R24_UNORM_X8_TYPELESS); CASE(X24_TYPELESS_G8_UINT); CASE(R8G8_TYPELESS); CASE(R8G8_UNORM); CASE(R8G8_UINT); CASE(R8G8_SNORM); CASE(R8G8_SINT); CASE(R16_TYPELESS); CASE(R16_FLOAT); CASE(D16_UNORM); CASE(R16_UNORM); CASE(R16_UINT); CASE(R16_SNORM); CASE(R16_SINT); CASE(R8_TYPELESS); CASE(R8_UNORM); CASE(R8_UINT); CASE(R8_SNORM); CASE(R8_SINT); CASE(A8_UNORM); CASE(R1_UNORM); CASE(R9G9B9E5_SHAREDEXP); CASE(R8G8_B8G8_UNORM); CASE(G8R8_G8B8_UNORM); CASE(BC1_TYPELESS); CASE(BC1_UNORM); CASE(BC1_UNORM_SRGB); CASE(BC2_TYPELESS); CASE(BC2_UNORM); CASE(BC2_UNORM_SRGB); CASE(BC3_TYPELESS); CASE(BC3_UNORM); CASE(BC3_UNORM_SRGB); CASE(BC4_TYPELESS); CASE(BC4_UNORM); CASE(BC4_SNORM); CASE(BC5_TYPELESS); CASE(BC5_UNORM); CASE(BC5_SNORM); CASE(B5G6R5_UNORM); CASE(B5G5R5A1_UNORM); CASE(B8G8R8A8_UNORM); CASE(B8G8R8X8_UNORM); default: return "UNKNOWN"; } #undef CASE } const char * getD3d10ResourceDimensionString(D3D10_RESOURCE_DIMENSION resourceDimension) { switch(resourceDimension) { default: case D3D10_RESOURCE_DIMENSION_UNKNOWN: return "UNKNOWN"; case D3D10_RESOURCE_DIMENSION_BUFFER: return "BUFFER"; case D3D10_RESOURCE_DIMENSION_TEXTURE1D: return "TEXTURE1D"; case D3D10_RESOURCE_DIMENSION_TEXTURE2D: return "TEXTURE2D"; case D3D10_RESOURCE_DIMENSION_TEXTURE3D: return "TEXTURE3D"; } } } // namespace namespace nv { static Stream & operator<< (Stream & s, DDSPixelFormat & pf) { nvStaticCheck(sizeof(DDSPixelFormat) == 32); s << pf.size; s << pf.flags; s << pf.fourcc; s << pf.bitcount; s << pf.rmask; s << pf.gmask; s << pf.bmask; s << pf.amask; return s; } static Stream & operator<< (Stream & s, DDSCaps & caps) { nvStaticCheck(sizeof(DDSCaps) == 16); s << caps.caps1; s << caps.caps2; s << caps.caps3; s << caps.caps4; return s; } static Stream & operator<< (Stream & s, DDSHeader10 & header) { nvStaticCheck(sizeof(DDSHeader10) == 20); s << header.dxgiFormat; s << header.resourceDimension; s << header.miscFlag; s << header.arraySize; s << header.reserved; return s; } Stream & operator<< (Stream & s, DDSHeader & header) { nvStaticCheck(sizeof(DDSHeader) == 148); s << header.fourcc; s << header.size; s << header.flags; s << header.height; s << header.width; s << header.pitch; s << header.depth; s << header.mipmapcount; s.serialize(header.reserved, 11 * sizeof(uint)); s << header.pf; s << header.caps; s << header.notused; if (header.hasDX10Header()) { s << header.header10; } return s; } } // nv namespace /* Not used! namespace { struct FormatDescriptor { uint format; uint bitcount; uint rmask; uint gmask; uint bmask; uint amask; }; static const FormatDescriptor s_d3dFormats[] = { { D3DFMT_R8G8B8, 24, 0xFF0000, 0xFF00, 0xFF, 0 }, { D3DFMT_A8R8G8B8, 32, 0xFF0000, 0xFF00, 0xFF, 0xFF000000 }, // DXGI_FORMAT_B8G8R8A8_UNORM { D3DFMT_X8R8G8B8, 32, 0xFF0000, 0xFF00, 0xFF, 0 }, // DXGI_FORMAT_B8G8R8X8_UNORM { D3DFMT_R5G6B5, 16, 0xF800, 0x7E0, 0x1F, 0 }, // DXGI_FORMAT_B5G6R5_UNORM { D3DFMT_X1R5G5B5, 16, 0x7C00, 0x3E0, 0x1F, 0 }, { D3DFMT_A1R5G5B5, 16, 0x7C00, 0x3E0, 0x1F, 0x8000 }, // DXGI_FORMAT_B5G5R5A1_UNORM { D3DFMT_A4R4G4B4, 16, 0xF00, 0xF0, 0xF, 0xF000 }, { D3DFMT_R3G3B2, 8, 0xE0, 0x1C, 0x3, 0 }, { D3DFMT_A8, 8, 0, 0, 0, 8 }, // DXGI_FORMAT_A8_UNORM { D3DFMT_A8R3G3B2, 16, 0xE0, 0x1C, 0x3, 0xFF00 }, { D3DFMT_X4R4G4B4, 16, 0xF00, 0xF0, 0xF, 0 }, { D3DFMT_A2B10G10R10, 32, 0x3FF, 0xFFC00, 0x3FF00000, 0xC0000000 }, // DXGI_FORMAT_R10G10B10A2 { D3DFMT_A8B8G8R8, 32, 0xFF, 0xFF00, 0xFF0000, 0xFF000000 }, // DXGI_FORMAT_R8G8B8A8_UNORM { D3DFMT_X8B8G8R8, 32, 0xFF, 0xFF00, 0xFF0000, 0 }, { D3DFMT_G16R16, 32, 0xFFFF, 0xFFFF0000, 0, 0 }, // DXGI_FORMAT_R16G16_UNORM { D3DFMT_A2R10G10B10, 32, 0x3FF00000, 0xFFC00, 0x3FF, 0xC0000000 }, { D3DFMT_L8, 8, 8, 0, 0, 0 }, // DXGI_FORMAT_R8_UNORM { D3DFMT_L16, 16, 16, 0, 0, 0 }, // DXGI_FORMAT_R16_UNORM }; static const uint s_d3dFormatCount = sizeof(s_d3dFormats) / sizeof(s_d3dFormats[0]); static uint findD3D9Format(uint bitcount, uint rmask, uint gmask, uint bmask, uint amask) { for (int i = 0; i < s_d3dFormatCount; i++) { if (s_d3dFormats[i].bitcount == bitcount && s_d3dFormats[i].rmask == rmask && s_d3dFormats[i].gmask == gmask && s_d3dFormats[i].bmask == bmask && s_d3dFormats[i].amask == amask) { return s_d3dFormats[i].format; } } return 0; } } // nv namespace */ DDSHeader::DDSHeader() { this->fourcc = FOURCC_DDS; this->size = 124; this->flags = (DDSD_CAPS|DDSD_PIXELFORMAT); this->height = 0; this->width = 0; this->pitch = 0; this->depth = 0; this->mipmapcount = 0; memset(this->reserved, 0, sizeof(this->reserved)); // Store version information on the reserved header attributes. this->reserved[9] = MAKEFOURCC('N', 'V', 'T', 'T'); this->reserved[10] = (2 << 16) | (1 << 8) | (0); // major.minor.revision this->pf.size = 32; this->pf.flags = 0; this->pf.fourcc = 0; this->pf.bitcount = 0; this->pf.rmask = 0; this->pf.gmask = 0; this->pf.bmask = 0; this->pf.amask = 0; this->caps.caps1 = DDSCAPS_TEXTURE; this->caps.caps2 = 0; this->caps.caps3 = 0; this->caps.caps4 = 0; this->notused = 0; this->header10.dxgiFormat = DXGI_FORMAT_UNKNOWN; this->header10.resourceDimension = D3D10_RESOURCE_DIMENSION_UNKNOWN; this->header10.miscFlag = 0; this->header10.arraySize = 0; this->header10.reserved = 0; } void DDSHeader::setWidth(uint w) { this->flags |= DDSD_WIDTH; this->width = w; } void DDSHeader::setHeight(uint h) { this->flags |= DDSD_HEIGHT; this->height = h; } void DDSHeader::setDepth(uint d) { this->flags |= DDSD_DEPTH; this->depth = d; } void DDSHeader::setMipmapCount(uint count) { if (count == 0 || count == 1) { this->flags &= ~DDSD_MIPMAPCOUNT; this->mipmapcount = 0; if (this->caps.caps2 == 0) { this->caps.caps1 = DDSCAPS_TEXTURE; } else { this->caps.caps1 = DDSCAPS_TEXTURE | DDSCAPS_COMPLEX; } } else { this->flags |= DDSD_MIPMAPCOUNT; this->mipmapcount = count; this->caps.caps1 |= DDSCAPS_COMPLEX | DDSCAPS_MIPMAP; } } void DDSHeader::setTexture2D() { this->header10.resourceDimension = D3D10_RESOURCE_DIMENSION_TEXTURE2D; this->header10.arraySize = 1; } void DDSHeader::setTexture3D() { this->caps.caps2 = DDSCAPS2_VOLUME; this->header10.resourceDimension = D3D10_RESOURCE_DIMENSION_TEXTURE3D; this->header10.arraySize = 1; } void DDSHeader::setTextureCube() { this->caps.caps1 |= DDSCAPS_COMPLEX; this->caps.caps2 = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_ALL_FACES; this->header10.resourceDimension = D3D10_RESOURCE_DIMENSION_TEXTURE2D; this->header10.arraySize = 6; } void DDSHeader::setLinearSize(uint size) { this->flags &= ~DDSD_PITCH; this->flags |= DDSD_LINEARSIZE; this->pitch = size; } void DDSHeader::setPitch(uint pitch) { this->flags &= ~DDSD_LINEARSIZE; this->flags |= DDSD_PITCH; this->pitch = pitch; } void DDSHeader::setFourCC(uint8 c0, uint8 c1, uint8 c2, uint8 c3) { // set fourcc pixel format. this->pf.flags = DDPF_FOURCC; this->pf.fourcc = MAKEFOURCC(c0, c1, c2, c3); this->pf.bitcount = 0; this->pf.rmask = 0; this->pf.gmask = 0; this->pf.bmask = 0; this->pf.amask = 0; } void DDSHeader::setFormatCode(uint32 code) { // set fourcc pixel format. this->pf.flags = DDPF_FOURCC; this->pf.fourcc = code; this->pf.bitcount = 0; this->pf.rmask = 0; this->pf.gmask = 0; this->pf.bmask = 0; this->pf.amask = 0; } void DDSHeader::setSwizzleCode(uint8 c0, uint8 c1, uint8 c2, uint8 c3) { this->pf.bitcount = MAKEFOURCC(c0, c1, c2, c3); } void DDSHeader::setPixelFormat(uint bitcount, uint rmask, uint gmask, uint bmask, uint amask) { // Make sure the masks are correct. nvCheck((rmask & gmask) == 0); nvCheck((rmask & bmask) == 0); nvCheck((rmask & amask) == 0); nvCheck((gmask & bmask) == 0); nvCheck((gmask & amask) == 0); nvCheck((bmask & amask) == 0); this->pf.flags = DDPF_RGB; if (amask != 0) { this->pf.flags |= DDPF_ALPHAPIXELS; } if (bitcount == 0) { // Compute bit count from the masks. uint total = rmask | gmask | bmask | amask; while(total != 0) { bitcount++; total >>= 1; } } nvCheck(bitcount > 0 && bitcount <= 32); // Align to 8. if (bitcount <= 8) bitcount = 8; else if (bitcount <= 16) bitcount = 16; else if (bitcount <= 24) bitcount = 24; else bitcount = 32; this->pf.fourcc = 0; //findD3D9Format(bitcount, rmask, gmask, bmask, amask); this->pf.bitcount = bitcount; this->pf.rmask = rmask; this->pf.gmask = gmask; this->pf.bmask = bmask; this->pf.amask = amask; } void DDSHeader::setDX10Format(uint format) { //this->pf.flags = 0; this->pf.fourcc = FOURCC_DX10; this->header10.dxgiFormat = format; } void DDSHeader::setNormalFlag(bool b) { if (b) this->pf.flags |= DDPF_NORMAL; else this->pf.flags &= ~DDPF_NORMAL; } void DDSHeader::swapBytes() { this->fourcc = POSH_LittleU32(this->fourcc); this->size = POSH_LittleU32(this->size); this->flags = POSH_LittleU32(this->flags); this->height = POSH_LittleU32(this->height); this->width = POSH_LittleU32(this->width); this->pitch = POSH_LittleU32(this->pitch); this->depth = POSH_LittleU32(this->depth); this->mipmapcount = POSH_LittleU32(this->mipmapcount); for(int i = 0; i < 11; i++) { this->reserved[i] = POSH_LittleU32(this->reserved[i]); } this->pf.size = POSH_LittleU32(this->pf.size); this->pf.flags = POSH_LittleU32(this->pf.flags); this->pf.fourcc = POSH_LittleU32(this->pf.fourcc); this->pf.bitcount = POSH_LittleU32(this->pf.bitcount); this->pf.rmask = POSH_LittleU32(this->pf.rmask); this->pf.gmask = POSH_LittleU32(this->pf.gmask); this->pf.bmask = POSH_LittleU32(this->pf.bmask); this->pf.amask = POSH_LittleU32(this->pf.amask); this->caps.caps1 = POSH_LittleU32(this->caps.caps1); this->caps.caps2 = POSH_LittleU32(this->caps.caps2); this->caps.caps3 = POSH_LittleU32(this->caps.caps3); this->caps.caps4 = POSH_LittleU32(this->caps.caps4); this->notused = POSH_LittleU32(this->notused); this->header10.dxgiFormat = POSH_LittleU32(this->header10.dxgiFormat); this->header10.resourceDimension = POSH_LittleU32(this->header10.resourceDimension); this->header10.miscFlag = POSH_LittleU32(this->header10.miscFlag); this->header10.arraySize = POSH_LittleU32(this->header10.arraySize); this->header10.reserved = POSH_LittleU32(this->header10.reserved); } bool DDSHeader::hasDX10Header() const { return this->pf.fourcc == FOURCC_DX10; // @@ This is according to AMD //return this->pf.flags == 0; // @@ This is according to MS } DirectDrawSurface::DirectDrawSurface(const char * name) : stream(new StdInputStream(name)) { if (!stream->isError()) { (*stream) << header; } } DirectDrawSurface::~DirectDrawSurface() { delete stream; } bool DirectDrawSurface::isValid() const { if (stream->isError()) { return false; } if (header.fourcc != FOURCC_DDS || header.size != 124) { return false; } const uint required = (DDSD_WIDTH|DDSD_HEIGHT/*|DDSD_CAPS|DDSD_PIXELFORMAT*/); if( (header.flags & required) != required ) { return false; } if (header.pf.size != 32) { return false; } if( !(header.caps.caps1 & DDSCAPS_TEXTURE) ) { return false; } return true; } bool DirectDrawSurface::isSupported() const { nvDebugCheck(isValid()); if (header.hasDX10Header()) { if (header.header10.dxgiFormat == DXGI_FORMAT_BC1_UNORM || header.header10.dxgiFormat == DXGI_FORMAT_BC2_UNORM || header.header10.dxgiFormat == DXGI_FORMAT_BC3_UNORM || header.header10.dxgiFormat == DXGI_FORMAT_BC4_UNORM || header.header10.dxgiFormat == DXGI_FORMAT_BC5_UNORM) { return true; } return false; } else { if (header.pf.flags & DDPF_FOURCC) { if (header.pf.fourcc != FOURCC_DXT1 && header.pf.fourcc != FOURCC_DXT2 && header.pf.fourcc != FOURCC_DXT3 && header.pf.fourcc != FOURCC_DXT4 && header.pf.fourcc != FOURCC_DXT5 && header.pf.fourcc != FOURCC_RXGB && header.pf.fourcc != FOURCC_ATI1 && header.pf.fourcc != FOURCC_ATI2) { // Unknown fourcc code. return false; } } else if (header.pf.flags & DDPF_RGB) { // All RGB formats are supported now. } else { return false; } if (isTextureCube() && (header.caps.caps2 & DDSCAPS2_CUBEMAP_ALL_FACES) != DDSCAPS2_CUBEMAP_ALL_FACES) { // Cubemaps must contain all faces. return false; } if (isTexture3D()) { // @@ 3D textures not supported yet. return false; } } return true; } bool DirectDrawSurface::hasAlpha() const { if (header.hasDX10Header()) { // @@ TODO: Update with all formats. return header.header10.dxgiFormat == DXGI_FORMAT_BC1_UNORM || header.header10.dxgiFormat == DXGI_FORMAT_BC2_UNORM || header.header10.dxgiFormat == DXGI_FORMAT_BC3_UNORM; } else { if (header.pf.flags & DDPF_RGB) { return header.pf.amask != 0; } else if (header.pf.flags & DDPF_FOURCC) { if (header.pf.fourcc == FOURCC_RXGB || header.pf.fourcc == FOURCC_ATI1 || header.pf.fourcc == FOURCC_ATI2 || header.pf.flags & DDPF_NORMAL) { return false; } else { return true; } } return false; } } uint DirectDrawSurface::mipmapCount() const { nvDebugCheck(isValid()); if (header.flags & DDSD_MIPMAPCOUNT) return header.mipmapcount; else return 1; } uint DirectDrawSurface::width() const { nvDebugCheck(isValid()); if (header.flags & DDSD_WIDTH) return header.width; else return 1; } uint DirectDrawSurface::height() const { nvDebugCheck(isValid()); if (header.flags & DDSD_HEIGHT) return header.height; else return 1; } uint DirectDrawSurface::depth() const { nvDebugCheck(isValid()); if (header.flags & DDSD_DEPTH) return header.depth; else return 1; } bool DirectDrawSurface::isTexture1D() const { nvDebugCheck(isValid()); if (header.hasDX10Header()) { return header.header10.resourceDimension == D3D10_RESOURCE_DIMENSION_TEXTURE1D; } return false; } bool DirectDrawSurface::isTexture2D() const { nvDebugCheck(isValid()); if (header.hasDX10Header()) { return header.header10.resourceDimension == D3D10_RESOURCE_DIMENSION_TEXTURE2D; } else { return !isTexture3D() && !isTextureCube(); } } bool DirectDrawSurface::isTexture3D() const { nvDebugCheck(isValid()); if (header.hasDX10Header()) { return header.header10.resourceDimension == D3D10_RESOURCE_DIMENSION_TEXTURE3D; } else { return (header.caps.caps2 & DDSCAPS2_VOLUME) != 0; } } bool DirectDrawSurface::isTextureCube() const { nvDebugCheck(isValid()); return (header.caps.caps2 & DDSCAPS2_CUBEMAP) != 0; } void DirectDrawSurface::setNormalFlag(bool b) { nvDebugCheck(isValid()); header.setNormalFlag(b); } void DirectDrawSurface::mipmap(Image * img, uint face, uint mipmap) { nvDebugCheck(isValid()); stream->seek(offset(face, mipmap)); uint w = width(); uint h = height(); // Compute width and height. for (uint m = 0; m < mipmap; m++) { w = max(1U, w / 2); h = max(1U, h / 2); } img->allocate(w, h); if (hasAlpha()) { img->setFormat(Image::Format_ARGB); } else { img->setFormat(Image::Format_RGB); } if (header.hasDX10Header()) { // So far only block formats supported. readBlockImage(img); } else { if (header.pf.flags & DDPF_RGB) { readLinearImage(img); } else if (header.pf.flags & DDPF_FOURCC) { readBlockImage(img); } } } void DirectDrawSurface::readLinearImage(Image * img) { nvDebugCheck(stream != NULL); nvDebugCheck(img != NULL); const uint w = img->width(); const uint h = img->height(); uint rshift, rsize; PixelFormat::maskShiftAndSize(header.pf.rmask, &rshift, &rsize); uint gshift, gsize; PixelFormat::maskShiftAndSize(header.pf.gmask, &gshift, &gsize); uint bshift, bsize; PixelFormat::maskShiftAndSize(header.pf.bmask, &bshift, &bsize); uint ashift, asize; PixelFormat::maskShiftAndSize(header.pf.amask, &ashift, &asize); uint byteCount = (header.pf.bitcount + 7) / 8; // Read linear RGB images. for (uint y = 0; y < h; y++) { for (uint x = 0; x < w; x++) { uint c = 0; stream->serialize(&c, byteCount); Color32 pixel(0, 0, 0, 0xFF); pixel.r = PixelFormat::convert(c >> rshift, rsize, 8); pixel.g = PixelFormat::convert(c >> gshift, gsize, 8); pixel.b = PixelFormat::convert(c >> bshift, bsize, 8); pixel.a = PixelFormat::convert(c >> ashift, asize, 8); img->pixel(x, y) = pixel; } } } void DirectDrawSurface::readBlockImage(Image * img) { nvDebugCheck(stream != NULL); nvDebugCheck(img != NULL); const uint w = img->width(); const uint h = img->height(); const uint bw = (w + 3) / 4; const uint bh = (h + 3) / 4; for (uint by = 0; by < bh; by++) { for (uint bx = 0; bx < bw; bx++) { ColorBlock block; // Read color block. readBlock(&block); // Write color block. for (uint y = 0; y < min(4U, h-4*by); y++) { for (uint x = 0; x < min(4U, w-4*bx); x++) { img->pixel(4*bx+x, 4*by+y) = block.color(x, y); } } } } } static Color32 buildNormal(uint8 x, uint8 y) { float nx = 2 * (x / 255.0f) - 1; float ny = 2 * (y / 255.0f) - 1; float nz = 0.0f; if (1 - nx*nx - ny*ny > 0) nz = sqrtf(1 - nx*nx - ny*ny); uint8 z = clamp(int(255.0f * (nz + 1) / 2.0f), 0, 255); return Color32(x, y, z); } void DirectDrawSurface::readBlock(ColorBlock * rgba) { nvDebugCheck(stream != NULL); nvDebugCheck(rgba != NULL); uint fourcc = header.pf.fourcc; // Map DX10 block formats to fourcc codes. if (header.hasDX10Header()) { if (header.header10.dxgiFormat == DXGI_FORMAT_BC1_UNORM) fourcc = FOURCC_DXT1; if (header.header10.dxgiFormat == DXGI_FORMAT_BC2_UNORM) fourcc = FOURCC_DXT3; if (header.header10.dxgiFormat == DXGI_FORMAT_BC3_UNORM) fourcc = FOURCC_DXT5; if (header.header10.dxgiFormat == DXGI_FORMAT_BC4_UNORM) fourcc = FOURCC_ATI1; if (header.header10.dxgiFormat == DXGI_FORMAT_BC5_UNORM) fourcc = FOURCC_ATI2; } if (fourcc == FOURCC_DXT1) { BlockDXT1 block; *stream << block; block.decodeBlock(rgba); } else if (fourcc == FOURCC_DXT2 || header.pf.fourcc == FOURCC_DXT3) { BlockDXT3 block; *stream << block; block.decodeBlock(rgba); } else if (fourcc == FOURCC_DXT4 || header.pf.fourcc == FOURCC_DXT5 || header.pf.fourcc == FOURCC_RXGB) { BlockDXT5 block; *stream << block; block.decodeBlock(rgba); if (fourcc == FOURCC_RXGB) { // Swap R & A. for (int i = 0; i < 16; i++) { Color32 & c = rgba->color(i); uint tmp = c.r; c.r = c.a; c.a = tmp; } } } else if (fourcc == FOURCC_ATI1) { BlockATI1 block; *stream << block; block.decodeBlock(rgba); } else if (fourcc == FOURCC_ATI2) { BlockATI2 block; *stream << block; block.decodeBlock(rgba); } // If normal flag set, convert to normal. if (header.pf.flags & DDPF_NORMAL) { if (fourcc == FOURCC_ATI2) { for (int i = 0; i < 16; i++) { Color32 & c = rgba->color(i); c = buildNormal(c.r, c.g); } } else if (fourcc == FOURCC_DXT5) { for (int i = 0; i < 16; i++) { Color32 & c = rgba->color(i); c = buildNormal(c.a, c.g); } } } } uint DirectDrawSurface::blockSize() const { switch(header.pf.fourcc) { case FOURCC_DXT1: case FOURCC_ATI1: return 8; case FOURCC_DXT2: case FOURCC_DXT3: case FOURCC_DXT4: case FOURCC_DXT5: case FOURCC_RXGB: case FOURCC_ATI2: return 16; case FOURCC_DX10: switch(header.header10.dxgiFormat) { case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC1_UNORM: case DXGI_FORMAT_BC1_UNORM_SRGB: case DXGI_FORMAT_BC4_TYPELESS: case DXGI_FORMAT_BC4_UNORM: case DXGI_FORMAT_BC4_SNORM: return 8; case DXGI_FORMAT_BC2_TYPELESS: case DXGI_FORMAT_BC2_UNORM: case DXGI_FORMAT_BC2_UNORM_SRGB: case DXGI_FORMAT_BC3_TYPELESS: case DXGI_FORMAT_BC3_UNORM: case DXGI_FORMAT_BC3_UNORM_SRGB: case DXGI_FORMAT_BC5_TYPELESS: case DXGI_FORMAT_BC5_UNORM: case DXGI_FORMAT_BC5_SNORM: return 16; }; }; // Not a block image. return 0; } uint DirectDrawSurface::mipmapSize(uint mipmap) const { uint w = width(); uint h = height(); uint d = depth(); for (uint m = 0; m < mipmap; m++) { w = max(1U, w / 2); h = max(1U, h / 2); d = max(1U, d / 2); } if (header.pf.flags & DDPF_FOURCC) { // @@ How are 3D textures aligned? w = (w + 3) / 4; h = (h + 3) / 4; return blockSize() * w * h; } else { nvDebugCheck(header.pf.flags & DDPF_RGB); // Align pixels to bytes. uint byteCount = (header.pf.bitcount + 7) / 8; // Align pitch to 4 bytes. uint pitch = 4 * ((w * byteCount + 3) / 4); return pitch * h * d; } } uint DirectDrawSurface::faceSize() const { const uint count = mipmapCount(); uint size = 0; for (uint m = 0; m < count; m++) { size += mipmapSize(m); } return size; } uint DirectDrawSurface::offset(const uint face, const uint mipmap) { uint size = 128; // sizeof(DDSHeader); if (header.hasDX10Header()) { size += 20; // sizeof(DDSHeader10); } if (face != 0) { size += face * faceSize(); } for (uint m = 0; m < mipmap; m++) { size += mipmapSize(m); } return size; } void DirectDrawSurface::printInfo() const { printf("Flags: 0x%.8X\n", header.flags); if (header.flags & DDSD_CAPS) printf("\tDDSD_CAPS\n"); if (header.flags & DDSD_PIXELFORMAT) printf("\tDDSD_PIXELFORMAT\n"); if (header.flags & DDSD_WIDTH) printf("\tDDSD_WIDTH\n"); if (header.flags & DDSD_HEIGHT) printf("\tDDSD_HEIGHT\n"); if (header.flags & DDSD_DEPTH) printf("\tDDSD_DEPTH\n"); if (header.flags & DDSD_PITCH) printf("\tDDSD_PITCH\n"); if (header.flags & DDSD_LINEARSIZE) printf("\tDDSD_LINEARSIZE\n"); if (header.flags & DDSD_MIPMAPCOUNT) printf("\tDDSD_MIPMAPCOUNT\n"); printf("Height: %d\n", header.height); printf("Width: %d\n", header.width); printf("Depth: %d\n", header.depth); if (header.flags & DDSD_PITCH) printf("Pitch: %d\n", header.pitch); else if (header.flags & DDSD_LINEARSIZE) printf("Linear size: %d\n", header.pitch); printf("Mipmap count: %d\n", header.mipmapcount); printf("Pixel Format:\n"); printf("\tFlags: 0x%.8X\n", header.pf.flags); if (header.pf.flags & DDPF_RGB) printf("\t\tDDPF_RGB\n"); if (header.pf.flags & DDPF_FOURCC) printf("\t\tDDPF_FOURCC\n"); if (header.pf.flags & DDPF_ALPHAPIXELS) printf("\t\tDDPF_ALPHAPIXELS\n"); if (header.pf.flags & DDPF_ALPHA) printf("\t\tDDPF_ALPHA\n"); if (header.pf.flags & DDPF_PALETTEINDEXED1) printf("\t\tDDPF_PALETTEINDEXED1\n"); if (header.pf.flags & DDPF_PALETTEINDEXED2) printf("\t\tDDPF_PALETTEINDEXED2\n"); if (header.pf.flags & DDPF_PALETTEINDEXED4) printf("\t\tDDPF_PALETTEINDEXED4\n"); if (header.pf.flags & DDPF_PALETTEINDEXED8) printf("\t\tDDPF_PALETTEINDEXED8\n"); if (header.pf.flags & DDPF_ALPHAPREMULT) printf("\t\tDDPF_ALPHAPREMULT\n"); if (header.pf.flags & DDPF_NORMAL) printf("\t\tDDPF_NORMAL\n"); printf("\tFourCC: '%c%c%c%c'\n", ((header.pf.fourcc >> 0) & 0xFF), ((header.pf.fourcc >> 8) & 0xFF), ((header.pf.fourcc >> 16) & 0xFF), ((header.pf.fourcc >> 24) & 0xFF)); if ((header.pf.fourcc & DDPF_FOURCC) && (header.pf.bitcount != 0)) { printf("\tSwizzle: '%c%c%c%c'\n", (header.pf.bitcount >> 0) & 0xFF, (header.pf.bitcount >> 8) & 0xFF, (header.pf.bitcount >> 16) & 0xFF, (header.pf.bitcount >> 24) & 0xFF); } else { printf("\tBit count: %d\n", header.pf.bitcount); } printf("\tRed mask: 0x%.8X\n", header.pf.rmask); printf("\tGreen mask: 0x%.8X\n", header.pf.gmask); printf("\tBlue mask: 0x%.8X\n", header.pf.bmask); printf("\tAlpha mask: 0x%.8X\n", header.pf.amask); printf("Caps:\n"); printf("\tCaps 1: 0x%.8X\n", header.caps.caps1); if (header.caps.caps1 & DDSCAPS_COMPLEX) printf("\t\tDDSCAPS_COMPLEX\n"); if (header.caps.caps1 & DDSCAPS_TEXTURE) printf("\t\tDDSCAPS_TEXTURE\n"); if (header.caps.caps1 & DDSCAPS_MIPMAP) printf("\t\tDDSCAPS_MIPMAP\n"); printf("\tCaps 2: 0x%.8X\n", header.caps.caps2); if (header.caps.caps2 & DDSCAPS2_VOLUME) printf("\t\tDDSCAPS2_VOLUME\n"); else if (header.caps.caps2 & DDSCAPS2_CUBEMAP) { printf("\t\tDDSCAPS2_CUBEMAP\n"); if ((header.caps.caps2 & DDSCAPS2_CUBEMAP_ALL_FACES) == DDSCAPS2_CUBEMAP_ALL_FACES) printf("\t\tDDSCAPS2_CUBEMAP_ALL_FACES\n"); else { if (header.caps.caps2 & DDSCAPS2_CUBEMAP_POSITIVEX) printf("\t\tDDSCAPS2_CUBEMAP_POSITIVEX\n"); if (header.caps.caps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) printf("\t\tDDSCAPS2_CUBEMAP_NEGATIVEX\n"); if (header.caps.caps2 & DDSCAPS2_CUBEMAP_POSITIVEY) printf("\t\tDDSCAPS2_CUBEMAP_POSITIVEY\n"); if (header.caps.caps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) printf("\t\tDDSCAPS2_CUBEMAP_NEGATIVEY\n"); if (header.caps.caps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) printf("\t\tDDSCAPS2_CUBEMAP_POSITIVEZ\n"); if (header.caps.caps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) printf("\t\tDDSCAPS2_CUBEMAP_NEGATIVEZ\n"); } } printf("\tCaps 3: 0x%.8X\n", header.caps.caps3); printf("\tCaps 4: 0x%.8X\n", header.caps.caps4); if (header.hasDX10Header()) { printf("DX10 Header:\n"); printf("\tDXGI Format: %u (%s)\n", header.header10.dxgiFormat, getDxgiFormatString((DXGI_FORMAT)header.header10.dxgiFormat)); printf("\tResource dimension: %u (%s)\n", header.header10.resourceDimension, getD3d10ResourceDimensionString((D3D10_RESOURCE_DIMENSION)header.header10.resourceDimension)); printf("\tMisc flag: %u\n", header.header10.miscFlag); printf("\tArray size: %u\n", header.header10.arraySize); } if (header.reserved[9] == MAKEFOURCC('N', 'V', 'T', 'T')) { int major = (header.reserved[10] >> 16) & 0xFF; int minor = (header.reserved[10] >> 8) & 0xFF; int revision= header.reserved[10] & 0xFF; printf("Version:\n"); printf("\tNVIDIA Texture Tools %d.%d.%d\n", major, minor, revision); } }
[ "castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c" ]
[ [ [ 1, 1405 ] ] ]
0d564839f1f87efec43bdab12b4153ac5b5a6299
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2006-01-19/eeschema/dangling_ends.cpp
cba1c73ac17801b314d2908f0131c0b19c571be4
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
ISO-8859-1
C++
false
false
11,579
cpp
/*********************/ /* dangling_ends.cpp */ /*********************/ #include "fctsys.h" #include "gr_basic.h" #include "common.h" #include "program.h" #include "libcmp.h" #include "general.h" #include "netlist.h" /* Definitions generales liees au calcul de netliste */ #include "protos.h" enum End_Type { UNKNOWN = 0, WIRE_START_END, WIRE_END_END, BUS_START_END, BUS_END_END, JUNCTION_END, PIN_END, LABEL_END, ENTRY_END, SHEET_LABEL_END }; class DanglingEndHandle { public: const void * m_Item; wxPoint m_Pos; int m_Type; DanglingEndHandle * m_Pnext; DanglingEndHandle(int type) { m_Item = NULL; m_Type = type; m_Pnext = NULL; } }; DanglingEndHandle * ItemList; static void TestWireForDangling(EDA_DrawLineStruct * DrawRef, WinEDA_SchematicFrame * frame, wxDC * DC); void TestLabelForDangling(DrawTextStruct * label, WinEDA_SchematicFrame * frame, wxDC * DC); DanglingEndHandle * RebuildEndList(EDA_BaseStruct *DrawList); /**********************************************************/ bool SegmentIntersect(int Sx1, int Sy1, int Sx2, int Sy2, int Px1, int Py1) /**********************************************************/ /* Retourne TRUE si le point P est sur le segment S. Le segment est suppose horizontal ou vertical. */ { int Sxmin, Sxmax, Symin, Symax; if (Sx1 == Sx2) /* Line S is vertical. */ { Symin = MIN(Sy1, Sy2); Symax = MAX(Sy1, Sy2); if (Px1 != Sx1) return FALSE; if (Py1 >= Symin && Py1 <= Symax) return TRUE; else return FALSE; } else if (Sy1 == Sy2) /* Line S is horizontal. */ { Sxmin = MIN(Sx1, Sx2); Sxmax = MAX(Sx1, Sx2); if (Py1 != Sy1) return FALSE; if (Px1 >= Sxmin && Px1 <= Sxmax) return TRUE; else return FALSE; } else return FALSE; // Segments quelconques } /******************************************************************************/ void WinEDA_SchematicFrame::TestDanglingEnds(EDA_BaseStruct *DrawList, wxDC *DC) /******************************************************************************/ /* Met a jour les membres m_Dangling des wires, bus, labels */ { EDA_BaseStruct * DrawItem; const DanglingEndHandle * DanglingItem, * nextitem; if ( ItemList ) for ( DanglingItem = ItemList; DanglingItem != NULL; DanglingItem = nextitem) { nextitem = DanglingItem->m_Pnext; delete DanglingItem; } ItemList = RebuildEndList(DrawList); // Controle des elements for ( DrawItem = DrawList; DrawItem != NULL; DrawItem= DrawItem->Pnext) { switch( DrawItem->m_StructType ) { case DRAW_GLOBAL_LABEL_STRUCT_TYPE: case DRAW_LABEL_STRUCT_TYPE: #undef STRUCT #define STRUCT ((DrawLabelStruct*)DrawItem) TestLabelForDangling(STRUCT, this, DC); break; break; case DRAW_SEGMENT_STRUCT_TYPE: #undef STRUCT #define STRUCT ((EDA_DrawLineStruct*)DrawItem) if( STRUCT->m_Layer == LAYER_WIRE) { TestWireForDangling(STRUCT, this, DC); break; } if( STRUCT->m_Layer == LAYER_NOTES) break; if( STRUCT->m_Layer == LAYER_BUS) { STRUCT->m_StartIsDangling = STRUCT->m_EndIsDangling = FALSE; break; } break; } } } /********************************************************************/ LibDrawPin * WinEDA_SchematicFrame::LocatePinEnd(EDA_BaseStruct *DrawList, const wxPoint & pos) /********************************************************************/ /* Teste si le point de coordonnรฉes pos est sur l'extrรฉmitรฉ d'une PIN retourne un pointeur sur la pin NULL sinon */ { EDA_SchComponentStruct * DrawLibItem; LibDrawPin * Pin; wxPoint pinpos; Pin = LocateAnyPin(DrawList,pos, &DrawLibItem); if( ! Pin ) return NULL; pinpos = Pin->m_Pos; if(DrawLibItem == NULL ) pinpos.y = -pinpos.y; else { int x1 = pinpos.x, y1 = pinpos.y; pinpos.x = DrawLibItem->m_Pos.x + DrawLibItem->m_Transform[0][0] * x1 + DrawLibItem->m_Transform[0][1] * y1; pinpos.y = DrawLibItem->m_Pos.y + DrawLibItem->m_Transform[1][0] * x1 + DrawLibItem->m_Transform[1][1] * y1; } if( (pos.x == pinpos.x) && (pos.y == pinpos.y) ) return Pin; return NULL; } /****************************************************************************/ void TestWireForDangling(EDA_DrawLineStruct * DrawRef, WinEDA_SchematicFrame * frame, wxDC * DC) /****************************************************************************/ { DanglingEndHandle * terminal_item; bool Sdangstate = TRUE, Edangstate = TRUE; for ( terminal_item = ItemList; terminal_item != NULL; terminal_item = terminal_item->m_Pnext) { if ( terminal_item->m_Item == DrawRef ) continue; if ( (DrawRef->m_Start.x == terminal_item->m_Pos.x) && (DrawRef->m_Start.y == terminal_item->m_Pos.y) ) Sdangstate = FALSE; if ( (DrawRef->m_End.x == terminal_item->m_Pos.x) && (DrawRef->m_End.y == terminal_item->m_Pos.y) ) Edangstate = FALSE; if ( (Sdangstate == FALSE) && (Edangstate == FALSE) ) break; } if ( (Sdangstate != DrawRef->m_StartIsDangling) || (Edangstate != DrawRef->m_EndIsDangling) ) { if ( DC ) RedrawOneStruct(frame->DrawPanel,DC, DrawRef, g_XorMode); DrawRef->m_StartIsDangling = Sdangstate; DrawRef->m_EndIsDangling = Edangstate; if ( DC ) RedrawOneStruct(frame->DrawPanel,DC, DrawRef, GR_DEFAULT_DRAWMODE); } } /********************************************************/ void TestLabelForDangling(DrawTextStruct * label, WinEDA_SchematicFrame * frame, wxDC * DC) /********************************************************/ { DanglingEndHandle * terminal_item; bool dangstate = TRUE; for ( terminal_item = ItemList; terminal_item != NULL; terminal_item = terminal_item->m_Pnext) { if ( terminal_item->m_Item == label ) continue; switch( terminal_item->m_Type ) { case PIN_END: case LABEL_END: case SHEET_LABEL_END: if ( (label->m_Pos.x == terminal_item->m_Pos.x) && (label->m_Pos.y == terminal_item->m_Pos.y) ) dangstate = FALSE; break; case WIRE_START_END: case BUS_START_END: dangstate = ! SegmentIntersect(terminal_item->m_Pos.x, terminal_item->m_Pos.y, terminal_item->m_Pnext->m_Pos.x, terminal_item->m_Pnext->m_Pos.y, label->m_Pos.x, label->m_Pos.y); terminal_item = terminal_item->m_Pnext; break; case UNKNOWN: case JUNCTION_END: case ENTRY_END: case WIRE_END_END: case BUS_END_END: break; } if (dangstate == FALSE) break; } if ( dangstate != label->m_IsDangling ) { if ( DC ) RedrawOneStruct(frame->DrawPanel,DC, label, g_XorMode); label->m_IsDangling = dangstate; if ( DC ) RedrawOneStruct(frame->DrawPanel,DC, label, GR_DEFAULT_DRAWMODE); } } /****************************************************/ wxPoint ReturnPinPhysicalPosition( LibDrawPin * Pin, EDA_SchComponentStruct * DrawLibItem) /****************************************************/ /* Retourne la position physique de la pin, qui dรฉpend de l'orientation du composant */ { wxPoint PinPos = Pin->m_Pos; if(DrawLibItem == NULL ) PinPos.y = -PinPos.y; else { int x = Pin->m_Pos.x, y = Pin->m_Pos.y; PinPos.x = DrawLibItem->m_Pos.x + DrawLibItem->m_Transform[0][0] * x + DrawLibItem->m_Transform[0][1] * y; PinPos.y = DrawLibItem->m_Pos.y + DrawLibItem->m_Transform[1][0] * x + DrawLibItem->m_Transform[1][1] * y; } return PinPos; } /***********************************************************/ DanglingEndHandle * RebuildEndList(EDA_BaseStruct *DrawList) /***********************************************************/ { DanglingEndHandle * StartList = NULL, *item, *lastitem = NULL; EDA_BaseStruct * DrawItem; for ( DrawItem = DrawList; DrawItem != NULL; DrawItem = DrawItem->Pnext) { switch( DrawItem->m_StructType ) { case DRAW_LABEL_STRUCT_TYPE: break; case DRAW_GLOBAL_LABEL_STRUCT_TYPE: #undef STRUCT #define STRUCT ((DrawGlobalLabelStruct*)DrawItem) item = new DanglingEndHandle(LABEL_END); item->m_Item = DrawItem; item->m_Pos = STRUCT->m_Pos; if ( lastitem ) lastitem->m_Pnext = item; else StartList = item; lastitem = item; break; case DRAW_SEGMENT_STRUCT_TYPE: #undef STRUCT #define STRUCT ((EDA_DrawLineStruct*)DrawItem) if( STRUCT->m_Layer == LAYER_NOTES ) break; if( (STRUCT->m_Layer == LAYER_BUS) || (STRUCT->m_Layer == LAYER_WIRE) ) { item = new DanglingEndHandle((STRUCT->m_Layer == LAYER_BUS) ? BUS_START_END : WIRE_START_END); item->m_Item = DrawItem; item->m_Pos = STRUCT->m_Start; if ( lastitem ) lastitem->m_Pnext = item; else StartList = item; lastitem = item; item = new DanglingEndHandle((STRUCT->m_Layer == LAYER_BUS) ? BUS_END_END : WIRE_END_END); item->m_Item = DrawItem; item->m_Pos = STRUCT->m_End; lastitem->m_Pnext = item; lastitem = item; } break; case DRAW_JUNCTION_STRUCT_TYPE: #undef STRUCT #define STRUCT ((DrawJunctionStruct*)DrawItem) item = new DanglingEndHandle(JUNCTION_END); item->m_Item = DrawItem; item->m_Pos = STRUCT->m_Pos; if ( lastitem ) lastitem->m_Pnext = item; else StartList = item; lastitem = item; break; case DRAW_BUSENTRY_STRUCT_TYPE: #undef STRUCT #define STRUCT ((DrawBusEntryStruct*)DrawItem) item = new DanglingEndHandle(ENTRY_END); item->m_Item = DrawItem; item->m_Pos = STRUCT->m_Pos; if ( lastitem ) lastitem->m_Pnext = item; else StartList = item; lastitem = item; item = new DanglingEndHandle(ENTRY_END); item->m_Item = DrawItem; item->m_Pos = STRUCT->m_End(); lastitem->m_Pnext = item; lastitem = item; break; case DRAW_LIB_ITEM_STRUCT_TYPE: { #undef STRUCT #define STRUCT ((EDA_SchComponentStruct*)DrawItem) EDA_LibComponentStruct * Entry; Entry = FindLibPart( STRUCT->m_ChipName, wxEmptyString, FIND_ROOT); if( Entry == NULL ) break; LibEDA_BaseStruct * DrawLibItem = Entry->m_Drawings; for ( ; DrawLibItem != NULL; DrawLibItem = DrawLibItem->Next()) { if(DrawLibItem->m_StructType != COMPONENT_PIN_DRAW_TYPE) continue; LibDrawPin * Pin = (LibDrawPin *) DrawLibItem; if( Pin->m_Unit && DrawLibItem->m_Unit && (DrawLibItem->m_Unit != Pin->m_Unit) ) continue; if( Pin->m_Convert && DrawLibItem->m_Convert && (DrawLibItem->m_Convert != Pin->m_Convert) ) continue; item = new DanglingEndHandle(PIN_END); item->m_Item = Pin; item->m_Pos = ReturnPinPhysicalPosition( Pin,STRUCT); if ( lastitem ) lastitem->m_Pnext = item; else StartList = item; lastitem = item; } break; } case DRAW_SHEET_STRUCT_TYPE: { #undef STRUCT #define STRUCT ((DrawSheetStruct*)DrawItem) DrawSheetLabelStruct * pinsheet = STRUCT->m_Label; while(pinsheet) { item = new DanglingEndHandle(SHEET_LABEL_END); item->m_Item = pinsheet; item->m_Pos = pinsheet->m_Pos; if ( lastitem ) lastitem->m_Pnext = item; else StartList = item; lastitem = item; pinsheet = (DrawSheetLabelStruct*)pinsheet->Pnext; } break; } } } return StartList; }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 409 ] ] ]
25080d340009e4d75376340ec2203007863def55
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/framework/psvi/XSIDCDefinition.cpp
53015e1d67becb309f4ed432276b69c793343ca5
[ "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
5,495
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: XSIDCDefinition.cpp,v $ * Revision 1.9 2004/09/08 13:56:08 peiyongz * Apache License Version 2.0 * * Revision 1.8 2004/01/29 11:46:30 cargilld * Code cleanup changes to get rid of various compiler diagnostic messages. * * Revision 1.7 2003/12/15 17:23:48 cargilld * psvi updates; cleanup revisits and bug fixes * * Revision 1.6 2003/11/21 17:29:53 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/XSIDCDefinition.hpp> #include <xercesc/validators/schema/identity/IC_KeyRef.hpp> #include <xercesc/validators/schema/identity/IC_Selector.hpp> #include <xercesc/validators/schema/identity/XercesXPath.hpp> #include <xercesc/framework/psvi/XSModel.hpp> #include <xercesc/framework/psvi/XSAnnotation.hpp> #include <xercesc/util/StringPool.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // XSIDCDefinition: Constructors and Destructor // --------------------------------------------------------------------------- XSIDCDefinition::XSIDCDefinition(IdentityConstraint* const identityConstraint, XSIDCDefinition* const keyIC, XSAnnotation* const headAnnot, StringList* const stringList, XSModel* const xsModel, MemoryManager* const manager) : XSObject(XSConstants::IDENTITY_CONSTRAINT, xsModel, manager) , fIdentityConstraint(identityConstraint) , fKey(keyIC) , fStringList(stringList) , fXSAnnotationList(0) { if (headAnnot) { fXSAnnotationList = new (manager) RefVectorOf<XSAnnotation>(1, false, manager); XSAnnotation* annot = headAnnot; do { fXSAnnotationList->addElement(annot); annot = annot->getNext(); } while (annot); } } XSIDCDefinition::~XSIDCDefinition() { if (fStringList) delete fStringList; // don't delete fKey - deleted by XSModel if (fXSAnnotationList) delete fXSAnnotationList; } // --------------------------------------------------------------------------- // XSIDCDefinition: XSObject virtual methods // --------------------------------------------------------------------------- const XMLCh *XSIDCDefinition::getName() { return fIdentityConstraint->getIdentityConstraintName(); } const XMLCh *XSIDCDefinition::getNamespace() { return fXSModel->getURIStringPool()->getValueForId(fIdentityConstraint->getNamespaceURI()); } XSNamespaceItem *XSIDCDefinition::getNamespaceItem() { return fXSModel->getNamespaceItem(getNamespace()); } // --------------------------------------------------------------------------- // XSIDCDefinition: access methods // --------------------------------------------------------------------------- XSIDCDefinition::IC_CATEGORY XSIDCDefinition::getCategory() const { switch(fIdentityConstraint->getType()) { case IdentityConstraint::UNIQUE: return IC_UNIQUE; case IdentityConstraint::KEY: return IC_KEY; case IdentityConstraint::KEYREF: return IC_KEYREF; default: // REVISIT: // should never really get here... IdentityConstraint::Unknown is the other // choice so need a default case for completeness; should issues error? return IC_KEY; } } const XMLCh *XSIDCDefinition::getSelectorStr() { return fIdentityConstraint->getSelector()->getXPath()->getExpression(); } XSAnnotationList *XSIDCDefinition::getAnnotations() { return fXSAnnotationList; } XERCES_CPP_NAMESPACE_END
[ [ [ 1, 151 ] ] ]
0697dd53d9eb362939588a378f4c1469ae1ded8f
668dc83d4bc041d522e35b0c783c3e073fcc0bd2
/fbide-vs/Sdk/TypeManager.cpp
37a2207f1125d893bd4c31ee249311648904e890
[]
no_license
albeva/fbide-old-svn
4add934982ce1ce95960c9b3859aeaf22477f10b
bde1e72e7e182fabc89452738f7655e3307296f4
refs/heads/master
2021-01-13T10:22:25.921182
2009-11-19T16:50:48
2009-11-19T16:50:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,745
cpp
/* * This file is part of FBIde project * * FBIde 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. * * FBIde 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 FBIde. If not, see <http://www.gnu.org/licenses/>. * * Author: Albert Varaksin <[email protected]> * Copyright (C) The FBIde development team */ #include "sdk_pch.h" #include "Manager.h" #include "UiManager.h" #include "TypeManager.h" #include "Document.h" using namespace fbi; /** * Manager class implementation */ struct TheTypeManager : TypeManager { // forward ref struct TypeInfo; // Hold a list of typeinfos typedef std::vector<TypeInfo*> TypeInfoVector; // Register new type virtual void Register (const wxString & type, const wxString & desc, DocCreatorFn creator ) { // type already registered? if (IsRegistered(type)) { wxLogError("Type '%s' already registered with TypeManager", type); return; } // create type and set info auto & info = m_typeMap[type]; info.isAlias = false; info.type = type; info.desc = desc; info.creator = creator; } // Bind file extensions to the type virtual void BindExtensions (const wxString & type, const wxString & extensions) { // find one level only auto info = FindType(type, false); if (info == nullptr) { wxLogError("Type '%s' is not registered with TypeManager", type); return; } // explode extensions into an array wxArrayString arr; ExplodeString(extensions, arr, ";"); // add the extensions for (size_t i = 0; i < arr.Count(); i++) { // Get the extension anc clean it wxString ext = arr[i].Lower().Trim(); //if (!ext.Len()) continue; // avoid duplicates if (info->exts.Index(ext) != wxNOT_FOUND) continue; // Bind the extenions info->exts.Add(ext); m_extMap[ext].push_back(info); } } // Bind type alias to an existing type virtual void BindAlias (const wxString & alias, const wxString & target, bool overwrite) { // Get target type. However One alias may point to another // and later alias might change the target. So resolve one level only auto targetInfo = FindType(target, false); if (targetInfo == nullptr) { wxLogError("Target '%s' is not registered with TypeManager", target); return; } // Get alias type auto aliasInfo = FindType(alias, false); if (aliasInfo != nullptr) { // type exists ... if (!overwrite || !aliasInfo->isAlias) { wxLogError("Cannot convert '%s' into an alias in TypeManager", alias); return; } // overwrite the alias auto oldTarget = aliasInfo->alias; aliasInfo->alias = targetInfo; // check for circular references auto check = aliasInfo; while (check->isAlias) { // circular reference if (check->alias = aliasInfo) { wxLogError("Alias '%s' creates a circular reference with '%s' in TypeManager", alias, target); aliasInfo->alias = oldTarget; return; } check = check->alias; } return; } // add new auto & entry = m_typeMap[alias]; entry.isAlias = true; entry.alias = targetInfo; } // Create new document. Deduct type from extension // if failed show a dialog with an option to open the file // with any other registered loaders or use OS to open it // return nullptr if not opened in the editor virtual Document * CreateFromFile (const wxString & file) { // get the extension and clean it wxString ext = wxFileName(file).GetExt().Lower().Trim(); // if extension is already registered ? auto extIter = m_extMap.find(ext); if (extIter != m_extMap.end()) { auto doc =_createFromExt( extIter->second, true );; if (doc != nullptr) _loadFile( doc, file ); return doc; } // Get different loaders and ignore aliases TypeInfoVector list; for (auto iter = m_typeMap.begin(); iter != m_typeMap.end(); iter++) { TypeInfo * info = &iter->second; while (info->isAlias) info = info->alias; if (std::find(list.begin(), list.end(), info) == list.end()) list.push_back(info); } // choises. wxArrayString choices; for (size_t i = 0; i < list.size(); i++) choices.Add(list[i]->desc); // Allow user to select the document type to create // todo - add option to open with external program // todo - add option to use shell to open auto & lang = GET_LANG(); wxSingleChoiceDialog select( GET_FRAME(), lang.Get("open.document.type.message", "file", file), lang.Get("open.document.type.title", "file", file), choices ); if (select.ShowModal() == wxID_CANCEL) return nullptr; // create the document and load file auto doc = list[select.GetSelection()]->creator(); if (doc != nullptr) _loadFile( doc, file ); return doc; } // Load file void _loadFile ( Document * doc, const wxString & file ) { auto & lang = GET_LANG(); wxFileName f(file); if (!f.FileExists()) { wxMessageBox(lang.Get("error.file-not-found", "filename", file)); return; } if (doc->LoadDocFile(file)) { doc->SetDocFilename(file); doc->SetDocTitle(f.GetFullName()); } } // Create new document using type name. If not registred // return nullptr and log a warning. virtual Document * CreateFromType (const wxString & type) { auto info = FindType(type, true); if (info == nullptr) { wxLogError("Type '%s' is not registered with TypeManager", type); return nullptr; } return info->creator(); } // Create new document by registered extenions. // if multiple creators are registered show a dialog allowing // to select the proper type. // return nullptr and log a warning if no extension is registered // with the type virtual Document * CreateFromExtension (const wxString & ext) { auto extIter = m_extMap.find(ext); if (extIter == m_extMap.end()) { wxLogError("File extension '%s' is not registered with TypeManager", ext); return nullptr; } // create return _createFromExt( extIter->second, false ); } // Create from extension // internal implementation Document * _createFromExt (TypeInfoVector & types, bool fromFile) { // there is only one registered type then return it if (types.size() == 1) return types[0]->creator(); // get the types and elimiate duplicates TypeInfoVector list; for (auto iter = types.begin(); iter != types.end(); iter++) { auto info = *iter; while (info->isAlias) info = info->alias; if (std::find(list.begin(), list.end(), info) == list.end()) list.push_back(info); } // is only one type left ? if (list.size() == 1) return list[0]->creator(); // choises. // NB! don't sort this. order is important as // index is used to match wxArrayString choices; for (size_t i = 0; i < list.size(); i++) choices.Add(list[i]->desc); // Allow user to select the document type to create auto & lang = GET_LANG(); wxSingleChoiceDialog select( GET_FRAME(), lang["select.document.type.message"], lang["select.document.type.title"], choices ); if (select.ShowModal() == wxID_CANCEL) return nullptr; // and create the document return list[select.GetSelection()]->creator(); } // check if type is registered. Will resolve aliases to the // actual type virtual bool IsRegistered ( const wxString & type ) { return m_typeMap.find(type) != m_typeMap.end(); } // Get file filters to be used with file load / save dialogs virtual wxString GetFileFilters ( bool incAllFiles ) { // Collect all information needed into a map std::map<TypeInfo *, wxString> map; // iterate through the extensions for (auto extIter = m_extMap.begin(); extIter != m_extMap.end(); extIter++) { // get list where the extension can possibly belong auto & list = extIter->second; for (auto typeIter = list.begin(); typeIter != list.end(); typeIter++) { // resolve aliases TypeInfo * info = *typeIter; while (info->isAlias) info = info->alias; // add extension to the map wxString & exts = map[info]; if (exts.Len()) exts << ";"; exts << "*." << extIter->first; } } // generate the string wxString result; for (auto iter = map.begin(); iter != map.end(); iter++) { if (result.Len()) result << "|"; result << iter->first->desc << " (" << iter->second << ")|" << iter->second; } // add All files if (incAllFiles) { if (result.Len()) result << "|"; result << GET_LANG()["all-files"] << " (*.*)|*.*"; } return result; } // find type by name and return TypeInfo * or nullptr // if not found. TypeInfo * FindType ( const wxString & type, bool resolveAlias ) { // find auto iter = m_typeMap.find(type); if (iter == m_typeMap.end()) return nullptr; // don't care about aliases if (!resolveAlias) return &iter->second; // resolve alias TypeInfo * info = &iter->second; while (info->isAlias) info = info->alias; return info; } /** * PHP like explode function by Ryan Norton * from http://wxforum.shadonet.com/viewtopic.php?p=12929#12929 */ void ExplodeString( const wxString& s, wxArrayString& retArray, const char * cpszExp, const size_t& crnStart = 0, const size_t& crnCount = (size_t)-1, const bool& crbCIComp = false) { wxASSERT_MSG(cpszExp != NULL, wxT("Invalid value for First Param of wxString::Split (cpszExp)")); retArray.Clear(); size_t nOldPos = crnStart, nPos = crnStart; wxString szComp, szExp = cpszExp; if (crbCIComp) { szComp = s.Lower(); szExp.MakeLower(); } else szComp = s; if(crnCount == (size_t)-1) { for (; (nPos = szComp.find(szExp, nPos)) != wxString::npos;) { retArray.Add(s.Mid(nOldPos, nPos - nOldPos)); nOldPos = nPos += szExp.Length(); } } else { for (int i = crnCount; (nPos = szComp.find(szExp, nPos)) != wxString::npos && i != 0; --i) { retArray.Add(s.Mid(nOldPos, nPos - nOldPos)); nOldPos = nPos += szExp.Length(); } } if (nOldPos != s.Length()) retArray.Add(s.Mid(nOldPos) ); } // hold type information struct TypeInfo { // is this an alias to another type ? bool isAlias; // type name wxString type; // type description wxString desc; // type extensions wxArrayString exts; // if is alias then a pointer to typeinfo it points to // otherwise document creaor function pointer union { TypeInfo * alias; DocCreatorFn creator; }; }; // hold types HashMap<TypeInfo> m_typeMap; // hold extension to typeinfo HashMap<TypeInfoVector> m_extMap; }; // Implement Manager IMPLEMENT_MANAGER(TypeManager, TheTypeManager)
[ "vongodric@957c6b5c-1c3a-0410-895f-c76cfc11fbc7" ]
[ [ [ 1, 438 ] ] ]
244fab4627886c0cd1de43ea771e1606475329ba
fa134e5f64c51ccc1c2cac9b9cb0186036e41563
/GT/AirspeedIndicator.cpp
c900799c9236c0dc989c53e122bed8fa7d997b15
[]
no_license
dlsyaim/gradthes
70b626f08c5d64a1d19edc46d67637d9766437a6
db6ba305cca09f273e99febda4a8347816429700
refs/heads/master
2016-08-11T10:44:45.165199
2010-07-19T05:44:40
2010-07-19T05:44:40
36,058,688
0
1
null
null
null
null
UTF-8
C++
false
false
318
cpp
#include "stdafx.h" #include <stdio.h> #include <olectl.h> #include <math.h> #include <GL\gl.h> #include <string> #include <vector> #include "AirspeedIndicator.h" AirspeedIndicator::AirspeedIndicator(void) { } AirspeedIndicator::~AirspeedIndicator(void) { }
[ "[email protected]@3a95c3f6-2b41-11df-be6c-f52728ce0ce6" ]
[ [ [ 1, 17 ] ] ]
e704835c58ea6d5e6b56536fc30dff5fd324fdff
b3b0c727bbafdb33619dedb0b61b6419692e03d3
/Source/RSSPlugin/common/inc/RSSParse_VC6_com.h
97fe8204bd110768b0011a716a2130e45ed3d71b
[]
no_license
testzzzz/hwccnet
5b8fb8be799a42ef84d261e74ee6f91ecba96b1d
4dbb1d1a5d8b4143e8c7e2f1537908cb9bb98113
refs/heads/master
2021-01-10T02:59:32.527961
2009-11-04T03:39:39
2009-11-04T03:39:39
45,688,112
0
1
null
null
null
null
UTF-8
C++
false
false
36,353
h
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 5.01.0164 */ /* at Wed Jan 14 17:24:54 2009 */ //@@MIDL_FILE_HEADING( ) /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 440 #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 COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif /*COM_NO_WINDOWS_H*/ #ifndef __RSSParse_VC6_com_h__ #define __RSSParse_VC6_com_h__ #ifdef __cplusplus extern "C"{ #endif /* Forward Declarations */ #ifndef __IRSSParse_FWD_DEFINED__ #define __IRSSParse_FWD_DEFINED__ typedef interface IRSSParse IRSSParse; #endif /* __IRSSParse_FWD_DEFINED__ */ #ifndef __RSSParse_FWD_DEFINED__ #define __RSSParse_FWD_DEFINED__ #ifdef __cplusplus typedef class RSSParse RSSParse; #else typedef struct RSSParse RSSParse; #endif /* __cplusplus */ #endif /* __RSSParse_FWD_DEFINED__ */ /* header files for imported files */ #include "oaidl.h" #include "ocidl.h" void __RPC_FAR * __RPC_USER MIDL_user_allocate(size_t); void __RPC_USER MIDL_user_free( void __RPC_FAR * ); #ifndef __IRSSParse_INTERFACE_DEFINED__ #define __IRSSParse_INTERFACE_DEFINED__ /* interface IRSSParse */ /* [unique][helpstring][dual][uuid][object] */ EXTERN_C const IID IID_IRSSParse; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("1E76FA32-DFD4-4000-908B-B2D4A256F644") IRSSParse : public IDispatch { public: virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetChannel( /* [in] */ BSTR channel) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetNotify( /* [in] */ long hwnd, /* [in] */ long msg) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Start( void) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetTimeout( /* [in] */ long time) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Refresh( void) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IsReady( /* [in] */ VARIANT_BOOL isAsyn, /* [retval][out] */ VARIANT_BOOL __RPC_FAR *bResult) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE WhichSpec( /* [retval][out] */ BSTR __RPC_FAR *bstr) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetFirstNodePos( void) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetNextNode( /* [retval][out] */ BSTR __RPC_FAR *node) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetFirstItemPos( void) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetNextItem( /* [retval][out] */ BSTR __RPC_FAR *node) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetFirstAttributePos( void) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetNextAttribute( /* [in] */ BSTR node, /* [retval][out] */ BSTR __RPC_FAR *attribute) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetItemCount( /* [retval][out] */ long __RPC_FAR *count) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetAttributeValue( /* [in] */ BSTR attribute, /* [retval][out] */ BSTR __RPC_FAR *value) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetContent( /* [in] */ BSTR node, /* [retval][out] */ BSTR __RPC_FAR *content) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetTimer( /* [in] */ long time) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE KillTimer( void) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetFeedTitle( /* [retval][out] */ BSTR __RPC_FAR *title) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetFeedLink( /* [retval][out] */ BSTR __RPC_FAR *Link) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetFeedDescription( /* [retval][out] */ BSTR __RPC_FAR *Description) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetFeedCopyright( /* [retval][out] */ BSTR __RPC_FAR *Copyright) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetFeedPubDate( /* [retval][out] */ BSTR __RPC_FAR *PubDate) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetFeedLastBuildDate( /* [retval][out] */ BSTR __RPC_FAR *LastBuildDate) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetFeedCategory( /* [retval][out] */ BSTR __RPC_FAR *Category) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetImageUrl( /* [retval][out] */ BSTR __RPC_FAR *url) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetImageTitle( /* [retval][out] */ BSTR __RPC_FAR *Title) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetImageLink( /* [retval][out] */ BSTR __RPC_FAR *Link) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetImageDescription( /* [retval][out] */ BSTR __RPC_FAR *Description) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetItemTitle( /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *title) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetItemLink( /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *Link) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetItemDescription( /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *Description) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetItemAuthor( /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *Author) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetItemCategory( /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *Category) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetItemPubDate( /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *PubDate) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetItemGuid( /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *Guid) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetItemSource( /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *Source) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE WriteNodes2File( /* [in] */ BSTR filename) = 0; }; #else /* C style interface */ typedef struct IRSSParseVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )( IRSSParse __RPC_FAR * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )( IRSSParse __RPC_FAR * This); ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )( IRSSParse __RPC_FAR * This); HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetTypeInfoCount )( IRSSParse __RPC_FAR * This, /* [out] */ UINT __RPC_FAR *pctinfo); HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetTypeInfo )( IRSSParse __RPC_FAR * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo); HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetIDsOfNames )( IRSSParse __RPC_FAR * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Invoke )( IRSSParse __RPC_FAR * This, /* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetChannel )( IRSSParse __RPC_FAR * This, /* [in] */ BSTR channel); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetNotify )( IRSSParse __RPC_FAR * This, /* [in] */ long hwnd, /* [in] */ long msg); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Start )( IRSSParse __RPC_FAR * This); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetTimeout )( IRSSParse __RPC_FAR * This, /* [in] */ long time); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Refresh )( IRSSParse __RPC_FAR * This); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *IsReady )( IRSSParse __RPC_FAR * This, /* [in] */ VARIANT_BOOL isAsyn, /* [retval][out] */ VARIANT_BOOL __RPC_FAR *bResult); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *WhichSpec )( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *bstr); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetFirstNodePos )( IRSSParse __RPC_FAR * This); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetNextNode )( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *node); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetFirstItemPos )( IRSSParse __RPC_FAR * This); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetNextItem )( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *node); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetFirstAttributePos )( IRSSParse __RPC_FAR * This); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetNextAttribute )( IRSSParse __RPC_FAR * This, /* [in] */ BSTR node, /* [retval][out] */ BSTR __RPC_FAR *attribute); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetItemCount )( IRSSParse __RPC_FAR * This, /* [retval][out] */ long __RPC_FAR *count); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetAttributeValue )( IRSSParse __RPC_FAR * This, /* [in] */ BSTR attribute, /* [retval][out] */ BSTR __RPC_FAR *value); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetContent )( IRSSParse __RPC_FAR * This, /* [in] */ BSTR node, /* [retval][out] */ BSTR __RPC_FAR *content); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetTimer )( IRSSParse __RPC_FAR * This, /* [in] */ long time); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *KillTimer )( IRSSParse __RPC_FAR * This); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetFeedTitle )( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *title); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetFeedLink )( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *Link); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetFeedDescription )( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *Description); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetFeedCopyright )( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *Copyright); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetFeedPubDate )( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *PubDate); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetFeedLastBuildDate )( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *LastBuildDate); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetFeedCategory )( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *Category); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetImageUrl )( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *url); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetImageTitle )( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *Title); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetImageLink )( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *Link); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetImageDescription )( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *Description); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetItemTitle )( IRSSParse __RPC_FAR * This, /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *title); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetItemLink )( IRSSParse __RPC_FAR * This, /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *Link); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetItemDescription )( IRSSParse __RPC_FAR * This, /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *Description); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetItemAuthor )( IRSSParse __RPC_FAR * This, /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *Author); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetItemCategory )( IRSSParse __RPC_FAR * This, /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *Category); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetItemPubDate )( IRSSParse __RPC_FAR * This, /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *PubDate); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetItemGuid )( IRSSParse __RPC_FAR * This, /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *Guid); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetItemSource )( IRSSParse __RPC_FAR * This, /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *Source); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *WriteNodes2File )( IRSSParse __RPC_FAR * This, /* [in] */ BSTR filename); END_INTERFACE } IRSSParseVtbl; interface IRSSParse { CONST_VTBL struct IRSSParseVtbl __RPC_FAR *lpVtbl; }; #ifdef COBJMACROS #define IRSSParse_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IRSSParse_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IRSSParse_Release(This) \ (This)->lpVtbl -> Release(This) #define IRSSParse_GetTypeInfoCount(This,pctinfo) \ (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) #define IRSSParse_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) #define IRSSParse_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) #define IRSSParse_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) #define IRSSParse_SetChannel(This,channel) \ (This)->lpVtbl -> SetChannel(This,channel) #define IRSSParse_SetNotify(This,hwnd,msg) \ (This)->lpVtbl -> SetNotify(This,hwnd,msg) #define IRSSParse_Start(This) \ (This)->lpVtbl -> Start(This) #define IRSSParse_SetTimeout(This,time) \ (This)->lpVtbl -> SetTimeout(This,time) #define IRSSParse_Refresh(This) \ (This)->lpVtbl -> Refresh(This) #define IRSSParse_IsReady(This,isAsyn,bResult) \ (This)->lpVtbl -> IsReady(This,isAsyn,bResult) #define IRSSParse_WhichSpec(This,bstr) \ (This)->lpVtbl -> WhichSpec(This,bstr) #define IRSSParse_SetFirstNodePos(This) \ (This)->lpVtbl -> SetFirstNodePos(This) #define IRSSParse_GetNextNode(This,node) \ (This)->lpVtbl -> GetNextNode(This,node) #define IRSSParse_SetFirstItemPos(This) \ (This)->lpVtbl -> SetFirstItemPos(This) #define IRSSParse_GetNextItem(This,node) \ (This)->lpVtbl -> GetNextItem(This,node) #define IRSSParse_SetFirstAttributePos(This) \ (This)->lpVtbl -> SetFirstAttributePos(This) #define IRSSParse_GetNextAttribute(This,node,attribute) \ (This)->lpVtbl -> GetNextAttribute(This,node,attribute) #define IRSSParse_GetItemCount(This,count) \ (This)->lpVtbl -> GetItemCount(This,count) #define IRSSParse_GetAttributeValue(This,attribute,value) \ (This)->lpVtbl -> GetAttributeValue(This,attribute,value) #define IRSSParse_GetContent(This,node,content) \ (This)->lpVtbl -> GetContent(This,node,content) #define IRSSParse_SetTimer(This,time) \ (This)->lpVtbl -> SetTimer(This,time) #define IRSSParse_KillTimer(This) \ (This)->lpVtbl -> KillTimer(This) #define IRSSParse_GetFeedTitle(This,title) \ (This)->lpVtbl -> GetFeedTitle(This,title) #define IRSSParse_GetFeedLink(This,Link) \ (This)->lpVtbl -> GetFeedLink(This,Link) #define IRSSParse_GetFeedDescription(This,Description) \ (This)->lpVtbl -> GetFeedDescription(This,Description) #define IRSSParse_GetFeedCopyright(This,Copyright) \ (This)->lpVtbl -> GetFeedCopyright(This,Copyright) #define IRSSParse_GetFeedPubDate(This,PubDate) \ (This)->lpVtbl -> GetFeedPubDate(This,PubDate) #define IRSSParse_GetFeedLastBuildDate(This,LastBuildDate) \ (This)->lpVtbl -> GetFeedLastBuildDate(This,LastBuildDate) #define IRSSParse_GetFeedCategory(This,Category) \ (This)->lpVtbl -> GetFeedCategory(This,Category) #define IRSSParse_GetImageUrl(This,url) \ (This)->lpVtbl -> GetImageUrl(This,url) #define IRSSParse_GetImageTitle(This,Title) \ (This)->lpVtbl -> GetImageTitle(This,Title) #define IRSSParse_GetImageLink(This,Link) \ (This)->lpVtbl -> GetImageLink(This,Link) #define IRSSParse_GetImageDescription(This,Description) \ (This)->lpVtbl -> GetImageDescription(This,Description) #define IRSSParse_GetItemTitle(This,n,title) \ (This)->lpVtbl -> GetItemTitle(This,n,title) #define IRSSParse_GetItemLink(This,n,Link) \ (This)->lpVtbl -> GetItemLink(This,n,Link) #define IRSSParse_GetItemDescription(This,n,Description) \ (This)->lpVtbl -> GetItemDescription(This,n,Description) #define IRSSParse_GetItemAuthor(This,n,Author) \ (This)->lpVtbl -> GetItemAuthor(This,n,Author) #define IRSSParse_GetItemCategory(This,n,Category) \ (This)->lpVtbl -> GetItemCategory(This,n,Category) #define IRSSParse_GetItemPubDate(This,n,PubDate) \ (This)->lpVtbl -> GetItemPubDate(This,n,PubDate) #define IRSSParse_GetItemGuid(This,n,Guid) \ (This)->lpVtbl -> GetItemGuid(This,n,Guid) #define IRSSParse_GetItemSource(This,n,Source) \ (This)->lpVtbl -> GetItemSource(This,n,Source) #define IRSSParse_WriteNodes2File(This,filename) \ (This)->lpVtbl -> WriteNodes2File(This,filename) #endif /* COBJMACROS */ #endif /* C style interface */ /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_SetChannel_Proxy( IRSSParse __RPC_FAR * This, /* [in] */ BSTR channel); void __RPC_STUB IRSSParse_SetChannel_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_SetNotify_Proxy( IRSSParse __RPC_FAR * This, /* [in] */ long hwnd, /* [in] */ long msg); void __RPC_STUB IRSSParse_SetNotify_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_Start_Proxy( IRSSParse __RPC_FAR * This); void __RPC_STUB IRSSParse_Start_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_SetTimeout_Proxy( IRSSParse __RPC_FAR * This, /* [in] */ long time); void __RPC_STUB IRSSParse_SetTimeout_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_Refresh_Proxy( IRSSParse __RPC_FAR * This); void __RPC_STUB IRSSParse_Refresh_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_IsReady_Proxy( IRSSParse __RPC_FAR * This, /* [in] */ VARIANT_BOOL isAsyn, /* [retval][out] */ VARIANT_BOOL __RPC_FAR *bResult); void __RPC_STUB IRSSParse_IsReady_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_WhichSpec_Proxy( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *bstr); void __RPC_STUB IRSSParse_WhichSpec_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_SetFirstNodePos_Proxy( IRSSParse __RPC_FAR * This); void __RPC_STUB IRSSParse_SetFirstNodePos_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetNextNode_Proxy( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *node); void __RPC_STUB IRSSParse_GetNextNode_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_SetFirstItemPos_Proxy( IRSSParse __RPC_FAR * This); void __RPC_STUB IRSSParse_SetFirstItemPos_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetNextItem_Proxy( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *node); void __RPC_STUB IRSSParse_GetNextItem_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_SetFirstAttributePos_Proxy( IRSSParse __RPC_FAR * This); void __RPC_STUB IRSSParse_SetFirstAttributePos_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetNextAttribute_Proxy( IRSSParse __RPC_FAR * This, /* [in] */ BSTR node, /* [retval][out] */ BSTR __RPC_FAR *attribute); void __RPC_STUB IRSSParse_GetNextAttribute_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetItemCount_Proxy( IRSSParse __RPC_FAR * This, /* [retval][out] */ long __RPC_FAR *count); void __RPC_STUB IRSSParse_GetItemCount_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetAttributeValue_Proxy( IRSSParse __RPC_FAR * This, /* [in] */ BSTR attribute, /* [retval][out] */ BSTR __RPC_FAR *value); void __RPC_STUB IRSSParse_GetAttributeValue_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetContent_Proxy( IRSSParse __RPC_FAR * This, /* [in] */ BSTR node, /* [retval][out] */ BSTR __RPC_FAR *content); void __RPC_STUB IRSSParse_GetContent_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_SetTimer_Proxy( IRSSParse __RPC_FAR * This, /* [in] */ long time); void __RPC_STUB IRSSParse_SetTimer_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_KillTimer_Proxy( IRSSParse __RPC_FAR * This); void __RPC_STUB IRSSParse_KillTimer_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetFeedTitle_Proxy( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *title); void __RPC_STUB IRSSParse_GetFeedTitle_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetFeedLink_Proxy( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *Link); void __RPC_STUB IRSSParse_GetFeedLink_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetFeedDescription_Proxy( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *Description); void __RPC_STUB IRSSParse_GetFeedDescription_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetFeedCopyright_Proxy( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *Copyright); void __RPC_STUB IRSSParse_GetFeedCopyright_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetFeedPubDate_Proxy( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *PubDate); void __RPC_STUB IRSSParse_GetFeedPubDate_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetFeedLastBuildDate_Proxy( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *LastBuildDate); void __RPC_STUB IRSSParse_GetFeedLastBuildDate_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetFeedCategory_Proxy( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *Category); void __RPC_STUB IRSSParse_GetFeedCategory_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetImageUrl_Proxy( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *url); void __RPC_STUB IRSSParse_GetImageUrl_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetImageTitle_Proxy( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *Title); void __RPC_STUB IRSSParse_GetImageTitle_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetImageLink_Proxy( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *Link); void __RPC_STUB IRSSParse_GetImageLink_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetImageDescription_Proxy( IRSSParse __RPC_FAR * This, /* [retval][out] */ BSTR __RPC_FAR *Description); void __RPC_STUB IRSSParse_GetImageDescription_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetItemTitle_Proxy( IRSSParse __RPC_FAR * This, /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *title); void __RPC_STUB IRSSParse_GetItemTitle_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetItemLink_Proxy( IRSSParse __RPC_FAR * This, /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *Link); void __RPC_STUB IRSSParse_GetItemLink_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetItemDescription_Proxy( IRSSParse __RPC_FAR * This, /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *Description); void __RPC_STUB IRSSParse_GetItemDescription_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetItemAuthor_Proxy( IRSSParse __RPC_FAR * This, /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *Author); void __RPC_STUB IRSSParse_GetItemAuthor_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetItemCategory_Proxy( IRSSParse __RPC_FAR * This, /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *Category); void __RPC_STUB IRSSParse_GetItemCategory_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetItemPubDate_Proxy( IRSSParse __RPC_FAR * This, /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *PubDate); void __RPC_STUB IRSSParse_GetItemPubDate_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetItemGuid_Proxy( IRSSParse __RPC_FAR * This, /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *Guid); void __RPC_STUB IRSSParse_GetItemGuid_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_GetItemSource_Proxy( IRSSParse __RPC_FAR * This, /* [in] */ long n, /* [retval][out] */ BSTR __RPC_FAR *Source); void __RPC_STUB IRSSParse_GetItemSource_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IRSSParse_WriteNodes2File_Proxy( IRSSParse __RPC_FAR * This, /* [in] */ BSTR filename); void __RPC_STUB IRSSParse_WriteNodes2File_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IRSSParse_INTERFACE_DEFINED__ */ #ifndef __RSSPARSE_VC6_COMLib_LIBRARY_DEFINED__ #define __RSSPARSE_VC6_COMLib_LIBRARY_DEFINED__ /* library RSSPARSE_VC6_COMLib */ /* [helpstring][version][uuid] */ EXTERN_C const IID LIBID_RSSPARSE_VC6_COMLib; EXTERN_C const CLSID CLSID_RSSParse; #ifdef __cplusplus class DECLSPEC_UUID("F5789789-A93D-4BBA-B1DE-C1EE43E80C2B") RSSParse; #endif #endif /* __RSSPARSE_VC6_COMLib_LIBRARY_DEFINED__ */ /* Additional Prototypes for ALL interfaces */ unsigned long __RPC_USER BSTR_UserSize( unsigned long __RPC_FAR *, unsigned long , BSTR __RPC_FAR * ); unsigned char __RPC_FAR * __RPC_USER BSTR_UserMarshal( unsigned long __RPC_FAR *, unsigned char __RPC_FAR *, BSTR __RPC_FAR * ); unsigned char __RPC_FAR * __RPC_USER BSTR_UserUnmarshal(unsigned long __RPC_FAR *, unsigned char __RPC_FAR *, BSTR __RPC_FAR * ); void __RPC_USER BSTR_UserFree( unsigned long __RPC_FAR *, BSTR __RPC_FAR * ); /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
[ [ [ 1, 1060 ] ] ]
2e292577f3ea844ff54e151ff48ff32dff955089
971b000b9e6c4bf91d28f3723923a678520f5bcf
/PaginationFormat/fop_format/Fo_Writter.cpp
999fc6062fed2e42ae17db176af27c957746d9af
[]
no_license
google-code-export/fop-miniscribus
14ce53d21893ce1821386a94d42485ee0465121f
966a9ca7097268c18e690aa0ea4b24b308475af9
refs/heads/master
2020-12-24T17:08:51.551987
2011-09-02T07:55:05
2011-09-02T07:55:05
32,133,292
2
0
null
null
null
null
UTF-8
C++
false
false
36,974
cpp
#include "Fo_Writter.h" #include "SessionManager.h" #include "Config.h" /* http://www.bessrc.aps.anl.gov/software/qt4-x11-4.2.2-browser/d0/dbc/qtextdocument_8cpp-source.html */ using namespace ApacheFop; FopDom::~FopDom() { } FopDom::FopDom( QTextDocument * docin , M_PageSize page , LEVEL e ) : sumblox(0) { m_page = page; PageName = Imagename(m_page.name); SetDoc(docin,page,e); } void FopDom::SetDoc( QTextDocument * docin , M_PageSize page , LEVEL e /*FOP_APACHE*/ ) { dom.clear(); const QString ReferenzeNames = Imagename(page.name); Q_ASSERT(ReferenzeNames.size() > 0); QDomProcessingInstruction header = dom.createProcessingInstruction( "xml",QString("version=\"1.0\" encoding=\"utf-8\"" )); dom.appendChild( header ); QDateTime timer1( QDateTime::currentDateTime() ); /* time root */ QDomElement basexslforoot = dom.createElement("fo:root"); basexslforoot.setAttribute ("xmlns:fo","http://www.w3.org/1999/XSL/Format"); basexslforoot.setAttribute ("xmlns:svg","http://www.w3.org/2000/svg"); basexslforoot.setAttribute ("xmlns:cms","http://www.pulitzer.ch/2007/CMSFormat"); basexslforoot.setAttribute ("xmlns:fox","http://xmlgraphics.apache.org/fop/extensions"); dom.appendChild( basexslforoot ); QDomElement layout = dom.createElement("fo:layout-master-set"); basexslforoot.appendChild( layout ); QDomElement pagesetup = dom.createElement("fo:simple-page-master"); m_page.ReportPage(pagesetup ); pagesetup.setAttribute ("master-name",ReferenzeNames); layout.appendChild( pagesetup ); QDomElement rb = dom.createElement("fo:region-body"); m_page.ReportPage(rb); rb.setAttribute ("region-name","xsl-region-body"); pagesetup.appendChild( rb ); QDomElement pageseq1 = dom.createElement("fo:page-sequence"); pageseq1.setAttribute ("master-reference",ReferenzeNames); basexslforoot.appendChild( pageseq1 ); doc = docin->clone(); styler = e; RootDocFrame = doc->rootFrame(); /* go null margin fop pagination */ QDomElement body = dom.createElement("fo:flow"); body.setAttribute ("flow-name","xsl-region-body"); qDebug() << "### Start read doc .........................................."; FrameLoop(doc->rootFrame()->begin(),body); pageseq1.appendChild( body ); emit DomReady(); } QDomElement FopDom::NodeFooter() { QDomDocumentFragment anode; QString dot1 = QString("<fo:instream-foreign-object content-width=\"11pt\">" "<svg:svg width=\"20\" height=\"20\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">" "<svg:circle cx=\"10\" cy=\"10\" r=\"5\" stroke=\"red\" stroke-width=\"0.3\" fill=\"black\"/>" "</svg:svg>" "</fo:instream-foreign-object>"); anode.setNodeValue(dot1); QDomNode panew = anode.cloneNode( true ); return panew.toElement(); } /* loop frame contenents */ /* http://www.bessrc.aps.anl.gov/software/qt4-x11-4.2.2-browser/d0/dbc/qtextdocument_8cpp-source.html */ void FopDom::FrameLoop( QTextFrame::Iterator frameIt , QDomElement appender ) { /* root frame! */ BigframeProcessing++; QStringList pretext; if (!frameIt.atEnd()) { QTextFrame::Iterator next = frameIt; ++next; if (next.atEnd() && frameIt.currentFrame() == 0 && frameIt.parentFrame() != doc->rootFrame() && frameIt.currentBlock().begin().atEnd()) { return; /* last frame */ } } for (QTextFrame::Iterator it = frameIt; !it.atEnd(); ++it) { if (QTextFrame *f = it.currentFrame()) { if (QTextTable *table = qobject_cast<QTextTable *>(f)) { /* table here */ HandleTable(table,appender); } else { /* other simple table from QTextDocument like <div> htmls */ QTextFrameFormat format = f->frameFormat(); QDomElement inlinediv = dom.createElement("fo:block-container"); PaintFrameFormat(inlinediv,format); QString widhtarea = TranslateTextLengh( format.width()); inlinediv.setAttribute ("width",widhtarea); HandleFrameInline(f->begin(),inlinediv); appender.appendChild(inlinediv); } } else if (it.currentBlock().isValid()) { qDebug() << "### Read Root blockNumber / HandleBlock " << it.currentBlock().blockNumber(); HandleBlock(it.currentBlock(),appender); } } qDebug() << "### END read doc .........................................."; } void FopDom::HandleFrameInline( QTextFrame::Iterator frameIt , QDomElement appender ) /* frame tag is set !!!!! */ { /* root frame! */ QTextFrame *actualframe = frameIt.currentFrame(); BigframeProcessing++; if (!frameIt.atEnd()) { QTextFrame::Iterator next = frameIt; ++next; if (next.atEnd() && actualframe == 0 && frameIt.parentFrame() != doc->rootFrame() && frameIt.currentBlock().begin().atEnd()) { return; /* last frame */ } } for (QTextFrame::Iterator it = frameIt; !it.atEnd(); ++it) { if (QTextFrame *f = it.currentFrame()) { if (QTextTable *table = qobject_cast<QTextTable *>(f)) { /* table here */ HandleTable(table,appender); } else { /* other simple table from QTextDocument like <div> htmls */ if ( actualframe != f ) { /* next child */ QTextFrameFormat format = f->frameFormat(); QDomElement inlinediv = dom.createElement("fo:block-container"); PaintFrameFormat(inlinediv,format); QString widhtarea = TranslateTextLengh( format.width()); inlinediv.setAttribute ("width",widhtarea); HandleFrameInline(f->begin(),inlinediv); appender.appendChild(inlinediv); } } } else if (it.currentBlock().isValid()) { HandleBlock(it.currentBlock(),appender); } } } void FopDom::PaintFrameFormat(QDomElement e , QTextFrameFormat bf ) { if ( bf.position() == QTextFrameFormat::InFlow) { e.setAttribute ("display-align","auto"); /* center */ e.setAttribute ("float","inherit"); } else if (bf.position() == QTextFrameFormat::FloatLeft) { e.setAttribute ("display-align","before"); } else if (bf.position() == QTextFrameFormat::FloatRight) { e.setAttribute ("display-align","after"); e.setAttribute ("float","right"); ///// inherit } if (bf.background().color().name() !="#000000" && bf.background().color().isValid() ) { e.setAttribute ("background-color",ColorFopString(bf.background())); } if (bf.hasProperty(QTextFormat::FrameMargin)) { if (bf.topMargin() !=0) { e.setAttribute ("margin-top",QString("%1pt").arg(bf.topMargin())); } if (bf.bottomMargin() !=0) { e.setAttribute ("margin-bottom",QString("%1pt").arg(bf.bottomMargin())); } if (bf.rightMargin() !=0) { e.setAttribute ("margin-right",QString("%1pt").arg(bf.rightMargin())); } if (bf.leftMargin() !=0) { e.setAttribute ("margin-left",QString("%1pt").arg(bf.leftMargin())); } } QBrush boof = bf.borderBrush(); if (bf.hasProperty(QTextFormat::FrameBorder)) { const QString bordertype = BorderStyleCss(bf.borderStyle()); if (bordertype != "none" ) { //////// style width color "border-left-" << "border-right-" << "border-bottom-" << "border-top-" QStringList SSBorder; SSBorder << "border-"; for (int i = 0; i < SSBorder.size(); ++i) { e.setAttribute (SSBorder.at(i)+"style",bordertype); e.setAttribute (SSBorder.at(i)+"width",QString("%1pt;").arg(bf.border())); if (boof != Qt::NoBrush) { e.setAttribute (SSBorder.at(i)+"color",ColorFopString(boof)); } } } } } QString FopDom::TranslateTextLengh( const QTextLength unit ) { if (unit.rawValue() < 1) { return QString(); } if (unit.type() == QTextLength::FixedLength) { return QString("%1pt").arg(Pointo(unit.rawValue(),"pt")); } else { return QString("%1\%").arg(unit.rawValue()); } } /* qt -> fop*/ void FopDom::HandleTable( QTextTable * childTable , QDomElement appender ) { if (!childTable) { return; } QDomElement base; QTextTableFormat tbforms = childTable->format(); if (tbforms.alignment() == Qt::AlignHCenter || tbforms.alignment() == Qt::AlignJustify || tbforms.alignment() == Qt::AlignRight) { QDomElement floater = dom.createElement("fo:float"); if (tbforms.alignment() == Qt::AlignHCenter || tbforms.alignment() == Qt::AlignJustify ) { floater.setAttribute ("float","inline"); } else if (tbforms.alignment() == Qt::AlignRight) { floater.setAttribute ("float","right"); } else { floater.setAttribute ("float","left"); } appender.appendChild(floater); base = dom.createElement("fo:table"); floater.appendChild(base); } else { base = dom.createElement("fo:table"); appender.appendChild(base); } FoBorder TableBorder; TableBorder.Change(TableBorder.rgb,QString("%1pt").arg(tbforms.border()),BorderStyleCss(tbforms.borderStyle())); const int coolsums = childTable->columns(); if (tbforms.background().color().name() !="#000000") { base.setAttribute("background-color",ColorFopString(tbforms.background())); } TableBorder.SetBorder(base); /* only if not 0 */ QVector<QTextLength> constraints = tbforms.columnWidthConstraints(); qDebug() << "### table coolsumns " << coolsums; qDebug() << "### table size large ............. " << constraints.size(); ///////qDebug() << "### coolsums b " << constraints.size(); if (constraints.size() != coolsums) { constraints.clear(); } for (int i = 0; i < coolsums; ++i) { QDomElement cools = dom.createElement("fo:table-column"); if ( constraints.size() != 0 ) { QString sizecool = TranslateTextLengh(constraints.at(i)); if (!sizecool.isEmpty()) { cools.setAttribute("column-width",sizecool); } else { cools.setAttribute("column-width",QString("%1\%").arg(100 / coolsums)); } } else { cools.setAttribute("column-width",QString("%1\%").arg(100 / coolsums)); } base.appendChild(cools); } QDomElement tbody = dom.createElement("fo:table-body"); if (tbforms.background().color().name() !="#000000") { tbody.setAttribute ("background-color",ColorFopString(tbforms.background())); } TableBorder.SetBorder(tbody); /* only if not 0 */ base.appendChild(tbody); const int rowline = childTable->rows(); for (int ttr = 0; ttr < rowline; ++ttr) { QDomElement rows = dom.createElement("fo:table-row"); tbody.appendChild(rows); for (int ttd = 0; ttd < coolsums; ++ttd) { QTextTableCell cell = childTable->cellAt(ttr,ttd); const int rspan = cell.rowSpan(); const int cspan = cell.columnSpan(); QDomElement celltds = dom.createElement("fo:table-cell"); if (cell.format().background().color().name() !="#000000") { celltds.setAttribute ("background-color",ColorFopString(cell.format().background())); } if (cspan > 1) { ttd = ttd + cspan - 1; celltds.setAttribute ("number-columns-spanned",cspan); } QTextFrame::iterator di; for (di = cell.begin(); !(di.atEnd()); ++di) { //////QTextFrame *tdFrame = di.currentFrame(); QTextBlock tdpara = di.currentBlock(); if (tdpara.isValid()) { HandleBlock(tdpara,celltds); } } if ( cspan > 1 || cspan == 1 ) { rows.appendChild(celltds); } } } } /* paragraph qt -> fop */ void FopDom::HandleBlock( QTextBlock para , QDomElement appender ) { if (!para.isValid()) { return; } sumblox++; QVariant footernote = para.blockFormat().property(FootNoteNummer); if (!footernote.isNull()) { qDebug() << "### footernote founddddddddddddddddddd " << para.blockNumber(); } /* page breack policy */ //////qDebug() << "### block init build .. "; const QString Actual_Text_Param = Qt::escape(para.text()).simplified(); QDomElement paragraph; QTextImageFormat Pics; QTextTableFormat Tabl; QTextListFormat Uls; QTextFrameFormat Frameinline; QTextCharFormat paraformats; QString newnameimage; QString ImageFilename; bool nobreackline = false; int positioner = -1; paragraph = dom.createElement("fo:block"); paragraph.setAttribute("id",QString("blocknr_%1").arg(para.blockNumber())); if (para.blockFormat().nonBreakableLines()) { paragraph.setAttribute("white-space-collapse","false"); nobreackline = true; } ////const QTextBlockFormat BBnormal = DefaultMargin(); //////const QTextCharFormat CCnormal = DefaultCharFormats(); ////////////// QTextFormat::PageBreakFlags actual = bbformat.pageBreakPolicy(); PaintFopBlockFormat(paragraph,para.blockFormat()); PaintFopCharFormat(paragraph,para.charFormat()); if (para.blockFormat().nonBreakableLines()) { PaintFopCharFormat(paragraph,PreFormatChar()); } LINEHIGHT_CURRENT = LineHightCurrent(para.blockFormat(),para.charFormat()); qreal currentHi = qBound (4.9,LINEHIGHT_CURRENT,33.2); if (Actual_Text_Param.isEmpty()) { appender.appendChild(paragraph); paragraph.setAttribute("line-height",QString("%1pt").arg(currentHi)); SendBreakLine(paragraph,false); return; } QTextList *list = para.textList(); if (list) { const int sumlist = list->count(); const int BListPosition = list->itemNumber(para); /* fo list block like html ul / li */ if ( BListPosition == 0) { // first item? QDomComment listblocke = dom.createComment(QString("Start list block nr %1 from %2 .").arg(BListPosition).arg(sumlist)); appender.appendChild(listblocke); ulblock = dom.createElement("fo:list-block"); appender.appendChild(ulblock); } QDomElement listitem = dom.createElement("fo:list-item"); ulblock.appendChild(listitem); QDomElement labelli = dom.createElement("fo:list-item-label"); labelli.setAttribute ("end-indent","label-end()"); ListUlLiSymbol(labelli,list); listitem.appendChild(labelli); /* label header */ QDomElement libody = dom.createElement("fo:list-item-body"); libody.setAttribute ("start-indent","body-start()"); QDomElement textlabel = dom.createElement("fo:block"); if (para.blockFormat().nonBreakableLines()) { textlabel.setAttribute("white-space-collapse","false"); } PaintFopCharFormat(textlabel,para.charFormat()); PaintFopBlockFormat(textlabel,para.blockFormat()); libody.appendChild(textlabel); listitem.appendChild(libody); QTextBlock::iterator li; for (li = para.begin(); !(li.atEnd()); ++li) { QTextFragment lifr = li.fragment(); if (lifr.isValid()) { HandleFragment(lifr,textlabel,nobreackline); } } if ( BListPosition == (sumlist - 1) ) { ///////ulblock.clear(); ////qDebug() << "### last BListPosition " << BListPosition << " from " << sumlist; QDomComment listblocke = dom.createComment(QString("End list block nr %1 from %2 .").arg(BListPosition).arg(sumlist)); ulblock.appendChild(listblocke); } return; } QTextBlock::iterator de; for (de = para.begin(); !(de.atEnd()); ++de) { /////////////qDebug() << "### para " << para.text(); QTextFragment fr = de.fragment(); if (fr.isValid()) { ///////LINEHIGHT_CURRENT = LineHightCurrent(para.blockFormat(),fr.charFormat()); if (para.text() == fr.text() && !fr.text().contains(QChar::ObjectReplacementCharacter)) { /////////paragraph.appendChild(dom.createTextNode(para.text())); PaintFopCharFormat(paragraph,fr.charFormat()); QString txt = Qt::escape(para.text()); QString forcedLineBreakRegExp = QString::fromLatin1("[\\na]"); forcedLineBreakRegExp[3] = QChar::LineSeparator; const QStringList lines = txt.split(QRegExp(forcedLineBreakRegExp)); for (int i = 0; i < lines.count(); ++i) { if (i > 0) { if (nobreackline) { paragraph.appendChild(dom.createTextNode(QString(" "))); } else { SendBreakLine(paragraph,true); } } if (!nobreackline) { HumanRead(paragraph,lines.at(i)); } else { paragraph.appendChild(dom.createTextNode(lines.at(i))); } } } else { HandleFragment(fr,paragraph,nobreackline); } } } paragraph.appendChild(NodeFooter()); if (para.blockFormat().hasProperty(QTextFormat::BlockTrailingHorizontalRulerWidth)) { /////QDomElement Horizontal = dom.createElement("hr"); /* svg line 100% */ //////paragraph.appendChild(Horizontal); } if (para.blockFormat().nonBreakableLines()) { paragraph.setAttribute("white-space-collapse","false"); } /* check footenotes to resave*/ if (!footernote.isNull()) { FopLeader FooterBlock = footernote.value<FopLeader>(); FooterBlock.RestoreOn(paragraph); } appender.appendChild(paragraph); //////////QDomComment footerBlock = dom.createComment(QString("End block %1.").arg(sumblox)); //////////appender.appendChild(footerBlock); } /* the big xsl-fo format not know <br> !!!!!! */ void FopDom::SendBreakLine( QDomElement appender , bool blockcreate ) { /* http://www.zvon.org/xxl/xslfoReference/Output/el_leader.html */ qreal currentHi = qBound (4.9,LINEHIGHT_CURRENT,33.2); if (blockcreate) { QDomElement spaceline = dom.createElement("fo:block"); spaceline.setAttribute("space-after",QString("%1pt").arg(currentHi / 2)); } else { QDomElement spaceline = dom.createElement("fo:leader"); spaceline.setAttribute("content-height",QString("%1pt").arg(currentHi)); spaceline.setAttribute("leader-pattern","space"); spaceline.setAttribute("leader-length",RecoveryBreackLineParagraph()); spaceline.setAttribute("speak-numeral",ApplicationsVersionFopConvert); spaceline.appendChild(dom.createComment(QString("\nSipmle Breack line / empty Paragraph version %1. \nUse margin space to make space!\n").arg(ApplicationsVersionFopConvert))); appender.appendChild(spaceline); } } void FopDom::HumanRead( QDomElement appender , QString longtext ) { QStringList list = longtext.split(" "); ///// QString::SkipEmptyParts QStringList roottxt; QString one =""; int fox = -1; for (int i = 0; i < list.size(); ++i) { const QString word = list.at(i).simplified(); bool islast = list.at(i) == list.last() ? true : false; if (!islast) { if (!word.endsWith(" ")) { one.append(word+" "); } else { one.append(word); } } else { one.append(word); } fox++; if (fox == 15) { fox = -1; roottxt.append(one); one =""; } if (islast) { roottxt.append(one); one =""; } } if (roottxt.size() > 0) { appender.appendChild(appender.ownerDocument().createTextNode("\n")); } for (int x = 0; x < roottxt.size(); ++x) { //////QDomComment footerBlock = appender.ownerDocument().createComment(QString("L.%1").arg(x)); //////appender.appendChild(footerBlock); appender.appendChild(appender.ownerDocument().createTextNode(roottxt.at(x))); if (roottxt.at(x) != roottxt.last()) { appender.appendChild(appender.ownerDocument().createTextNode("\n")); } } } void FopDom::HandleFragment( QTextFragment fr , QDomElement appender , bool pref ) /* pref = nobreack line space = true */ { QDomElement linkers; QDomElement span; QDomElement onechar; QString txt = fr.text(); ApiSession *session = ApiSession::instance(); const QTextCharFormat format = fr.charFormat(); if (format.isAnchor()) { QStringList namelist = format.anchorNames(); const QString href = format.anchorHref().trimmed(); if (namelist.size() > 0 || !format.anchorName().isEmpty() ) { QString first; if (!format.anchorName().isEmpty()) { first = format.anchorName(); } else { first = namelist.first(); } appender.setAttribute ("id",namelist.first().trimmed()); /* bookmark target here */ return; } if (!href.isEmpty()) { linkers = dom.createElement("fo:basic-link"); if (pref) { linkers.setAttribute("white-space-collapse","false"); } PaintFopCharFormat(linkers,fr.charFormat()); linkers.setAttribute ("external-destination",href); appender.appendChild(linkers); QString txt = Qt::escape(fr.text()); QString forcedLineBreakRegExp = QString::fromLatin1("[\\na]"); forcedLineBreakRegExp[3] = QChar::LineSeparator; const QStringList lines = txt.split(QRegExp(forcedLineBreakRegExp)); for (int i = 0; i < lines.count(); ++i) { if (i > 0) { if (pref) { linkers.appendChild(dom.createTextNode(QString(" "))); } else { SendBreakLine(linkers,true); } } linkers.appendChild(dom.createTextNode(lines.at(i))); } } return; } /* image creator xml */ if (txt.count() == 1 && txt.at(0) == QChar::ObjectReplacementCharacter) { if (format.isImageFormat()) { bool svg_inline_image = false; QTextImageFormat Pics = format.toImageFormat(); const QString hrefadress = Pics.name(); qDebug() << "### QTextImageFormat .. " << hrefadress; if (hrefadress.startsWith("foleader")) { qDebug() << "### foleader found .. "; QVariant xfx = Pics.property(LeaderNummer); if (!xfx.isNull()) { FopLeader spacedoc = xfx.value<FopLeader>(); spacedoc.RestoreOn(appender); return; } } if (hrefadress.startsWith("/svg/")) { svg_inline_image = true; } qDebug() << "### svg having .. " << svg_inline_image; QString titles; QString Ivariant = "Gf-200"; QVariant xx = Pics.property(_IMAGE_PICS_ITEM_); if (xx.isNull()) { bool session_havingimg = false; /* session having image? */ QMapIterator<QString,SPics> i(session->ImagePageList); while (i.hasNext()) { i.next(); SPics record = i.value(); if ( record.name == hrefadress ) { session_havingimg = true; xx = QVariant(record); } } if (!session_havingimg) { Ivariant = "Gf-404"; } } if (svg_inline_image) { QByteArray domsvg; QDomDocument dimg; bool session_havingimg = false; QMapIterator<QString,QByteArray> e(session->SvgList); while (e.hasNext()) { e.next(); domsvg = e.value(); if ( e.key() == hrefadress ) { qDebug() << "### session found e.key() " << e.key(); session_havingimg = true; } } if (session_havingimg && dimg.setContent(domsvg,false)) { QDomElement root_extern = dimg.documentElement(); QDomNamedNodeMap alist = root_extern.attributes(); /* copy all attributes from other doc */ QDomElement svg = dom.createElement("svg:svg"); for (int i=0; i<alist.count(); i++){ QDomNode nod = alist.item(i); svg.setAttribute(nod.nodeName().toLower(),nod.nodeValue()); } svg.setAttribute ("xmlns","http://www.w3.org/2000/svg"); svg.setAttribute ("version","1.2"); svg.setAttribute ("baseProfile","tiny"); QDomNode child = root_extern.firstChild(); while ( !child.isNull() ) { if ( child.isElement() ) { svg.appendChild(dom.importNode(child,true).toElement()); } child = child.nextSibling(); } QDomElement simagen = dom.createElement("fo:instream-foreign-object"); simagen.setAttribute ("width",QString("%1px").arg(Pics.width())); simagen.setAttribute ("height",QString("%1px").arg(Pics.height())); simagen.setAttribute ("id",Imagename(hrefadress)); simagen.setAttribute ("scaling","non-uniform"); /* forever wi x hi corect ! */ simagen.setAttribute ("content-width",QString("%1px").arg(Pics.width())); simagen.setAttribute ("content-height",QString("%1px").arg(Pics.height())); ////////simagen.setAttribute ("id",Imagename(hrefadress)+"-"+Ivariant); simagen.appendChild(svg); appender.appendChild(simagen); } } if (!svg_inline_image) { QDomElement imagen = dom.createElement("fo:external-graphic"); imagen.setAttribute ("width",QString("%1px").arg(Pics.width())); imagen.setAttribute ("height",QString("%1px").arg(Pics.height())); imagen.setAttribute ("scaling","non-uniform"); /* forever wi x hi corect ! */ imagen.setAttribute ("content-width",QString("%1px").arg(Pics.width())); imagen.setAttribute ("content-height",QString("%1px").arg(Pics.height())); imagen.setAttribute ("src",hrefadress); /* session check if having this file !! */ imagen.setAttribute ("id",Imagename(hrefadress)+"-"+Ivariant); if (!xx.isNull()) { SPics pico = xx.value<SPics>(); pico.FopSaveImage(imagen); imagen.setAttribute ("id",Imagename(pico.info)+"-"+Ivariant); } appender.appendChild(imagen); } } } else { Q_ASSERT(!txt.contains(QChar::ObjectReplacementCharacter)); /* no image no other choises */ QString txt = Qt::escape(fr.text()); QString forcedLineBreakRegExp = QString::fromLatin1("[\\na]"); forcedLineBreakRegExp[3] = QChar::LineSeparator; const QStringList lines = txt.split(QRegExp(forcedLineBreakRegExp)); span = dom.createElement("fo:inline"); PaintFopCharFormat(span,fr.charFormat()); if (pref) { span.setAttribute("white-space-collapse","false"); } appender.appendChild(span); for (int i = 0; i < lines.count(); ++i) { if (i > 0) { SendBreakLine(span,true); } if (!pref) { HumanRead(span,lines.at(i)); } else { span.appendChild(dom.createTextNode(lines.at(i))); } } } } void FopDom::PaintLastBlockformat( QDomElement e , QTextCharFormat bf ) { } void FopDom::PaintFopCharFormat( QDomElement e , QTextCharFormat bf ) { QTextCharFormat dax = DefaultCharFormats(); QFont userfont = bf.font(); QColor bb(Qt::black); const QString col = ColorFopString(bf.foreground()); if ( bf.foreground().color().name() != "#000000" ) { if (bf.foreground().color().alpha() > 20) /* no trasparent zero */ { e.setAttribute ("color",col); } } if ( bf.background().color().name() != "#000000" ) { if (bf.background().color().alpha() > 20) /* no trasparent zero */ { e.setAttribute("background-color",ColorFopString(bf.background())); } } if ( bf.font().family() != QApplication::font().family() ) { e.setAttribute ("font-family",userfont.family()); } if (dax.font().pointSize() != userfont.pointSize()) { e.setAttribute ("font-size",QString("%1pt").arg(userfont.pointSize())); } QStringList fontvario; fontvario.clear(); QStringList txtdeco; txtdeco.clear(); if (bf.fontWeight() > 51) { ///////const int fonftwbold = qBound (100,bf.fontWeight() * 6,900); e.setAttribute ("font-weight","bold"); } if (bf.fontItalic()) { fontvario.append("italic"); } if (bf.fontStrikeOut() ) { ///////fontvario.append("line-through"); txtdeco.append("line-through"); } if (bf.fontUnderline() ) { //////fontvario.append("underline"); txtdeco.append("underline"); } if (bf.fontOverline()) { ////////fontvario.append("overline"); txtdeco.append("overline"); } if (fontvario.size() > 0) { e.setAttribute ("font-style",fontvario.join(" ")); } if (txtdeco.size() > 0) { e.setAttribute ("text-decoration",txtdeco.join(" ")); } ///////int hundert = bf.fontLetterSpacing(); ///////if (hundert !=0 && hundert != 100.00) { QFont userfontee = bf.font(); if ( userfontee.letterSpacingType() != QFont::PercentageSpacing) { e.setAttribute ("letter-spacing",QString("%1pt").arg(userfontee.letterSpacing())); } /////} if (bf.verticalAlignment() == QTextCharFormat::AlignSuperScript) { e.setAttribute ("baseline-shift","super"); } if (bf.verticalAlignment() == QTextCharFormat::AlignSubScript) { e.setAttribute ("baseline-shift","sub"); } } void FopDom::TextAlignment(Qt::Alignment align , QDomElement e ) { if (align & Qt::AlignLeft) return; else if (align & Qt::AlignRight) e.setAttribute ("text-align","right"); else if (align & Qt::AlignHCenter) e.setAttribute ("text-align","center"); else if (align & Qt::AlignJustify) e.setAttribute ("text-align","justify"); } void FopDom::PaintFopBlockFormat( QDomElement e , QTextBlockFormat bf ) { TextAlignment(bf.alignment(),e); QTextFormat::PageBreakFlags actual = bf.pageBreakPolicy(); if (actual == QTextFormat::PageBreak_AlwaysBefore) { e.setAttribute("break-before","page"); } else if ( actual == QTextFormat::PageBreak_AlwaysAfter ) { e.setAttribute("break-after","page"); } if (bf.topMargin() !=0) { e.setAttribute ("margin-top",QString("%1pt").arg(bf.topMargin())); } if (bf.bottomMargin() !=0) { e.setAttribute ("margin-bottom",QString("%1pt").arg(bf.bottomMargin())); } if (bf.rightMargin() !=0) { e.setAttribute ("margin-right",QString("%1pt").arg(bf.rightMargin())); } if (bf.leftMargin() !=0) { e.setAttribute ("margin-left",QString("%1pt").arg(bf.leftMargin())); } if (bf.background().color().name() !="#000000" && bf.background().color().isValid() ) { e.setAttribute ("background-color",ColorFopString(bf.background())); } e.setAttribute ("color",ColorFopString(bf.foreground())); } /* loop to find attribute name xx */ QString FopDom::FilterAttribute( QDomElement element , QString attribute ) { QString base = ""; QDomNamedNodeMap attlist = element.attributes(); int bigint = attlist.count(); if ( bigint > 0 ) { for (int i=0; i<bigint; i++){ QDomNode nod = attlist.item(i); if (nod.nodeName() == attribute) { base = QString(nod.nodeValue()); return base; } } } return base; } QString FopDom::BorderStyleCss(QTextFrameFormat::BorderStyle style) { Q_ASSERT(style <= QTextFrameFormat::BorderStyle_Outset); QString html =""; switch (style) { case QTextFrameFormat::BorderStyle_None: html += QLatin1String("none"); break; case QTextFrameFormat::BorderStyle_Dotted: html += QLatin1String("dotted"); break; case QTextFrameFormat::BorderStyle_Dashed: html += QLatin1String("dashed"); break; case QTextFrameFormat::BorderStyle_Solid: html += QLatin1String("solid"); break; case QTextFrameFormat::BorderStyle_Double: html += QLatin1String("double"); break; case QTextFrameFormat::BorderStyle_DotDash: html += QLatin1String("dot-dash"); break; case QTextFrameFormat::BorderStyle_DotDotDash: html += QLatin1String("dot-dot-dash"); break; case QTextFrameFormat::BorderStyle_Groove: html += QLatin1String("groove"); break; case QTextFrameFormat::BorderStyle_Ridge: html += QLatin1String("ridge"); break; case QTextFrameFormat::BorderStyle_Inset: html += QLatin1String("inset"); break; case QTextFrameFormat::BorderStyle_Outset: html += QLatin1String("outset"); break; default: html += QLatin1String("none"); break; }; return html; } QString FopDom::ColorFopString( const QBrush paintcolor ) const { ///////QColor::QColor ( int r, int g, int b, int a = 255 ) QColor c = paintcolor.color(); QString StringColor = QString("rgb(%1,%2,%3,%4)").arg(c.red()).arg(c.green()).arg(c.blue()).arg(c.alpha()); return StringColor; } QString FopDom::ColorFopString( const QColor c ) const { ///////QColor::QColor ( int r, int g, int b, int a = 255 ) QString StringColor = QString("rgb(%1,%2,%3,%4)").arg(c.red()).arg(c.green()).arg(c.blue()).arg(c.alpha()); return StringColor; } void FopDom::ListUlLiSymbol( QDomElement appender , QTextList *list ) { QDomElement blocklabel = dom.createElement("fo:block"); /* list style !!!! */ appender.appendChild(blocklabel); DotList_Circle( blocklabel ); /* append svg dot 20pt */ } qreal FopDom::LineHightCurrent( QTextBlockFormat bf , QTextCharFormat cf ) { const qreal s1 = cf.font().pointSize(); const qreal s2 = bf.topMargin(); const qreal s3 = bf.bottomMargin(); return s1 + s2 + s3; }
[ "ppkciz@9af58faf-7e3e-0410-b956-55d145112073" ]
[ [ [ 1, 1028 ] ] ]
beb1da18a5ece0b516c741e33f74e259a3256273
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/nebula2/src/gui/nguitextview_cmds.cc
411a9c628dee93831b7ed80760b0c4615516f86a
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
7,749
cc
//------------------------------------------------------------------------------ // nguitextview_cmds.cc // (C) 2004 RadonLabs GmbH //------------------------------------------------------------------------------ #include "gui/nguitextview.h" static void n_setfont(void* slf, nCmd* cmd); static void n_getfont(void* slf, nCmd* cmd); static void n_settextcolor(void* slf, nCmd* cmd); static void n_gettextcolor(void* slf, nCmd* cmd); static void n_setborder(void* slf, nCmd* cmd); static void n_getborder(void* slf, nCmd* cmd); static void n_beginappend(void* slf, nCmd* cmd); static void n_appendline(void* slf, nCmd* cmd); static void n_endappend(void* slf, nCmd* cmd); static void n_getnumvisiblelines(void* slf, nCmd* cmd); static void n_setselectionenabled(void* slf, nCmd* cmd); static void n_getselectionenabled(void* slf, nCmd* cmd); static void n_setselectionindex(void* slf, nCmd* cmd); static void n_getselectionindex(void* slf, nCmd* cmd); //----------------------------------------------------------------------------- /** @scriptclass nguitextview @cppclass nGuiTextView @superclass nguiwidget @classinfo Simple widget which renders a vertical list of text lines. */ void n_initcmds(nClass* cl) { cl->BeginCmds(); cl->AddCmd("v_setfont_s", 'SFNT', n_setfont); cl->AddCmd("s_getfont_v", 'GFNT', n_getfont); cl->AddCmd("v_setborder_s", 'SBRD', n_setborder); cl->AddCmd("s_getborder_v", 'GBRD', n_getborder); cl->AddCmd("v_settextcolor_ffff", 'STXC', n_settextcolor); cl->AddCmd("ffff_gettextcolor_v", 'GTXC', n_gettextcolor); cl->AddCmd("v_beginappend_v", 'BGAP', n_beginappend); cl->AddCmd("v_appendline_s", 'APPL', n_appendline); cl->AddCmd("v_endappend_v", 'EDAP', n_endappend); cl->AddCmd("i_getnumvisiblelines_v", 'GNVL', n_getnumvisiblelines); cl->AddCmd("v_setselectionenabled_b", 'SSLE', n_setselectionenabled); cl->AddCmd("i_getselectionenabled_v", 'GSLE', n_getselectionenabled); cl->AddCmd("v_setselectionindex_i", 'SSLI', n_setselectionindex); cl->AddCmd("i_getselectionindex_v", 'GSLI', n_getselectionindex); cl->EndCmds(); } //----------------------------------------------------------------------------- /** @cmd setfont @input s(FontName) @output v @info Set the font name. The font must have been registered with the gui server with the nguiserver.addfont command. */ static void n_setfont(void* slf, nCmd* cmd) { nGuiTextView* self = (nGuiTextView*) slf; self->SetFont(cmd->In()->GetS()); } //----------------------------------------------------------------------------- /** @cmd getfont @input v @output s(FontName) @info Get the font name. */ static void n_getfont(void* slf, nCmd* cmd) { nGuiTextView* self = (nGuiTextView*) slf; cmd->Out()->SetS(self->GetFont().Get()); } //----------------------------------------------------------------------------- /** @cmd setborder @input f(HoriBorder) @output v @info Set a horizontal border for the text. */ static void n_setborder(void* slf, nCmd* cmd) { nGuiTextView* self = (nGuiTextView*) slf; self->SetBorder(cmd->In()->GetF()); } //----------------------------------------------------------------------------- /** @cmd getborder @input v @output f(HoriBorder) @info Get the horizontal border for the text. */ static void n_getborder(void* slf, nCmd* cmd) { nGuiTextView* self = (nGuiTextView*) slf; cmd->Out()->SetF(self->GetBorder()); } //----------------------------------------------------------------------------- /** @cmd settextcolor @input ffff(TextColor) @output v @info Set the text color. */ static void n_settextcolor(void* slf, nCmd* cmd) { nGuiTextView* self = (nGuiTextView*) slf; static vector4 v; v.x = cmd->In()->GetF(); v.y = cmd->In()->GetF(); v.z = cmd->In()->GetF(); v.w = cmd->In()->GetF(); self->SetTextColor(v); } //----------------------------------------------------------------------------- /** @cmd gettextcolor @input v @output ffff(TextColor) @info Get the text color. */ static void n_gettextcolor(void* slf, nCmd* cmd) { nGuiTextView* self = (nGuiTextView*) slf; const vector4& v = self->GetTextColor(); cmd->Out()->SetF(v.x); cmd->Out()->SetF(v.y); cmd->Out()->SetF(v.z); cmd->Out()->SetF(v.w); } //----------------------------------------------------------------------------- /** @cmd beginappend @input v @output v @info Begin appending text. */ static void n_beginappend(void* slf, nCmd* /*cmd*/) { nGuiTextView* self = (nGuiTextView*) slf; self->BeginAppend(); } //----------------------------------------------------------------------------- /** @cmd appendline @input s(TextLine) @output v @info Append a line of text to the internal text array. */ static void n_appendline(void* slf, nCmd* cmd) { nGuiTextView* self = (nGuiTextView*) slf; self->AppendLine(cmd->In()->GetS()); } //----------------------------------------------------------------------------- /** @cmd endappend @input v @output v @info Finish appending text. */ static void n_endappend(void* slf, nCmd* /*cmd*/) { nGuiTextView* self = (nGuiTextView*) slf; self->EndAppend(); } //----------------------------------------------------------------------------- /** @cmd getnumvisiblelines @input v @output i @info Returns the number of fully visible lines which would fit into the widget's area. */ static void n_getnumvisiblelines(void* slf, nCmd* cmd) { nGuiTextView* self = (nGuiTextView*) slf; cmd->Out()->SetI(self->GetNumVisibleLines()); } //----------------------------------------------------------------------------- /** @cmd setselectionindex @input i @output v @info Set the current selection index. */ static void n_setselectionindex(void* slf, nCmd* cmd) { nGuiTextView* self = (nGuiTextView*) slf; self->SetSelectionIndex(cmd->In()->GetI()); } //----------------------------------------------------------------------------- /** @cmd getselectionindex @input v @output i @info Get the current selection index. */ static void n_getselectionindex(void* slf, nCmd* cmd) { nGuiTextView* self = (nGuiTextView*) slf; cmd->Out()->SetI(self->GetSelectionIndex()); } //----------------------------------------------------------------------------- /** @cmd setselectionenabled @input b @output v @info Enable/disable selection handling. */ static void n_setselectionenabled(void* slf, nCmd* cmd) { nGuiTextView* self = (nGuiTextView*) slf; self->SetSelectionEnabled(cmd->In()->GetB()); } //----------------------------------------------------------------------------- /** @cmd getselectionenabled @input v @output b @info Get selection handling status. */ static void n_getselectionenabled(void* slf, nCmd* cmd) { nGuiTextView* self = (nGuiTextView*) slf; cmd->Out()->SetB(self->GetSelectionEnabled()); }
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 322 ] ] ]
60f6310f3268ef27ea3b42bfa32276c3499f0e3d
96fefafdfbb413a56e0a2444fcc1a7056afef757
/MQ2Main/MQ2DetourAPI.cpp
4b9d4f664631c55af5c3418d2e2ffc2799977d9b
[]
no_license
kevrgithub/peqtgc-mq2-sod
ffc105aedbfef16060769bb7a6fa6609d775b1fa
d0b7ec010bc64c3f0ac9dc32129a62277b8d42c0
refs/heads/master
2021-01-18T18:57:16.627137
2011-03-06T13:05:41
2011-03-06T13:05:41
32,849,784
1
3
null
null
null
null
UTF-8
C++
false
false
29,809
cpp
/***************************************************************************** MQ2Main.dll: MacroQuest2's extension DLL for EverQuest Copyright (C) 2002-2003 Plazmic, 2003-2005 Lax This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. 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. ******************************************************************************/ // Exclude rarely-used stuff from Windows headers #define WIN32_LEAN_AND_MEAN #define _WIN32_WINNT 0x510 #define DIRECTINPUT_VERSION 0x800 #if !defined(CINTERFACE) #error /DCINTERFACE #endif #define DBG_SPEW #include "MQ2Main.h" #ifndef ISXEQ typedef struct _OurDetours { /* 0x00 */ unsigned int addr; /* 0x04 */ unsigned int count; /* 0x08 */ unsigned char array[50]; /* 0x3a */ PBYTE pfDetour; /* 0x3e */ PBYTE pfTrampoline; /* 0x42 */ struct _OurDetours *pNext; /* 0x46 */ struct _OurDetours *pLast; } OurDetours; OurDetours *ourdetours=0; CRITICAL_SECTION gDetourCS; OurDetours *FindDetour(DWORD address) { OurDetours *pDetour=ourdetours; while(pDetour) { if (pDetour->addr==address) return pDetour; pDetour=pDetour->pNext; } return 0; } BOOL AddDetour(DWORD address, PBYTE pfDetour, PBYTE pfTrampoline, DWORD Count) { CAutoLock Lock(&gDetourCS); BOOL Ret=TRUE; DebugSpew("AddDetour(0x%X,0x%X,0x%X,0x%X)",address,pfDetour,pfTrampoline,Count); if (FindDetour(address)) { DebugSpew("Address 0x%x already detoured.",address); return FALSE; } OurDetours *detour = new OurDetours; detour->addr=address; detour->count=Count; memcpy(detour->array,(char *)address, Count); detour->pNext=ourdetours; if (ourdetours) ourdetours->pLast=detour; detour->pLast=0; if (pfDetour && !DetourFunctionWithEmptyTrampoline(pfTrampoline, (PBYTE)address, pfDetour)) { detour->pfDetour=0; detour->pfTrampoline=0; Ret=FALSE; DebugSpew("Detour failed."); } else { detour->pfDetour=pfDetour; detour->pfTrampoline=pfTrampoline; DebugSpew("Detour success."); } ourdetours=detour; return Ret; } void AddDetourf(DWORD address, ...) { va_list marker; int i=0; va_start(marker, address); DWORD Parameters[3]; DWORD nParameters=0; while (i!=-1) { if (nParameters<3) { Parameters[nParameters]=i; nParameters++; } i = va_arg(marker,int); } va_end(marker); if (nParameters==3) { AddDetour(address,(PBYTE)Parameters[1],(PBYTE)Parameters[2],20); } else { DebugSpew("Illegal AddDetourf call"); } } void RemoveDetour(DWORD address) { CAutoLock Lock(&gDetourCS); DebugSpew("RemoveDetour(%X)",address); OurDetours *detour = ourdetours; while (detour) { if (detour->addr==address) { if (detour->pfDetour) { DetourRemove(detour->pfTrampoline, detour->pfDetour); } if (detour->pLast) detour->pLast->pNext=detour->pNext; else ourdetours=detour->pNext; if (detour->pNext) detour->pNext->pLast=detour->pLast; delete detour; DebugSpew("Detour removed."); return; } detour=detour->pNext; } DebugSpew("Detour not found in RemoveDetour()"); } void RemoveOurDetours() { CAutoLock Lock(&gDetourCS); DebugSpew("RemoveOurDetours()"); if (!ourdetours) return; while (ourdetours) { if (ourdetours->pfDetour) { DebugSpew("RemoveOurDetours() -- Removing %X",ourdetours->addr); DetourRemove(ourdetours->pfTrampoline,ourdetours->pfDetour); } OurDetours *pNext=ourdetours->pNext; delete ourdetours; ourdetours=pNext; } } #endif class CObfuscator { public: int doit_tramp(int, int); int doit_detour(int opcode, int flag); }; int CObfuscator::doit_detour(int opcode, int flag) { #if 0 if (EQ_BEGIN_ZONE == opcode) { DebugSpewAlways("EQ_BEGIN_ZONE"); } else { DebugSpewAlways("opcode %d", opcode); } #endif if (opcode==EQ_BEGIN_ZONE) PluginsBeginZone(); if (opcode==EQ_END_ZONE) PluginsEndZone(); return doit_tramp(opcode, flag); }; DETOUR_TRAMPOLINE_EMPTY(int CObfuscator::doit_tramp(int, int)); #define EB_SIZE (1024*4) void emotify(void); void emotify2(char *buffer); // we need this detour to clean up the stack because // emote sends 1024 bytes no matter how many bytes in the string // MQ2 variables get left on the stack.... class CEmoteHook { public: VOID Trampoline(void); VOID Detour(void); }; VOID CEmoteHook::Detour(void) { emotify(); Trampoline(); } DETOUR_TRAMPOLINE_EMPTY(VOID CEmoteHook::Trampoline(void)); // this is the memory checker key struct struct mckey { union { int x; unsigned char a[4]; char sa[4]; }; }; // pointer to encryption pad for memory checker unsigned int *extern_array0 = NULL; unsigned int *extern_array1 = NULL; unsigned int *extern_array2 = NULL; unsigned int *extern_array3 = NULL; unsigned int *extern_array4 = NULL; #ifndef ISXEQ int __cdecl memcheck0(unsigned char *buffer, int count); int __cdecl memcheck1(unsigned char *buffer, int count, struct mckey key); int __cdecl memcheck2(unsigned char *buffer, int count, struct mckey key); int __cdecl memcheck3(unsigned char *buffer, int count, struct mckey key); int __cdecl memcheck4(unsigned char *buffer, int count, struct mckey key); #endif // *************************************************************************** // Function: HookMemChecker // Description: Hook MemChecker // *************************************************************************** int (__cdecl *memcheck0_tramp)(unsigned char *buffer, int count); int (__cdecl *memcheck1_tramp)(unsigned char *buffer, int count, struct mckey key); int (__cdecl *memcheck2_tramp)(unsigned char *buffer, int count, struct mckey key); int (__cdecl *memcheck3_tramp)(unsigned char *buffer, int count, struct mckey key); int (__cdecl *memcheck4_tramp)(unsigned char *buffer, int count, struct mckey key); VOID HookInlineChecks(BOOL Patch) { int i; DWORD oldperm, tmp, NewData; /* add these to eqgame.h */ //.text:0063BA30 cmp int g_radd, (offset loc_7C1AB9+1) int cmps[] = { 0x63BA30+6 }; //.text:004D6D55 cmp ecx, 0D7BD62AEh //.text:004F2488 cmp eax, 0F1BD3A34h //.text:004F7A48 cmp eax, 4123EADBh //.text:004FAC0B cmp eax, 3C12B82Dh //.text:004F2A64 cmp ecx, 0C38F1142h int cmps2[] = { 0x4D6D55, 0x4F2488, 0x4F7A48, 0x4FAC0B, 0x4F2A64 }; int len2[] = { 6, 5, 5, 5, 6 }; char NewData2[20]; static char OldData2[sizeof(cmps2)/sizeof(cmps2[0])][20]; if (Patch) { // .text:005DE39D 81 3D 28 EF 97 00 0E C0 6D 00 cmp dword_97EF28, 6DC00Eh // change only these bytes ^^ ^^ ^^ ^^ NewData = 0x7fffffff; for (i=0;i<sizeof(cmps)/sizeof(cmps[0]);i++) { #ifdef ISXEQ EzModify(cmps[i],&NewData,4); #else AddDetour(cmps[i], NULL, NULL, 4); VirtualProtectEx(GetCurrentProcess(), (LPVOID)cmps[i], 4, PAGE_EXECUTE_READWRITE, &oldperm); WriteProcessMemory(GetCurrentProcess(), (LPVOID)cmps[i], (LPVOID)&NewData, 4, NULL); VirtualProtectEx(GetCurrentProcess(), (LPVOID)cmps[i], 4, oldperm, &tmp); #endif } // .text:004E1AEF 81 F9 31 BD 3E CE cmp ecx, 0CE3EBD31h // zap these into oblivion memset(NewData2, 0x90, 20); for (i=0;i<sizeof(cmps2)/sizeof(cmps2[0]);i++) { #ifdef ISXEQ EzModify(cmps2[i],NewData2,len2[i]); #else AddDetour(cmps2[i], NULL, NULL, len2[i]); VirtualProtectEx(GetCurrentProcess(), (LPVOID)cmps2[i], len2[i], PAGE_EXECUTE_READWRITE, &oldperm); memcpy((void *)OldData2[i], (void *)cmps2[i], len2[i]); WriteProcessMemory(GetCurrentProcess(), (LPVOID)cmps2[i], (LPVOID)NewData2, len2[i], NULL); VirtualProtectEx(GetCurrentProcess(), (LPVOID)cmps2[i], len2[i], oldperm, &tmp); #endif } // __asm int 3; } else { NewData = 0x7C1ABA; for (i=0;i<sizeof(cmps)/sizeof(cmps[0]);i++) { #ifdef ISXEQ EzUnModify(cmps[i]); #else VirtualProtectEx(GetCurrentProcess(), (LPVOID)cmps[i], 4, PAGE_EXECUTE_READWRITE, &oldperm); WriteProcessMemory(GetCurrentProcess(), (LPVOID)cmps[i], (LPVOID)&NewData, 4, NULL); VirtualProtectEx(GetCurrentProcess(), (LPVOID)cmps[i], 4, oldperm, &tmp); RemoveDetour(cmps[i]); #endif } for (i=0;i<sizeof(cmps2)/sizeof(cmps2[0]);i++) { #ifdef ISXEQ EzUnModify(cmps2[i]); #else VirtualProtectEx(GetCurrentProcess(), (LPVOID)cmps2[i], len2[i], PAGE_EXECUTE_READWRITE, &oldperm); WriteProcessMemory(GetCurrentProcess(), (LPVOID)cmps2[i], (LPVOID)OldData2[i], len2[i], NULL); VirtualProtectEx(GetCurrentProcess(), (LPVOID)cmps2[i], len2[i], oldperm, &tmp); RemoveDetour(cmps2[i]); #endif } } } #ifndef ISXEQ VOID HookMemChecker(BOOL Patch) { // hit the debugger if we don't hook this // take no chances if ((!EQADDR_MEMCHECK0) || (!EQADDR_MEMCHECK1) || (!EQADDR_MEMCHECK2) || (!EQADDR_MEMCHECK3) || (!EQADDR_MEMCHECK4)) { _asm int 3 } DebugSpew("HookMemChecker - %satching",(Patch)?"P":"Unp"); if (Patch) { AddDetour((DWORD)EQADDR_MEMCHECK0); (*(PBYTE*)&memcheck0_tramp) = DetourFunction( (PBYTE) EQADDR_MEMCHECK0, (PBYTE) memcheck0); AddDetour((DWORD)EQADDR_MEMCHECK1); (*(PBYTE*)&memcheck1_tramp) = DetourFunction( (PBYTE) EQADDR_MEMCHECK1, (PBYTE) memcheck1); AddDetour((DWORD)EQADDR_MEMCHECK2); (*(PBYTE*)&memcheck2_tramp) = DetourFunction( (PBYTE) EQADDR_MEMCHECK2, (PBYTE) memcheck2); AddDetour((DWORD)EQADDR_MEMCHECK3); (*(PBYTE*)&memcheck3_tramp) = DetourFunction( (PBYTE) EQADDR_MEMCHECK3, (PBYTE) memcheck3); AddDetour((DWORD)EQADDR_MEMCHECK4); (*(PBYTE*)&memcheck4_tramp) = DetourFunction( (PBYTE) EQADDR_MEMCHECK4, (PBYTE) memcheck4); EzDetour(CObfuscator__doit,&CObfuscator::doit_detour,&CObfuscator::doit_tramp); EzDetour(CEverQuest__Emote,&CEmoteHook::Detour,&CEmoteHook::Trampoline); HookInlineChecks(Patch); } else { HookInlineChecks(Patch); DetourRemove((PBYTE) memcheck0_tramp, (PBYTE) memcheck0); memcheck0_tramp = NULL; RemoveDetour(EQADDR_MEMCHECK0); DetourRemove((PBYTE) memcheck1_tramp, (PBYTE) memcheck1); memcheck1_tramp = NULL; RemoveDetour(EQADDR_MEMCHECK1); DetourRemove((PBYTE) memcheck2_tramp, (PBYTE) memcheck2); memcheck2_tramp = NULL; RemoveDetour(EQADDR_MEMCHECK2); DetourRemove((PBYTE) memcheck3_tramp, (PBYTE) memcheck3); memcheck3_tramp = NULL; RemoveDetour(EQADDR_MEMCHECK3); DetourRemove((PBYTE) memcheck4_tramp, (PBYTE) memcheck4); memcheck4_tramp = NULL; RemoveDetour(EQADDR_MEMCHECK4); RemoveDetour(CObfuscator__doit); RemoveDetour(CEverQuest__Emote); } } #endif int __cdecl memcheck0(unsigned char *buffer, int count) { unsigned int x, i; unsigned int eax = 0xffffffff; if (!extern_array0) { if (!EQADDR_ENCRYPTPAD0) { //_asm int 3 } else { extern_array0 = (unsigned int *)EQADDR_ENCRYPTPAD0; } } #ifdef ISXEQ unsigned char *realbuffer=(unsigned char *)malloc(count); pExtension->Memcpy_Clean((unsigned int)buffer,realbuffer,count); #endif for (i=0;i<(unsigned int)count;i++) { unsigned char tmp; #ifdef ISXEQ tmp=realbuffer[i]; #else unsigned int b=(int) &buffer[i]; OurDetours *detour = ourdetours; while(detour) { if (detour->count && (b >= detour->addr) && (b < detour->addr+detour->count) ) { tmp = detour->array[b - detour->addr]; break; } detour=detour->pNext; } if (!detour) tmp = buffer[i]; #endif x = (int)tmp ^ (eax & 0xff); eax = ((int)eax >> 8) & 0xffffff; x = extern_array0[x]; eax ^= x; } #ifdef ISXEQ free(realbuffer); #endif return eax; } int __cdecl memcheck1(unsigned char *buffer, int count, struct mckey key) { unsigned int i; unsigned int ebx, eax, edx; if (!extern_array1) { if (!EQADDR_ENCRYPTPAD1) { //_asm int 3 } else { extern_array1 = (unsigned int *)EQADDR_ENCRYPTPAD1; } } // push ebp // mov ebp, esp // push esi // push edi // or edi, 0FFFFFFFFh // cmp [ebp+arg_8], 0 if (key.x != 0) { // mov esi, 0FFh // mov ecx, 0FFFFFFh // jz short loc_4C3978 // xor eax, eax // mov al, byte ptr [ebp+arg_8] // xor edx, edx // mov dl, byte ptr [ebp+arg_8+1] edx = key.a[1]; // not eax // and eax, esi eax = ~key.a[0] & 0xff; // mov eax, encryptpad1[eax*4] eax = extern_array1[eax]; // xor eax, ecx eax ^= 0xffffff; // xor edx, eax // and edx, esi edx = (edx ^ eax) & 0xff; // sar eax, 8 // and eax, ecx eax = ((int)eax >> 8) & 0xffffff; // xor eax, encryptpad1[edx*4] eax ^= extern_array1[edx]; // xor edx, edx // mov dl, byte ptr [ebp+arg_8+2] edx = key.a[2]; // xor edx, eax // sar eax, 8 // and edx, esi edx = (edx ^ eax) & 0xff; // and eax, ecx eax = ((int)eax >> 8) & 0xffffff; // xor eax, encryptpad1[edx*4] eax ^= extern_array1[edx]; // xor edx, edx // mov dl, byte ptr [ebp+arg_8+3] edx = key.a[3]; // xor edx, eax // sar eax, 8 // and edx, esi edx = (edx ^ eax) & 0xff; // and eax, ecx eax = ((int)eax >> 8) & 0xffffff; // xor eax, encryptpad1[edx*4] eax ^= extern_array1[edx]; // mov edi, eax // } else { // key.x != 0 eax = 0xffffffff; } //loc_4C3978: ; CODE XREF: new_memcheck1+16j // mov edx, [ebp+arg_0] // mov eax, [ebp+arg_4] // add eax, edx // cmp edx, eax // jnb short loc_4C399F // push ebx // //loc_4C3985: ; CODE XREF: new_memcheck1+8Fj // xor ebx, ebx // mov bl, [edx] // xor ebx, edi // sar edi, 8 // and ebx, esi // and edi, ecx // xor edi, encryptpad1[ebx*4] // inc edx // cmp edx, eax // jb short loc_4C3985 // pop ebx // //loc_4C399F: ; CODE XREF: new_memcheck1+75j // mov eax, edi // pop edi // not eax // pop esi // pop ebp // retn // #ifdef ISXEQ unsigned char *realbuffer=(unsigned char *)malloc(count); pExtension->Memcpy_Clean((unsigned int)buffer,realbuffer,count); #endif for (i=0;i<(unsigned int)count;i++) { unsigned char tmp; #ifdef ISXEQ tmp=realbuffer[i]; #else unsigned int b=(int) &buffer[i]; OurDetours *detour = ourdetours; while(detour) { if (detour->count && (b >= detour->addr) && (b < detour->addr+detour->count) ) { tmp = detour->array[b - detour->addr]; break; } detour=detour->pNext; } if (!detour) tmp = buffer[i]; #endif ebx = ((int)tmp ^ eax) & 0xff; eax = ((int)eax >> 8) & 0xffffff; eax ^= extern_array1[ebx]; } #ifdef ISXEQ free(realbuffer); #endif return ~eax; } int __cdecl memcheck2(unsigned char *buffer, int count, struct mckey key) { unsigned int i; unsigned int ebx, edx, eax; //DebugSpewAlways("memcheck2: 0x%x", buffer); if (!extern_array2) { if (!EQADDR_ENCRYPTPAD2) { //_asm int 3 } else { extern_array2 = (unsigned int *)EQADDR_ENCRYPTPAD2; } } // push ebp // mov ebp, esp // push ecx // xor eax, eax // mov al, [ebp+arg_8] // xor edx, edx // mov dl, [ebp+arg_9] edx = key.a[1]; // push ebx // push esi // mov esi, 0FFh // mov ecx, 0FFFFFFh // not eax // and eax, esi eax = ~key.a[0] & 0xff; // mov eax, encryptpad2[eax*4] eax = extern_array2[eax]; // xor eax, ecx eax ^= 0xffffff; // xor edx, eax edx = (edx ^ eax) & 0xff; // sar eax, 8 // and edx, esi // and eax, ecx eax = ((int)eax >> 8) & 0xffffff; // xor eax, encryptpad2[edx*4] eax ^= extern_array2[edx]; // xor edx, edx // mov dl, [ebp+arg_A] edx = key.a[2]; // push edi // xor edx, eax edx = (edx ^ eax) & 0xff; // sar eax, 8 // and edx, esi // and eax, ecx eax = ((int)eax >> 8) & 0xffffff; // xor eax, encryptpad2[edx*4] // mov edx, eax edx = eax ^ extern_array2[edx]; // call null_sub_ret_0 eax = 0; // mov edi, [ebp+arg_0] // xor ebx, ebx // mov bl, [ebp+arg_B] ebx = key.a[3]; // mov [ebp+var_4], eax // xor ebx, edx ebx = (edx ^ ebx) & 0xff; // sar edx, 8 // and edx, ecx // and ebx, esi edx = ((int)edx >> 8) & 0xffffff; // xor edx, encryptpad2[ebx*4] edx ^= extern_array2[ebx]; // xor edx, eax edx ^= eax; // mov eax, [ebp+arg_4] // add eax, edi // jmp short loc_4C5776 //; --------------------------------------------------------------------------- // //loc_4C5761: ; CODE XREF: new_memcheck2+8Fj // xor ebx, ebx // mov bl, [edi] // xor ebx, edx // sar edx, 8 // and ebx, esi // and edx, ecx // xor edx, encryptpad2[ebx*4] // inc edi // //loc_4C5776: ; CODE XREF: new_memcheck2+76j // cmp edi, eax // jb short loc_4C5761 // pop edi // mov eax, edx // not eax // xor eax, [ebp+var_4] // pop esi // pop ebx // leave // retn #ifdef ISXEQ unsigned char *realbuffer=(unsigned char *)malloc(count); pExtension->Memcpy_Clean((unsigned int)buffer,realbuffer,count); #endif for (i=0;i<(unsigned int)count;i++) { unsigned char tmp; #ifdef ISXEQ tmp=realbuffer[i]; #else unsigned int b=(int) &buffer[i]; OurDetours *detour = ourdetours; while(detour) { if (detour->count && (b >= detour->addr) && (b < detour->addr+detour->count) ) { tmp = detour->array[b - detour->addr]; break; } detour=detour->pNext; } if (!detour) tmp = buffer[i]; #endif ebx = ((int) tmp ^ edx) & 0xff; edx = ((int)edx >> 8) & 0xffffff; edx ^= extern_array2[ebx]; } eax = ~edx ^ 0; #ifdef ISXEQ free(realbuffer); #endif return eax; } //extern int extern_arrray[]; //unsigned int *extern_array3 = (unsigned int *)0x5C0E98; // 004F4AB9: 55 push ebp // 004F4ABA: 8B EC mov ebp,esp // 004F4ABC: 56 push esi // bah - 83 /1 ib OR r/m16,imm8 r/m16 OR imm8 (sign-extended) // sign extended!!!!!!!!!!!! // 004F4ABD: 83 C8 FF or eax,0FFh int __cdecl memcheck3(unsigned char *buffer, int count, struct mckey key) { unsigned int eax, ebx, edx, i; if (!extern_array3) { if (!EQADDR_ENCRYPTPAD3) { //_asm int 3 } else { extern_array3 = (unsigned int *)EQADDR_ENCRYPTPAD3; } } // push ebp // mov ebp, esp // push ecx // xor eax, eax // mov al, [ebp+arg_8] // xor edx, edx // mov dl, [ebp+arg_9] edx = key.a[1]; // push ebx // push esi // mov esi, 0FFh // mov ecx, 0FFFFFFh // not eax // and eax, esi eax = ~key.a[0] & 0xff; // mov eax, encryptpad3[eax*4] eax = extern_array3[eax]; // xor eax, ecx eax ^= 0xffffff; // xor edx, eax // sar eax, 8 // and edx, esi edx = (edx ^ eax) & 0xff; // and eax, ecx eax = ((int)eax>>8) & 0xffffff; // xor eax, encryptpad3[edx*4] eax ^= extern_array3[edx]; // xor edx, edx // mov dl, [ebp+arg_A] edx = key.a[2]; // push edi // xor edx, eax edx = (edx ^ eax) & 0xff; // sar eax, 8 // and edx, esi // and eax, ecx eax = ((int)eax>>8) & 0xffffff; // xor eax, encryptpad3[edx*4] // mov edx, eax edx = eax ^ extern_array3[edx]; // call null_sub_ret_0 eax = 0; // mov edi, [ebp+arg_0] // xor ebx, ebx // mov bl, [ebp+arg_B] ebx = key.a[3]; // mov [ebp+var_4], eax // xor ebx, edx // sar edx, 8 // and edx, ecx // and ebx, esi ebx = (ebx ^ edx) & 0xff; edx = ((int)edx>>8) & 0xffffff; // xor edx, encryptpad3[ebx*4] edx ^= extern_array3[ebx]; // xor edx, eax edx ^= eax; // mov eax, [ebp+arg_4] // add eax, edi // jmp short loc_4C5813 //; --------------------------------------------------------------------------- // //loc_4C57FE: ; CODE XREF: new_memcheck3+8Fj // xor ebx, ebx // mov bl, [edi] // xor ebx, edx // sar edx, 8 // and ebx, esi // and edx, ecx // xor edx, encryptpad3[ebx*4] // inc edi // #ifdef ISXEQ unsigned char *realbuffer=(unsigned char *)malloc(count); pExtension->Memcpy_Clean((unsigned int)buffer,realbuffer,count); #endif for (i=0;i<(unsigned int)count;i++) { unsigned char tmp; #ifdef ISXEQ tmp=realbuffer[i]; #else unsigned int b=(int) &buffer[i]; OurDetours *detour = ourdetours; while(detour) { if (detour->count && (b >= detour->addr) && (b < detour->addr+detour->count) ) { tmp = detour->array[b - detour->addr]; break; } detour=detour->pNext; } if (!detour) tmp = buffer[i]; #endif ebx = (tmp ^ edx) & 0xff; edx = ((int)edx >> 8) & 0xffffff; edx ^= extern_array3[ebx]; } //loc_4C5813: ; CODE XREF: new_memcheck3+76j // cmp edi, eax // jb short loc_4C57FE // pop edi // mov eax, edx // not eax // xor eax, [ebp+var_4] eax = ~edx ^ 0; #ifdef ISXEQ free(realbuffer); #endif return eax; // pop esi // pop ebx // leave // retn } int __cdecl memcheck4(unsigned char *buffer, int count, struct mckey key) { unsigned int eax, ebx, edx, i; if (!extern_array4) { if (!EQADDR_ENCRYPTPAD4) { //_asm int 3 } else { extern_array4 = (unsigned int *)EQADDR_ENCRYPTPAD4; } } edx = key.a[1]; eax = ~key.a[0] & 0xff; eax = extern_array4[eax]; eax ^= 0xffffff; edx = (edx ^ eax) & 0xff; eax = ((int)eax>>8) & 0xffffff; eax ^= extern_array4[edx]; edx = key.a[2]; edx = (edx ^ eax) & 0xff; eax = ((int)eax>>8) & 0xffffff; edx = eax ^ extern_array4[edx]; eax = 0; ebx = key.a[3]; ebx = (ebx ^ edx) & 0xff; edx = ((int)edx>>8) & 0xffffff; edx ^= extern_array4[ebx]; edx ^= eax; #ifdef ISXEQ unsigned char *realbuffer=(unsigned char *)malloc(count); pExtension->Memcpy_Clean((unsigned int)buffer,realbuffer,count); #endif for (i=0;i<(unsigned int)count;i++) { unsigned char tmp; #ifdef ISXEQ tmp=realbuffer[i]; #else unsigned int b=(int) &buffer[i]; OurDetours *detour = ourdetours; while(detour) { if (detour->count && (b >= detour->addr) && (b < detour->addr+detour->count) ) { tmp = detour->array[b - detour->addr]; break; } detour=detour->pNext; } if (!detour) tmp = buffer[i]; #endif ebx = (tmp ^ edx) & 0xff; edx = ((int)edx >> 8) & 0xffffff; edx ^= extern_array4[ebx]; } eax = ~edx ^ 0; #ifdef ISXEQ free(realbuffer); #endif return eax; } VOID __cdecl CrashDetected_Trampoline(DWORD,DWORD,DWORD,DWORD,DWORD); VOID __cdecl CrashDetected_Detour(DWORD a,DWORD b,DWORD c,DWORD d,DWORD e) { MessageBox(0,"MacroQuest2 is blocking the 'send Sony crash info?' box for your safety and privacy. Crashes are usually bugs either in EQ or in MacroQuest2. It is generally not something that you yourself did, unless you have custom MQ2 plugins loaded. If you want to submit a bug report to the MacroQuest2 message boards, please follow the instructions on how to submit a crash bug report at the top of the MQ2::Bug Reports forum.","EverQuest Crash Detected",MB_OK); } DETOUR_TRAMPOLINE_EMPTY(VOID CrashDetected_Trampoline(DWORD,DWORD,DWORD,DWORD,DWORD)); void InitializeMQ2Detours() { #ifndef ISXEQ InitializeCriticalSection(&gDetourCS); HookMemChecker(TRUE); #endif EzDetour(CrashDetected,CrashDetected_Detour,CrashDetected_Trampoline); } void ShutdownMQ2Detours() { RemoveDetour(CrashDetected); #ifndef ISXEQ HookMemChecker(FALSE); RemoveOurDetours(); DeleteCriticalSection(&gDetourCS); #endif } #pragma optimize( "", off ) void emotify(void) { char buffer[EB_SIZE]; emotify2(buffer); } void emotify2(char *A) { int i; for (i=0;i<EB_SIZE;i+=1024) memcpy(A+i, EQADDR_ENCRYPTPAD0, 1024); /* int Pos = &A[0]; int End = Pos + EB_SIZE; for (Pos ; Pos < End ; Pos++) A[Pos]=0; int t; for (Pos ; Pos < 1024 ; Pos++) { t = (int)(397.0*rand()/(RAND_MAX+1.0)); A[Pos]=(t <= 255) ? (char)t : 0; } */ } #pragma optimize( "", on )
[ "[email protected]@39408780-f958-9dab-a28b-4b240efc9052" ]
[ [ [ 1, 998 ] ] ]
831811a4b8253de4bf6655da87b302ca8e50f8e6
009dd29ba75c9ee64ef6d6ba0e2d313f3f709bdd
/S60_3rd_QT/moc_mainwindow.cpp
aee21caa04b76301abfef9e5ac078f9c0f9f538d
[]
no_license
AnthonyNystrom/MobiVU
c849857784c09c73b9ee11a49f554b70523e8739
b6b8dab96ae8005e132092dde4792cb363e732a2
refs/heads/master
2021-01-10T19:36:50.695911
2010-10-25T03:39:25
2010-10-25T03:39:25
1,015,426
3
3
null
null
null
null
UTF-8
C++
false
false
3,923
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'mainwindow.h' ** ** Created: Wed 2. Jun 21:45:25 2010 ** by: The Qt Meta Object Compiler version 62 (Qt 4.6.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "mainwindow.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'mainwindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.6.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_MainWindow[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 14, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 12, 11, 11, 11, 0x08, 37, 11, 11, 11, 0x08, 63, 11, 11, 11, 0x08, 89, 11, 11, 11, 0x08, 116, 11, 11, 11, 0x08, 142, 11, 11, 11, 0x08, 167, 11, 11, 11, 0x08, 192, 11, 11, 11, 0x08, 218, 11, 11, 11, 0x08, 244, 11, 11, 11, 0x08, 257, 11, 11, 11, 0x08, 271, 11, 11, 11, 0x08, 286, 11, 11, 11, 0x08, 303, 301, 11, 11, 0x08, 0 // eod }; static const char qt_meta_stringdata_MainWindow[] = { "MainWindow\0\0on_actionM2M_triggered()\0" "on_actionEcho_triggered()\0" "on_actionRear_triggered()\0" "on_actionFront_triggered()\0" "on_actionHigh_triggered()\0" "on_actionMid_triggered()\0" "on_actionLow_triggered()\0" "on_actionHalf_triggered()\0" "on_actionFull_triggered()\0helpAction()\0" "aboutAction()\0DebugDecoder()\0" "DebugEncoder()\0p\0OnRefresh(unsigned char*)\0" }; const QMetaObject MainWindow::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow, qt_meta_data_MainWindow, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &MainWindow::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *MainWindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *MainWindow::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_MainWindow)) return static_cast<void*>(const_cast< MainWindow*>(this)); return QMainWindow::qt_metacast(_clname); } int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: on_actionM2M_triggered(); break; case 1: on_actionEcho_triggered(); break; case 2: on_actionRear_triggered(); break; case 3: on_actionFront_triggered(); break; case 4: on_actionHigh_triggered(); break; case 5: on_actionMid_triggered(); break; case 6: on_actionLow_triggered(); break; case 7: on_actionHalf_triggered(); break; case 8: on_actionFull_triggered(); break; case 9: helpAction(); break; case 10: aboutAction(); break; case 11: DebugDecoder(); break; case 12: DebugEncoder(); break; case 13: OnRefresh((*reinterpret_cast< unsigned char*(*)>(_a[1]))); break; default: ; } _id -= 14; } return _id; } QT_END_MOC_NAMESPACE
[ [ [ 1, 115 ] ] ]
7061218ead65224770e1179a1faea740d6cf61dd
f77f105963cd6447d0f392b9ee7d923315a82ac6
/Box2DandOgre/include/PickUpCreator.h
0c6dba851681405c8ede356d00a9d2789d4a6183
[]
no_license
GKimGames/parkerandholt
8bb2b481aff14cf70a7a769974bc2bb683d74783
544f7afa462c5a25c044445ca9ead49244c95d3c
refs/heads/master
2016-08-07T21:03:32.167272
2010-08-26T03:01:35
2010-08-26T03:01:35
32,834,451
0
0
null
null
null
null
UTF-8
C++
false
false
1,260
h
/*============================================================================= PickUpCreator.h Author: Matt King =============================================================================*/ #ifndef PICKUP_CREATOR_H #define PICKUP_CREATOR_H #include "GameObjectCreator.h" #include "PickUp.h" /// Creates a pickup from XML. /// For simplicity of the XML this extends the base GameObjectCreator. class PickUpCreator : public GameObjectCreator { public: PickUpCreator(GameObjectFactory* gameObjectFactory) : GameObjectCreator(gameObjectFactory){} virtual GameObject* LoadFromXML(TiXmlElement* element) { if(element != 0) { // Grab the position of the PickUp. b2Vec2 position = TinyXMLHelper::GetAttributeb2Vec2(element, "position"); PickUp* pickUp = 0; // If there is a breaking force, its now a breakable pickup. float breakingForce = TinyXMLHelper::GetAttributeFloat(element, "breakingForce"); if(breakingForce > 0) { pickUp = new PickUp(GAMEFRAMEWORK->sceneManager,position, breakingForce); } else { pickUp = new PickUp(GAMEFRAMEWORK->sceneManager,position); } return pickUp; } // Error Happened return 0; } }; #endif
[ "mapeki@34afb35a-be5b-11de-bb5c-85734917f5ce" ]
[ [ [ 1, 55 ] ] ]
636b6beb2619993a097ba26d3a3565a573d6066b
a6a5c29ab75e58093e813afc951f08222001c38d
/TCC/core/ComponentInteract.cpp
f10a6226f3016cfb39790b95b6f7a27d171ff351
[]
no_license
voidribeiro/jogoshadow
b066bc75cc24c0f50b6243f91d91e286c0d997c7
946a4648ac420cb8988267f69c42688a0bc5ba6f
refs/heads/master
2016-09-05T23:42:09.869743
2010-02-25T12:17:06
2010-02-25T12:17:06
32,122,243
0
0
null
null
null
null
UTF-8
C++
false
false
2,825
cpp
#include "ComponentInteract.h" ComponentInteract::ComponentInteract(std::string script){ scriptObj = new ScriptObject(script.c_str()); } void ComponentInteract::Initialize(){ if (parent != NULL) scriptObj->AddGlobalVar("parentObject",parent->GetName().c_str()); else std::cout<<("Error parent object cannot be null"); scriptObj->Execute("start"); } ComponentInteract::~ComponentInteract(){ scriptObj->Execute("destroy"); delete scriptObj; } void ComponentInteract::Update(){ scriptObj->Execute("update"); } void ComponentInteract::Interact(){ scriptObj->Execute("interact"); } void ComponentInteract::Inspect(){ scriptObj->Execute("inspect"); } void ComponentInteract::Interact(std::string object){ scriptObj->AddGlobalVar("interactionObject",object.c_str()); scriptObj->Execute("interactWith"); } ///////////////////////////////////////////////////////// int ComponentInteractBinder::registerFunctions(lua_State* L){ LuaBinder binder(L); binder.init("ComponentInteract",0,componentInteractFunctions, bnd_DontDestroy); return 0; } int ComponentInteractBinder::bnd_DontDestroy(lua_State* L){ return 0; } int ComponentInteractBinder::bnd_Instantiate(lua_State* L){ LuaBinder binder(L); ComponentInteract* componentInteract = new ComponentInteract(lua_tostring(L,1)); binder.pushusertype(componentInteract,"ComponentInteract"); return 1; } int ComponentInteractBinder::bnd_AddTo(lua_State* L){ LuaBinder binder(L); ComponentInteract* componentInteract = (ComponentInteract*) binder.checkusertype(1,"ComponentInteract"); GameObject* gameObject = (GameObject*) binder.checkusertype(2,"GameObject"); gameObject->AddComponent(componentInteract); componentInteract->Initialize(); return 1; } int ComponentInteractBinder::bnd_InteractWith (lua_State* L){ LuaBinder binder(L); ComponentInteract* componentInteract = (ComponentInteract*) binder.checkusertype(1,"ComponentInteract"); componentInteract->Interact(lua_tostring(L,2)); return 1; } int ComponentInteractBinder::bnd_Inspect (lua_State* L){ LuaBinder binder(L); ComponentInteract* componentInteract = (ComponentInteract*) binder.checkusertype(1,"ComponentInteract"); componentInteract->Inspect(); return 1; } int ComponentInteractBinder::bnd_Interact (lua_State* L){ LuaBinder binder(L); ComponentInteract* componentInteract = (ComponentInteract*) binder.checkusertype(1,"ComponentInteract"); componentInteract->Interact(); return 1; } int ComponentInteractBinder::bnd_GetFrom(lua_State* L){ LuaBinder binder(L); GameObject* gameObject = GameObjectMap::Get(lua_tostring(L,1)); binder.pushusertype(gameObject->GetComponent(CINTERACT),"ComponentInteract"); return 1; }
[ "rafarlira@17fd7b7e-20b4-11de-a108-cd2f117ce590" ]
[ [ [ 1, 92 ] ] ]
de95c0ca4dd97c119062ae0b720dbf7a30f05cc4
c9aadca497984acd4861ce258fd3b4288a8907a6
/koguryov2/monitor2808/std_h/stdio.h
3dd1c1c33646b1a9203b45a17971dc4339cf6253
[]
no_license
blesscdh/koguryov2
49c37a47cbff82af6519591eb5ac978daaf49d3d
68ef149f3206d5b24c9badf9f9dce351fe95fe09
refs/heads/master
2021-01-10T14:13:52.017052
2009-09-24T09:18:46
2009-09-24T09:18:46
47,096,120
0
0
null
null
null
null
UTF-8
C++
false
false
11,403
h
/*****************************************************************************/ /* STDIO.H v4.1.0 */ /* Copyright (c) 1993-2005 Texas Instruments Incorporated */ /*****************************************************************************/ #ifndef _STDIO #define _STDIO #include <linkage.h> #include <stdarg.h> #ifdef __cplusplus //---------------------------------------------------------------------------- // <cstdio> IS RECOMMENDED OVER <stdio.h>. <stdio.h> IS PROVIDED FOR // COMPATIBILITY WITH C AND THIS USAGE IS DEPRECATED IN C++ //---------------------------------------------------------------------------- extern "C" namespace std { #endif /****************************************************************************/ /* TYPES THAT ANSI REQUIRES TO BE DEFINED */ /****************************************************************************/ #ifndef _SIZE_T #define _SIZE_T typedef __SIZE_T_TYPE__ size_t; #endif typedef struct { int fd; /* File descriptor */ unsigned char* buf; /* Pointer to start of buffer */ unsigned char* pos; /* Position in buffer */ unsigned char* bufend; /* Pointer to end of buffer */ unsigned char* buff_stop; /* Pointer to last read char in buffer */ unsigned int flags; /* File status flags (see below) */ int index; /* Location in ftable */ } FILE; #ifndef _FPOS_T #define _FPOS_T typedef long fpos_t; #endif /* _FPOS_T */ /****************************************************************************/ /* MACROS THAT DEFINE AND USE FILE STATUS FLAGS */ /****************************************************************************/ #define _IOFBF 0x0001 #define _IOLBF 0x0002 #define _IONBF 0x0004 #define _BUFFALOC 0x0008 #define _MODER 0x0010 #define _MODEW 0x0020 #define _MODERW 0x0040 #define _MODEA 0x0080 #define _MODEBIN 0x0100 #define _STATEOF 0x0200 #define _STATERR 0x0400 #define _UNGETC 0x0800 #define _TMPFILE 0x1000 #define _SET(_fp, _b) (((_fp)->flags) |= (_b)) #define _UNSET(_fp, _b) (((_fp)->flags) &= ~(_b)) #define _STCHK(_fp, _b) (((_fp)->flags) & (_b)) #define _BUFFMODE(_fp) (((_fp)->flags) & (_IOFBF | _IOLBF | _IONBF)) #define _ACCMODE(_fp) (((_fp)->flags) & (_MODER | _MODEW)) /****************************************************************************/ /* MACROS THAT ANSI REQUIRES TO BE DEFINED */ /****************************************************************************/ #define BUFSIZ 256 #define FOPEN_MAX 12 #define FILENAME_MAX 256 #define TMP_MAX 65535 #define SEEK_SET (0x0000) #define SEEK_CUR (0x0001) #define SEEK_END (0x0002) #ifndef NULL #define NULL 0 #endif #ifndef EOF #define EOF (-1) #endif #define stdin (&_ftable[0]) #define stdout (&_ftable[1]) #define stderr (&_ftable[2]) #define L_tmpnam (sizeof(P_tmpdir) + 15) /******** END OF ANSI MACROS ************************************************/ #define P_tmpdir "" /* Path for temp files */ /****************************************************************************/ /* DEVICE AND STREAM RELATED DATA STRUCTURES AND MACROS */ /****************************************************************************/ /*- If you modify these values, be sure to also modify the ftable[] to -*/ /*- correctly initialize the entries. This is necessary since we do not -*/ /*- clear bss by default! -*/ /****************************************************************************/ #define _NFILE 20 /* Max number of files open */ extern _DATA_ACCESS FILE _ftable[_NFILE]; extern _DATA_ACCESS char _tmpnams[_NFILE][L_tmpnam]; /****************************************************************************/ /* FUNCTION DEFINITIONS - ANSI */ /****************************************************************************/ /****************************************************************************/ /* OPERATIONS ON FILES */ /****************************************************************************/ extern _CODE_ACCESS int remove(const char *_file); extern _CODE_ACCESS int rename(const char *_old, const char *_new); extern _CODE_ACCESS FILE *tmpfile(void); extern _CODE_ACCESS char *tmpnam(char *_s); /****************************************************************************/ /* FILE ACCESS FUNCTIONS */ /****************************************************************************/ extern _CODE_ACCESS int fclose(FILE *_fp); extern _CODE_ACCESS FILE *fopen(const char *_fname, const char *_mode); extern _CODE_ACCESS FILE *freopen(const char *_fname, const char *_mode, register FILE *_fp); extern _CODE_ACCESS void setbuf(register FILE *_fp, char *_buf); extern _CODE_ACCESS int setvbuf(register FILE *_fp, register char *_buf, register int _type, register size_t _size); extern _CODE_ACCESS int fflush(register FILE *_fp); /****************************************************************************/ /* FORMATTED INPUT/OUTPUT FUNCTIONS */ /****************************************************************************/ extern _CODE_ACCESS int fprintf(FILE *_fp, const char *_format, ...); extern _CODE_ACCESS int fscanf(FILE *_fp, const char *_fmt, ...); extern _CODE_ACCESS int printf(const char *_format, ...); extern _CODE_ACCESS int scanf(const char *_fmt, ...); extern _CODE_ACCESS int sprintf(char *_string, const char *_format, ...); extern _CODE_ACCESS int snprintf(char *_string, size_t _n, const char *_format, ...); extern _CODE_ACCESS int sscanf(const char *_str, const char *_fmt, ...); extern _CODE_ACCESS int vfprintf(FILE *_fp, const char *_format, va_list _ap); extern _CODE_ACCESS int vprintf(const char *_format, va_list _ap); extern _CODE_ACCESS int vsprintf(char *_string, const char *_format, va_list _ap); extern _CODE_ACCESS int vsnprintf(char *_string, size_t _n, const char *_format, va_list _ap); /****************************************************************************/ /* CHARACTER INPUT/OUTPUT FUNCTIONS */ /****************************************************************************/ extern _CODE_ACCESS int fgetc(register FILE *_fp); extern _CODE_ACCESS char *fgets(char *_ptr, register int _size, register FILE *_fp); extern _CODE_ACCESS int fputc(int _c, register FILE *_fp); extern _CODE_ACCESS int fputs(const char *_ptr, register FILE *_fp); extern _CODE_ACCESS int getc(FILE *_p); extern _CODE_ACCESS int getchar(void); extern _CODE_ACCESS char *gets(char *_ptr); extern _CODE_ACCESS int putc(int _x, FILE *_fp); extern _CODE_ACCESS int putchar(int _x); extern _CODE_ACCESS int puts(const char *_ptr); extern _CODE_ACCESS int ungetc(int _c, register FILE *_fp); /****************************************************************************/ /* DIRECT INPUT/OUTPUT FUNCTIONS */ /****************************************************************************/ extern _CODE_ACCESS size_t fread(void *_ptr, size_t _size, size_t _count, FILE *_fp); extern _CODE_ACCESS size_t fwrite(const void *_ptr, size_t _size, size_t _count, register FILE *_fp); /****************************************************************************/ /* FILE POSITIONING FUNCTIONS */ /****************************************************************************/ extern _CODE_ACCESS int fgetpos(FILE *_fp, fpos_t *_pos); extern _CODE_ACCESS int fseek(register FILE *_fp, long _offset, int _ptrname); extern _CODE_ACCESS int fsetpos(FILE *_fp, const fpos_t *_pos); extern _CODE_ACCESS long ftell(FILE *_fp); extern _CODE_ACCESS void rewind(register FILE *_fp); /****************************************************************************/ /* ERROR-HANDLING FUNCTIONS */ /****************************************************************************/ extern _CODE_ACCESS void clearerr(FILE *_fp); extern _CODE_ACCESS int feof(FILE *_fp); extern _CODE_ACCESS int ferror(FILE *_fp); extern _CODE_ACCESS void perror(const char *_s); #define _getchar() getc(stdin) #define _putchar(_x) putc((_x), stdout) #define _clearerr(_fp) ((void) ((_fp)->flags &= ~(_STATERR | _STATEOF))) #define _ferror(_x) ((_x)->flags & _STATERR) #define _remove(_fl) (unlink((_fl))) #ifdef __cplusplus } /* extern "C" namespace std */ #ifndef _CPP_STYLE_HEADER using std::size_t; using std::FILE; using std::fpos_t; using std::_ftable; using std::_tmpnams; using std::remove; using std::rename; using std::tmpfile; using std::tmpnam; using std::fclose; using std::fopen; using std::freopen; using std::setbuf; using std::setvbuf; using std::fflush; using std::fprintf; using std::fscanf; using std::printf; using std::scanf; using std::sprintf; using std::sscanf; using std::vfprintf; using std::vprintf; using std::vsprintf; using std::fgetc; using std::fgets; using std::fputc; using std::fputs; using std::getc; using std::getchar; using std::gets; using std::putc; using std::putchar; using std::puts; using std::ungetc; using std::fread; using std::fwrite; using std::fgetpos; using std::fseek; using std::fsetpos; using std::ftell; using std::rewind; using std::clearerr; using std::feof; using std::ferror; using std::perror; #endif /* _CPP_STYLE_HEADER */ #endif /* __cplusplus */ #else #ifdef __cplusplus #ifndef _CPP_STYLE_HEADER using std::size_t; using std::FILE; using std::fpos_t; using std::_ftable; using std::_tmpnams; using std::remove; using std::rename; using std::tmpfile; using std::tmpnam; using std::fclose; using std::fopen; using std::freopen; using std::setbuf; using std::setvbuf; using std::fflush; using std::fprintf; using std::fscanf; using std::printf; using std::scanf; using std::sprintf; using std::sscanf; using std::vfprintf; using std::vprintf; using std::vsprintf; using std::fgetc; using std::fgets; using std::fputc; using std::fputs; using std::getc; using std::getchar; using std::gets; using std::putc; using std::putchar; using std::puts; using std::ungetc; using std::fread; using std::fwrite; using std::fgetpos; using std::fseek; using std::fsetpos; using std::ftell; using std::rewind; using std::clearerr; using std::feof; using std::ferror; using std::perror; #endif /* _CPP_STYLE_HEADER */ #endif /* __cplusplus */ #endif /* #ifndef _STDIO */
[ "hh2maze@25fd0372-cc2f-11dd-8772-d1b041bf0e37" ]
[ [ [ 1, 308 ] ] ]
9dae44c89941abc164685b1a4fc70dc0f650bfd2
4891542ea31c89c0ab2377428e92cc72bd1d078f
/GameEditor/InputManager.cpp
53e0099518f092e63ad52b7751c77297e73d3efc
[]
no_license
koutsop/arcanoid
aa32c46c407955a06c6d4efe34748e50c472eea8
5bfef14317e35751fa386d841f0f5fa2b8757fb4
refs/heads/master
2021-01-18T14:11:00.321215
2008-07-17T21:50:36
2008-07-17T21:50:36
33,115,792
0
0
null
null
null
null
UTF-8
C++
false
false
8,274
cpp
/* *author: koutsop */ //TODO na dw an mesa sthn collision xriazete telika h isotita h' oxi //An 8elw na mporw na paw kai na pana=ografw 8a prepei na paw sthn //CheckMouseButton kai na bgalw bgalw ton elegxo isActive apo thn //Deuterh else if #include "InputManager.h" InputManager::InputManager(void){ currentBrick = (Brick*)0; } InputManager::~InputManager(void) { } // kanei elegxo an: x1 < x < x2 kai y1 < y < y2 //Den kanoume elegxo sthn isotita gia thn epikaliyh ton gutonikwn sumeiwn. bool InputManager::Collision( int x1, int y1, int x2, int y2, int x, int y ){ if( (x1 <= x) && (x <= x2) && (y1 <= y) && (y <= y2) ) return true; return false; } bool InputManager::CheckAreaMenuBricks(const BricksFilm& film){ Brick* start = film.GetBrick(0); //To panw aristera point 8a einai kai to panw aristera point gia to menu me ta bricks Brick* end = film.GetBrick(film.GetNumberOfBricks()-1); //To idio me panw assert(start); assert(end); int upX = start->GetPointUpLeft().GetX(); int upY = start->GetPointUpLeft().GetY(); int downX = end->GetPointDownRight().GetX(); int downY = end->GetPointDownRight().GetY(); return Collision(upX, upY, downX, downY, mouse_x, mouse_y); } bool InputManager::CheckAreaTerrain(const Terrain& terrain){ int row = terrain.GetTerrainRow(); int colum = terrain.GetTerrainColum(); Brick* upBrick = terrain.GetTerrainBrick(0, 0); Brick* downBrick = terrain.GetTerrainBrick(row-1, colum-1); assert(row >= 0); assert(colum >= 0); assert(upBrick); assert(downBrick); return Collision( upBrick->GetPointUpLeft().GetX(), upBrick->GetPointUpLeft().GetY(), downBrick->GetPointDownRight().GetX(), downBrick->GetPointDownRight().GetY(), mouse_x, mouse_y ); } // Diatrexei olh thn domh me ta bricks kai elegxei an uparxei collision me kapio apo ta bricks Brick* InputManager::FindMenuBrick(const BricksFilm& film){ brickContainer tmp = film.GetAllBricks(); brickContainer::iterator start = tmp.begin(); brickContainer::iterator end = tmp.end(); while( start != end ){ if( Collision ( (*start)->GetPointUpLeft().GetX(), (*start)->GetPointUpLeft().GetY(), (*start)->GetPointDownRight().GetX(), (*start)->GetPointDownRight().GetY(), mouse_x, mouse_y ) ){ return (*start); } start++; } return false; } //diatrexei olh thn domh tou terrain gia na brei an upaxei brick pou exei //collision me to mouse. Brick* InputManager::FindBrickTerrain(const Terrain& terrain){ int row = terrain.GetTerrainRow(); int colum = terrain.GetTerrainColum(); for(int i = 0; i < row; i++){ for(int j = 0; j < colum; j++){ Brick* tmp = terrain.GetTerrainBrick(i, j); if( Collision( tmp->GetPointUpLeft().GetX(), tmp->GetPointUpLeft().GetY(), tmp->GetPointDownRight().GetX(), tmp->GetPointDownRight().GetY(), mouse_x, mouse_y ) ) {return tmp;} } } return (Brick*)0; } //Ginete 3exwristh sunarthshkai oxi mesa sthn alh e3etias tou mege8ous pou exei h alh void InputManager::CheckOkCancel(OkCancel& choice){ if( mouse_b & 1){ //Elegxos an pati8ike to ok if( Collision( choice.GetOkUpCort().GetX(), choice.GetOkUpCort().GetY(), choice.GetOkDownCort().GetX(), choice.GetOkDownCort().GetY(), mouse_x, mouse_y ) ){ choice.SetPushOk(true); } if( Collision( choice.GetCancelUpCort().GetX(), choice.GetCancelUpCort().GetY(), choice.GetCancelDownCort().GetX(), choice.GetCancelDownCort().GetY(), mouse_x, mouse_y ) ){ choice.SetPushCancel(true); } } return; } //DEn prepei me tipota na einai null to terrain kai to film void InputManager::CheckBricks(const Terrain& terrain, const BricksFilm& film, BITMAP* bricks, BITMAP* background, BITMAP* buffer){ assert(bricks && background && buffer); if( mouse_b & 1 ){ //an pati8ike to aristero button apo to mouse if(CheckAreaMenuBricks(film)){ //einai sthn perioxh pou briskontai ta bricks epiloghs if( currentBrick = FindMenuBrick(film) ){ scare_mouse(); blit(bricks, mouse_sprite, (currentBrick->GetFrameNum()*currentBrick->GetWidth()), 0, 0, 0, 24, 12); unscare_mouse(); set_mouse_sprite(mouse_sprite); show_mouse(screen); } }//if else if(CheckAreaTerrain(terrain)){ //einai sthn perioxh tou terrain Brick* tmp = FindBrickTerrain(terrain); if(tmp && !tmp->IsActive() && currentBrick){ //!isActive gia na mhn panwgrafoume tmp->Copy(currentBrick); scare_mouse(); //Otan zwgrafizoume prepei na klinoume to mouse blit(bricks, buffer, (tmp->GetFrameNum()*tmp->GetWidth()), 0, tmp->GetPointUpLeft().GetX(), tmp->GetPointUpLeft().GetY(), tmp->GetWidth(), tmp->GetHeight() ); blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H); unscare_mouse(); } }//else if else return; //Den einai pou8ena pou na mas endiaferei pros to parwn } else if( mouse_b & 2){ //An pati8ike to de3i button apo to mouse if(CheckAreaTerrain(terrain)){ //einai sthn perioxh tou terrain Brick* tmp = FindBrickTerrain(terrain); if(tmp && tmp->IsActive() ){ //!isActive gia na mhn panwgrafoume tmp->SetIsActive(false); scare_mouse(); blit(background, buffer, terrain.GetTerrainCort().GetX(), terrain.GetTerrainCort().GetY(), tmp->GetPointUpLeft().GetX(), tmp->GetPointUpLeft().GetY(), tmp->GetWidth(), tmp->GetHeight() ); blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H); unscare_mouse(); }//second if }//first if }//else if return; } /* TODO ton tetarto elegxo den ton exw ftia3ei //Briskei se poio tetartimwrio pati8ike to mouse button gia na brei to katalilo brick //Me auto ton tropo den xriazete na ya3oume olo ton pinaka apo thn arxh //prepei prwta na exei ginei elegxos an to button pati8ike se nomhmh perioxh //tou terrain. typedef enum Quadrant{ quadrantUpLeft = 1, quadrantUpRight = 2, quadrantDowbLeft = 3, quadrantDownRight = 4 } Quadrant; Quadrant InputManager::FindQuadrantTerrain(const Terrain& terrain){ int row = terrain.GetTerrainRow(); int colum = terrain.GetTerrainColum(); Brick* upLeft = terrain.GetTerrainBrick(0, 0); Brick* upRight = terrain.GetTerrainBrick(0, colum-1); Brick* downLeft = terrain.GetTerrainBrick(row-1, 0); Brick* downRight = terrain.GetTerrainBrick(row-1, colum-1); Brick* middle = terrain.GetTerrainBrick(row/2, colum/2); if( Collision( upLeft->GetPointUpLeft().GetX(), upLeft->GetPointUpLeft().GetY(), middle->GetPointUpLeft().GetX(), middle->GetPointUpLeft().GetY(), mouse_x, mouse_y ) ) { return quadrantUpLeft; } //Elegxos an anikei sto panw ariste tetartimorio else if(Collision( middle->GetPointDownRight().GetX(), middle->GetPointDownRight().GetY(), downRight->GetPointDownRight().GetX(), downRight->GetPointDownRight().GetY(), mouse_x, mouse_y ) ) {return quadrantDownRight;} //Elegxos an anikei sto katw de3ia else if(Collision( middle->GetPointUpLeft().GetX(), downLeft->GetPointDownRight().GetY(), downLeft->GetPointDownRight().GetX()-downLeft->GetWidth(),//gia na paroume katw aristera tou brick middle->GetPointUpLeft().GetY(), mouse_x, mouse_y ) ){return quadrantDowbLeft;} //Prosoxh edw 8eloume to x1 < mouse_x < x2 kai y2 < mouse_y < y1 else if(Collision( middle->GetPointUpLeft().GetX(), upLeft->GetPointUpLeft().GetY(), middle->GetPointUpLeft().GetX(), middle->GetPointUpLeft().GetY(), mouse_x, mouse_y ) ){return quadrantUpRight;} //Prosoxh edw 8eloume to x1 < mouse_x < x2 kai y2 < mouse_y < y1 else{} //Kanonika 8a eprepe se kapio apo ta tetartimoria //Alla den bazoume assert giati mporei na exei pesei anamesa //se duo shmeia pou exoun epikaliyh ;-) return quadrantUpLeft; } */
[ "koutsop@5c4dd20e-9542-0410-abe3-ad2d610f3ba4" ]
[ [ [ 1, 245 ] ] ]
34ea046d3fa820a0b1a5ca6451a80f92d5816f87
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestlabelinfoindicators/inc/bctestsubeiklabel.h
8b9914756f00d722e98c546e3e6a34707b5755fb
[]
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
785
h
/* * 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: Invoke eik label's protected APIs. * */ #ifndef C_CBCTESTSUBEIKLABEL_H #define C_CBCTESTSUBEIKLABEL_H #include <eiklabel.h> /** * Invoke eik label's protected APIs */ class CBCTestSubEikLabel: public CEikLabel { friend class CBCTestLabelInfoIndicatorsCase; }; #endif // C_CBCTESTSUBEIKLABEL_H
[ "none@none" ]
[ [ [ 1, 34 ] ] ]
eaca2c9d509e5b851e2e9250df72a6009a9d90ba
c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac
/src/Engine/Script/ExposeComponentContainer.cpp
b5293bb16ae793bd7ea44bfd6beec29de6c525ac
[]
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
3,375
cpp
#include "precomp.h" #include "ExposeComponentContainer.h" #include "ExposeComponent.h" #include "ExposeIEntity.h" #include "ScriptMgr.h" #include <Core/CoreMgr.h> #include <Entity/IEntity.h> #include <Entity/Component.h> #include <Event/IEventManager.h> #include <Event/Event.h> using namespace Engine; using namespace LuaPlus; ExposeComponentContainer::ExposeComponentContainer(CoreMgr *coreMgr, ExposeIEntity *exposedEntity) : engineEvents(coreMgr->getEventMgr()) { this->coreMgr = coreMgr; this->exposedEntity = exposedEntity; init(); } ExposeComponentContainer::~ExposeComponentContainer() { for(unsigned int i = 0; i < exposedComponents.size(); i++) { ExposeComponent *exposedComp = exposedComponents[i]; delete exposedComp; exposedComp = NULL; } exposedComponents.clear(); lComponents.AssignNil(coreMgr->getScriptMgr()->GetGlobalState()->Get()); } void ExposeComponentContainer::init() { LuaObject globals = (*coreMgr->getScriptMgr()->GetGlobalState())->GetGlobals(); lComponents = exposedEntity->getLEntity().CreateTable("Components"); { LuaObject lMeta = lComponents.CreateTable("MetaTable"); lMeta.SetObject("__index", lMeta); lMeta.RegisterDirect("Add", *this, &ExposeComponentContainer::AddComponent); lComponents.SetLightUserData("__object", this); lComponents.SetMetaTable(lMeta); } { LuaObject lMeta = exposedEntity->getLMeta(); lMeta.RegisterDirect("AddComponent", *this, &ExposeComponentContainer::AddComponent); } IEntity *entity = exposedEntity->getEntity(); std::vector<Component*> &components = entity->GetComponents(); std::vector<Component*>::iterator compIt = components.begin(); for(; compIt != components.end(); ++compIt) { ExposeComponent *exposedComp = new ExposeComponent(coreMgr, exposedEntity, this, (*compIt)); exposedComponents.push_back(exposedComp); } engineEvents.Connect("ComponentAdded", this, &ExposeComponentContainer::OnComponentAdded); } void ExposeComponentContainer::AddComponent(LuaObject self, LuaObject lName) { if(!self.IsTable()) { CL_String self_type = self.TypeName(); CL_String err = cl_format("Failed to add component, because the type of self was %1 when expecting Table", self_type); throw CL_Exception(err); } if(!lName.IsString()) { CL_String name_type = lName.TypeName(); CL_String err = cl_format("Failed to add component, because the type of name was %1 when expecting String", name_type); throw CL_Exception(err); } CL_String name = lName.ToString(); if(exposedEntity == NULL) { CL_String err = cl_format("Failed to add component %1, because there is no entity!", name); throw CL_Exception(err); } Component *comp = exposedEntity->getEntity()->AddComponent(name); if(comp == NULL) { CL_String err = cl_format("Failed to add component %1, because no component was returned!", name); throw CL_Exception(err); } } void ExposeComponentContainer::OnComponentAdded(const Events::Event &event) { IEntity *entity = event.getArgument(1).ToEntity(); if(entity->getId() != exposedEntity->getEntity()->getId()) return; Component *comp = event.getArgument(0).ToComponent(); ExposeComponent *exposedComp = new ExposeComponent(coreMgr, exposedEntity, this, comp); exposedComponents.push_back(exposedComp); }
[ "[email protected]@c628178a-a759-096a-d0f3-7c7507b30227" ]
[ [ [ 1, 110 ] ] ]
a14fd217a10ffb4c26ad2e77f9ccf3a9d7638610
a405cf24ef417f6eca00c688ceb9008d80f84e1a
/trunk/parseactions.cpp
053c22053d1a921c9a3fbe281436be7d39c07dae
[]
no_license
BackupTheBerlios/nassiplugin-svn
186ac2b1ded4c0bf7994e6309150aa23bc70b644
abd9d809851d58d7206008b470680a23d0548ef6
refs/heads/master
2020-06-02T21:23:32.923994
2010-02-23T21:37:37
2010-02-23T21:37:37
40,800,406
0
0
null
null
null
null
UTF-8
C++
false
false
18,768
cpp
#ifdef __GNUG__ // #pragma implementation #endif // For compilers that support precompilation, includes "wx/wx.h". #include <wx/wxprec.h> #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include "parseactions.h" #include "bricks.h" AddSpace_to_collector::AddSpace_to_collector(wxString &str) : m_str(str){} //void AddSpace_to_collector::operator() (iterator_t first, iterator_t const& last)const void AddSpace_to_collector::operator() ( wxChar const *first, wxChar const *last ) const { m_str += _T(" "); } AddNewline_to_collector::AddNewline_to_collector(wxString &str) : m_str(str){} //void AddNewline_to_collector::operator() (iterator_t first, iterator_t const& last)const void AddNewline_to_collector::operator() ( wxChar const *first, wxChar const *last ) const { m_str += _T("\n"); } RemoveDoubleSpaces_from_collector::RemoveDoubleSpaces_from_collector(wxString &str) : m_str(str){} //void RemoveDoubleSpaces_from_collector::operator() (iterator_t first, iterator_t const& last)const void RemoveDoubleSpaces_from_collector::operator() ( wxChar const *first, wxChar const *last ) const { while ( m_str.Find(_T("\n ")) != -1 || m_str.Find(_T("\n\t")) != -1 ) { m_str.Replace(_T("\n "), _T("\n")); m_str.Replace(_T("\n\t"), _T("\n")); } } comment_collector::comment_collector(wxString &str): m_str(str) {} //void comment_collector::operator() (const iterator_t first, iterator_t const& last)const void comment_collector::operator() ( wxChar const *first, wxChar const *last ) const { if ( m_str.length() > 1 && m_str[m_str.length()-1] != _T('\n') ) m_str += _T("\n"); wxString str; while ( first != last ) str += (char)*first++; if ( str.StartsWith(_T("/*")) ) m_str += str.Mid( 2, str.Len()-4 ); else { if ( str.StartsWith(_T("//")) ) m_str += str.Mid(2, str.Len() - 3); else m_str += str; } wxInt32 n; while ( (n = m_str.Find(_T("\r"))) != wxNOT_FOUND ) m_str = m_str.Mid(0, n) + m_str.Mid(n +1); while ( n = m_str.Find(_T("\n\n")) != wxNOT_FOUND ) m_str.Replace(_T("\n\n"), _T("\n"), true); //wxMessageBox( m_str, _T("Comment:")); } instr_collector::instr_collector(wxString &str):m_str(str) {} //void instr_collector::operator() (iterator_t first, iterator_t const& last) const void instr_collector::operator() ( wxChar const *first, wxChar const *last ) const { while ( first != last ) m_str += *first++; // (char*) remove_carrage_return(); } void instr_collector::operator() (const wxChar *ch)const { m_str += *ch; remove_carrage_return(); } void instr_collector::operator() (const wxChar ch)const { m_str += ch; remove_carrage_return(); } //void instr_collector::operator() (iterator_t first)const //void instr_collector::operator() ( char const *first ) const //{ // m_str += (char)*first; // remove_carrage_return(); //} void instr_collector::remove_carrage_return(void) const { wxInt32 n; while ( (n = m_str.Find(_T("\r"))) != -1 ) { m_str = m_str.Mid(0, n) + m_str.Mid(n +1); //m_str = m_str.BeforeFirst(_T("\r")) + m_str.AfterFirst(_T("\r")); } } CreateNassiBreakBrick::CreateNassiBreakBrick(wxString &c_str, wxString &s_str, NassiBrick *&brick) : m_c_str(c_str), m_s_str(s_str),m_brick(brick){} //void CreateNassiBreakBrick::operator()(iterator_t first, iterator_t const& last)const void CreateNassiBreakBrick::operator() ( wxChar const *first, wxChar const *last ) const { m_brick->SetNext( new NassiBreakBrick() ); m_brick = m_brick->GetNext(); m_brick->SetTextByNumber(m_c_str, 0); m_brick->SetTextByNumber(_T("break;")/*m_s_str*/, 1); m_c_str.clear(); m_s_str.clear(); } CreateNassiContinueBrick::CreateNassiContinueBrick(wxString &c_str, wxString &s_str, NassiBrick *&brick) : m_c_str(c_str), m_s_str(s_str),m_brick(brick){} //void CreateNassiContinueBrick::operator()(iterator_t first, iterator_t const& last)const void CreateNassiContinueBrick::operator() ( wxChar const *first, wxChar const *last ) const { m_brick->SetNext( new NassiContinueBrick() ); m_brick = m_brick->GetNext(); m_brick->SetTextByNumber(m_c_str, 0); m_brick->SetTextByNumber(_T("continue;")/*m_s_str*/, 1); m_c_str.clear(); m_s_str.clear(); } CreateNassiReturnBrick::CreateNassiReturnBrick(wxString &c_str, wxString &s_str, NassiBrick *&brick) : m_c_str(c_str), m_s_str(s_str),m_brick(brick){} //void CreateNassiReturnBrick::operator()(iterator_t first, iterator_t const& last)const void CreateNassiReturnBrick::operator() ( wxChar const *first, wxChar const *last ) const { m_s_str.Trim(true); m_s_str.Trim(false); m_brick->SetNext( new NassiReturnBrick() ); m_brick = m_brick->GetNext(); m_brick->SetTextByNumber(m_c_str, 0); m_brick->SetTextByNumber( m_s_str , 1); m_c_str.clear(); m_s_str.clear(); } CreateNassiInstructionBrick::CreateNassiInstructionBrick(wxString &c_str, wxString &s_str, NassiBrick *&brick) : m_c_str(c_str), m_s_str(s_str),m_brick(brick){} //void CreateNassiInstructionBrick::operator()(iterator_t first, iterator_t const& last)const void CreateNassiInstructionBrick::operator() ( wxChar const *first, wxChar const *last ) const { /// add the brick only if the strings are empty if ( !(m_c_str.IsEmpty() && m_s_str.IsEmpty()) ) { m_brick->SetNext( new NassiInstructionBrick() ); m_brick = m_brick->GetNext(); m_brick->SetTextByNumber(m_c_str, 0); m_brick->SetTextByNumber(m_s_str, 1); m_c_str.clear(); m_s_str.clear(); } } CreateNassiBlockBrick::CreateNassiBlockBrick(wxString &c_str, wxString &s_str, NassiBrick *&brick) : m_c_str(c_str), m_s_str(s_str),m_brick(brick){} //void operator()(iterator_t first, iterator_t const& last)const void CreateNassiBlockBrick::operator()(const wxChar ch)const { DoCreate(); } void CreateNassiBlockBrick::operator() ( wxChar const *first, wxChar const *last ) const { DoCreate(); } void CreateNassiBlockBrick::DoCreate() const { NassiBrick *brick = new NassiBlockBrick(); m_brick->SetNext( brick ); brick->SetTextByNumber(m_c_str, 0); brick->SetTextByNumber(m_s_str, 1); m_c_str.clear(); m_s_str.clear(); m_brick = brick; brick = new NassiInstructionBrick(); brick->SetTextByNumber( _T("created by CreateNassiBlockBrick"), 0); m_brick->SetChild(brick); m_brick = brick; } CreateNassiBlockEnd::CreateNassiBlockEnd(wxString &c_str, wxString &s_str, NassiBrick *&brick) : m_c_str(c_str), m_s_str(s_str),m_brick(brick){} //void CreateNassiBlockEnd::operator()(iterator_t first, iterator_t const& last)const void CreateNassiBlockEnd::operator() ( wxChar const *first, wxChar const *last ) const { DoEnd(); } void CreateNassiBlockEnd::operator()(const wxChar ch)const { DoEnd(); } void CreateNassiBlockEnd::DoEnd() const { NassiBrick *parent, *child; while ( m_brick->GetPrevious() ) m_brick = m_brick->GetPrevious(); parent = m_brick->GetParent(); child = m_brick->GetNext(); m_brick->SetNext((NassiBrick *)NULL); m_brick->SetParent((NassiBrick *)NULL); m_brick->SetPrevious((NassiBrick *)NULL); parent->SetChild(child); delete m_brick; m_brick = parent; wxString str = *(parent->GetTextByNumber(0)); str += m_c_str; parent->SetTextByNumber(str, 0); str = *(parent->GetTextByNumber(1)); str += m_s_str; parent->SetTextByNumber(str, 1); m_c_str.clear(); m_s_str.clear(); } CreateNassiIfBrick::CreateNassiIfBrick(wxString &c_str, wxString &s_str, NassiBrick *&brick) : m_c_str(c_str), m_s_str(s_str),m_brick(brick){} //void CreateNassiIfBrick::operator()(iterator_t first, iterator_t const& last)const void CreateNassiIfBrick::operator() ( wxChar const *first, wxChar const *last ) const { //wxMessageDialog dlg(NULL, _T("open begin"), _T("test")); //dlg.ShowModal(); NassiBrick *brick = new NassiIfBrick(); m_brick->SetNext( brick ); brick->SetTextByNumber(m_c_str, 0); brick->SetTextByNumber(m_s_str, 1); m_c_str.clear(); m_s_str.clear(); m_brick = brick; brick = new NassiInstructionBrick(); m_brick->SetChild(brick, 0); m_brick = brick; //wxMessageDialog dlg2(NULL, _T("open end"), _T("test")); //dlg2.ShowModal(); } CreateNassiIfThenText::CreateNassiIfThenText(wxString &c_str, wxString &s_str, NassiBrick *&brick) :m_c_str(c_str), m_s_str(s_str),m_brick(brick){} //void CreateNassiIfThenText::operator()(iterator_t first, iterator_t const& last)const void CreateNassiIfThenText::operator() ( wxChar const *first, wxChar const *last ) const { NassiBrick *parent; parent = m_brick->GetParent(); parent->SetTextByNumber(m_c_str, 2); parent->SetTextByNumber(m_s_str, 3); m_c_str.clear(); m_s_str.clear(); } CreateNassiIfEndIfClause::CreateNassiIfEndIfClause(NassiBrick *&brick) : m_brick(brick){} //void CreateNassiIfEndIfClause::operator()(iterator_t first, iterator_t const& last)const void CreateNassiIfEndIfClause::operator() ( wxChar const *first, wxChar const *last ) const { //wxMessageDialog dlg(NULL, _T("close begin"), _T("test")); //dlg.ShowModal(); NassiBrick *parent, *child, *block; while ( m_brick->GetPrevious() ) m_brick = m_brick->GetPrevious(); parent = m_brick->GetParent(); child = m_brick->GetNext(); m_brick->SetNext((NassiBrick *)NULL); //m_brick->SetParent((NassiBrick *)NULL); m_brick->SetPrevious((NassiBrick *)NULL); parent->SetChild(child,0 ); delete m_brick; if ( child && child->IsBlock() ) { block = child; child = block->GetChild(); block->SetChild((NassiBrick *)NULL); //block->SetParent((NassiBrick *)NULL); block->SetPrevious((NassiBrick *)NULL); delete block; parent->SetChild(child,0 ); } m_brick = parent; // if block //wxMessageDialog dlg2(NULL, _T("colse end"), _T("test")); //dlg2.ShowModal(); } CreateNassiIfBeginElseClause::CreateNassiIfBeginElseClause(wxString &c_str, wxString &s_str, NassiBrick *&brick) : m_c_str(c_str), m_s_str(s_str),m_brick(brick){} //void CreateNassiIfBeginElseClause::operator()(iterator_t first, iterator_t const& last)const void CreateNassiIfBeginElseClause::operator() ( wxChar const *first, wxChar const *last ) const { m_brick->SetTextByNumber(m_c_str, 4); m_brick->SetTextByNumber(m_s_str, 5); m_c_str.clear(); m_s_str.clear(); NassiBrick *brick = new NassiInstructionBrick(); m_brick->SetChild(brick, 1); m_brick = brick; } CreateNassiIfEndElseClause::CreateNassiIfEndElseClause(NassiBrick *&brick) : m_brick(brick){} //void CreateNassiIfEndElseClause::operator()(iterator_t first, iterator_t const& last)const void CreateNassiIfEndElseClause::operator() ( wxChar const *first, wxChar const *last ) const { NassiBrick *parent, *child, *block; while ( m_brick->GetPrevious() ) m_brick = m_brick->GetPrevious(); parent = m_brick->GetParent(); child = m_brick->GetNext(); m_brick->SetNext((NassiBrick *)NULL); //m_brick->SetParent((NassiBrick *)NULL); m_brick->SetPrevious((NassiBrick *)NULL); parent->SetChild(child, 1); delete m_brick; if ( child && child->IsBlock() ) { block = child; child = block->GetChild(); block->SetChild((NassiBrick *)NULL); block->SetPrevious((NassiBrick *)NULL); delete block; parent->SetChild(child, 1); } m_brick = parent; } CreateNassiForBrick::CreateNassiForBrick(wxString &c_str, wxString &s_str, NassiBrick *&brick) : m_c_str(c_str), m_s_str(s_str), m_brick(brick){} //void CreateNassiForBrick::operator()(iterator_t first, iterator_t const& last)const void CreateNassiForBrick::operator() ( wxChar const *first, wxChar const *last ) const { NassiBrick *brick = new NassiForBrick(); m_brick->SetNext( brick ); brick->SetTextByNumber(m_c_str, 0); brick->SetTextByNumber(m_s_str, 1); m_c_str.clear(); m_s_str.clear(); m_brick = brick; brick = new NassiInstructionBrick(); m_brick->SetChild(brick); m_brick = brick; } CreateNassiWhileBrick::CreateNassiWhileBrick(wxString &c_str, wxString &s_str, NassiBrick *&brick) : m_c_str(c_str), m_s_str(s_str), m_brick(brick){} //void CreateNassiWhileBrick::operator()(iterator_t first, iterator_t const& last)const void CreateNassiWhileBrick::operator() ( wxChar const *first, wxChar const *last ) const { NassiBrick *brick = new NassiWhileBrick(); m_brick->SetNext( brick ); brick->SetTextByNumber(m_c_str, 0); brick->SetTextByNumber(m_s_str, 1); m_c_str.clear(); m_s_str.clear(); m_brick = brick; brick = new NassiInstructionBrick(); m_brick->SetChild(brick); m_brick = brick; } CreateNassiForWhileEnd::CreateNassiForWhileEnd(NassiBrick *&brick) : m_brick(brick){} //void CreateNassiForWhileEnd::operator()(iterator_t first, iterator_t const& last)const void CreateNassiForWhileEnd::operator() ( wxChar const *first, wxChar const *last ) const { NassiBrick *parent, *child, *block; while ( m_brick->GetPrevious() ) m_brick = m_brick->GetPrevious(); parent = m_brick->GetParent(); child = m_brick->GetNext(); m_brick->SetNext((NassiBrick *)NULL); m_brick->SetPrevious((NassiBrick *)NULL); parent->SetChild(child); delete m_brick; if ( child && child->IsBlock() ) { block = child; child = block->GetChild(); block->SetChild((NassiBrick *)NULL); //block->SetParent((NassiBrick *)NULL); block->SetPrevious((NassiBrick *)NULL); delete block; parent->SetChild(child, 0); } m_brick = parent; } CreateNassiDoWhileBrick::CreateNassiDoWhileBrick(NassiBrick *&brick) : m_brick(brick){} //void CreateNassiDoWhileBrick::operator()(iterator_t first, iterator_t const& last)const void CreateNassiDoWhileBrick::operator() ( wxChar const *first, wxChar const *last ) const { NassiBrick *brick = new NassiDoWhileBrick(); m_brick->SetNext(brick); //brick->SetTextByNumber(m_c_str, 0); //brick->SetTextByNumber(m_s_str, 1); //m_c_str.clear(); //m_s_str.clear(); m_brick = brick; brick = new NassiInstructionBrick(); m_brick->SetChild(brick); m_brick = brick; } CreateNassiDoWhileEnd::CreateNassiDoWhileEnd(wxString &c_str, wxString &s_str, NassiBrick *&brick) : m_c_str(c_str), m_s_str(s_str),m_brick(brick){} //void CreateNassiDoWhileEnd::operator()(iterator_t first, iterator_t const& last)const void CreateNassiDoWhileEnd::operator() ( wxChar const *first, wxChar const *last ) const { NassiBrick *parent, *child, *block; while ( m_brick->GetPrevious() ) m_brick = m_brick->GetPrevious(); parent = m_brick->GetParent(); child = m_brick->GetNext(); m_brick->SetNext((NassiBrick *)NULL); m_brick->SetPrevious((NassiBrick *)NULL); parent->SetChild(child); delete m_brick; if ( child && child->IsBlock() ) { block = child; child = block->GetChild(); block->SetChild((NassiBrick *)NULL); block->SetPrevious((NassiBrick *)NULL); delete block; parent->SetChild(child); } m_brick = parent; parent->SetTextByNumber(m_c_str, 0); parent->SetTextByNumber(m_s_str, 1); m_c_str.clear(); m_s_str.clear(); } CreateNassiSwitchBrick::CreateNassiSwitchBrick(wxString &c_str, wxString &s_str, NassiBrick *&brick) : m_c_str(c_str), m_s_str(s_str),m_brick(brick){} //void CreateNassiSwitchBrick::operator()(iterator_t first, iterator_t const& last)const void CreateNassiSwitchBrick::operator() ( wxChar const *first, wxChar const *last ) const { NassiBrick *brick = new NassiSwitchBrick(); m_brick->SetNext(brick); brick->SetTextByNumber(m_c_str, 0); brick->SetTextByNumber(m_s_str, 1); m_c_str.clear(); m_s_str.clear(); m_brick = brick; brick = new NassiInstructionBrick(); m_brick->AddChild(0); m_brick->SetChild(brick, 0); m_brick = brick; //wxMessageBox(_T("Switch brick"), _T("Created:")); } CreateNassiSwitchEnd::CreateNassiSwitchEnd( NassiBrick *&brick) : m_brick(brick){} //void CreateNassiSwitchEnd::operator()(iterator_t first, iterator_t const& last)const void CreateNassiSwitchEnd::operator() ( wxChar const *first, wxChar const *last ) const { wxInt32 n; NassiBrick *parent, *child;//, *block; while ( m_brick->GetPrevious() ) m_brick = m_brick->GetPrevious(); parent = m_brick->GetParent(); n = parent->GetChildCount(); child = m_brick->GetNext(); m_brick->SetNext((NassiBrick *)NULL); m_brick->SetPrevious((NassiBrick *)NULL); parent->SetChild(child, n-1); delete m_brick; m_brick = parent; m_brick->RemoveChild(0); //wxMessageBox(_T("Switch End"), _T("Created:")); } CreateNassiSwitchChild::CreateNassiSwitchChild(wxString &c_str, wxString &s_str, NassiBrick *&brick) : m_c_str(c_str), m_s_str(s_str),m_brick(brick){} //void CreateNassiSwitchChild::operator()(iterator_t first, iterator_t const& last)const void CreateNassiSwitchChild::operator() ( wxChar const *first, wxChar const *last ) const { NassiBrick *parent, *child, *brick; wxInt32 n; while ( m_brick->GetPrevious() ) m_brick = m_brick->GetPrevious(); parent = m_brick->GetParent(); n = parent->GetChildCount(); //0..n-1 brick = parent->GetChild(n-1); child = brick->GetNext(); brick->SetNext((NassiBrick *)NULL); brick->SetParent((NassiBrick *)NULL); brick->SetPrevious((NassiBrick *)NULL); parent->SetChild(child, n-1); parent->AddChild(n); parent->SetTextByNumber(m_c_str, 2 * (n+1)); parent->SetTextByNumber(m_s_str, 2 * (n+1) + 1); m_c_str.clear(); m_s_str.clear(); parent->SetChild(brick, n); m_brick = brick; //wxMessageBox(_T("Switch Child"), _T("Created:")); } /// //////////////////////////////////////////////////////////////////////////
[ "danselmi@1ca45b2e-1973-0410-a226-9012aad761af" ]
[ [ [ 1, 528 ] ] ]
3da65e1fdd511e996da9f96fa6163568c4062449
34c65c99c538c020e4ed644d88b9b5095095425e
/CGame.cpp
a1f4808824407dc29c9b924b0b5721b3cd1ad1cf
[]
no_license
rpmessner/Marbles
c30947233fa25ad840f9a3ce308d5b88e367c516
d1108b5eb7f6b3ccde20b78803ad5b6b0a63041f
refs/heads/master
2016-09-06T01:50:35.745908
2011-02-24T23:47:39
2011-02-24T23:47:39
1,408,878
0
0
null
null
null
null
UTF-8
C++
false
false
8,809
cpp
#include "CGame.h" #include "CGLRender.h" #include "CObjectManager.h" #include "CMarble.h" #include "CInputManager.h" #include <windows.h> #include <gl\glut.h> #include <stdio.h> #include <cmath> #define NUM_MARBLES 25 #define LEFT_MB 0 #define RIGHT_MB 2 CGame::CGame() { CMessage* message = new CMessage(); message->text = "Dude is on"; message->xpos = 0; message->ypos = 0; m_messageList.push_back(message); int time = GetTickCount(); srand(time); sprintf(m_windowTitle, "Marbles"); for(int i=0;i<256;i++) { m_keys[i]=false; } m_throbber = 0; m_throbIncrSign = 1; m_pause = 0; m_viewInterp = 0; CCamera::Instance().LookAt( 40, 20, 40, 0, 0, 0, 0, 1, 0 ); m_gameState = GS_LoadLevel; m_tolleyPos.set(-20, 0, 50); m_aimPos.set(0,0,0); m_p1Tolley = new CTolley; m_objectManager.AddObject(m_p1Tolley); m_marbleList.push_back(m_p1Tolley); m_p1Tolley->setPos(m_tolleyPos.x, 1, m_tolleyPos.z); m_soundManager.init(); //m_soundManager.startMusic(); //m_p1Tolley->DisableBody(); } CGame::~CGame() { ; } //======================================================================================== // CreateMarbles(int number) creates number amount of marbles and arranges them in // a grid at the origin //======================================================================================== bool CGame::CreateMarbles(int number) { CMarble* temp = NULL; for (int i = 0; i < number; i++) m_marbleList.push_back((CMarble*)m_objectManager.CreateObject(Marble_Type)); double x = m_marbleList[1]->getRadius()*2; int cols = (int)sqrt((double)number)+1; int z = 0; for (int i = 0; i < cols; i++) for (int j = 0; j < cols; j++) { m_marbleList[z++]->setPos((cols/2-i)*x, x/2, (cols/2-j)*x); if (z >= number) return true; } return true; } WPARAM CGame::Start() { m_quit = false; // Bool Variable To Exit Loop bool fullscreen = false; // Create Our OpenGL Window if (!CGLRender::Instance().CreateGLWindow(m_windowTitle,1024,768,32,fullscreen)) { return 0; // Quit If Window Was Not Created } while(!m_quit) // Loop That Runs While done=FALSE { if (CInputManager::Instance().CheckInput()) ; else { // Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene() if (CGLRender::Instance().getActive()) // Program Active? { CGLRender::Instance().StartGLScene(); // Draw The Scene MainLoop(); //CGLRender::Instance().drawFloor(); CGLRender::Instance().EndGLScene(); } if (CInputManager::Instance().KeyState(VK_F1)) { CInputManager::Instance().KeyUp(VK_F1); CGLRender::Instance().KillGLWindow(); // Kill Our Current Window fullscreen=!fullscreen; // Toggle Fullscreen / Windowed Mode // Recreate Our OpenGL Window if (!CGLRender::Instance().CreateGLWindow(m_windowTitle,1024,768,32,fullscreen)) { return 0; // Quit If Window Was Not Created } } } } // Shutdown CGLRender::Instance().KillGLWindow(); // Kill The Window return 0; // Exit The Program } void CGame::MainLoop () { if (CInputManager::Instance().KeyState(VK_F2)) SoundManager::Instance().startMusic(); if (CInputManager::Instance().KeyState(VK_F3)) SoundManager::Instance().stopMusic(); int width = CGLRender::Instance().getWidth() >> 1; int height = CGLRender::Instance().getHeight() >> 1; if (m_gameState == GS_Menu) { ; } else if (m_gameState == GS_LoadLevel) { CreateMarbles(NUM_MARBLES); m_gameState = GS_DynamicsSettle; } else { m_tolleyForward = m_tolleyPos-m_aimPos; m_tolleyForward.y = 0; m_tolleyForward.Normalize(); CVector3 up(0, 1, 0); m_tolleyStrafe.Cross(m_tolleyForward, up); m_tolleyStrafe.Normalize(); CTimer::Instance().FrameUpdate(); m_deltaT = CTimer::Instance().getDeltaT(); if (m_throbber < 0.0 || m_throbber > 1.0) m_throbIncrSign = -m_throbIncrSign; m_throbber += m_deltaT*m_throbIncrSign; ODEManager::Instance().SimLoop(m_pause); if (m_gameState == GS_DynamicsSettle) { interpView(); if (CObjectManager::Instance().DynamicsDone()) m_gameState = GS_AimShot; } else if (m_gameState == GS_AimShot) { double speed = m_deltaT*5; if (!CObjectManager::Instance().DynamicsDone()) { m_gameState = GS_DynamicsSettle; m_viewInterp = 0.0; } if (CInputManager::Instance().MouseState(LEFT_MB)) { m_gameState = GS_ShotDetect; ShowCursor(FALSE); SetCursorPos(width, height); m_forwardAim.set(0,0,0); m_sideAim.set(0,0,0); } if (CInputManager::Instance().KeyState(VK_SPACE)) { m_toggleTolleyMove = !m_toggleTolleyMove; CInputManager::Instance().KeyUp(VK_SPACE); } if (m_toggleTolleyMove) { if (CInputManager::Instance().KeyState(VK_UP)) m_tolleyPos = m_tolleyPos - m_tolleyForward*speed; if (CInputManager::Instance().KeyState(VK_DOWN)) m_tolleyPos = m_tolleyPos + m_tolleyForward*speed; if (CInputManager::Instance().KeyState(VK_LEFT)) m_tolleyPos = m_tolleyPos + m_tolleyStrafe*speed; if (CInputManager::Instance().KeyState(VK_RIGHT)) m_tolleyPos = m_tolleyPos - m_tolleyStrafe*speed; } else { if (CInputManager::Instance().KeyState(VK_UP)) m_aimPos = m_aimPos - m_tolleyForward*speed*1.5; if (CInputManager::Instance().KeyState(VK_DOWN)) m_aimPos = m_aimPos + m_tolleyForward*speed*1.5; if (CInputManager::Instance().KeyState(VK_LEFT)) m_aimPos = m_aimPos + m_tolleyStrafe*speed*1.5; if (CInputManager::Instance().KeyState(VK_RIGHT)) m_aimPos = m_aimPos - m_tolleyStrafe*speed*1.5; } m_p1Tolley->setPos(m_tolleyPos.x, m_tolleyPos.y, m_tolleyPos.z); CCamera::Instance().LookAt(m_tolleyPos.x + m_tolleyForward.x*10 , 5, m_tolleyPos.z + m_tolleyForward.z*10, m_aimPos.x, m_aimPos.y, m_aimPos.z, 0, 1, 0); } else if (m_gameState == GS_ShotDetect) { if (!CInputManager::Instance().MouseState(LEFT_MB)) { ShootMarble(m_forwardAim, m_sideAim, m_aimPos - m_tolleyPos); ShowCursor(TRUE); m_gameState = GS_DynamicsSettle; m_viewInterp = 0.0; } CInputManager::Instance().UpdateMouse(width, height); m_sideAim = m_sideAim + m_tolleyForward*CInputManager::Instance().getMouseDX(); m_forwardAim = m_forwardAim + (m_tolleyStrafe*CInputManager::Instance().getMouseDY()); } CCamera::Instance().Look(); m_tolleyPos.set(m_p1Tolley->getPos()[0], m_p1Tolley->getPos()[1], m_p1Tolley->getPos()[2]); CObjectManager::Instance().UpdateObjects(); CObjectManager::Instance().DrawObjects(); //CGLRender::Instance().drawGrid(); CGLRender::Instance().drawFloor(); CGLRender::Instance().drawAim(m_aimPos.x, m_aimPos.z, m_throbber); } } void printOut(int x, int y, char * text) { glRasterPos2i(x,y); int length=strlen(text); for (int i = 0; i < length; i++) { glutBitmapCharacter(GLUT_BITMAP_8_BY_13, text[i]); } } void CGame::DrawTexts() { for (vector<CMessage*>::iterator it = m_messageList.begin(); it < m_messageList.end(); it++) { printOut((*it)->xpos, (*it)->ypos, (*it)->text); } } void CGame::interpView () { CVector3 viewPos, viewCtr; CVector3 destPos(3, 40, 3); CVector3 sourcePos(m_tolleyPos.x + m_tolleyForward.x*10 , 5, m_tolleyPos.z + m_tolleyForward.z*10); if (m_viewInterp < 1) { m_viewInterp+=m_deltaT; viewPos = sourcePos *(1-m_viewInterp) + destPos * m_viewInterp; viewCtr = m_aimPos *(1-m_viewInterp) + m_tolleyPos * m_viewInterp; } else { viewCtr = m_tolleyPos; viewPos = destPos;//CCamera::Instance().LookAt( 3, 20, 3, 0, 0, 0, 0, 1, 0 ); } CCamera::Instance().LookAt(viewPos.x, viewPos.y, viewPos.z, viewCtr.x, viewCtr.y, viewCtr.z, 0, 1, 0); } void CGame::CheckCollisions(dBodyID b1, dBodyID b2) { CGameObject* obj1 = CObjectManager::Instance().getObject(b1); CGameObject* obj2 = CObjectManager::Instance().getObject(b2); if (((CMarble*)obj1)->getVel() > 0.3 || ((CMarble*)obj2)->getVel() > 0.3) { float volume = max(((CMarble*)obj1)->getVel(), ((CMarble*)obj2)->getVel()); m_soundManager.playFX(volume * 2.0f); } } void CGame::ShootMarble(CVector3 forward, CVector3 side, CVector3 aim) { double yVel = aim.Magnitude()/30.0; if (yVel > 5.0) yVel = 10.0; m_p1Tolley->setVel(aim.x*1.3,yVel, aim.z*1.3); if (forward.Magnitude() != 0) m_p1Tolley->AddTorque(forward.x/10, forward.y/10, forward.z/10); if (side.Magnitude() != 0) m_p1Tolley->AddTorque(side.x/3, side.y/3, side.z/3); m_gameState = GS_DynamicsSettle; } void CGame::OnKeyUp(WPARAM w) { } void CGame::OnKeyDown(WPARAM w) { }
[ [ [ 1, 289 ] ] ]
1adfa3abe0a07a2a7f8a0c6c0e38be4648025e72
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/webcontnrs.hpp
75cf5a8099ba75b09bbdb1729fde008cf2eedd8c
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
7,061
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'WebContnrs.pas' rev: 6.00 #ifndef WebContnrsHPP #define WebContnrsHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <SysUtils.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Webcontnrs { //-- type declarations ------------------------------------------------------- class DELPHICLASS ENamedVariantsError; class PASCALIMPLEMENTATION ENamedVariantsError : public Sysutils::Exception { typedef Sysutils::Exception inherited; public: #pragma option push -w-inl /* Exception.Create */ inline __fastcall ENamedVariantsError(const AnsiString Msg) : Sysutils::Exception(Msg) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateFmt */ inline __fastcall ENamedVariantsError(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size) : Sysutils::Exception(Msg, Args, Args_Size) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateRes */ inline __fastcall ENamedVariantsError(int Ident)/* overload */ : Sysutils::Exception(Ident) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResFmt */ inline __fastcall ENamedVariantsError(int Ident, const System::TVarRec * Args, const int Args_Size)/* overload */ : Sysutils::Exception(Ident, Args, Args_Size) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateHelp */ inline __fastcall ENamedVariantsError(const AnsiString Msg, int AHelpContext) : Sysutils::Exception(Msg, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateFmtHelp */ inline __fastcall ENamedVariantsError(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size, int AHelpContext) : Sysutils::Exception(Msg, Args, Args_Size, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResHelp */ inline __fastcall ENamedVariantsError(int Ident, int AHelpContext)/* overload */ : Sysutils::Exception(Ident, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResFmtHelp */ inline __fastcall ENamedVariantsError(System::PResStringRec ResStringRec, const System::TVarRec * Args, const int Args_Size, int AHelpContext)/* overload */ : Sysutils::Exception(ResStringRec, Args, Args_Size, AHelpContext) { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~ENamedVariantsError(void) { } #pragma option pop }; class DELPHICLASS TAbstractNamedVariants; class PASCALIMPLEMENTATION TAbstractNamedVariants : public Classes::TPersistent { typedef Classes::TPersistent inherited; private: int FUpdateCount; AnsiString __fastcall GetName(int Index); Variant __fastcall GetValue(const AnsiString Name); void __fastcall ReadData(Classes::TReader* Reader); void __fastcall SetValue(const AnsiString Name, const Variant &Value); void __fastcall WriteData(Classes::TWriter* Writer); void __fastcall AddNamedVariants(TAbstractNamedVariants* ANamedVariants); Variant __fastcall GetVariant(int Index); void __fastcall PutVariant(int Index, const Variant &Value); protected: virtual void __fastcall DefineProperties(Classes::TFiler* Filer); void __fastcall Error(const AnsiString Msg, int Data)/* overload */; virtual bool __fastcall Get(int Index, /* out */ AnsiString &AName, /* out */ Variant &AValue) = 0 ; virtual int __fastcall GetCapacity(void); virtual int __fastcall GetCount(void) = 0 ; virtual void __fastcall Put(int Index, const AnsiString AName, const Variant &AValue) = 0 ; virtual void __fastcall SetCapacity(int NewCapacity); virtual void __fastcall SetUpdateState(bool Updating); __property int UpdateCount = {read=FUpdateCount, nodefault}; virtual int __fastcall CompareStrings(const AnsiString S1, const AnsiString S2); public: __fastcall virtual ~TAbstractNamedVariants(void); virtual int __fastcall Add(const AnsiString S, const Variant &AValue); void __fastcall Append(const AnsiString S, const Variant &AValue); virtual void __fastcall Assign(Classes::TPersistent* Source); void __fastcall BeginUpdate(void); virtual void __fastcall Clear(void) = 0 ; virtual void __fastcall Delete(int Index) = 0 ; void __fastcall EndUpdate(void); bool __fastcall Equals(TAbstractNamedVariants* ANamedVariants); virtual void __fastcall Exchange(int Index1, int Index2); virtual int __fastcall IndexOfName(const AnsiString Name); virtual void __fastcall Insert(int Index, const AnsiString S, const Variant &AValue) = 0 ; virtual void __fastcall Move(int CurIndex, int NewIndex); __property int Capacity = {read=GetCapacity, write=SetCapacity, nodefault}; __property int Count = {read=GetCount, nodefault}; __property AnsiString Names[int Index] = {read=GetName}; __property Variant Values[AnsiString Name] = {read=GetValue, write=SetValue}; __property Variant Variants[int Index] = {read=GetVariant, write=PutVariant}; public: #pragma option push -w-inl /* TObject.Create */ inline __fastcall TAbstractNamedVariants(void) : Classes::TPersistent() { } #pragma option pop }; struct TNamedVariantItem; typedef TNamedVariantItem *PNamedVariantItem; struct TNamedVariantItem { AnsiString FString; Variant FVariant; } ; typedef TNamedVariantItem TNamedVariantList[83333334]; typedef TNamedVariantItem *PNamedVariantList; class DELPHICLASS TNamedVariantsList; class PASCALIMPLEMENTATION TNamedVariantsList : public TAbstractNamedVariants { typedef TAbstractNamedVariants inherited; private: TNamedVariantItem *FList; int FCount; int FCapacity; void __fastcall Grow(void); protected: virtual void __fastcall SetCapacity(int NewCapacity); virtual int __fastcall GetCapacity(void); virtual bool __fastcall Get(int Index, /* out */ AnsiString &AName, /* out */ Variant &AValue); virtual void __fastcall Put(int Index, const AnsiString AName, const Variant &AValue); virtual int __fastcall GetCount(void); public: __fastcall virtual ~TNamedVariantsList(void); virtual void __fastcall Clear(void); virtual void __fastcall Delete(int Index); virtual void __fastcall Insert(int Index, const AnsiString S, const Variant &AValue); public: #pragma option push -w-inl /* TObject.Create */ inline __fastcall TNamedVariantsList(void) : TAbstractNamedVariants() { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- } /* namespace Webcontnrs */ using namespace Webcontnrs; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // WebContnrs
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 170 ] ] ]
0ba9eb00cccf3787ec5851db1e232a028df799d1
adb2ebb4b7f74f62228c7dd9ca1441ee95297243
/UI/mainWindow.h
483329367f3e6b65ba7af39711fb8f6dc3192a63
[]
no_license
BackupTheBerlios/blazefilesearch-svn
5984480677ad0a7ae64c082e16dde4e7b2394c2c
b910de6af6f1ae8e018f06a484a8b6d9c4c2f280
refs/heads/master
2021-01-22T17:53:29.216195
2005-03-05T05:17:38
2005-03-05T05:17:38
40,608,509
0
0
null
null
null
null
UTF-8
C++
false
false
25,069
h
#pragma once #include "UI_global.h" #include "FeedbackForm.h" #include "UI_engineInterface.h" using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; // The following namespace imports are for SandBar/SandDock using namespace TD::SandDock; using namespace TD::SandDock::Rendering; // For the engine using namespace Blaze::Engine; namespace UI { /// <summary> /// The main window of Blaze's GUI /// </summary> public __gc class mainWindow : public System::Windows::Forms::Form { public: mainWindow(void) { InitializeComponent(); InitWindow(); } protected: void Dispose(Boolean disposing) { if (disposing && components) { components->Dispose(); } __super::Dispose(disposing); } // The GUI variables private: TD::SandDock::SandDockManager * sandDockManager; private: TD::SandDock::DockContainer * leftSandDock; private: TD::SandDock::DockContainer * rightSandDock; private: TD::SandDock::DockContainer * bottomSandDock; private: TD::SandDock::DockContainer * topSandDock; private: TD::SandBar::SandBarManager * sandBarManager; private: TD::SandBar::ToolBarContainer * leftSandBarDock; private: TD::SandBar::ToolBarContainer * rightSandBarDock; private: TD::SandBar::ToolBarContainer * bottomSandBarDock; private: TD::SandBar::ToolBarContainer * topSandBarDock; private: TD::SandDock::DockControl * sdcSearch; private: TD::SandBar::MenuButtonItem * mbiAbout; private: TD::SandBar::MenuButtonItem * mbiClose; private: TD::SandBar::MenuButtonItem * mbiExit; private: TD::SandBar::ToolBar * stbShortcuts; private: TD::SandBar::MenuBarItem * mbhSearches; private: TD::SandBar::MenuBarItem * mbhHelp; private: TD::SandBar::MenuButtonItem * mbiHelp; private: TD::SandBar::MenuButtonItem * mbiSendFeedback; private: TD::SandBar::MenuBarItem * mbhView; private: TD::SandBar::MenuButtonItem * mbiSearchPaneSelect; private: TD::SandDock::DocumentContainer * sctSearchesContainer; private: TD::SandDock::DockControl * sdcWelcome; private: System::Windows::Forms::PictureBox * picHomeBackground; private: TD::SandDock::DockControl * sdcOptions; private: TD::SandBar::MenuButtonItem * mbiOptionsPaneSelect; private: TD::SandBar::ButtonItem * sbiHelp; private: TD::SandBar::ButtonItem * sbiAbout; private: TD::SandBar::MenuButtonItem * mbiShowWelcomeTab; private: System::Windows::Forms::Label * lblWelcome; private: TD::SandBar::MenuBar * mbiMain; private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container* components; /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { System::Resources::ResourceManager * resources = new System::Resources::ResourceManager(__typeof(UI::mainWindow)); this->sandDockManager = new TD::SandDock::SandDockManager(); this->leftSandDock = new TD::SandDock::DockContainer(); this->sdcSearch = new TD::SandDock::DockControl(); this->sdcOptions = new TD::SandDock::DockControl(); this->rightSandDock = new TD::SandDock::DockContainer(); this->bottomSandDock = new TD::SandDock::DockContainer(); this->topSandDock = new TD::SandDock::DockContainer(); this->sandBarManager = new TD::SandBar::SandBarManager(); this->leftSandBarDock = new TD::SandBar::ToolBarContainer(); this->rightSandBarDock = new TD::SandBar::ToolBarContainer(); this->bottomSandBarDock = new TD::SandBar::ToolBarContainer(); this->topSandBarDock = new TD::SandBar::ToolBarContainer(); this->mbiMain = new TD::SandBar::MenuBar(); this->mbhSearches = new TD::SandBar::MenuBarItem(); this->mbiClose = new TD::SandBar::MenuButtonItem(); this->mbiExit = new TD::SandBar::MenuButtonItem(); this->mbhView = new TD::SandBar::MenuBarItem(); this->mbiSearchPaneSelect = new TD::SandBar::MenuButtonItem(); this->mbiOptionsPaneSelect = new TD::SandBar::MenuButtonItem(); this->mbiShowWelcomeTab = new TD::SandBar::MenuButtonItem(); this->mbhHelp = new TD::SandBar::MenuBarItem(); this->mbiHelp = new TD::SandBar::MenuButtonItem(); this->mbiSendFeedback = new TD::SandBar::MenuButtonItem(); this->mbiAbout = new TD::SandBar::MenuButtonItem(); this->stbShortcuts = new TD::SandBar::ToolBar(); this->sbiHelp = new TD::SandBar::ButtonItem(); this->sbiAbout = new TD::SandBar::ButtonItem(); this->sctSearchesContainer = new TD::SandDock::DocumentContainer(); this->sdcWelcome = new TD::SandDock::DockControl(); this->lblWelcome = new System::Windows::Forms::Label(); this->picHomeBackground = new System::Windows::Forms::PictureBox(); this->leftSandDock->SuspendLayout(); this->topSandBarDock->SuspendLayout(); this->sctSearchesContainer->SuspendLayout(); this->sdcWelcome->SuspendLayout(); this->SuspendLayout(); // // sandDockManager // this->sandDockManager->DockingManager = TD::SandDock::DockingManager::Whidbey; this->sandDockManager->OwnerForm = this; this->sandDockManager->Renderer = new TD::SandDock::Rendering::Office2003Renderer(); // // leftSandDock // this->leftSandDock->Controls->Add(this->sdcSearch); this->leftSandDock->Controls->Add(this->sdcOptions); this->leftSandDock->Dock = System::Windows::Forms::DockStyle::Left; this->leftSandDock->Guid = System::Guid(S"8b2183b4-63c6-4437-b491-d923b42aa2ca"); TD::SandDock::LayoutSystemBase* __mcTemp__1[] = new TD::SandDock::LayoutSystemBase*[1]; TD::SandDock::DockControl* __mcTemp__2[] = new TD::SandDock::DockControl*[2]; __mcTemp__2[0] = this->sdcSearch; __mcTemp__2[1] = this->sdcOptions; __mcTemp__1[0] = new TD::SandDock::ControlLayoutSystem(180, 411, __mcTemp__2, this->sdcSearch); this->leftSandDock->LayoutSystem = new TD::SandDock::SplitLayoutSystem(250, 400, System::Windows::Forms::Orientation::Horizontal, __mcTemp__1); this->leftSandDock->Location = System::Drawing::Point(0, 50); this->leftSandDock->Manager = this->sandDockManager; this->leftSandDock->Name = S"leftSandDock"; this->leftSandDock->Size = System::Drawing::Size(184, 411); this->leftSandDock->TabIndex = 4; // // sdcSearch // this->sdcSearch->BackColor = System::Drawing::SystemColors::InactiveCaptionText; this->sdcSearch->Guid = System::Guid(S"853affb6-c2cb-4ce8-8359-f304526c475d"); this->sdcSearch->Location = System::Drawing::Point(0, 25); this->sdcSearch->Name = S"sdcSearch"; this->sdcSearch->Size = System::Drawing::Size(180, 363); this->sdcSearch->TabImage = (__try_cast<System::Drawing::Image * >(resources->GetObject(S"sdcSearch.TabImage"))); this->sdcSearch->TabIndex = 0; this->sdcSearch->Text = S"Search"; this->sdcSearch->Closed += new System::EventHandler(this, sdcSearch_Closed); // // sdcOptions // this->sdcOptions->BackColor = System::Drawing::SystemColors::InactiveCaptionText; this->sdcOptions->Guid = System::Guid(S"344ca479-91c0-4621-b8aa-726913f16b0f"); this->sdcOptions->Location = System::Drawing::Point(0, 25); this->sdcOptions->Name = S"sdcOptions"; this->sdcOptions->Size = System::Drawing::Size(180, 363); this->sdcOptions->TabImage = (__try_cast<System::Drawing::Image * >(resources->GetObject(S"sdcOptions.TabImage"))); this->sdcOptions->TabIndex = 0; this->sdcOptions->Text = S"Options"; this->sdcOptions->Closed += new System::EventHandler(this, sdcOptions_Closed); // // rightSandDock // this->rightSandDock->Dock = System::Windows::Forms::DockStyle::Right; this->rightSandDock->Guid = System::Guid(S"d118fb89-0d33-462b-9f47-1bed434bc309"); this->rightSandDock->LayoutSystem = new TD::SandDock::SplitLayoutSystem(250, 400); this->rightSandDock->Location = System::Drawing::Point(712, 50); this->rightSandDock->Manager = this->sandDockManager; this->rightSandDock->Name = S"rightSandDock"; this->rightSandDock->Size = System::Drawing::Size(0, 411); this->rightSandDock->TabIndex = 5; // // bottomSandDock // this->bottomSandDock->Dock = System::Windows::Forms::DockStyle::Bottom; this->bottomSandDock->Guid = System::Guid(S"41bd64c4-5b0f-41ea-8844-2f5597b61618"); this->bottomSandDock->LayoutSystem = new TD::SandDock::SplitLayoutSystem(250, 400); this->bottomSandDock->Location = System::Drawing::Point(0, 461); this->bottomSandDock->Manager = this->sandDockManager; this->bottomSandDock->Name = S"bottomSandDock"; this->bottomSandDock->Size = System::Drawing::Size(712, 0); this->bottomSandDock->TabIndex = 6; // // topSandDock // this->topSandDock->Dock = System::Windows::Forms::DockStyle::Top; this->topSandDock->DockingManager = TD::SandDock::DockingManager::Whidbey; this->topSandDock->Guid = System::Guid(S"48454df2-f926-467b-8a9a-500dadcb4601"); this->topSandDock->LayoutSystem = new TD::SandDock::SplitLayoutSystem(250, 400); this->topSandDock->Location = System::Drawing::Point(0, 50); this->topSandDock->Manager = this->sandDockManager; this->topSandDock->Name = S"topSandDock"; this->topSandDock->Size = System::Drawing::Size(712, 0); this->topSandDock->TabIndex = 7; // // sandBarManager // this->sandBarManager->OwnerForm = this; // // leftSandBarDock // this->leftSandBarDock->Dock = System::Windows::Forms::DockStyle::Left; this->leftSandBarDock->Guid = System::Guid(S"be85f063-ec9b-4138-a508-3716663caae9"); this->leftSandBarDock->Location = System::Drawing::Point(0, 50); this->leftSandBarDock->Manager = this->sandBarManager; this->leftSandBarDock->Name = S"leftSandBarDock"; this->leftSandBarDock->Size = System::Drawing::Size(0, 411); this->leftSandBarDock->TabIndex = 8; // // rightSandBarDock // this->rightSandBarDock->Dock = System::Windows::Forms::DockStyle::Right; this->rightSandBarDock->Guid = System::Guid(S"15f5fe3a-8379-482b-94be-dbb514e50729"); this->rightSandBarDock->Location = System::Drawing::Point(712, 50); this->rightSandBarDock->Manager = this->sandBarManager; this->rightSandBarDock->Name = S"rightSandBarDock"; this->rightSandBarDock->Size = System::Drawing::Size(0, 411); this->rightSandBarDock->TabIndex = 9; // // bottomSandBarDock // this->bottomSandBarDock->Dock = System::Windows::Forms::DockStyle::Bottom; this->bottomSandBarDock->Guid = System::Guid(S"03678732-c68f-4f6f-8840-4b0fe220f75c"); this->bottomSandBarDock->Location = System::Drawing::Point(0, 461); this->bottomSandBarDock->Manager = this->sandBarManager; this->bottomSandBarDock->Name = S"bottomSandBarDock"; this->bottomSandBarDock->Size = System::Drawing::Size(712, 0); this->bottomSandBarDock->TabIndex = 10; // // topSandBarDock // this->topSandBarDock->Controls->Add(this->mbiMain); this->topSandBarDock->Controls->Add(this->stbShortcuts); this->topSandBarDock->Dock = System::Windows::Forms::DockStyle::Top; this->topSandBarDock->Guid = System::Guid(S"fb86d486-d317-457f-b3cb-d612d3615a19"); this->topSandBarDock->Location = System::Drawing::Point(0, 0); this->topSandBarDock->Manager = this->sandBarManager; this->topSandBarDock->Name = S"topSandBarDock"; this->topSandBarDock->Size = System::Drawing::Size(712, 50); this->topSandBarDock->TabIndex = 11; // // mbiMain // this->mbiMain->Guid = System::Guid(S"e3b8fc63-2489-4dec-b885-f02302a33bad"); TD::SandBar::ToolbarItemBase* __mcTemp__3[] = new TD::SandBar::ToolbarItemBase*[3]; __mcTemp__3[0] = this->mbhSearches; __mcTemp__3[1] = this->mbhView; __mcTemp__3[2] = this->mbhHelp; this->mbiMain->Items->AddRange(__mcTemp__3); this->mbiMain->Location = System::Drawing::Point(2, 0); this->mbiMain->Name = S"mbiMain"; this->mbiMain->OwnerForm = this; this->mbiMain->Size = System::Drawing::Size(710, 24); this->mbiMain->TabIndex = 0; this->mbiMain->Text = S"Main"; // // mbhSearches // TD::SandBar::ToolbarItemBase* __mcTemp__4[] = new TD::SandBar::ToolbarItemBase*[2]; __mcTemp__4[0] = this->mbiClose; __mcTemp__4[1] = this->mbiExit; this->mbhSearches->Items->AddRange(__mcTemp__4); this->mbhSearches->Text = S"&Searches"; // // mbiClose // this->mbiClose->Shortcut = System::Windows::Forms::Shortcut::CtrlC; this->mbiClose->Text = S"&Close"; this->mbiClose->Activate += new System::EventHandler(this, mbiClose_Activate); // // mbiExit // this->mbiExit->Image = (__try_cast<System::Drawing::Image * >(resources->GetObject(S"mbiExit.Image"))); this->mbiExit->Shortcut = System::Windows::Forms::Shortcut::AltF4; this->mbiExit->Text = S"E&xit"; this->mbiExit->Activate += new System::EventHandler(this, mbiExit_Activate); // // mbhView // TD::SandBar::ToolbarItemBase* __mcTemp__5[] = new TD::SandBar::ToolbarItemBase*[3]; __mcTemp__5[0] = this->mbiSearchPaneSelect; __mcTemp__5[1] = this->mbiOptionsPaneSelect; __mcTemp__5[2] = this->mbiShowWelcomeTab; this->mbhView->Items->AddRange(__mcTemp__5); this->mbhView->Text = S"View"; // // mbiSearchPaneSelect // this->mbiSearchPaneSelect->Checked = true; this->mbiSearchPaneSelect->Image = (__try_cast<System::Drawing::Image * >(resources->GetObject(S"mbiSearchPaneSelect.Image"))); this->mbiSearchPaneSelect->Text = S"Search Pane"; this->mbiSearchPaneSelect->Activate += new System::EventHandler(this, mbiSearchPaneSelect_Activate); // // mbiOptionsPaneSelect // this->mbiOptionsPaneSelect->Image = (__try_cast<System::Drawing::Image * >(resources->GetObject(S"mbiOptionsPaneSelect.Image"))); this->mbiOptionsPaneSelect->Text = S"Options"; this->mbiOptionsPaneSelect->Activate += new System::EventHandler(this, mbiOptionsPaneSelect_Activate); // // mbiShowWelcomeTab // this->mbiShowWelcomeTab->BeginGroup = true; this->mbiShowWelcomeTab->Checked = true; this->mbiShowWelcomeTab->Text = S"Show Welcome Tab"; this->mbiShowWelcomeTab->Activate += new System::EventHandler(this, mbiShowWelcomeTab_Activate); // // mbhHelp // TD::SandBar::ToolbarItemBase* __mcTemp__6[] = new TD::SandBar::ToolbarItemBase*[3]; __mcTemp__6[0] = this->mbiHelp; __mcTemp__6[1] = this->mbiSendFeedback; __mcTemp__6[2] = this->mbiAbout; this->mbhHelp->Items->AddRange(__mcTemp__6); this->mbhHelp->Text = S"&Help"; // // mbiHelp // this->mbiHelp->Image = (__try_cast<System::Drawing::Image * >(resources->GetObject(S"mbiHelp.Image"))); this->mbiHelp->Shortcut = System::Windows::Forms::Shortcut::F1; this->mbiHelp->Text = S"&Help"; this->mbiHelp->Activate += new System::EventHandler(this, mbiHelp_Activate); // // mbiSendFeedback // this->mbiSendFeedback->BeginGroup = true; this->mbiSendFeedback->Image = (__try_cast<System::Drawing::Image * >(resources->GetObject(S"mbiSendFeedback.Image"))); this->mbiSendFeedback->Text = S"&Send Feedback"; this->mbiSendFeedback->Activate += new System::EventHandler(this, mbiSendFeedback_Activate); // // mbiAbout // this->mbiAbout->BeginGroup = true; this->mbiAbout->Image = (__try_cast<System::Drawing::Image * >(resources->GetObject(S"mbiAbout.Image"))); this->mbiAbout->Text = S"&About"; this->mbiAbout->Activate += new System::EventHandler(this, mbiAbout_Activate); // // stbShortcuts // this->stbShortcuts->DockLine = 1; this->stbShortcuts->Guid = System::Guid(S"726b8794-3a0e-44f5-b587-10c0a7ab248b"); TD::SandBar::ToolbarItemBase* __mcTemp__7[] = new TD::SandBar::ToolbarItemBase*[2]; __mcTemp__7[0] = this->sbiHelp; __mcTemp__7[1] = this->sbiAbout; this->stbShortcuts->Items->AddRange(__mcTemp__7); this->stbShortcuts->Location = System::Drawing::Point(2, 24); this->stbShortcuts->Name = S"stbShortcuts"; this->stbShortcuts->Size = System::Drawing::Size(136, 26); this->stbShortcuts->TabIndex = 1; this->stbShortcuts->Text = S"Shortcuts"; // // sbiHelp // this->sbiHelp->BuddyMenu = this->mbiHelp; this->sbiHelp->Image = (__try_cast<System::Drawing::Image * >(resources->GetObject(S"sbiHelp.Image"))); this->sbiHelp->Text = S"Help"; this->sbiHelp->ToolTipText = S"Get help on how to use Blaze"; // // sbiAbout // this->sbiAbout->BuddyMenu = this->mbiAbout; this->sbiAbout->Image = (__try_cast<System::Drawing::Image * >(resources->GetObject(S"sbiAbout.Image"))); this->sbiAbout->Text = S"About"; this->sbiAbout->ToolTipText = S"About"; // // sctSearchesContainer // this->sctSearchesContainer->BorderStyle = TD::SandDock::Rendering::BorderStyle::None; this->sctSearchesContainer->Controls->Add(this->sdcWelcome); this->sctSearchesContainer->Cursor = System::Windows::Forms::Cursors::Default; this->sctSearchesContainer->DockingManager = TD::SandDock::DockingManager::Whidbey; this->sctSearchesContainer->Guid = System::Guid(S"14b44871-d8b6-4875-a483-8d0377b74328"); TD::SandDock::LayoutSystemBase* __mcTemp__8[] = new TD::SandDock::LayoutSystemBase*[1]; TD::SandDock::DockControl* __mcTemp__9[] = new TD::SandDock::DockControl*[1]; __mcTemp__9[0] = this->sdcWelcome; __mcTemp__8[0] = new TD::SandDock::DocumentLayoutSystem(528, 411, __mcTemp__9, this->sdcWelcome); this->sctSearchesContainer->LayoutSystem = new TD::SandDock::SplitLayoutSystem(250, 400, System::Windows::Forms::Orientation::Horizontal, __mcTemp__8); this->sctSearchesContainer->Location = System::Drawing::Point(184, 50); this->sctSearchesContainer->Manager = 0; this->sctSearchesContainer->Name = S"sctSearchesContainer"; this->sctSearchesContainer->Renderer = new TD::SandDock::Rendering::Office2003Renderer(); this->sctSearchesContainer->Size = System::Drawing::Size(528, 411); this->sctSearchesContainer->TabIndex = 12; // // sdcWelcome // this->sdcWelcome->Anchor = (System::Windows::Forms::AnchorStyles)(System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Right); this->sdcWelcome->BackColor = System::Drawing::Color::FromArgb((System::Byte)254, (System::Byte)255, (System::Byte)242); this->sdcWelcome->Controls->Add(this->lblWelcome); this->sdcWelcome->Controls->Add(this->picHomeBackground); this->sdcWelcome->Guid = System::Guid(S"892daf64-e8bd-4f65-9739-6b40f7a146e2"); this->sdcWelcome->Location = System::Drawing::Point(4, 32); this->sdcWelcome->Name = S"sdcWelcome"; this->sdcWelcome->Size = System::Drawing::Size(520, 375); this->sdcWelcome->TabIndex = 0; this->sdcWelcome->Text = S"Welcome"; this->sdcWelcome->Closed += new System::EventHandler(this, sdcWelcome_Closed); this->sdcWelcome->Closing += new System::ComponentModel::CancelEventHandler(this, sdcWelcome_Closing); // // lblWelcome // this->lblWelcome->Anchor = System::Windows::Forms::AnchorStyles::Top; this->lblWelcome->AutoSize = true; this->lblWelcome->BackColor = System::Drawing::Color::Transparent; this->lblWelcome->Font = new System::Drawing::Font(S"Verdana", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, (System::Byte)0); this->lblWelcome->Location = System::Drawing::Point(172, 16); this->lblWelcome->Name = S"lblWelcome"; this->lblWelcome->Size = System::Drawing::Size(177, 23); this->lblWelcome->TabIndex = 1; this->lblWelcome->Text = S"Welcome to Blaze!"; // // picHomeBackground // this->picHomeBackground->Anchor = (System::Windows::Forms::AnchorStyles)(System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Right); this->picHomeBackground->BackColor = System::Drawing::Color::Transparent; this->picHomeBackground->Image = (__try_cast<System::Drawing::Image * >(resources->GetObject(S"picHomeBackground.Image"))); this->picHomeBackground->Location = System::Drawing::Point(392, 240); this->picHomeBackground->Name = S"picHomeBackground"; this->picHomeBackground->Size = System::Drawing::Size(128, 136); this->picHomeBackground->TabIndex = 0; this->picHomeBackground->TabStop = false; // // mainWindow // this->AutoScaleBaseSize = System::Drawing::Size(5, 13); this->ClientSize = System::Drawing::Size(712, 461); this->Controls->Add(this->sctSearchesContainer); this->Controls->Add(this->leftSandDock); this->Controls->Add(this->rightSandDock); this->Controls->Add(this->bottomSandDock); this->Controls->Add(this->topSandDock); this->Controls->Add(this->leftSandBarDock); this->Controls->Add(this->rightSandBarDock); this->Controls->Add(this->bottomSandBarDock); this->Controls->Add(this->topSandBarDock); this->Name = S"mainWindow"; this->Text = S"Blaze"; this->leftSandDock->ResumeLayout(false); this->topSandBarDock->ResumeLayout(false); this->sctSearchesContainer->ResumeLayout(false); this->sdcWelcome->ResumeLayout(false); this->ResumeLayout(false); } // Init code void InitWindow() { this->sdcOptions->Close(); this->sdcWelcome->Activate(); } private: System::Void mbiExit_Activate(System::Object * sender, System::EventArgs * e) { Application::Exit(); } private: System::Void mbiClose_Activate(System::Object * sender, System::EventArgs * e) { // TODO: fix window close code later when needed mbiExit_Activate(sender, e); } private: System::Void mbiAbout_Activate(System::Object * sender, System::EventArgs * e) { // TODO: beef up about box MessageBox::Show(this, S"Blaze 0.01a\nby the International Association of Idiots", S"About", MessageBoxButtons::OK, MessageBoxIcon::Information); } private: System::Void mbiSendFeedback_Activate(System::Object * sender, System::EventArgs * e) { FeedbackForm *ff = new FeedbackForm(); ff->Show(); } /* * rendererID is to signify the renderer: * - Automatic * - Standard * - LunaBlue * - LunaOlive * - LunaSilver */ /* private: System::Boolean changeRendererColorScheme(System::String *cs) { if (!cs->Equals(S"Automatic") && !cs->Equals(S"Standard") && !cs->Equals(S"LunaBlue") && !cs->Equals(S"LunaOlive") && !cs->Equals(S"LunaSilver")) { return false; } Office2003Renderer *oR_buf = new Office2003Renderer(); if (this->sctSearchesContainer->Renderer->Equals(oR_buf)) { Office2003Renderer Office2003Renderer::Office2003ColorScheme *colorScheme = (Office2003Renderer::Office2003ColorScheme) Enum::Parse(__typeof(Office2003Renderer::Office2003ColorScheme), cs); Office2003Renderer *renderer = (Office2003Renderer)sctSearchesContainer->Renderer; if (renderer->ColorScheme != colorScheme) { renderer->ColorScheme = colorScheme; sctSearchesContainer->Invalidate(); } } return true; }*/ private: System::Void mbiSearchPaneSelect_Activate(System::Object * sender, System::EventArgs * e) { if (this->mbiSearchPaneSelect->Checked) { mbiSearchPaneSelect->Checked = false; sdcSearch->Close(); } else { mbiSearchPaneSelect->Checked = true; sdcSearch->Open(); } } private: System::Void mbiOptionsPaneSelect_Activate(System::Object * sender, System::EventArgs * e) { if (this->mbiOptionsPaneSelect->Checked) { mbiOptionsPaneSelect->Checked = false; sdcOptions->Close(); } else { mbiOptionsPaneSelect->Checked = true; sdcOptions->Open(); } } private: System::Void mbiHelp_Activate(System::Object * sender, System::EventArgs * e) { // TODO: implement help MessageBox::Show("not implemented yet :-("); } private: System::Void mbiShowWelcomeTab_Activate(System::Object * sender, System::EventArgs * e) { if (this->sctSearchesContainer->Documents->Contains(this->sdcWelcome)) { this->sctSearchesContainer->RemoveDocument(this->sdcWelcome); // Close the tab this->mbiShowWelcomeTab->Checked = false; } else { this->sctSearchesContainer->AddDocument(this->sdcWelcome); this->mbiShowWelcomeTab->Checked = true; } } private: System::Void sdcWelcome_Closed(System::Object * sender, System::EventArgs * e) { this->mbiShowWelcomeTab->Checked = false; } private: System::Void sdcSearch_Closed(System::Object * sender, System::EventArgs * e) { this->mbiSearchPaneSelect->Checked = false; } private: System::Void sdcOptions_Closed(System::Object * sender, System::EventArgs * e) { this->mbiOptionsPaneSelect->Checked = false; } private: System::Void sdcWelcome_Closing(System::Object * sender, System::ComponentModel::CancelEventArgs * e) { } }; }
[ "hyperfusion@8d202536-25f0-0310-b7fd-af1e855a3320" ]
[ [ [ 1, 616 ] ] ]
a07417b520fbb62e72bcf20697dcff2fd7ff61e5
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKitTools/WebKitTestRunner/InjectedBundle/InjectedBundlePage.cpp
a5680158601f6325fccb0035c69fa778d52aa642
[]
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
28,155
cpp
/* * Copyright (C) 2010 Apple 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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "InjectedBundlePage.h" #include "InjectedBundle.h" #include "StringFunctions.h" #include <JavaScriptCore/JSRetainPtr.h> #include <WebKit2/WKArray.h> #include <WebKit2/WKBundleFrame.h> #include <WebKit2/WKBundleFramePrivate.h> #include <WebKit2/WKBundleNode.h> #include <WebKit2/WKBundlePagePrivate.h> #include <WebKit2/WKRetainPtr.h> #include <WebKit2/WKBundleRange.h> #include <WebKit2/WKBundleScriptWorld.h> using namespace std; namespace WTR { static ostream& operator<<(ostream& out, WKBundleFrameRef frame) { WKRetainPtr<WKStringRef> name(AdoptWK, WKBundleFrameCopyName(frame)); if (WKBundleFrameIsMainFrame(frame)) { if (!WKStringIsEmpty(name.get())) out << "main frame \"" << name << "\""; else out << "main frame"; } else { if (!WKStringIsEmpty(name.get())) out << "frame \"" << name << "\""; else out << "frame (anonymous)"; } return out; } static string dumpPath(WKBundleNodeRef node) { if (!node) return "(null)"; WKRetainPtr<WKStringRef> nodeName(AdoptWK, WKBundleNodeCopyNodeName(node)); ostringstream out; out << nodeName; if (WKBundleNodeRef parent = WKBundleNodeGetParent(node)) out << " > " << dumpPath(parent); return out.str(); } static ostream& operator<<(ostream& out, WKBundleRangeRef rangeRef) { if (rangeRef) out << "range from " << WKBundleRangeGetStartOffset(rangeRef) << " of " << dumpPath(WKBundleRangeGetStartContainer(rangeRef)) << " to " << WKBundleRangeGetEndOffset(rangeRef) << " of " << dumpPath(WKBundleRangeGetEndContainer(rangeRef)); else out << "(null)"; return out; } static ostream& operator<<(ostream& out, WKBundleCSSStyleDeclarationRef style) { // DumpRenderTree calls -[DOMCSSStyleDeclaration description], which just dumps class name and object address. // No existing tests actually hit this code path at the time of this writing, because WebCore doesn't call // the editing client if the styling operation source is CommandFromDOM or CommandFromDOMWithUserInterface. out << "<DOMCSSStyleDeclaration ADDRESS>"; return out; } InjectedBundlePage::InjectedBundlePage(WKBundlePageRef page) : m_page(page) , m_isLoading(false) { WKBundlePageLoaderClient loaderClient = { 0, this, didStartProvisionalLoadForFrame, didReceiveServerRedirectForProvisionalLoadForFrame, didFailProvisionalLoadWithErrorForFrame, didCommitLoadForFrame, didFinishDocumentLoadForFrame, didFinishLoadForFrame, didFailLoadWithErrorForFrame, didReceiveTitleForFrame, didClearWindowForFrame, didCancelClientRedirectForFrame, willPerformClientRedirectForFrame, didChangeLocationWithinPageForFrame, didHandleOnloadEventsForFrame, didDisplayInsecureContentForFrame, didRunInsecureContentForFrame }; WKBundlePageSetLoaderClient(m_page, &loaderClient); WKBundlePageUIClient uiClient = { 0, this, willAddMessageToConsole, willSetStatusbarText, willRunJavaScriptAlert, willRunJavaScriptConfirm, willRunJavaScriptPrompt }; WKBundlePageSetUIClient(m_page, &uiClient); WKBundlePageEditorClient editorClient = { 0, this, shouldBeginEditing, shouldEndEditing, shouldInsertNode, shouldInsertText, shouldDeleteRange, shouldChangeSelectedRange, shouldApplyStyle, didBeginEditing, didEndEditing, didChange, didChangeSelection }; WKBundlePageSetEditorClient(m_page, &editorClient); } InjectedBundlePage::~InjectedBundlePage() { } void InjectedBundlePage::stopLoading() { WKBundlePageStopLoading(m_page); m_isLoading = false; } void InjectedBundlePage::reset() { WKBundlePageClearMainFrameName(m_page); WKBundlePageSetPageZoomFactor(m_page, 1); WKBundlePageSetTextZoomFactor(m_page, 1); } // Loader Client Callbacks void InjectedBundlePage::didStartProvisionalLoadForFrame(WKBundlePageRef page, WKBundleFrameRef frame, const void *clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->didStartProvisionalLoadForFrame(frame); } void InjectedBundlePage::didReceiveServerRedirectForProvisionalLoadForFrame(WKBundlePageRef page, WKBundleFrameRef frame, const void *clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->didReceiveServerRedirectForProvisionalLoadForFrame(frame); } void InjectedBundlePage::didFailProvisionalLoadWithErrorForFrame(WKBundlePageRef page, WKBundleFrameRef frame, const void *clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->didFailProvisionalLoadWithErrorForFrame(frame); } void InjectedBundlePage::didCommitLoadForFrame(WKBundlePageRef page, WKBundleFrameRef frame, const void *clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->didCommitLoadForFrame(frame); } void InjectedBundlePage::didFinishLoadForFrame(WKBundlePageRef page, WKBundleFrameRef frame, const void *clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->didFinishLoadForFrame(frame); } void InjectedBundlePage::didFailLoadWithErrorForFrame(WKBundlePageRef page, WKBundleFrameRef frame, const void *clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->didFailLoadWithErrorForFrame(frame); } void InjectedBundlePage::didReceiveTitleForFrame(WKBundlePageRef page, WKStringRef title, WKBundleFrameRef frame, const void *clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->didReceiveTitleForFrame(title, frame); } void InjectedBundlePage::didClearWindowForFrame(WKBundlePageRef page, WKBundleFrameRef frame, WKBundleScriptWorldRef world, const void *clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->didClearWindowForFrame(frame, world); } void InjectedBundlePage::didCancelClientRedirectForFrame(WKBundlePageRef page, WKBundleFrameRef frame, const void* clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->didCancelClientRedirectForFrame(frame); } void InjectedBundlePage::willPerformClientRedirectForFrame(WKBundlePageRef page, WKBundleFrameRef frame, WKURLRef url, double delay, double date, const void* clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->willPerformClientRedirectForFrame(frame, url, delay, date); } void InjectedBundlePage::didChangeLocationWithinPageForFrame(WKBundlePageRef page, WKBundleFrameRef frame, const void* clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->didChangeLocationWithinPageForFrame(frame); } void InjectedBundlePage::didFinishDocumentLoadForFrame(WKBundlePageRef page, WKBundleFrameRef frame, const void* clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->didFinishDocumentLoadForFrame(frame); } void InjectedBundlePage::didHandleOnloadEventsForFrame(WKBundlePageRef page, WKBundleFrameRef frame, const void* clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->didHandleOnloadEventsForFrame(frame); } void InjectedBundlePage::didDisplayInsecureContentForFrame(WKBundlePageRef page, WKBundleFrameRef frame, const void* clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->didDisplayInsecureContentForFrame(frame); } void InjectedBundlePage::didRunInsecureContentForFrame(WKBundlePageRef page, WKBundleFrameRef frame, const void* clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->didRunInsecureContentForFrame(frame); } void InjectedBundlePage::didStartProvisionalLoadForFrame(WKBundleFrameRef frame) { if (!InjectedBundle::shared().isTestRunning()) return; if (frame == WKBundlePageGetMainFrame(m_page)) m_isLoading = true; } void InjectedBundlePage::didReceiveServerRedirectForProvisionalLoadForFrame(WKBundleFrameRef frame) { } void InjectedBundlePage::didFailProvisionalLoadWithErrorForFrame(WKBundleFrameRef frame) { } void InjectedBundlePage::didCommitLoadForFrame(WKBundleFrameRef frame) { } static JSValueRef propertyValue(JSContextRef context, JSObjectRef object, const char* propertyName) { if (!object) return 0; JSRetainPtr<JSStringRef> propertyNameString(Adopt, JSStringCreateWithUTF8CString(propertyName)); JSValueRef exception; return JSObjectGetProperty(context, object, propertyNameString.get(), &exception); } static double numericWindowPropertyValue(WKBundleFrameRef frame, const char* propertyName) { JSGlobalContextRef context = WKBundleFrameGetJavaScriptContext(frame); JSValueRef value = propertyValue(context, JSContextGetGlobalObject(context), propertyName); if (!value) return 0; JSValueRef exception; return JSValueToNumber(context, value, &exception); } enum FrameNamePolicy { ShouldNotIncludeFrameName, ShouldIncludeFrameName }; static void dumpFrameScrollPosition(WKBundleFrameRef frame, FrameNamePolicy shouldIncludeFrameName = ShouldNotIncludeFrameName) { double x = numericWindowPropertyValue(frame, "pageXOffset"); double y = numericWindowPropertyValue(frame, "pageYOffset"); if (fabs(x) > 0.00000001 || fabs(y) > 0.00000001) { if (shouldIncludeFrameName) { WKRetainPtr<WKStringRef> name(AdoptWK, WKBundleFrameCopyName(frame)); InjectedBundle::shared().os() << "frame '" << name << "' "; } InjectedBundle::shared().os() << "scrolled to " << x << "," << y << "\n"; } } static void dumpDescendantFrameScrollPositions(WKBundleFrameRef frame) { WKRetainPtr<WKArrayRef> childFrames(AdoptWK, WKBundleFrameCopyChildFrames(frame)); size_t size = WKArrayGetSize(childFrames.get()); for (size_t i = 0; i < size; ++i) { WKBundleFrameRef subframe = static_cast<WKBundleFrameRef>(WKArrayGetItemAtIndex(childFrames.get(), i)); dumpFrameScrollPosition(subframe, ShouldIncludeFrameName); dumpDescendantFrameScrollPositions(subframe); } } void InjectedBundlePage::dumpAllFrameScrollPositions() { WKBundleFrameRef frame = WKBundlePageGetMainFrame(m_page); dumpFrameScrollPosition(frame); dumpDescendantFrameScrollPositions(frame); } static void dumpFrameText(WKBundleFrameRef frame) { WKRetainPtr<WKStringRef> text(AdoptWK, WKBundleFrameCopyInnerText(frame)); InjectedBundle::shared().os() << text << "\n"; } static void dumpDescendantFramesText(WKBundleFrameRef frame) { WKRetainPtr<WKArrayRef> childFrames(AdoptWK, WKBundleFrameCopyChildFrames(frame)); size_t size = WKArrayGetSize(childFrames.get()); for (size_t i = 0; i < size; ++i) { WKBundleFrameRef subframe = static_cast<WKBundleFrameRef>(WKArrayGetItemAtIndex(childFrames.get(), i)); WKRetainPtr<WKStringRef> subframeName(AdoptWK, WKBundleFrameCopyName(subframe)); InjectedBundle::shared().os() << "\n--------\nFrame: '" << subframeName << "'\n--------\n"; dumpFrameText(subframe); dumpDescendantFramesText(subframe); } } void InjectedBundlePage::dumpAllFramesText() { WKBundleFrameRef frame = WKBundlePageGetMainFrame(m_page); dumpFrameText(frame); dumpDescendantFramesText(frame); } void InjectedBundlePage::dump() { ASSERT(InjectedBundle::shared().isTestRunning()); InjectedBundle::shared().layoutTestController()->invalidateWaitToDumpWatchdog(); switch (InjectedBundle::shared().layoutTestController()->whatToDump()) { case LayoutTestController::RenderTree: { WKRetainPtr<WKStringRef> text(AdoptWK, WKBundlePageCopyRenderTreeExternalRepresentation(m_page)); InjectedBundle::shared().os() << text; break; } case LayoutTestController::MainFrameText: dumpFrameText(WKBundlePageGetMainFrame(m_page)); break; case LayoutTestController::AllFramesText: dumpAllFramesText(); break; } if (InjectedBundle::shared().layoutTestController()->shouldDumpAllFrameScrollPositions()) dumpAllFrameScrollPositions(); else if (InjectedBundle::shared().layoutTestController()->shouldDumpMainFrameScrollPosition()) dumpFrameScrollPosition(WKBundlePageGetMainFrame(m_page)); InjectedBundle::shared().done(); } void InjectedBundlePage::didFinishLoadForFrame(WKBundleFrameRef frame) { if (!InjectedBundle::shared().isTestRunning()) return; if (!WKBundleFrameIsMainFrame(frame)) return; m_isLoading = false; if (this != InjectedBundle::shared().page()) return; if (InjectedBundle::shared().layoutTestController()->waitToDump()) return; dump(); } void InjectedBundlePage::didFailLoadWithErrorForFrame(WKBundleFrameRef frame) { if (!InjectedBundle::shared().isTestRunning()) return; if (!WKBundleFrameIsMainFrame(frame)) return; m_isLoading = false; if (this != InjectedBundle::shared().page()) return; InjectedBundle::shared().done(); } void InjectedBundlePage::didReceiveTitleForFrame(WKStringRef title, WKBundleFrameRef frame) { if (!InjectedBundle::shared().isTestRunning()) return; if (!InjectedBundle::shared().layoutTestController()->shouldDumpTitleChanges()) return; InjectedBundle::shared().os() << "TITLE CHANGED: " << title << "\n"; } void InjectedBundlePage::didClearWindowForFrame(WKBundleFrameRef frame, WKBundleScriptWorldRef world) { if (!InjectedBundle::shared().isTestRunning()) return; if (WKBundleScriptWorldNormalWorld() != world) return; JSGlobalContextRef context = WKBundleFrameGetJavaScriptContextForWorld(frame, world); JSObjectRef window = JSContextGetGlobalObject(context); JSValueRef exception = 0; InjectedBundle::shared().layoutTestController()->makeWindowObject(context, window, &exception); InjectedBundle::shared().gcController()->makeWindowObject(context, window, &exception); InjectedBundle::shared().eventSendingController()->makeWindowObject(context, window, &exception); } void InjectedBundlePage::didCancelClientRedirectForFrame(WKBundleFrameRef frame) { } void InjectedBundlePage::willPerformClientRedirectForFrame(WKBundleFrameRef frame, WKURLRef url, double delay, double date) { } void InjectedBundlePage::didChangeLocationWithinPageForFrame(WKBundleFrameRef frame) { } void InjectedBundlePage::didFinishDocumentLoadForFrame(WKBundleFrameRef frame) { if (!InjectedBundle::shared().isTestRunning()) return; unsigned pendingFrameUnloadEvents = WKBundleFrameGetPendingUnloadCount(frame); if (pendingFrameUnloadEvents) InjectedBundle::shared().os() << frame << " - has " << pendingFrameUnloadEvents << " onunload handler(s)\n"; } void InjectedBundlePage::didHandleOnloadEventsForFrame(WKBundleFrameRef frame) { } void InjectedBundlePage::didDisplayInsecureContentForFrame(WKBundleFrameRef frame) { } void InjectedBundlePage::didRunInsecureContentForFrame(WKBundleFrameRef frame) { } // UI Client Callbacks void InjectedBundlePage::willAddMessageToConsole(WKBundlePageRef page, WKStringRef message, uint32_t lineNumber, const void *clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->willAddMessageToConsole(message, lineNumber); } void InjectedBundlePage::willSetStatusbarText(WKBundlePageRef page, WKStringRef statusbarText, const void *clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->willSetStatusbarText(statusbarText); } void InjectedBundlePage::willRunJavaScriptAlert(WKBundlePageRef page, WKStringRef message, WKBundleFrameRef frame, const void *clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->willRunJavaScriptAlert(message, frame); } void InjectedBundlePage::willRunJavaScriptConfirm(WKBundlePageRef page, WKStringRef message, WKBundleFrameRef frame, const void *clientInfo) { return static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->willRunJavaScriptConfirm(message, frame); } void InjectedBundlePage::willRunJavaScriptPrompt(WKBundlePageRef page, WKStringRef message, WKStringRef defaultValue, WKBundleFrameRef frame, const void *clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->willRunJavaScriptPrompt(message, defaultValue, frame); } void InjectedBundlePage::willAddMessageToConsole(WKStringRef message, uint32_t lineNumber) { if (!InjectedBundle::shared().isTestRunning()) return; // FIXME: Strip file: urls. InjectedBundle::shared().os() << "CONSOLE MESSAGE: line " << lineNumber << ": " << message << "\n"; } void InjectedBundlePage::willSetStatusbarText(WKStringRef statusbarText) { if (!InjectedBundle::shared().isTestRunning()) return; if (!InjectedBundle::shared().layoutTestController()->shouldDumpStatusCallbacks()) return; InjectedBundle::shared().os() << "UI DELEGATE STATUS CALLBACK: setStatusText:" << statusbarText << "\n"; } void InjectedBundlePage::willRunJavaScriptAlert(WKStringRef message, WKBundleFrameRef) { if (!InjectedBundle::shared().isTestRunning()) return; InjectedBundle::shared().os() << "ALERT: " << message << "\n"; } void InjectedBundlePage::willRunJavaScriptConfirm(WKStringRef message, WKBundleFrameRef) { if (!InjectedBundle::shared().isTestRunning()) return; InjectedBundle::shared().os() << "CONFIRM: " << message << "\n"; } void InjectedBundlePage::willRunJavaScriptPrompt(WKStringRef message, WKStringRef defaultValue, WKBundleFrameRef) { InjectedBundle::shared().os() << "PROMPT: " << message << ", default text: " << defaultValue << "\n"; } // Editor Client Callbacks bool InjectedBundlePage::shouldBeginEditing(WKBundlePageRef page, WKBundleRangeRef range, const void* clientInfo) { return static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->shouldBeginEditing(range); } bool InjectedBundlePage::shouldEndEditing(WKBundlePageRef page, WKBundleRangeRef range, const void* clientInfo) { return static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->shouldEndEditing(range); } bool InjectedBundlePage::shouldInsertNode(WKBundlePageRef page, WKBundleNodeRef node, WKBundleRangeRef rangeToReplace, WKInsertActionType action, const void* clientInfo) { return static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->shouldInsertNode(node, rangeToReplace, action); } bool InjectedBundlePage::shouldInsertText(WKBundlePageRef page, WKStringRef text, WKBundleRangeRef rangeToReplace, WKInsertActionType action, const void* clientInfo) { return static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->shouldInsertText(text, rangeToReplace, action); } bool InjectedBundlePage::shouldDeleteRange(WKBundlePageRef page, WKBundleRangeRef range, const void* clientInfo) { return static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->shouldDeleteRange(range); } bool InjectedBundlePage::shouldChangeSelectedRange(WKBundlePageRef page, WKBundleRangeRef fromRange, WKBundleRangeRef toRange, WKAffinityType affinity, bool stillSelecting, const void* clientInfo) { return static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->shouldChangeSelectedRange(fromRange, toRange, affinity, stillSelecting); } bool InjectedBundlePage::shouldApplyStyle(WKBundlePageRef page, WKBundleCSSStyleDeclarationRef style, WKBundleRangeRef range, const void* clientInfo) { return static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->shouldApplyStyle(style, range); } void InjectedBundlePage::didBeginEditing(WKBundlePageRef page, WKStringRef notificationName, const void* clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->didBeginEditing(notificationName); } void InjectedBundlePage::didEndEditing(WKBundlePageRef page, WKStringRef notificationName, const void* clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->didEndEditing(notificationName); } void InjectedBundlePage::didChange(WKBundlePageRef page, WKStringRef notificationName, const void* clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->didChange(notificationName); } void InjectedBundlePage::didChangeSelection(WKBundlePageRef page, WKStringRef notificationName, const void* clientInfo) { static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->didChangeSelection(notificationName); } bool InjectedBundlePage::shouldBeginEditing(WKBundleRangeRef range) { if (!InjectedBundle::shared().isTestRunning()) return true; if (InjectedBundle::shared().layoutTestController()->shouldDumpEditingCallbacks()) InjectedBundle::shared().os() << "EDITING DELEGATE: shouldBeginEditingInDOMRange:" << range << "\n"; return InjectedBundle::shared().layoutTestController()->shouldAllowEditing(); } bool InjectedBundlePage::shouldEndEditing(WKBundleRangeRef range) { if (!InjectedBundle::shared().isTestRunning()) return true; if (InjectedBundle::shared().layoutTestController()->shouldDumpEditingCallbacks()) InjectedBundle::shared().os() << "EDITING DELEGATE: shouldEndEditingInDOMRange:" << range << "\n"; return InjectedBundle::shared().layoutTestController()->shouldAllowEditing(); } bool InjectedBundlePage::shouldInsertNode(WKBundleNodeRef node, WKBundleRangeRef rangeToReplace, WKInsertActionType action) { if (!InjectedBundle::shared().isTestRunning()) return true; static const char* insertactionstring[] = { "WebViewInsertActionTyped", "WebViewInsertActionPasted", "WebViewInsertActionDropped", }; if (InjectedBundle::shared().layoutTestController()->shouldDumpEditingCallbacks()) InjectedBundle::shared().os() << "EDITING DELEGATE: shouldInsertNode:" << dumpPath(node) << " replacingDOMRange:" << rangeToReplace << " givenAction:" << insertactionstring[action] << "\n"; return InjectedBundle::shared().layoutTestController()->shouldAllowEditing(); } bool InjectedBundlePage::shouldInsertText(WKStringRef text, WKBundleRangeRef rangeToReplace, WKInsertActionType action) { if (!InjectedBundle::shared().isTestRunning()) return true; static const char *insertactionstring[] = { "WebViewInsertActionTyped", "WebViewInsertActionPasted", "WebViewInsertActionDropped", }; if (InjectedBundle::shared().layoutTestController()->shouldDumpEditingCallbacks()) InjectedBundle::shared().os() << "EDITING DELEGATE: shouldInsertText:" << text << " replacingDOMRange:" << rangeToReplace << " givenAction:" << insertactionstring[action] << "\n"; return InjectedBundle::shared().layoutTestController()->shouldAllowEditing(); } bool InjectedBundlePage::shouldDeleteRange(WKBundleRangeRef range) { if (!InjectedBundle::shared().isTestRunning()) return true; if (InjectedBundle::shared().layoutTestController()->shouldDumpEditingCallbacks()) InjectedBundle::shared().os() << "EDITING DELEGATE: shouldDeleteDOMRange:" << range << "\n"; return InjectedBundle::shared().layoutTestController()->shouldAllowEditing(); } bool InjectedBundlePage::shouldChangeSelectedRange(WKBundleRangeRef fromRange, WKBundleRangeRef toRange, WKAffinityType affinity, bool stillSelecting) { if (!InjectedBundle::shared().isTestRunning()) return true; static const char *affinitystring[] = { "NSSelectionAffinityUpstream", "NSSelectionAffinityDownstream" }; static const char *boolstring[] = { "FALSE", "TRUE" }; if (InjectedBundle::shared().layoutTestController()->shouldDumpEditingCallbacks()) InjectedBundle::shared().os() << "EDITING DELEGATE: shouldChangeSelectedDOMRange:" << fromRange << " toDOMRange:" << toRange << " affinity:" << affinitystring[affinity] << " stillSelecting:" << boolstring[stillSelecting] << "\n"; return InjectedBundle::shared().layoutTestController()->shouldAllowEditing(); } bool InjectedBundlePage::shouldApplyStyle(WKBundleCSSStyleDeclarationRef style, WKBundleRangeRef range) { if (!InjectedBundle::shared().isTestRunning()) return true; if (InjectedBundle::shared().layoutTestController()->shouldDumpEditingCallbacks()) InjectedBundle::shared().os() << "EDITING DELEGATE: shouldApplyStyle:" << style << " toElementsInDOMRange:" << range << "\n"; return InjectedBundle::shared().layoutTestController()->shouldAllowEditing(); } void InjectedBundlePage::didBeginEditing(WKStringRef notificationName) { if (!InjectedBundle::shared().isTestRunning()) return; if (InjectedBundle::shared().layoutTestController()->shouldDumpEditingCallbacks()) InjectedBundle::shared().os() << "EDITING DELEGATE: webViewDidBeginEditing:" << notificationName << "\n"; } void InjectedBundlePage::didEndEditing(WKStringRef notificationName) { if (!InjectedBundle::shared().isTestRunning()) return; if (InjectedBundle::shared().layoutTestController()->shouldDumpEditingCallbacks()) InjectedBundle::shared().os() << "EDITING DELEGATE: webViewDidEndEditing:" << notificationName << "\n"; } void InjectedBundlePage::didChange(WKStringRef notificationName) { if (!InjectedBundle::shared().isTestRunning()) return; if (InjectedBundle::shared().layoutTestController()->shouldDumpEditingCallbacks()) InjectedBundle::shared().os() << "EDITING DELEGATE: webViewDidChange:" << notificationName << "\n"; } void InjectedBundlePage::didChangeSelection(WKStringRef notificationName) { if (!InjectedBundle::shared().isTestRunning()) return; if (InjectedBundle::shared().layoutTestController()->shouldDumpEditingCallbacks()) InjectedBundle::shared().os() << "EDITING DELEGATE: webViewDidChangeSelection:" << notificationName << "\n"; } } // namespace WTR
[ [ [ 1, 719 ] ] ]
554ad73b6e7411e1ee35cbbc137c7c8f5b1cb485
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/web/favourites_api/src/FavouritesItemTestCases.cpp
b2582d6a28104f71b974801ea7413cb341e5b258
[]
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
42,826
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: * * */ // INCLUDE FILES #include <e32math.h> #include "FavouritesBCTest.h" // EXTERNAL DATA STRUCTURES // None // EXTERNAL FUNCTION PROTOTYPES // None // CONSTANTS // None // MACROS // None // LOCAL CONSTANTS AND MACROS // None // MODULE DATA STRUCTURES // None // LOCAL FUNCTION PROTOTYPES // None // FORWARD DECLARATIONS // None // ==================== LOCAL FUNCTIONS ======================================= /* ------------------------------------------------------------------------------- DESCRIPTION This module contains the implementation of CTestModuleDemo class member functions that does the actual tests. ------------------------------------------------------------------------------- */ // ============================ MEMBER FUNCTIONS =============================== /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemNewLCTestL Description: Test creating a new favourites item with the NewLC method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemNewLCTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Creating item with NewLC method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (item) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemNewLTestL Description: Test creating a new favourites item with the NewL method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemNewLTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Creating item with NewL method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewL(); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (item) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); delete item; } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemDestructorTestL Description: Test destroying an item with the ~CFavouritesItem method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemDestructorTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Destroying item with ~CFavouritesItem method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewL(); // item->~CFavouritesItem(); delete item; _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemAssignTestL Description: Assigning one item to another with the Assign(=) method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemAssignTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Assigning item with Assign(=) operator"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item1 = CFavouritesItem::NewLC(); item1->SetNameL( _L("Item1") ); CFavouritesItem* item2 = CFavouritesItem::NewLC(); item2->SetNameL( _L("Item2") ); *item1 = *item2; _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (item1->Name() == item2->Name()) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( 2 ); // item1, item2 // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemUidTestL Description: Test getting the item's Uid using the Uid method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemUidTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Getting item's Uid with Uid method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); TInt itemUid = item->Uid(); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (itemUid == 0) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemParentFolderTestL Description: Test getting the item's parent folder using the ParentFolder method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemParentFolderTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Getting item's parent folder with ParentFolder method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); TInt itemParent = item->ParentFolder(); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (itemParent == 0) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemTypeTestL Description: Test getting the item's type using the Type method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemTypeTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Getting item's type with Type method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); TInt itemType = item->Type(); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (itemType == 1) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemNameTestL Description: Test getting the item's name using the Name method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemNameTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Getting item's name with Name method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); TPtrC itemName = item->Name(); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); _LIT( KItemName ,""); if (itemName == KItemName) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemUrlTestL Description: Test getting the item's url using the Url method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemUrlTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Getting item's url with Url method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); TPtrC itemUrl = item->Url(); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); _LIT( KItemUrl ,""); if (itemUrl == KItemUrl) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemWapApTestL Description: Test getting the item's access point using the WapAp method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemWapApTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Getting item's access point with WapAp method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); TFavouritesWapAp itemAP = item->WapAp(); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (itemAP.IsDefault()) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemUserNameTestL Description: Test getting the item's user name using the UserName method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemUserNameTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Getting item's user name with UserName method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); TPtrC itemUserName = item->UserName(); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); _LIT( KItemUserName ,""); if (itemUserName == KItemUserName) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemPasswordTestL Description: Test getting the item's password using the Password method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemPasswordTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Getting item's password with Password method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); TPtrC itemPassword = item->Password(); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); _LIT( KItemPassword ,""); if (itemPassword == KItemPassword) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemContextIdTestL Description: Test getting the item's context id using the ContextId method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemContextIdTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Getting item's context id with ContextId method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); TInt32 itemContextId = item->ContextId(); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (itemContextId == 0) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemIsItemTestL Description: Test if the item is an item using the IsItem method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemIsItemTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Checking if the item is an item with IsItem method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); TBool itemIsItem = item->IsItem(); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (itemIsItem) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemIsFolderTestL Description: Test if the item is a folder using the IsFolder method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemIsFolderTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Checking if the item is a folder with IsFolder method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); TBool itemIsFolder = item->IsFolder(); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (!itemIsFolder) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemIsFactoryItemTestL Description: Test if the item is a factory item using the IsFactoryItem method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemIsFactoryItemTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Checking if the item is a factory item with IsFactory method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); TBool itemIsFactoryItem = item->IsFactoryItem(); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (!itemIsFactoryItem) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemIsReadOnlyTestL Description: Test if the item is read-only using the IsReadOnly method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemIsReadOnlyTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Checking if the item is read-only item with IsReadOnly method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); TBool itemIsReadOnly = item->IsReadOnly(); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (!itemIsReadOnly) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemModifiedTestL Description: Test getting the last modified time using the Modified method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemModifiedTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Getting the item's last modified time with Modified method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); TTime itemModified = item->Modified(); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (itemModified != NULL) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemClearLTestL Description: Test clearing the item using the ClearL method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemClearLTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Clearing the item with ClearL method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); item->SetType(CFavouritesItem::EFolder); item->SetNameL( _L("Item Name") ); item->ClearL(); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if ((item->Type() == CFavouritesItem::EFolder) || (item->Name() == _L("Item Name"))) { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } else { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemSetParentFolderTestL Description: Test setting the item's parent folder using the SetParentFolder method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemSetParentFolderTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Setting the item's parent folder with SetParentFolder method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); item->SetParentFolder(3); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (item->ParentFolder() == 3) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemSetTypeTestL Description: Test setting the item's type using the SetType method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemSetTypeTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Setting the item's type with SetType method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); item->SetType(CFavouritesItem::EFolder); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (item->Type() == CFavouritesItem::EFolder) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemSetNameLTestL Description: Test setting the item's name using the SetNameL method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemSetNameLTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Setting the item's name with SetNameL method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); item->SetNameL( _L("Item Name") ); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (item->Name() == _L("Item Name")) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemSetUrlLTestL Description: Test setting the item's url using the SetUrlL method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemSetUrlLTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Setting the item's url with SetUrlL method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); item->SetUrlL( _L("http://www.nokia.com") ); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (item->Url() == _L("http://www.nokia.com")) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemSetWapApTestL Description: Test setting the item's access point using the SetWapAp method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemSetWapApTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Setting the item's access point with SetWapAp method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); TFavouritesWapAp accessPoint; accessPoint.SetApId( 22 ); item->SetWapAp( accessPoint ); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (item->WapAp().ApId() == 22) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemSetUserNameLTestL Description: Test setting the item's user name using the SetUserNameL method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemSetUserNameLTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Setting the item's user name with SetUserNameL method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); item->SetUserNameL( _L("New User") ); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (item->UserName() == _L("New User")) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemSetPasswordLTestL Description: Test setting the item's password using the SetPasswordL method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemSetPasswordLTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Setting the item's password with SetPasswordL method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); item->SetPasswordL( _L("12345") ); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (item->Password() == _L("12345")) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemSetContextIdTestL Description: Test setting the item's context id using the SetContextId method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemSetContextIdTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Setting the item's context id with SetContextId method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); item->SetContextId(22); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (item->ContextId() == 22) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemIsHiddenTestL Description: Test if the item is hidden using the IsHidden method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemIsHiddenTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Checking if the item is hidden item with IsHidden method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); TBool itemIsHidden = item->IsHidden(); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (!itemIsHidden) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CFavouritesBCTest Method: ItemSetHiddenTestL Description: Test setting the item's hidden value using the SetHidden method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Approved ------------------------------------------------------------------------------- */ TInt CFavouritesBCTest::ItemSetHiddenTestL( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Setting the item's hidden value with SetHidden method"); TestModuleIf().Printf( 0, KDefinition, KData ); CFavouritesItem* item = CFavouritesItem::NewLC(); item->SetHidden(1); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if (item->IsHidden() == 1) { _LIT( KDescription , "Test case passed"); aResult.SetResult( KErrNone, KDescription ); } else { _LIT( KDescription , "Test case failed"); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy( item ); // Case was executed return KErrNone; } // ================= OTHER EXPORTED FUNCTIONS ================================= // End of File
[ "none@none" ]
[ [ [ 1, 1546 ] ] ]
0ad1ef6d8d885f973a52cea3aef3625ee8bff283
2a47a0a9749be9adae403d99f6392f9d412fca53
/OpenGL/Puppet/IGUANA_animated_textured.cpp
c706692978959c941e449cce7a4b127b49b04995
[]
no_license
waseemilahi/waseem
153bed6788475a88d234d75a323049a9d8ec47fe
0bb2bddcc8758477f0ad5db85bfc927db2ae07af
refs/heads/master
2020-03-30T14:59:17.066002
2008-11-22T01:21:04
2008-11-22T01:21:04
32,640,847
0
0
null
null
null
null
UTF-8
C++
false
false
15,473
cpp
/*Puppet Program by Waseem Ilahi*/ #include <Windows.h> #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> //Prototypes. void DrawTail(void); void DrawLegs(void); void DrawNeck(void); void DrawFace(void); void DrawEyes(void); float dist = -15.0; /* distance from camera to object */ float yaw = 0.0; /* rotate about Y axis */ float pitch = 0.0; /* rotate about X axis */ /* shading values */ float ambiantmat[]={0.19225}; float diffusemat[]={0.50754}; float specularmat[]={0.508273}; float shininessmat=51.2; float ambiantmattail[]={0.0}; float diffusemattail[]={0.01}; float specularmattail[]={0.5}; float tailshininessmat=32; float ambiantmatlegs[]={0.0}; float diffusematlegs[]={0.01}; float specularmatlegs[]={0.5}; float legsshininessmat=32; float ambiantmateyes[]={0.0}; float diffusemateyes[]={0.01}; float specularmateyes[]={0.5}; float eyesshininessmat=32; int rgb = GL_TRUE; int doubleBuffer = GL_TRUE; int windType; GLint windW, windH; GLUquadricObj *myQuadricObj; /* named parts of the iguana */ #define IGUANA_NONE 0 #define IGUANA_BODY 1 #define IGUANA_TAIL 2 #define IGUANA_LEFT_FRONT_LEG 3 #define IGUANA_RIGHT_FRONT_LEG 4 #define IGUANA_LEFT_HIND_LEG 5 #define IGUANA_RIGHT_HIND_LEG 6 #define IGUANA_NECK 7 #define IGUANA_RESET 8 int picked = IGUANA_NONE; /* transformation parameters */ GLdouble translate_increment; float Iguana_position[3] = {0.0, 0.0, 0.0}; float front_LLangle = 0.0; float front_RLangle = 0.0; float hind_LLangle = 0.0; float hind_RLangle = 0.0; float tail_angle = 0.0; float neck_angle = 0.0; float front_LLangle1 = 0.0; float front_RLangle1 = 0.0; float hind_LLangle1 = 0.0; float hind_RLangle1 = 0.0; float tail_angle1 = 0.0; float neck_angle1 = 0.0; /* Texture values */ #ifdef GL_VERSION_1_1 static GLuint texName; #endif #define TEXTURE_WIDTH 64 #define TEXTURE_HEIGHT 64 GLubyte Picture[TEXTURE_WIDTH][TEXTURE_HEIGHT][4]; /* Array of texels */ static void set_material(GLfloat *ambient, GLfloat *diffuse, GLfloat *specular, GLfloat shininess) { glMaterialfv (GL_FRONT, GL_AMBIENT, ambient); glMaterialfv (GL_FRONT, GL_DIFFUSE, diffuse); glMaterialfv (GL_FRONT, GL_SPECULAR, specular); glMaterialf (GL_FRONT, GL_SHININESS, shininess); } //The init function. static void Init(void) { /* Set background color */ glClearColor(0.2, 0.8, 1.0, 0.0); /* blue sky */ /* Enable depth buffer */ glEnable(GL_DEPTH_TEST); /* Set polygon attributes */ glPolygonMode (GL_FRONT, GL_FILL); //glEnable (GL_CULL_FACE); //glCullFace (GL_BACK); /* Set shading & lighting values*/ glShadeModel (GL_SMOOTH); glEnable (GL_LIGHTING); glEnable (GL_LIGHT0); /* Enable texture mapping */ glEnable(GL_TEXTURE_2D); /* Create quadric object for all of the puppet's parts */ myQuadricObj = gluNewQuadric(); gluQuadricDrawStyle(myQuadricObj, (GLenum)GLU_FILL); gluQuadricNormals(myQuadricObj, (GLenum)GLU_SMOOTH); gluQuadricTexture(myQuadricObj,GL_TRUE); } /* Generate a texture */ void GenerateTexture(void) { /* Generate the texture map */ int i, j; for (j=0; j<TEXTURE_HEIGHT; j++) { for (i=0; i<TEXTURE_WIDTH; i++) { //Creating texture from the function. Picture[i][j][0] = cos(cos(i+j+1)/sin(i+j+1))*255; Picture[i][j][1] = Picture[i][j][2] = 0; Picture[i][j][3] = 255; } } /* Define it as a texture map */ #ifdef GL_VERSION_1_1 glGenTextures(1, &texName); glBindTexture(GL_TEXTURE_2D, texName); #endif glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, TEXTURE_WIDTH, TEXTURE_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, Picture); } /* Window size has changed: adjust viewport and perspective transformations */ static void Reshape(int width, int height) { float aspect; windW = (GLint)width; windH = (GLint)height; aspect = (float)windW / (float)windH; translate_increment=0.1; /* Viewport fills the entire window */ glViewport(0, 0, width, height); /* Use perspective projection */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective (60.0, aspect, 1.0, 1000.0); /* fovy, aspect, near, far */ /* Return to modelview mode */ glMatrixMode(GL_MODELVIEW); } /* Set modeling and viewing transformations, then draw the letter polygons */ #define BUFSIZE 64 #define BODY_RADIUS 2.0 #define NECK_RADIUS 0.8 #define FACE_RADIUS 0.8 #define TOP_RADIUS 1.0 #define LEG_WIDTH 0.25 #define LEG_LENGTH 6.0 /* actually, a scale */ #define LEG_SHIFT 2.25 /* MIDDLE_RADIUS + 1/2 of LEG_LENGTH */ #define TAIL_WIDTH 0.25 #define TAIL_LENGTH 6.0 /* actually, a scale */ static void DrawIguana(void) { /* Transformation for entire Iguana */ glLoadIdentity(); glTranslatef(0.0, 0.0, dist); /* step back */ glRotatef(pitch, 1.0, 0.0, 0.0); /* spin on X axis */ glRotatef(yaw, 0.0, 1.0, 0.0); /* spin on Y axis */ /* Draw the body of the Iguana (The root of the hierarchy) */ glScalef(2.5,1.0,1.0); set_material( ambiantmat, diffusemat, specularmat, shininessmat); glTranslatef(Iguana_position[0], Iguana_position[1], Iguana_position[2]); gluSphere (myQuadricObj, BODY_RADIUS, 50, 50); //Draw Tail. DrawTail(); /* Draw the 4 legs */ DrawLegs(); //Draw the neck and face on it DrawNeck(); } void DrawNeck() { glPushMatrix(); // save Tx for body of Iguana set_material( ambiantmat, diffusemat, specularmat, shininessmat); glRotatef(-25,0.0,0.0,1.0); glTranslatef(-BODY_RADIUS,0.0,0.0); glRotatef(neck_angle,0.0,1.0,0.0); glRotatef(neck_angle1,0.0,0.0,1.0); gluSphere (myQuadricObj, NECK_RADIUS, 50, 50); //Draw the face DrawFace(); glPopMatrix(); // restore Tx for body of Iguana } void DrawFace() { glPushMatrix(); // save Tx for neck of Iguana glRotatef(-10,0.0,0.0,1.0); glScalef(0.5,1.0,1.0); glTranslatef(-NECK_RADIUS-.5,0.0,0.0); gluSphere (myQuadricObj, FACE_RADIUS, 50, 50); //Draw the Eyes DrawEyes(); glPopMatrix(); // restore Tx for neck of Iguana } void DrawEyes() { //Left glPushMatrix(); // save Tx for face of Iguana set_material(ambiantmateyes,diffusemateyes,specularmateyes,eyesshininessmat); glScalef(0.8,1.0,1.0); glTranslatef(-FACE_RADIUS+0.3,0.32,0.5); glutSolidSphere (TOP_RADIUS/6.0, 10, 6); // left eye glPopMatrix(); // restore Tx for face of Iguana //Right glPushMatrix(); // save Tx for face of Iguana set_material(ambiantmateyes,diffusemateyes,specularmateyes,eyesshininessmat); glScalef(0.8,1.0,1.0); glTranslatef(-FACE_RADIUS+0.3,0.32,-0.5); glutSolidSphere (TOP_RADIUS/6.0, 10, 6); // right eye glPopMatrix(); // restore Tx for face of Iguana } void DrawTail() { glPushMatrix(); // save Tx for body of Iguana set_material(ambiantmattail,diffusemattail,specularmattail,tailshininessmat); glRotatef(-5,0.0,0.0,1.0); glTranslatef(BODY_RADIUS-0.6,-0.6,2.0); glRotatef(90,0.0,1.0,0.0); glRotatef(90,0.0,0.0,1.0); glTranslatef(0.0, -BODY_RADIUS, 0.0); glScalef(TAIL_LENGTH/2, 1.0, 1.0); glTranslatef(TAIL_WIDTH/2.0,0.0 , 0.0); glRotatef(-tail_angle,1.0,0.0,0.0); glRotatef(-tail_angle1,0.0,1.0,0.0); gluCylinder(myQuadricObj,0.2,0.0,2.5,40,40); glPopMatrix(); // restore Tx for body of Iguana } void DrawLegs() { //Front left glPushMatrix(); // save Tx for body of Iguana set_material(ambiantmatlegs,diffusematlegs,specularmatlegs,legsshininessmat); glTranslatef(-0.8,-0.7,1.2); glRotatef(90,1.0,0.0,0.0); glRotatef(-front_LLangle,0.0,1.0,0.0); glRotatef(front_LLangle1,1.0,0.0,0.0); gluCylinder(myQuadricObj,0.1,0.025,2,40,40); glPopMatrix(); // restore Tx for body of Iguana //Front right glPushMatrix(); // save Tx for body of Iguana set_material(ambiantmatlegs,diffusematlegs,specularmatlegs,legsshininessmat); glTranslatef(-0.8,-0.7,-1.2); glRotatef(90,1.0,0.0,0.0); glRotatef(-front_RLangle,0.0,1.0,0.0); glRotatef(-front_RLangle1,1.0,0.0,0.0); gluCylinder(myQuadricObj,0.1,0.025,2,40,40); glPopMatrix(); // restore Tx for body of Iguana //Hind left glPushMatrix(); // save Tx for body of Iguana set_material(ambiantmatlegs,diffusematlegs,specularmatlegs,legsshininessmat); glTranslatef(0.8,-0.7,1.2); glRotatef(90,1.0,0.0,0.0); glRotatef(-hind_LLangle,0.0,1.0,0.0); glRotatef(hind_LLangle1,1.0,0.0,0.0); gluCylinder(myQuadricObj,0.1,0.025,2,40,40); glPopMatrix(); // restore Tx for body of Iguana //Hind right glPushMatrix(); // save Tx for body of Iguana set_material(ambiantmatlegs,diffusematlegs,specularmatlegs,legsshininessmat); glTranslatef(0.8,-0.7,-1.2); glRotatef(90,1.0,0.0,0.0); glRotatef(-hind_RLangle,0.0,1.0,0.0); glRotatef(-hind_RLangle1,1.0,0.0,0.0); gluCylinder(myQuadricObj,0.1,0.025,2,40,40); glPopMatrix(); // restore Tx for body of Iguana } static void Draw(void) { /* clear the screen */ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_TEXTURE_2D); glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE); /* draw the Iguana */ DrawIguana(); /* update the screen */ glFlush(); /* force all changes to be applied to buffer */ glutSwapBuffers(); /* display what you just drew */ } /* Arrow keys change angle of rotation */ static void Key2(int key, int x, int y) { switch (key) { case GLUT_KEY_LEFT: /* decrease angle about Y axis */ switch (picked) { case IGUANA_NONE: yaw -= 5.0; break; case IGUANA_BODY: Iguana_position[0] -= translate_increment; break; case IGUANA_LEFT_FRONT_LEG: front_LLangle += 5.0; break; case IGUANA_RIGHT_FRONT_LEG: front_RLangle += 5.0; break; case IGUANA_LEFT_HIND_LEG: hind_LLangle += 5.0; break; case IGUANA_RIGHT_HIND_LEG: hind_RLangle += 5.0; break; case IGUANA_TAIL: tail_angle += 5.0; break; case IGUANA_NECK: neck_angle += 5.0; break; } break; case GLUT_KEY_RIGHT: /* increase angle about Y axis */ switch (picked) { case IGUANA_NONE: yaw += 5.0; break; case IGUANA_BODY: Iguana_position[0] += translate_increment; break; case IGUANA_LEFT_FRONT_LEG: front_LLangle -= 5.0; break; case IGUANA_RIGHT_FRONT_LEG: front_RLangle -= 5.0; break; case IGUANA_LEFT_HIND_LEG: hind_LLangle -= 5.0; break; case IGUANA_RIGHT_HIND_LEG: hind_RLangle -= 5.0; break; case IGUANA_TAIL: tail_angle-= 5.0; break; case IGUANA_NECK: neck_angle -= 5.0; break; } break; case GLUT_KEY_UP: /* decrease angle about Z axis */ switch (picked) { case IGUANA_NONE: pitch -= 5.0; break; case IGUANA_BODY: Iguana_position[1] += translate_increment; break; case IGUANA_LEFT_FRONT_LEG: front_LLangle1 -= 5.0; break; case IGUANA_RIGHT_FRONT_LEG: front_RLangle1 -= 5.0; break; case IGUANA_LEFT_HIND_LEG: hind_LLangle1 -= 5.0; break; case IGUANA_RIGHT_HIND_LEG: hind_RLangle1 -= 5.0; break; case IGUANA_TAIL: tail_angle1 -= 5.0; break; case IGUANA_NECK: neck_angle1 -= 5.0; break; } break; case GLUT_KEY_DOWN: /* increase angle about X axis */ switch (picked) { case IGUANA_NONE: pitch += 5.0; break; case IGUANA_BODY: Iguana_position[1] -= translate_increment; break; case IGUANA_LEFT_FRONT_LEG: front_LLangle1 += 5.0; break; case IGUANA_RIGHT_FRONT_LEG: front_RLangle1 += 5.0; break; case IGUANA_LEFT_HIND_LEG: hind_LLangle1 += 5.0; break; case IGUANA_RIGHT_HIND_LEG: hind_RLangle1 += 5.0; break; case IGUANA_TAIL: tail_angle1 += 5.0; break; case IGUANA_NECK: neck_angle1 += 5.0; break; } break; default: return; } glutPostRedisplay(); /* force update of the display */ } /* Handle other keys */ static void Key(unsigned char key, int x, int y) { switch (key) { case 27: /* ESC to quit */ exit(1); case '+': dist += 1.0; /* move camera closer */ break; case '-': dist -= 1.0; /* move camera back */ break; default: return; } glutPostRedisplay(); /* force update of the display */ } /* Create pop-up window using GLUT */ #define ROTATE_BODY 1 void PopUp (int value) { if (value == IGUANA_RESET) { Iguana_position[0] = 0.0; Iguana_position[1] = 0.0; Iguana_position[2] = 0.0; front_LLangle = 0.0; front_RLangle = 0.0; hind_LLangle = 0.0; hind_RLangle = 0.0; tail_angle = 0.0; neck_angle = 0.0; front_LLangle1 = 0.0; front_RLangle1 = 0.0; hind_LLangle1 = 0.0; hind_RLangle1 = 0.0; tail_angle1 = 0.0; neck_angle1 = 0.0; yaw = 0.0; /* rotate about Y axis */ pitch = 0.0; /* rotate about X axis */ dist = -15.0; /* distance from camera to object */ glPolygonMode (GL_FRONT, GL_FILL); DrawIguana(); glutPostRedisplay(); } else picked = value; } void initMenu(void) { int menuid; /* create a menu and save the id */ menuid = glutCreateMenu(PopUp); /* add menu entries */ glutAddMenuEntry ("Rotate Body", IGUANA_NONE); glutAddMenuEntry ("Move Body", IGUANA_BODY); glutAddMenuEntry ("Move LEFT FRONT LEG", IGUANA_LEFT_FRONT_LEG); glutAddMenuEntry ("Move RIGHT FRONT LEG", IGUANA_RIGHT_FRONT_LEG); glutAddMenuEntry ("Move LEFT HIND LEG", IGUANA_LEFT_HIND_LEG); glutAddMenuEntry ("Move RIGHT HIND LEG", IGUANA_RIGHT_HIND_LEG); glutAddMenuEntry ("Move Tail", IGUANA_TAIL); glutAddMenuEntry ("Move Neck", IGUANA_NECK); glutAddMenuEntry ("Reset", IGUANA_RESET); /* attach menu to right button */ glutAttachMenu (GLUT_RIGHT_BUTTON); } int main() { /* Setup the window that logo will appear in */ windW = 1220; windH = 900; glutInitWindowPosition(10, 10); glutInitWindowSize( windW, windH); windType = GLUT_DEPTH; windType |= (rgb) ? GLUT_RGB : GLUT_INDEX; windType |= (doubleBuffer) ? GLUT_DOUBLE : GLUT_SINGLE; glutInitDisplayMode(( GLenum)windType); if (glutCreateWindow("Iguana") == GL_FALSE) { exit(1); } Init(); GenerateTexture(); initMenu(); glutKeyboardFunc(Key); glutSpecialFunc(Key2); glutReshapeFunc(Reshape); glutDisplayFunc(Draw); glutMainLoop(); return 0; }
[ "waseemilahi@b30cb682-9650-11dd-b20a-03c46e462ecf" ]
[ [ [ 1, 644 ] ] ]
6d4b3ef45947029a010cce8d6c0f950aa10475f8
f89e32cc183d64db5fc4eb17c47644a15c99e104
/pcsx2-rr/pcsx2/x86/iR3000A.cpp
48611e0a5949bb5e61e391d93919f913e1112dba
[]
no_license
mauzus/progenitor
f99b882a48eb47a1cdbfacd2f38505e4c87480b4
7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae
refs/heads/master
2021-01-10T07:24:00.383776
2011-04-28T11:03:43
2011-04-28T11:03:43
45,171,114
0
0
null
null
null
null
UTF-8
C++
false
false
35,688
cpp
/* PCSX2 - PS2 Emulator for PCs * Copyright (C) 2002-2010 PCSX2 Dev Team * * PCSX2 is free software: you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Found- * ation, either version 3 of the License, or (at your option) any later version. * * PCSX2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with PCSX2. * If not, see <http://www.gnu.org/licenses/>. */ // recompiler reworked to add dynamic linking Jan06 // and added reg caching, const propagation, block analysis Jun06 // zerofrog(@gmail.com) #include "PrecompiledHeader.h" #include "iR3000A.h" #include "BaseblockEx.h" #include <time.h> #ifndef _WIN32 #include <sys/types.h> #endif #include "IopCommon.h" #include "iCore.h" #include "SamplProf.h" #include "NakedAsm.h" #include "AppConfig.h" using namespace x86Emitter; extern u32 g_iopNextEventCycle; extern void psxBREAK(); u32 g_psxMaxRecMem = 0; u32 s_psxrecblocks[] = {0}; uptr psxRecLUT[0x10000]; uptr psxhwLUT[0x10000]; #define HWADDR(mem) (psxhwLUT[mem >> 16] + (mem)) #define MAPBASE 0x48000000 #define RECMEM_SIZE (8*1024*1024) // R3000A statics int psxreclog = 0; static u8 *recMem = NULL; // the recompiled blocks will be here static BASEBLOCK *recRAM = NULL; // and the ptr to the blocks here static BASEBLOCK *recROM = NULL; // and here static BASEBLOCK *recROM1 = NULL; // also here static BaseBlocks recBlocks; static u8 *recPtr = NULL; u32 psxpc; // recompiler psxpc int psxbranch; // set for branch u32 g_iopCyclePenalty; static EEINST* s_pInstCache = NULL; static u32 s_nInstCacheSize = 0; static BASEBLOCK* s_pCurBlock = NULL; static BASEBLOCKEX* s_pCurBlockEx = NULL; static u32 s_nEndBlock = 0; // what psxpc the current block ends static u32 s_branchTo; static bool s_nBlockFF; static u32 s_saveConstRegs[32]; static u32 s_saveHasConstReg = 0, s_saveFlushedConstReg = 0; static EEINST* s_psaveInstInfo = NULL; u32 s_psxBlockCycles = 0; // cycles of current block recompiling static u32 s_savenBlockCycles = 0; static void iPsxBranchTest(u32 newpc, u32 cpuBranch); void psxRecompileNextInstruction(int delayslot); extern void (*rpsxBSC[64])(); void rpsxpropBSC(EEINST* prev, EEINST* pinst); static void iopClearRecLUT(BASEBLOCK* base, int count); static u32 psxdump = 0; #define PSX_GETBLOCK(x) PC_GETBLOCK_(x, psxRecLUT) #define PSXREC_CLEARM(mem) \ (((mem) < g_psxMaxRecMem && (psxRecLUT[(mem) >> 16] + (mem))) ? \ psxRecClearMem(mem) : 4) // ===================================================================================================== // Dynamically Compiled Dispatchers - R3000A style // ===================================================================================================== static void __fastcall iopRecRecompile( const u32 startpc ); static u32 s_store_ebp, s_store_esp; // Recompiled code buffer for EE recompiler dispatchers! static u8 __pagealigned iopRecDispatchers[__pagesize]; typedef void DynGenFunc(); static DynGenFunc* iopDispatcherEvent = NULL; static DynGenFunc* iopDispatcherReg = NULL; static DynGenFunc* iopJITCompile = NULL; static DynGenFunc* iopJITCompileInBlock = NULL; static DynGenFunc* iopEnterRecompiledCode = NULL; static DynGenFunc* iopExitRecompiledCode = NULL; static void recEventTest() { _cpuEventTest_Shared(); } // parameters: // espORebp - 0 for ESP, or 1 for EBP. // regval - current value of the register at the time the fault was detected (predates the // stackframe setup code in this function) static void __fastcall StackFrameCheckFailed( int espORebp, int regval ) { pxFailDev( wxsFormat( L"(R3000A Recompiler Stackframe) Sanity check failed on %s\n\tCurrent=%d; Saved=%d", (espORebp==0) ? L"ESP" : L"EBP", regval, (espORebp==0) ? s_store_esp : s_store_ebp ) ); // Note: The recompiler will attempt to recover ESP and EBP after returning from this function, // so typically selecting Continue/Ignore/Cancel for this assertion should allow PCSX2 to con- // tinue to run with some degree of stability. } static void _DynGen_StackFrameCheck() { if( !IsDevBuild ) return; // --------- EBP Here ----------- xCMP( ebp, ptr[&s_store_ebp] ); xForwardJE8 skipassert_ebp; xMOV( ecx, 1 ); // 1 specifies EBP xMOV( edx, ebp ); xCALL( StackFrameCheckFailed ); xMOV( ebp, ptr[&s_store_ebp] ); // half-hearted frame recovery attempt! skipassert_ebp.SetTarget(); // --------- ESP There ----------- xCMP( esp, ptr[&s_store_esp] ); xForwardJE8 skipassert_esp; xXOR( ecx, ecx ); // 0 specifies ESP xMOV( edx, esp ); xCALL( StackFrameCheckFailed ); xMOV( esp, ptr[&s_store_esp] ); // half-hearted frame recovery attempt! skipassert_esp.SetTarget(); } // The address for all cleared blocks. It recompiles the current pc and then // dispatches to the recompiled block address. static DynGenFunc* _DynGen_JITCompile() { pxAssertMsg( iopDispatcherReg != NULL, "Please compile the DispatcherReg subroutine *before* JITComple. Thanks." ); u8* retval = xGetPtr(); _DynGen_StackFrameCheck(); xMOV( ecx, ptr[&psxRegs.pc] ); xCALL( iopRecRecompile ); xMOV( eax, ptr[&psxRegs.pc] ); xMOV( ebx, eax ); xSHR( eax, 16 ); xMOV( ecx, ptr[psxRecLUT + (eax*4)] ); xJMP( ptr32[ecx+ebx] ); return (DynGenFunc*)retval; } static DynGenFunc* _DynGen_JITCompileInBlock() { u8* retval = xGetPtr(); xJMP( iopJITCompile ); return (DynGenFunc*)retval; } // called when jumping to variable pc address static DynGenFunc* _DynGen_DispatcherReg() { u8* retval = xGetPtr(); _DynGen_StackFrameCheck(); xMOV( eax, ptr[&psxRegs.pc] ); xMOV( ebx, eax ); xSHR( eax, 16 ); xMOV( ecx, ptr[psxRecLUT + (eax*4)] ); xJMP( ptr32[ecx+ebx] ); return (DynGenFunc*)retval; } // -------------------------------------------------------------------------------------- // EnterRecompiledCode - dynamic compilation stub! // -------------------------------------------------------------------------------------- // In Release Builds this literally generates the following code: // push edi // push esi // push ebx // jmp DispatcherReg // pop ebx // pop esi // pop edi // // See notes on why this works in both GCC (aligned stack!) and other compilers (not-so- // aligned stack!). In debug/dev builds the code gen is more complicated, as it constructs // ebp stackframe mess, which allows for a complete backtrace from debug breakpoints (yay). // // Also, if you set PCSX2_IOP_FORCED_ALIGN_STACK to 1, the codegen for MSVC becomes slightly // more complicated since it has to perform a full stack alignment on entry. // #if defined(__GNUG__) || defined(__DARWIN__) # define PCSX2_ASSUME_ALIGNED_STACK 1 #else # define PCSX2_ASSUME_ALIGNED_STACK 0 #endif // Set to 0 for a speedup in release builds. // [doesn't apply to GCC/Mac, which must always align] #define PCSX2_IOP_FORCED_ALIGN_STACK 0 //1 // For overriding stackframe generation options in Debug builds (possibly useful for troubleshooting) // Typically this value should be the same as IsDevBuild. static const bool GenerateStackFrame = IsDevBuild; static DynGenFunc* _DynGen_EnterRecompiledCode() { u8* retval = xGetPtr(); bool allocatedStack = GenerateStackFrame || PCSX2_IOP_FORCED_ALIGN_STACK; // Optimization: The IOP never uses stack-based parameter invocation, so we can avoid // allocating any room on the stack for it (which is important since the IOP's entry // code gets invoked quite a lot). if( allocatedStack ) { xPUSH( ebp ); xMOV( ebp, esp ); xAND( esp, -0x10 ); xSUB( esp, 0x20 ); xMOV( ptr[ebp-12], edi ); xMOV( ptr[ebp-8], esi ); xMOV( ptr[ebp-4], ebx ); } else { // GCC Compiler: // The frame pointer coming in from the EE's event test can be safely assumed to be // aligned, since GCC always aligns stackframes. While handy in x86-64, where CALL + PUSH EBP // results in a neatly realigned stack on entry to every function, unfortunately in x86-32 // this is usually worthless because CALL+PUSH leaves us 8 byte aligned instead (fail). So // we have to do the usual set of stackframe alignments and simulated callstack mess // *regardless*. // MSVC/Intel compilers: // The PCSX2_IOP_FORCED_ALIGN_STACK setting is 0, so we don't care. Just push regs like // the good old days! (stack alignment will be indeterminate) xPUSH( edi ); xPUSH( esi ); xPUSH( ebx ); allocatedStack = false; } uptr* imm = NULL; if( allocatedStack ) { if( GenerateStackFrame ) { // Simulate a CALL function by pushing the call address and EBP onto the stack. // This retains proper stacktrace and stack unwinding (handy in devbuilds!) xMOV( ptr32[esp+0x0c], 0xffeeff ); imm = (uptr*)(xGetPtr()-4); // This part simulates the "normal" stackframe prep of "push ebp, mov ebp, esp" xMOV( ptr32[esp+0x08], ebp ); xLEA( ebp, ptr32[esp+0x08] ); } } if( IsDevBuild ) { xMOV( ptr[&s_store_esp], esp ); xMOV( ptr[&s_store_ebp], ebp ); } xJMP( iopDispatcherReg ); if( imm != NULL ) *imm = (uptr)xGetPtr(); // ---------------------- // ----> Cleanup! ----> iopExitRecompiledCode = (DynGenFunc*)xGetPtr(); if( allocatedStack ) { // pop the nested "simulated call" stackframe, if needed: if( GenerateStackFrame ) xLEAVE(); xMOV( edi, ptr[ebp-12] ); xMOV( esi, ptr[ebp-8] ); xMOV( ebx, ptr[ebp-4] ); xLEAVE(); } else { xPOP( ebx ); xPOP( esi ); xPOP( edi ); } xRET(); return (DynGenFunc*)retval; } static void _DynGen_Dispatchers() { // In case init gets called multiple times: HostSys::MemProtectStatic( iopRecDispatchers, Protect_ReadWrite, false ); // clear the buffer to 0xcc (easier debugging). memset_8<0xcc,__pagesize>( iopRecDispatchers ); xSetPtr( iopRecDispatchers ); // Place the EventTest and DispatcherReg stuff at the top, because they get called the // most and stand to benefit from strong alignment and direct referencing. iopDispatcherEvent = (DynGenFunc*)xGetPtr(); xCALL( recEventTest ); iopDispatcherReg = _DynGen_DispatcherReg(); iopJITCompile = _DynGen_JITCompile(); iopJITCompileInBlock = _DynGen_JITCompileInBlock(); iopEnterRecompiledCode = _DynGen_EnterRecompiledCode(); HostSys::MemProtectStatic( iopRecDispatchers, Protect_ReadOnly, true ); recBlocks.SetJITCompile( iopJITCompile ); } //////////////////////////////////////////////////// using namespace R3000A; #include "Utilities/AsciiFile.h" static void iIopDumpBlock( int startpc, u8 * ptr ) { u32 i, j; EEINST* pcur; u8 used[34]; int numused, count; Console.WriteLn( "dump1 %x:%x, %x", startpc, psxpc, psxRegs.cycle ); g_Conf->Folders.Logs.Mkdir(); wxString filename( Path::Combine( g_Conf->Folders.Logs, wxsFormat( L"psxdump%.8X.txt", startpc ) ) ); AsciiFile f( filename, L"w" ); /*for ( i = startpc; i < s_nEndBlock; i += 4 ) { f.Printf("%s\n", disR3000Fasm( iopMemRead32( i ), i ) ); }*/ // write the instruction info f.Printf("\n\nlive0 - %x, lastuse - %x used - %x\n", EEINST_LIVE0, EEINST_LASTUSE, EEINST_USED); memzero(used); numused = 0; for(i = 0; i < ArraySize(s_pInstCache->regs); ++i) { if( s_pInstCache->regs[i] & EEINST_USED ) { used[i] = 1; numused++; } } f.Printf(" "); for(i = 0; i < ArraySize(s_pInstCache->regs); ++i) { if( used[i] ) f.Printf("%2d ", i); } f.Printf("\n"); f.Printf(" "); for(i = 0; i < ArraySize(s_pInstCache->regs); ++i) { if( used[i] ) f.Printf("%s ", disRNameGPR[i]); } f.Printf("\n"); pcur = s_pInstCache+1; for( i = 0; i < (s_nEndBlock-startpc)/4; ++i, ++pcur) { f.Printf("%2d: %2.2x ", i+1, pcur->info); count = 1; for(j = 0; j < ArraySize(s_pInstCache->regs); j++) { if( used[j] ) { f.Printf("%2.2x%s", pcur->regs[j], ((count%8)&&count<numused)?"_":" "); ++count; } } f.Printf("\n"); } #ifdef __LINUX__ char command[256]; // dump the asm { AsciiFile f2( L"mydump1", L"w" ); f2.Write( ptr, (uptr)x86Ptr - (uptr)ptr ); } wxCharBuffer buf( filename.ToUTF8() ); const char* filenamea = buf.data(); sprintf( command, "objdump -D --target=binary --architecture=i386 -M intel mydump1 | cat %s - > tempdump", filenamea ); system( command ); sprintf( command, "mv tempdump %s", filenamea ); system( command ); //f = fopen( filename.c_str(), "a+" ); #endif } u8 _psxLoadWritesRs(u32 tempcode) { switch(tempcode>>26) { case 32: case 33: case 34: case 35: case 36: case 37: case 38: return ((tempcode>>21)&0x1f)==((tempcode>>16)&0x1f); // rs==rt } return 0; } u8 _psxIsLoadStore(u32 tempcode) { switch(tempcode>>26) { case 32: case 33: case 34: case 35: case 36: case 37: case 38: // 4 byte stores case 40: case 41: case 42: case 43: case 46: return 1; } return 0; } void _psxFlushAllUnused() { int i; for(i = 0; i < 34; ++i) { if( psxpc < s_nEndBlock ) { if( (g_pCurInstInfo[1].regs[i]&EEINST_USED) ) continue; } else if( (g_pCurInstInfo[0].regs[i]&EEINST_USED) ) continue; if( i < 32 && PSX_IS_CONST1(i) ) _psxFlushConstReg(i); else { _deleteX86reg(X86TYPE_PSX, i, 1); } } } int _psxFlushUnusedConstReg() { int i; for(i = 1; i < 32; ++i) { if( (g_psxHasConstReg & (1<<i)) && !(g_psxFlushedConstReg&(1<<i)) && !_recIsRegWritten(g_pCurInstInfo+1, (s_nEndBlock-psxpc)/4, XMMTYPE_GPRREG, i) ) { // check if will be written in the future MOV32ItoM((uptr)&psxRegs.GPR.r[i], g_psxConstRegs[i]); g_psxFlushedConstReg |= 1<<i; return 1; } } return 0; } void _psxFlushCachedRegs() { _psxFlushConstRegs(); } void _psxFlushConstReg(int reg) { if( PSX_IS_CONST1( reg ) && !(g_psxFlushedConstReg&(1<<reg)) ) { MOV32ItoM((uptr)&psxRegs.GPR.r[reg], g_psxConstRegs[reg]); g_psxFlushedConstReg |= (1<<reg); } } void _psxFlushConstRegs() { int i; // flush constants // ignore r0 for(i = 1; i < 32; ++i) { if( g_psxHasConstReg & (1<<i) ) { if( !(g_psxFlushedConstReg&(1<<i)) ) { MOV32ItoM((uptr)&psxRegs.GPR.r[i], g_psxConstRegs[i]); g_psxFlushedConstReg |= 1<<i; } if( g_psxHasConstReg == g_psxFlushedConstReg ) break; } } } void _psxDeleteReg(int reg, int flush) { if( !reg ) return; if( flush && PSX_IS_CONST1(reg) ) { _psxFlushConstReg(reg); return; } PSX_DEL_CONST(reg); _deleteX86reg(X86TYPE_PSX, reg, flush ? 0 : 2); } void _psxMoveGPRtoR(x86IntRegType to, int fromgpr) { if( PSX_IS_CONST1(fromgpr) ) MOV32ItoR( to, g_psxConstRegs[fromgpr] ); else { // check x86 MOV32MtoR(to, (uptr)&psxRegs.GPR.r[ fromgpr ] ); } } void _psxMoveGPRtoM(u32 to, int fromgpr) { if( PSX_IS_CONST1(fromgpr) ) MOV32ItoM( to, g_psxConstRegs[fromgpr] ); else { // check x86 MOV32MtoR(EAX, (uptr)&psxRegs.GPR.r[ fromgpr ] ); MOV32RtoM(to, EAX ); } } void _psxMoveGPRtoRm(x86IntRegType to, int fromgpr) { if( PSX_IS_CONST1(fromgpr) ) MOV32ItoRm( to, g_psxConstRegs[fromgpr] ); else { // check x86 MOV32MtoR(EAX, (uptr)&psxRegs.GPR.r[ fromgpr ] ); MOV32RtoRm(to, EAX ); } } void _psxFlushCall(int flushtype) { // x86-32 ABI : These registers are not preserved across calls: _freeX86reg( EAX ); _freeX86reg( ECX ); _freeX86reg( EDX ); if( flushtype & FLUSH_CACHED_REGS ) _psxFlushConstRegs(); } void psxSaveBranchState() { s_savenBlockCycles = s_psxBlockCycles; memcpy(s_saveConstRegs, g_psxConstRegs, sizeof(g_psxConstRegs)); s_saveHasConstReg = g_psxHasConstReg; s_saveFlushedConstReg = g_psxFlushedConstReg; s_psaveInstInfo = g_pCurInstInfo; // save all regs memcpy(s_saveX86regs, x86regs, sizeof(x86regs)); } void psxLoadBranchState() { s_psxBlockCycles = s_savenBlockCycles; memcpy(g_psxConstRegs, s_saveConstRegs, sizeof(g_psxConstRegs)); g_psxHasConstReg = s_saveHasConstReg; g_psxFlushedConstReg = s_saveFlushedConstReg; g_pCurInstInfo = s_psaveInstInfo; // restore all regs memcpy(x86regs, s_saveX86regs, sizeof(x86regs)); } //////////////////// // Code Templates // //////////////////// void _psxOnWriteReg(int reg) { PSX_DEL_CONST(reg); } // rd = rs op rt void psxRecompileCodeConst0(R3000AFNPTR constcode, R3000AFNPTR_INFO constscode, R3000AFNPTR_INFO consttcode, R3000AFNPTR_INFO noconstcode) { if ( ! _Rd_ ) return; // for now, don't support xmm _deleteX86reg(X86TYPE_PSX, _Rs_, 1); _deleteX86reg(X86TYPE_PSX, _Rt_, 1); _deleteX86reg(X86TYPE_PSX, _Rd_, 0); if( PSX_IS_CONST2(_Rs_, _Rt_) ) { PSX_SET_CONST(_Rd_); constcode(); return; } if( PSX_IS_CONST1(_Rs_) ) { constscode(0); PSX_DEL_CONST(_Rd_); return; } if( PSX_IS_CONST1(_Rt_) ) { consttcode(0); PSX_DEL_CONST(_Rd_); return; } noconstcode(0); PSX_DEL_CONST(_Rd_); } // rt = rs op imm16 void psxRecompileCodeConst1(R3000AFNPTR constcode, R3000AFNPTR_INFO noconstcode) { if ( ! _Rt_ ) { // check for iop module import table magic if (psxRegs.code >> 16 == 0x2400) { MOV32ItoM( (uptr)&psxRegs.code, psxRegs.code ); MOV32ItoM( (uptr)&psxRegs.pc, psxpc ); _psxFlushCall(FLUSH_NODESTROY); const char *libname = irxImportLibname(psxpc); u16 index = psxRegs.code & 0xffff; #ifdef PCSX2_DEVBUILD const char *funcname = irxImportFuncname(libname, index); irxDEBUG debug = irxImportDebug(libname, index); if (SysTraceActive(IOP.Bios)) { xMOV(ecx, (uptr)libname); xMOV(edx, index); xPUSH((uptr)funcname); xCALL(irxImportLog); } if (debug) xCALL(debug); #endif irxHLE hle = irxImportHLE(libname, index); if (hle) { xCALL(hle); xCMP(eax, 0); xJNE(iopDispatcherReg); } } return; } // for now, don't support xmm _deleteX86reg(X86TYPE_PSX, _Rs_, 1); _deleteX86reg(X86TYPE_PSX, _Rt_, 0); if( PSX_IS_CONST1(_Rs_) ) { PSX_SET_CONST(_Rt_); constcode(); return; } noconstcode(0); PSX_DEL_CONST(_Rt_); } // rd = rt op sa void psxRecompileCodeConst2(R3000AFNPTR constcode, R3000AFNPTR_INFO noconstcode) { if ( ! _Rd_ ) return; // for now, don't support xmm _deleteX86reg(X86TYPE_PSX, _Rt_, 1); _deleteX86reg(X86TYPE_PSX, _Rd_, 0); if( PSX_IS_CONST1(_Rt_) ) { PSX_SET_CONST(_Rd_); constcode(); return; } noconstcode(0); PSX_DEL_CONST(_Rd_); } // rd = rt MULT rs (SPECIAL) void psxRecompileCodeConst3(R3000AFNPTR constcode, R3000AFNPTR_INFO constscode, R3000AFNPTR_INFO consttcode, R3000AFNPTR_INFO noconstcode, int LOHI) { _deleteX86reg(X86TYPE_PSX, _Rs_, 1); _deleteX86reg(X86TYPE_PSX, _Rt_, 1); if( LOHI ) { _deleteX86reg(X86TYPE_PSX, PSX_HI, 1); _deleteX86reg(X86TYPE_PSX, PSX_LO, 1); } if( PSX_IS_CONST2(_Rs_, _Rt_) ) { constcode(); return; } if( PSX_IS_CONST1(_Rs_) ) { constscode(0); return; } if( PSX_IS_CONST1(_Rt_) ) { consttcode(0); return; } noconstcode(0); } static u8* m_recBlockAlloc = NULL; static const uint m_recBlockAllocSize = (((Ps2MemSize::IopRam + Ps2MemSize::Rom + Ps2MemSize::Rom1) / 4) * sizeof(BASEBLOCK)); static void recAlloc() { // Note: the VUrec depends on being able to grab an allocation below the 0x10000000 line, // so we give the EErec an address above that to try first as it's basemem address, hence // the 0x28000000 pick (0x20000000 is picked by the EE) if( recMem == NULL ) recMem = (u8*)SysMmapEx( 0x28000000, RECMEM_SIZE, 0, "recAlloc(R3000a)" ); if( recMem == NULL ) throw Exception::OutOfMemory( L"R3000A recompiled code cache" ); // Goal: Allocate BASEBLOCKs for every possible branch target in IOP memory. // Any 4-byte aligned address makes a valid branch target as per MIPS design (all instructions are // always 4 bytes long). if( m_recBlockAlloc == NULL ) m_recBlockAlloc = (u8*)_aligned_malloc( m_recBlockAllocSize, 4096 ); if( m_recBlockAlloc == NULL ) throw Exception::OutOfMemory( L"R3000A BASEBLOCK lookup tables" ); u8* curpos = m_recBlockAlloc; recRAM = (BASEBLOCK*)curpos; curpos += (Ps2MemSize::IopRam / 4) * sizeof(BASEBLOCK); recROM = (BASEBLOCK*)curpos; curpos += (Ps2MemSize::Rom / 4) * sizeof(BASEBLOCK); recROM1 = (BASEBLOCK*)curpos; curpos += (Ps2MemSize::Rom1 / 4) * sizeof(BASEBLOCK); if( s_pInstCache == NULL ) { s_nInstCacheSize = 128; s_pInstCache = (EEINST*)malloc( sizeof(EEINST) * s_nInstCacheSize ); } if( s_pInstCache == NULL ) throw Exception::OutOfMemory( L"R3000 InstCache." ); ProfilerRegisterSource( "IOP Rec", recMem, RECMEM_SIZE ); _DynGen_Dispatchers(); } void recResetIOP() { // calling recResetIOP without first calling recInit is bad mojo. pxAssert( recMem != NULL ); pxAssert( m_recBlockAlloc != NULL ); DevCon.WriteLn( "iR3000A Recompiler reset." ); memset_8<0xcc,RECMEM_SIZE>( recMem ); // 0xcc is INT3 iopClearRecLUT((BASEBLOCK*)m_recBlockAlloc, (((Ps2MemSize::IopRam + Ps2MemSize::Rom + Ps2MemSize::Rom1) / 4))); for (int i = 0; i < 0x10000; i++) recLUT_SetPage(psxRecLUT, 0, 0, 0, i, 0); // IOP knows 64k pages, hence for the 0x10000's // The bottom 2 bits of PC are always zero, so we <<14 to "compress" // the pc indexer into it's lower common denominator. // We're only mapping 20 pages here in 4 places. // 0x80 comes from : (Ps2MemSize::IopRam / 0x10000) * 4 for (int i=0; i<0x80; i++) { recLUT_SetPage(psxRecLUT, psxhwLUT, recRAM, 0x0000, i, i & 0x1f); recLUT_SetPage(psxRecLUT, psxhwLUT, recRAM, 0x8000, i, i & 0x1f); recLUT_SetPage(psxRecLUT, psxhwLUT, recRAM, 0xa000, i, i & 0x1f); } for (int i=0x1fc0; i<0x2000; i++) { recLUT_SetPage(psxRecLUT, psxhwLUT, recROM, 0x0000, i, i - 0x1fc0); recLUT_SetPage(psxRecLUT, psxhwLUT, recROM, 0x8000, i, i - 0x1fc0); recLUT_SetPage(psxRecLUT, psxhwLUT, recROM, 0xa000, i, i - 0x1fc0); } for (int i=0x1e00; i<0x1e04; i++) { recLUT_SetPage(psxRecLUT, psxhwLUT, recROM1, 0x0000, i, i - 0x1fc0); recLUT_SetPage(psxRecLUT, psxhwLUT, recROM1, 0x8000, i, i - 0x1fc0); recLUT_SetPage(psxRecLUT, psxhwLUT, recROM1, 0xa000, i, i - 0x1fc0); } if( s_pInstCache ) memset( s_pInstCache, 0, sizeof(EEINST)*s_nInstCacheSize ); recBlocks.Reset(); g_psxMaxRecMem = 0; recPtr = recMem; psxbranch = 0; } static void recShutdown() { ProfilerTerminateSource( "IOPRec" ); SafeSysMunmap(recMem, RECMEM_SIZE); safe_aligned_free( m_recBlockAlloc ); safe_free( s_pInstCache ); s_nInstCacheSize = 0; } static void iopClearRecLUT(BASEBLOCK* base, int count) { for (int i = 0; i < count; i++) base[i].SetFnptr((uptr)iopJITCompile); } static void recExecute() { // note: this function is currently never used. //for (;;) R3000AExecute(); } static __noinline s32 recExecuteBlock( s32 eeCycles ) { iopBreak = 0; iopCycleEE = eeCycles; // [TODO] recExecuteBlock could be replaced by a direct call to the iopEnterRecompiledCode() // (by assigning its address to the psxRec structure). But for that to happen, we need // to move iopBreak/iopCycleEE update code to emitted assembly code. >_< --air // Likely Disasm, as borrowed from MSVC: // Entry: // mov eax,dword ptr [esp+4] // mov dword ptr [iopBreak (0E88DCCh)],0 // mov dword ptr [iopCycleEE (832A84h)],eax // Exit: // mov ecx,dword ptr [iopBreak (0E88DCCh)] // mov edx,dword ptr [iopCycleEE (832A84h)] // lea eax,[edx+ecx] iopEnterRecompiledCode(); return iopBreak + iopCycleEE; } // Returns the offset to the next instruction after any cleared memory static __fi u32 psxRecClearMem(u32 pc) { BASEBLOCK* pblock; pblock = PSX_GETBLOCK(pc); // if ((u8*)iopJITCompile == pblock->GetFnptr()) if (pblock->GetFnptr() == (uptr)iopJITCompile) return 4; pc = HWADDR(pc); u32 lowerextent = pc, upperextent = pc + 4; int blockidx = recBlocks.Index(pc); pxAssert(blockidx != -1); while (BASEBLOCKEX* pexblock = recBlocks[blockidx - 1]) { if (pexblock->startpc + pexblock->size * 4 <= lowerextent) break; lowerextent = min(lowerextent, pexblock->startpc); blockidx--; } while (BASEBLOCKEX* pexblock = recBlocks[blockidx]) { if (pexblock->startpc >= upperextent) break; lowerextent = min(lowerextent, pexblock->startpc); upperextent = max(upperextent, pexblock->startpc + pexblock->size * 4); recBlocks.Remove(blockidx); } blockidx=0; while(BASEBLOCKEX* pexblock = recBlocks[blockidx++]) { if (pc >= pexblock->startpc && pc < pexblock->startpc + pexblock->size * 4) { DevCon.Error("Impossible block clearing failure"); pxFailDev( "Impossible block clearing failure" ); } } iopClearRecLUT(PSX_GETBLOCK(lowerextent), (upperextent - lowerextent) / 4); return upperextent - pc; } static __fi void recClearIOP(u32 Addr, u32 Size) { u32 pc = Addr; while (pc < Addr + Size*4) pc += PSXREC_CLEARM(pc); } void psxSetBranchReg(u32 reg) { psxbranch = 1; if( reg != 0xffffffff ) { _allocX86reg(ESI, X86TYPE_PCWRITEBACK, 0, MODE_WRITE); _psxMoveGPRtoR(ESI, reg); psxRecompileNextInstruction(1); if( x86regs[ESI].inuse ) { pxAssert( x86regs[ESI].type == X86TYPE_PCWRITEBACK ); MOV32RtoM((uptr)&psxRegs.pc, ESI); x86regs[ESI].inuse = 0; #ifdef PCSX2_DEBUG xOR( esi, esi ); #endif } else { MOV32MtoR(EAX, (uptr)&g_recWriteback); MOV32RtoM((uptr)&psxRegs.pc, EAX); #ifdef PCSX2_DEBUG xOR( eax, eax ); #endif } #ifdef PCSX2_DEBUG xForwardJNZ8 skipAssert; xWrite8( 0xcc ); skipAssert.SetTarget(); #endif } _psxFlushCall(FLUSH_EVERYTHING); iPsxBranchTest(0xffffffff, 1); JMP32((uptr)iopDispatcherReg - ( (uptr)x86Ptr + 5 )); } void psxSetBranchImm( u32 imm ) { psxbranch = 1; pxAssert( imm ); // end the current block MOV32ItoM( (uptr)&psxRegs.pc, imm ); _psxFlushCall(FLUSH_EVERYTHING); iPsxBranchTest(imm, imm <= psxpc); recBlocks.Link(HWADDR(imm), xJcc32()); } static __fi u32 psxScaleBlockCycles() { return s_psxBlockCycles; } static void iPsxBranchTest(u32 newpc, u32 cpuBranch) { u32 blockCycles = psxScaleBlockCycles(); if (EmuConfig.Speedhacks.WaitLoop && s_nBlockFF && newpc == s_branchTo) { xMOV(eax, ptr32[&psxRegs.cycle]); xMOV(ecx, eax); xMOV(edx, ptr32[&iopCycleEE]); xADD(edx, 7); xSHR(edx, 3); xADD(eax, edx); xCMP(eax, ptr32[&g_iopNextEventCycle]); xCMOVNS(eax, ptr32[&g_iopNextEventCycle]); xMOV(ptr32[&psxRegs.cycle], eax); xSUB(eax, ecx); xSHL(eax, 3); xSUB(ptr32[&iopCycleEE], eax); xJLE(iopExitRecompiledCode); xCALL(iopEventTest); if( newpc != 0xffffffff ) { xCMP(ptr32[&psxRegs.pc], newpc); xJNE(iopDispatcherReg); } } else { xMOV(eax, ptr32[&psxRegs.cycle]); xADD(eax, blockCycles); xMOV(ptr32[&psxRegs.cycle], eax); // update cycles // jump if iopCycleEE <= 0 (iop's timeslice timed out, so time to return control to the EE) xSUB(ptr32[&iopCycleEE], blockCycles*8); xJLE(iopExitRecompiledCode); // check if an event is pending xSUB(eax, ptr32[&g_iopNextEventCycle]); xForwardJS<u8> nointerruptpending; xCALL(iopEventTest); if( newpc != 0xffffffff ) { xCMP(ptr32[&psxRegs.pc], newpc); xJNE(iopDispatcherReg); } nointerruptpending.SetTarget(); } } #if 0 //static const int *s_pCode; #if !defined(_MSC_VER) static void checkcodefn() { int pctemp; #ifdef _MSC_VER __asm mov pctemp, eax; #else __asm__ __volatile__("movl %%eax, %[pctemp]" : [pctemp]"m="(pctemp) ); #endif Console.WriteLn("iop code changed! %x", pctemp); } #endif #endif void rpsxSYSCALL() { MOV32ItoM( (uptr)&psxRegs.code, psxRegs.code ); MOV32ItoM((uptr)&psxRegs.pc, psxpc - 4); _psxFlushCall(FLUSH_NODESTROY); xMOV( ecx, 0x20 ); // exception code xMOV( edx, psxbranch==1 ); // branch delay slot? xCALL( psxException ); CMP32ItoM((uptr)&psxRegs.pc, psxpc-4); j8Ptr[0] = JE8(0); ADD32ItoM((uptr)&psxRegs.cycle, psxScaleBlockCycles() ); SUB32ItoM((uptr)&iopCycleEE, psxScaleBlockCycles()*8 ); JMP32((uptr)iopDispatcherReg - ( (uptr)x86Ptr + 5 )); // jump target for skipping blockCycle updates x86SetJ8(j8Ptr[0]); //if (!psxbranch) psxbranch = 2; } void rpsxBREAK() { MOV32ItoM( (uptr)&psxRegs.code, psxRegs.code ); MOV32ItoM((uptr)&psxRegs.pc, psxpc - 4); _psxFlushCall(FLUSH_NODESTROY); xMOV( ecx, 0x24 ); // exception code xMOV( edx, psxbranch==1 ); // branch delay slot? xCALL( psxException ); CMP32ItoM((uptr)&psxRegs.pc, psxpc-4); j8Ptr[0] = JE8(0); ADD32ItoM((uptr)&psxRegs.cycle, psxScaleBlockCycles() ); SUB32ItoM((uptr)&iopCycleEE, psxScaleBlockCycles()*8 ); JMP32((uptr)iopDispatcherReg - ( (uptr)x86Ptr + 5 )); x86SetJ8(j8Ptr[0]); //if (!psxbranch) psxbranch = 2; } void psxRecompileNextInstruction(int delayslot) { static u8 s_bFlushReg = 1; // pblock isn't used elsewhere in this function. //BASEBLOCK* pblock = PSX_GETBLOCK(psxpc); if( IsDebugBuild ) MOV32ItoR(EAX, psxpc); psxRegs.code = iopMemRead32( psxpc ); s_psxBlockCycles++; psxpc += 4; g_pCurInstInfo++; g_iopCyclePenalty = 0; rpsxBSC[ psxRegs.code >> 26 ](); s_psxBlockCycles += g_iopCyclePenalty; if( !delayslot ) { if( s_bFlushReg ) { //_psxFlushUnusedConstReg(); } else s_bFlushReg = 1; } else s_bFlushReg = 1; _clearNeededX86regs(); } static void __fastcall PreBlockCheck( u32 blockpc ) { #ifdef PCSX2_DEBUG extern void iDumpPsxRegisters(u32 startpc, u32 temp); static int lastrec = 0; static int curcount = 0; const int skip = 0; //*(int*)PSXM(0x27990) = 1; // enables cdvd bios output for scph10000 if( (psxdump&2) && lastrec != blockpc ) { curcount++; if( curcount > skip ) { iDumpPsxRegisters(blockpc, 1); curcount = 0; } lastrec = blockpc; } #endif } static void __fastcall iopRecRecompile( const u32 startpc ) { u32 i; u32 willbranch3 = 0; if( IsDebugBuild && (psxdump & 4) ) { extern void iDumpPsxRegisters(u32 startpc, u32 temp); iDumpPsxRegisters(startpc, 0); } pxAssert( startpc ); // if recPtr reached the mem limit reset whole mem if (((uptr)recPtr - (uptr)recMem) >= (RECMEM_SIZE - 0x10000)) recResetIOP(); x86SetPtr( recPtr ); x86Align(16); recPtr = x86Ptr; s_pCurBlock = PSX_GETBLOCK(startpc); pxAssert(s_pCurBlock->GetFnptr() == (uptr)iopJITCompile || s_pCurBlock->GetFnptr() == (uptr)iopJITCompileInBlock); s_pCurBlockEx = recBlocks.Get(HWADDR(startpc)); if(!s_pCurBlockEx || s_pCurBlockEx->startpc != HWADDR(startpc)) s_pCurBlockEx = recBlocks.New(HWADDR(startpc), (uptr)recPtr); psxbranch = 0; s_pCurBlock->SetFnptr( (uptr)x86Ptr ); s_psxBlockCycles = 0; // reset recomp state variables psxpc = startpc; g_psxHasConstReg = g_psxFlushedConstReg = 1; _initX86regs(); if( IsDebugBuild ) { xMOV(ecx, psxpc); xCALL(PreBlockCheck); } // go until the next branch i = startpc; s_nEndBlock = 0xffffffff; s_branchTo = -1; while(1) { BASEBLOCK* pblock = PSX_GETBLOCK(i); if (i != startpc && pblock->GetFnptr() != (uptr)iopJITCompile && pblock->GetFnptr() != (uptr)iopJITCompileInBlock) { // branch = 3 willbranch3 = 1; s_nEndBlock = i; break; } psxRegs.code = iopMemRead32(i); switch(psxRegs.code >> 26) { case 0: // special if( _Funct_ == 8 || _Funct_ == 9 ) { // JR, JALR s_nEndBlock = i + 8; goto StartRecomp; } break; case 1: // regimm if( _Rt_ == 0 || _Rt_ == 1 || _Rt_ == 16 || _Rt_ == 17 ) { s_branchTo = _Imm_ * 4 + i + 4; if( s_branchTo > startpc && s_branchTo < i ) s_nEndBlock = s_branchTo; else s_nEndBlock = i+8; goto StartRecomp; } break; case 2: // J case 3: // JAL s_branchTo = _Target_ << 2 | (i + 4) & 0xf0000000; s_nEndBlock = i + 8; goto StartRecomp; // branches case 4: case 5: case 6: case 7: s_branchTo = _Imm_ * 4 + i + 4; if( s_branchTo > startpc && s_branchTo < i ) s_nEndBlock = s_branchTo; else s_nEndBlock = i+8; goto StartRecomp; } i += 4; } StartRecomp: s_nBlockFF = false; if (s_branchTo == startpc) { s_nBlockFF = true; for (i = startpc; i < s_nEndBlock; i += 4) { if (i != s_nEndBlock - 8) { switch (iopMemRead32(i)) { case 0: // nop break; default: s_nBlockFF = false; } } } } // rec info // { EEINST* pcur; if( s_nInstCacheSize < (s_nEndBlock-startpc)/4+1 ) { free(s_pInstCache); s_nInstCacheSize = (s_nEndBlock-startpc)/4+10; s_pInstCache = (EEINST*)malloc(sizeof(EEINST)*s_nInstCacheSize); pxAssert( s_pInstCache != NULL ); } pcur = s_pInstCache + (s_nEndBlock-startpc)/4; _recClearInst(pcur); pcur->info = 0; for(i = s_nEndBlock; i > startpc; i -= 4 ) { psxRegs.code = iopMemRead32(i-4); pcur[-1] = pcur[0]; rpsxpropBSC(pcur-1, pcur); pcur--; } } // dump code if( IsDebugBuild ) { for(i = 0; i < ArraySize(s_psxrecblocks); ++i) { if( startpc == s_psxrecblocks[i] ) { iIopDumpBlock(startpc, recPtr); } } if( (psxdump & 1) ) iIopDumpBlock(startpc, recPtr); } g_pCurInstInfo = s_pInstCache; while (!psxbranch && psxpc < s_nEndBlock) { psxRecompileNextInstruction(0); } if( IsDebugBuild && (psxdump & 1) ) iIopDumpBlock(startpc, recPtr); pxAssert( (psxpc-startpc)>>2 <= 0xffff ); s_pCurBlockEx->size = (psxpc-startpc)>>2; for(i = 1; i < (u32)s_pCurBlockEx->size; ++i) { if (s_pCurBlock[i].GetFnptr() == (uptr)iopJITCompile) s_pCurBlock[i].SetFnptr((uptr)iopJITCompileInBlock); } if( !(psxpc&0x10000000) ) g_psxMaxRecMem = std::max( (psxpc&~0xa0000000), g_psxMaxRecMem ); if( psxbranch == 2 ) { _psxFlushCall(FLUSH_EVERYTHING); iPsxBranchTest(0xffffffff, 1); JMP32((uptr)iopDispatcherReg - ( (uptr)x86Ptr + 5 )); } else { if( psxbranch ) pxAssert( !willbranch3 ); else { ADD32ItoM((uptr)&psxRegs.cycle, psxScaleBlockCycles() ); SUB32ItoM((uptr)&iopCycleEE, psxScaleBlockCycles()*8 ); } if (willbranch3 || !psxbranch) { pxAssert( psxpc == s_nEndBlock ); _psxFlushCall(FLUSH_EVERYTHING); MOV32ItoM((uptr)&psxRegs.pc, psxpc); recBlocks.Link(HWADDR(s_nEndBlock), xJcc32() ); psxbranch = 3; } } pxAssert( x86Ptr < recMem+RECMEM_SIZE ); pxAssert(x86Ptr - recPtr < 0x10000); s_pCurBlockEx->x86size = x86Ptr - recPtr; recPtr = x86Ptr; pxAssert( (g_psxHasConstReg&g_psxFlushedConstReg) == g_psxHasConstReg ); s_pCurBlock = NULL; s_pCurBlockEx = NULL; } R3000Acpu psxRec = { recAlloc, recResetIOP, recExecute, recExecuteBlock, recClearIOP, recShutdown };
[ "koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5" ]
[ [ [ 1, 1409 ] ] ]
1374b9f020b5d9855788ed834e3b2a4288dd0270
fd3f2268460656e395652b11ae1a5b358bfe0a59
/srchybrid/SearchList.cpp
896f1ebfe69a4e7c6fe751f5f26ed7054ac7cdfe
[]
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
65,991
cpp
//this file is part of eMule //Copyright (C)2002-2008 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net ) // //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., 675 Mass Ave, Cambridge, MA 02139, USA. #include "stdafx.h" #include "emule.h" #include "SearchFile.h" #include "SearchList.h" #include "SearchParams.h" #include "Packets.h" #include "OtherFunctions.h" #include "Preferences.h" #include "UpDownClient.h" #include "SafeFile.h" #include "MMServer.h" #include "SharedFileList.h" #include "KnownFileList.h" #include "DownloadQueue.h" #include "PartFile.h" #include "CxImage/xImage.h" #include "kademlia/utils/uint128.h" #include "Kademlia/Kademlia/Entry.h" #include "Kademlia/Kademlia/SearchManager.h" #include "emuledlg.h" #include "SearchDlg.h" #include "SearchListCtrl.h" #include "Log.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define SPAMFILTER_FILENAME _T("SearchSpam.met") #define STOREDSEARCHES_FILENAME _T("StoredSearches.met") #define STOREDSEARCHES_VERSION 1 /////////////////////////////////////////////////////////////////////////////// // CSearchList CSearchList::CSearchList() { outputwnd = NULL; m_MobilMuleSearch = false; m_bSpamFilterLoaded = false; } CSearchList::~CSearchList() { Clear(); POSITION pos = m_aUDPServerRecords.GetStartPosition(); while( pos != NULL ) { uint32 dwIP; UDPServerRecord* pRecord; m_aUDPServerRecords.GetNextAssoc(pos, dwIP, pRecord); delete pRecord; } m_aUDPServerRecords.RemoveAll(); } void CSearchList::Clear() { for (POSITION pos = m_listFileLists.GetHeadPosition(); pos != NULL;) { POSITION posLast = pos; SearchListsStruct* listCur = m_listFileLists.GetNext(pos); for(POSITION pos2 = listCur->m_listSearchFiles.GetHeadPosition(); pos2 != NULL; ) delete listCur->m_listSearchFiles.GetNext(pos2); listCur->m_listSearchFiles.RemoveAll(); m_listFileLists.RemoveAt(posLast); delete listCur; } } void CSearchList::RemoveResults(uint32 nSearchID) { // this will not delete the item from the window, make sure your code does it if you call this for (POSITION pos = m_listFileLists.GetHeadPosition(); pos != NULL;) { POSITION posLast = pos; SearchListsStruct* listCur = m_listFileLists.GetNext(pos); if (listCur->m_nSearchID == nSearchID) { for(POSITION pos2 = listCur->m_listSearchFiles.GetHeadPosition(); pos2 != NULL; ) delete listCur->m_listSearchFiles.GetNext(pos2); listCur->m_listSearchFiles.RemoveAll(); m_listFileLists.RemoveAt(posLast); delete listCur; return; } } } void CSearchList::ShowResults(uint32 nSearchID) { ASSERT( outputwnd ); outputwnd->SetRedraw(FALSE); CMuleListCtrl::EUpdateMode bCurUpdateMode = outputwnd->SetUpdateMode(CMuleListCtrl::none/*direct*/); SearchList* list = GetSearchListForID(nSearchID); for (POSITION pos = list->GetHeadPosition(); pos != NULL; ) { const CSearchFile* cur_file = list->GetNext(pos); ASSERT( cur_file->GetSearchID() == nSearchID ); if (cur_file->GetListParent() == NULL) { outputwnd->AddResult(cur_file); if (cur_file->IsListExpanded() && cur_file->GetListChildCount() > 0) outputwnd->UpdateSources(cur_file); } } outputwnd->SetUpdateMode(bCurUpdateMode); outputwnd->SetRedraw(TRUE); } void CSearchList::RemoveResult(CSearchFile* todel) { SearchList* list = GetSearchListForID(todel->GetSearchID()); for (POSITION pos = list->GetHeadPosition(); pos != NULL; ) { POSITION posLast = pos; CSearchFile* cur_file = list->GetNext(pos); if (cur_file == todel) { theApp.emuledlg->searchwnd->RemoveResult(todel); list->RemoveAt(posLast); delete todel; return; } } } void CSearchList::NewSearch(CSearchListCtrl* pWnd, CStringA strResultFileType, uint32 nSearchID, ESearchType eSearchType, CString strSearchExpression, bool bMobilMuleSearch) { if (pWnd) outputwnd = pWnd; m_strResultFileType = strResultFileType; ASSERT( eSearchType != SearchTypeAutomatic ); if (eSearchType == SearchTypeEd2kServer || eSearchType == SearchTypeEd2kGlobal){ m_nCurED2KSearchID = nSearchID; m_aCurED2KSentRequestsIPs.RemoveAll(); m_aCurED2KSentReceivedIPs.RemoveAll(); } m_foundFilesCount.SetAt(nSearchID, 0); m_foundSourcesCount.SetAt(nSearchID, 0); m_ReceivedUDPAnswersCount.SetAt(nSearchID, 0); m_RequestedUDPAnswersCount.SetAt(nSearchID, 0); m_MobilMuleSearch = bMobilMuleSearch; // convert the expression into an array of searchkeywords which the user has typed in // this is used for the spamfilter later and not at all semantically equal with the actual search expression anymore m_astrSpamCheckCurSearchExp.RemoveAll(); strSearchExpression.MakeLower(); if (strSearchExpression.Find(_T("related:"), 0) != 0){ // ignore special searches int nPos, nPos2; while ((nPos = strSearchExpression.Find(_T('"'))) != -1 && (nPos2 = strSearchExpression.Find(_T('"'), nPos + 1)) != -1){ CString strQuoted = strSearchExpression.Mid(nPos + 1, (nPos2 - nPos) - 1); m_astrSpamCheckCurSearchExp.Add(strQuoted); strSearchExpression.Delete(nPos, (nPos2 - nPos) + 1); } strSearchExpression.Replace(_T("AND"), _T("")); strSearchExpression.Replace(_T("OR"), _T("")); strSearchExpression.Replace(_T("NOT"), _T("")); nPos = 0; CString strToken = strSearchExpression.Tokenize(_T(".[]()!-'_ "), nPos); while (!strToken.IsEmpty()){ m_astrSpamCheckCurSearchExp.Add(strToken); strToken = strSearchExpression.Tokenize(_T(".[]()!-'_ "), nPos); } } } UINT CSearchList::ProcessSearchAnswer(const uchar* in_packet, uint32 size, CUpDownClient* Sender, bool* pbMoreResultsAvailable, LPCTSTR pszDirectory) { ASSERT( Sender != NULL ); uint32 nSearchID = (uint32)Sender; SSearchParams* pParams = new SSearchParams; pParams->strExpression = Sender->GetUserName(); pParams->dwSearchID = nSearchID; pParams->bClientSharedFiles = true; if (theApp.emuledlg->searchwnd->CreateNewTab(pParams)){ m_foundFilesCount.SetAt(nSearchID, 0); m_foundSourcesCount.SetAt(nSearchID, 0); } else{ delete pParams; pParams = NULL; } CSafeMemFile packet(in_packet, size); UINT results = packet.ReadUInt32(); for (UINT i = 0; i < results; i++){ CSearchFile* toadd = new CSearchFile(&packet, Sender ? Sender->GetUnicodeSupport()!=utf8strNone : false, nSearchID, 0, 0, pszDirectory); if (toadd->IsLargeFile() && (Sender == NULL || !Sender->SupportsLargeFiles())){ DebugLogWarning(_T("Client offers large file (%s) but doesn't announced support for it - ignoring file"), toadd->GetFileName()); continue; } if (Sender){ toadd->SetClientID(Sender->GetIP()); toadd->SetClientPort(Sender->GetUserPort()); toadd->SetClientServerIP(Sender->GetServerIP()); toadd->SetClientServerPort(Sender->GetServerPort()); if (Sender->GetServerIP() && Sender->GetServerPort()){ CSearchFile::SServer server(Sender->GetServerIP(), Sender->GetServerPort(), false); server.m_uAvail = 1; toadd->AddServer(server); } toadd->SetPreviewPossible( Sender->GetPreviewSupport() && ED2KFT_VIDEO == GetED2KFileTypeID(toadd->GetFileName()) ); } AddToList(toadd, true); } if (pbMoreResultsAvailable) *pbMoreResultsAvailable = false; int iAddData = (int)(packet.GetLength() - packet.GetPosition()); if (iAddData == 1){ uint8 ucMore = packet.ReadUInt8(); if (ucMore == 0x00 || ucMore == 0x01){ if (pbMoreResultsAvailable) *pbMoreResultsAvailable = ucMore!=0; if (thePrefs.GetDebugClientTCPLevel() > 0) Debug(_T(" Client search answer(%s): More=%u\n"), Sender->GetUserName(), ucMore); } else{ if (thePrefs.GetDebugClientTCPLevel() > 0) Debug(_T("*** NOTE: Client ProcessSearchAnswer(%s): ***AddData: 1 byte: 0x%02x\n"), Sender->GetUserName(), ucMore); } } else if (iAddData > 0){ if (thePrefs.GetDebugClientTCPLevel() > 0){ Debug(_T("*** NOTE: Client ProcessSearchAnswer(%s): ***AddData: %u bytes\n"), Sender->GetUserName(), iAddData); DebugHexDump(in_packet + packet.GetPosition(), iAddData); } } packet.Close(); return GetResultCount(nSearchID); } UINT CSearchList::ProcessSearchAnswer(const uchar* in_packet, uint32 size, bool bOptUTF8, uint32 nServerIP, uint16 nServerPort, bool* pbMoreResultsAvailable) { CSafeMemFile packet(in_packet, size); UINT results = packet.ReadUInt32(); for (UINT i = 0; i < results; i++){ CSearchFile* toadd = new CSearchFile(&packet, bOptUTF8, m_nCurED2KSearchID); toadd->SetClientServerIP(nServerIP); toadd->SetClientServerPort(nServerPort); if (nServerIP && nServerPort){ CSearchFile::SServer server(nServerIP, nServerPort, false); server.m_uAvail = toadd->GetIntTagValue(FT_SOURCES); toadd->AddServer(server); } AddToList(toadd, false); } if (m_MobilMuleSearch) theApp.mmserver->SearchFinished(false); m_MobilMuleSearch = false; if (pbMoreResultsAvailable) *pbMoreResultsAvailable = false; int iAddData = (int)(packet.GetLength() - packet.GetPosition()); if (iAddData == 1){ uint8 ucMore = packet.ReadUInt8(); if (ucMore == 0x00 || ucMore == 0x01){ if (pbMoreResultsAvailable) *pbMoreResultsAvailable = ucMore!=0; if (thePrefs.GetDebugServerTCPLevel() > 0) Debug(_T(" Search answer(Server %s:%u): More=%u\n"), ipstr(nServerIP), nServerPort, ucMore); } else{ if (thePrefs.GetDebugServerTCPLevel() > 0) Debug(_T("*** NOTE: ProcessSearchAnswer(Server %s:%u): ***AddData: 1 byte: 0x%02x\n"), ipstr(nServerIP), nServerPort, ucMore); } } else if (iAddData > 0){ if (thePrefs.GetDebugServerTCPLevel() > 0){ Debug(_T("*** NOTE: ProcessSearchAnswer(Server %s:%u): ***AddData: %u bytes\n"), ipstr(nServerIP), nServerPort, iAddData); DebugHexDump(in_packet + packet.GetPosition(), iAddData); } } packet.Close(); return GetED2KResultCount(); } UINT CSearchList::ProcessUDPSearchAnswer(CFileDataIO& packet, bool bOptUTF8, uint32 nServerIP, uint16 nServerPort) { CSearchFile* toadd = new CSearchFile(&packet, bOptUTF8, m_nCurED2KSearchID, nServerIP, nServerPort, NULL, false, true); bool bFound = false; for (int i = 0; i != m_aCurED2KSentRequestsIPs.GetCount(); i++){ if (m_aCurED2KSentRequestsIPs[i] == nServerIP){ bFound = true; break; } } if (!bFound){ DebugLogError(_T("Unrequested or delayed Server UDP Searchresult received from IP %s, ignoring"), ipstr(nServerIP)); delete toadd; return 0; } bool bNewResponse = true; for (int i = 0; i != m_aCurED2KSentReceivedIPs.GetCount(); i++){ if (m_aCurED2KSentReceivedIPs[i] == nServerIP){ bNewResponse = false; break; } } if (bNewResponse){ uint32 nResponses = 0; VERIFY( m_ReceivedUDPAnswersCount.Lookup(m_nCurED2KSearchID, nResponses) ); m_ReceivedUDPAnswersCount.SetAt(m_nCurED2KSearchID, nResponses + 1); m_aCurED2KSentReceivedIPs.Add(nServerIP); } UDPServerRecord* pRecord = NULL; m_aUDPServerRecords.Lookup(nServerIP, pRecord); if (pRecord == NULL){ pRecord = new UDPServerRecord; pRecord->m_nResults = 1; pRecord->m_nSpamResults = 0; m_aUDPServerRecords.SetAt(nServerIP, pRecord); } else pRecord->m_nResults++; AddToList(toadd, false, nServerIP); return GetED2KResultCount(); } UINT CSearchList::GetResultCount(uint32 nSearchID) const { UINT nSources = 0; VERIFY( m_foundSourcesCount.Lookup(nSearchID, nSources) ); return nSources; } UINT CSearchList::GetED2KResultCount() const { return GetResultCount(m_nCurED2KSearchID); } void CSearchList::GetWebList(CQArray<SearchFileStruct, SearchFileStruct> *SearchFileArray, int iSortBy) const { for (POSITION pos = m_listFileLists.GetHeadPosition(); pos != NULL;) { SearchListsStruct* listCur = m_listFileLists.GetNext(pos); for(POSITION pos2 = listCur->m_listSearchFiles.GetHeadPosition(); pos2 != NULL; ) { const CSearchFile* pFile = listCur->m_listSearchFiles.GetNext(pos2); if (pFile == NULL || pFile->GetListParent() != NULL || pFile->GetFileSize() == (uint64)0 || pFile->GetFileName().IsEmpty()) continue; SearchFileStruct structFile; structFile.m_strFileName = pFile->GetFileName(); structFile.m_strFileType = pFile->GetFileTypeDisplayStr(); structFile.m_strFileHash = md4str(pFile->GetFileHash()); structFile.m_uSourceCount = pFile->GetSourceCount(); structFile.m_dwCompleteSourceCount = pFile->GetCompleteSourceCount(); structFile.m_uFileSize = pFile->GetFileSize(); switch (iSortBy) { case 0: structFile.m_strIndex = structFile.m_strFileName; break; case 1: structFile.m_strIndex.Format(_T("%10u"), structFile.m_uFileSize); break; case 2: structFile.m_strIndex = structFile.m_strFileHash; break; case 3: structFile.m_strIndex.Format(_T("%09u"), structFile.m_uSourceCount); break; case 4: structFile.m_strIndex = structFile.m_strFileType; break; default: structFile.m_strIndex.Empty(); } SearchFileArray->Add(structFile); } } } void CSearchList::AddFileToDownloadByHash(const uchar* hash, int cat) { for (POSITION pos = m_listFileLists.GetHeadPosition(); pos != NULL;) { const SearchListsStruct* listCur = m_listFileLists.GetNext(pos); for(POSITION pos2 = listCur->m_listSearchFiles.GetHeadPosition(); pos2 != NULL; ) { CSearchFile* sf = listCur->m_listSearchFiles.GetNext(pos2); if (!md4cmp(hash, sf->GetFileHash())){ theApp.downloadqueue->AddSearchToDownload(sf, 2, cat); return; } } } } // mobilemule CSearchFile* CSearchList::DetachNextFile(uint32 nSearchID) { // the files are NOT deleted, make sure you do this if you call this function // find, removes and returns the searchresult with most Sources uint32 nHighSource = 0; POSITION resultpos = 0; SearchList* list = GetSearchListForID(nSearchID); for (POSITION pos = list->GetHeadPosition(); pos != NULL; ) { POSITION cur_pos = pos; CSearchFile* cur_file = list->GetNext(pos); ASSERT( cur_file->GetSearchID() == nSearchID ); if (cur_file->GetIntTagValue(FT_SOURCES) >= nHighSource) { nHighSource = cur_file->GetIntTagValue(FT_SOURCES); resultpos = cur_pos; } } if (resultpos == 0){ ASSERT ( false ); return NULL; } CSearchFile* result = list->GetAt(resultpos); list->RemoveAt(resultpos); return result; } bool CSearchList::AddToList(CSearchFile* toadd, bool bClientResponse, uint32 dwFromUDPServerIP) { //Xman // SLUGFILLER: searchCatch CPartFile *file = theApp.downloadqueue->GetFileByID(toadd->GetFileHash()); if (file){ if (toadd->GetClientID() && toadd->GetClientPort()){ // pre-filter sources which would be dropped in CPartFile::AddSources if (CPartFile::CanAddSource(toadd->GetClientID(), toadd->GetClientPort(), toadd->GetClientServerIP(), toadd->GetClientServerPort())){ CSafeMemFile sources(1+4+2); sources.WriteUInt8(1); sources.WriteUInt32(toadd->GetClientID()); sources.WriteUInt16(toadd->GetClientPort()); sources.SeekToBegin(); file->AddSources(&sources,toadd->GetClientServerIP(),toadd->GetClientServerPort(),false); } } } // SLUGFILLER: searchCatch if (!bClientResponse && !m_strResultFileType.IsEmpty() && _tcscmp(m_strResultFileType, toadd->GetFileType()) != 0) { delete toadd; return false; } SearchList* list = GetSearchListForID(toadd->GetSearchID()); // Spamfilter: Calculate the filename without any used keywords (and seperators) for later use CString strNameWithoutKeyword; CString strName = toadd->GetFileName(); strName.MakeLower(); int nPos = 0; CString strToken = strName.Tokenize(_T(".[]()!-'_ "), nPos); bool bFound; while (!strToken.IsEmpty()){ bFound = false; if (!bClientResponse && toadd->GetSearchID() == m_nCurED2KSearchID){ for (int i = 0; i < m_astrSpamCheckCurSearchExp.GetCount(); i++){ if (strToken.Compare(m_astrSpamCheckCurSearchExp[i]) == 0){ bFound = true; break; } } } if (!bFound){ if (!strNameWithoutKeyword.IsEmpty()) strNameWithoutKeyword += _T(" "); strNameWithoutKeyword += strToken; } strToken = strName.Tokenize(_T(".[]()!-'_ "), nPos); } toadd->SetNameWithoutKeyword(strNameWithoutKeyword); // search for a 'parent' with same filehash and search-id as the new search result entry for (POSITION pos = list->GetHeadPosition(); pos != NULL; ) { CSearchFile* parent = list->GetNext(pos); if ( parent->GetListParent() == NULL && md4cmp(parent->GetFileHash(), toadd->GetFileHash()) == 0) { // if this parent does not yet have any child entries, create one child entry // which is equal to the current parent entry (needed for GUI when expanding the child list). if (parent->GetListChildCount() == 0) { CSearchFile* child = new CSearchFile(parent); child->SetListParent(parent); int iSources = parent->GetIntTagValue(FT_SOURCES); if (iSources == 0) iSources = 1; child->SetListChildCount(iSources); list->AddTail(child); parent->SetListChildCount(1); } // get the 'Availability' of the new search result entry UINT uAvail; if (bClientResponse) { // If this is a response from a client ("View Shared Files"), we set the "Availability" at least to 1. if (!toadd->GetIntTagValue(FT_SOURCES, uAvail) || uAvail==0) uAvail = 1; } else uAvail = toadd->GetIntTagValue(FT_SOURCES); // get 'Complete Sources' of the new search result entry uint32 uCompleteSources = (uint32)-1; bool bHasCompleteSources = toadd->GetIntTagValue(FT_COMPLETE_SOURCES, uCompleteSources); bool bFound = false; if (thePrefs.GetDebugSearchResultDetailLevel() >= 1) { ; // for debugging: do not merge search results } else { // check if that parent already has a child with same filename as the new search result entry for (POSITION pos2 = list->GetHeadPosition(); pos2 != NULL && !bFound; ) { CSearchFile* child = list->GetNext(pos2); if ( child != toadd // not the same object && child->GetListParent() == parent // is a child of our result (one filehash) && toadd->GetFileName().CompareNoCase(child->GetFileName()) == 0) // same name { bFound = true; // add properties of new search result entry to the already available child entry (with same filename) // ed2k: use the sum of all values, kad: use the max. values if (toadd->IsKademlia()) { if (uAvail > child->GetListChildCount()) child->SetListChildCount(uAvail); } else { child->AddListChildCount(uAvail); } child->AddSources(uAvail); if (bHasCompleteSources) child->AddCompleteSources(uCompleteSources); // Check AICH Hash - if they differ, clear it (see KademliaSearchKeyword) // if we didn't have a hash yet, take it over if (toadd->GetFileIdentifier().HasAICHHash()) { if (child->GetFileIdentifier().HasAICHHash()) { if (parent->GetFileIdentifier().GetAICHHash() != toadd->GetFileIdentifier().GetAICHHash()) { DEBUG_ONLY(DebugLogWarning(_T("Kad: SearchList: AddToList: Received searchresult with different AICH hash than existing one, ignoring AICH for result %s"), child->GetFileName()) ); child->SetFoundMultipleAICH(); child->GetFileIdentifier().ClearAICHHash(); } } else if (!child->DidFoundMultipleAICH()) { DEBUG_ONLY(DebugLog(_T("Kad: SearchList: AddToList: Received searchresult with new AICH hash %s, taking over to existing result. Entry: %s"), toadd->GetFileIdentifier().GetAICHHash().GetString(), child->GetFileName()) ); child->GetFileIdentifier().SetAICHHash(toadd->GetFileIdentifier().GetAICHHash()); } } break; } } } if (!bFound) { // the parent which we had found does not yet have a child with that new search result's entry name, // add the new entry as a new child // toadd->SetListParent(parent); toadd->SetListChildCount(uAvail); parent->AddListChildCount(1); list->AddHead(toadd); } // copy possible available sources from new search result entry to parent if (toadd->GetClientID() && toadd->GetClientPort()) { if (IsValidSearchResultClientIPPort(toadd->GetClientID(), toadd->GetClientPort())) { // pre-filter sources which would be dropped in CPartFile::AddSources if (CPartFile::CanAddSource(toadd->GetClientID(), toadd->GetClientPort(), toadd->GetClientServerIP(), toadd->GetClientServerPort())) { CSearchFile::SClient client(toadd->GetClientID(), toadd->GetClientPort(), toadd->GetClientServerIP(), toadd->GetClientServerPort()); if (parent->GetClients().Find(client) == -1) parent->AddClient(client); } } else { if (thePrefs.GetDebugServerSearchesLevel() > 1) { uint32 nIP = toadd->GetClientID(); Debug(_T("Filtered source from search result %s:%u\n"), DbgGetClientID(nIP), toadd->GetClientPort()); } } } // copy possible available servers from new search result entry to parent // will be used in future if (toadd->GetClientServerIP() && toadd->GetClientServerPort()) { CSearchFile::SServer server(toadd->GetClientServerIP(), toadd->GetClientServerPort(), toadd->IsServerUDPAnswer()); int iFound = parent->GetServers().Find(server); if (iFound == -1) { server.m_uAvail = uAvail; parent->AddServer(server); } else parent->GetServerAt(iFound).m_uAvail += uAvail; } UINT uAllChildsSourceCount = 0; // ed2k: sum of all sources, kad: the max. sources found UINT uAllChildsCompleteSourceCount = 0; // ed2k: sum of all sources, kad: the max. sources found UINT uDifferentNames = 0; // max known different names UINT uPublishersKnown = 0; // max publishers known (might be changed to median) UINT uTrustValue = 0; // average trust value (might be changed to median) uint32 nPublishInfoTags = 0; const CSearchFile* bestEntry = NULL; bool bHasMultipleAICHHashs = false; CAICHHash aichHash; bool bAICHHashValid = false; for (POSITION pos2 = list->GetHeadPosition(); pos2 != NULL; ) { const CSearchFile* child = list->GetNext(pos2); if (child->GetListParent() == parent) { // figure out if the childs of different AICH hashs if (child->GetFileIdentifierC().HasAICHHash()) { if (bAICHHashValid && aichHash != child->GetFileIdentifierC().GetAICHHash()) bHasMultipleAICHHashs = true; else if (!bAICHHashValid) { aichHash = child->GetFileIdentifierC().GetAICHHash(); bAICHHashValid = true; } } else if (child->DidFoundMultipleAICH()) bHasMultipleAICHHashs = true; if (parent->IsKademlia()) { if (child->GetListChildCount() > uAllChildsSourceCount) uAllChildsSourceCount = child->GetListChildCount(); /*if (child->GetCompleteSourceCount() > uAllChildsCompleteSourceCount) // not yet supported uAllChildsCompleteSourceCount = child->GetCompleteSourceCount();*/ if (child->GetKadPublishInfo() != 0){ nPublishInfoTags++; uDifferentNames = max(uDifferentNames, ((child->GetKadPublishInfo() & 0xFF000000) >> 24)); uPublishersKnown = max (uPublishersKnown, ((child->GetKadPublishInfo() & 0x00FF0000) >> 16)); uTrustValue += child->GetKadPublishInfo() & 0x0000FFFF; } } else { uAllChildsSourceCount += child->GetListChildCount(); uAllChildsCompleteSourceCount += child->GetCompleteSourceCount(); } if (bestEntry == NULL) bestEntry = child; else if (child->GetListChildCount() > bestEntry->GetListChildCount()) bestEntry = child; } } if (bestEntry) { parent->SetFileSize(bestEntry->GetFileSize()); parent->SetFileName(bestEntry->GetFileName()); parent->SetFileType(bestEntry->GetFileType()); parent->ClearTags(); parent->CopyTags(bestEntry->GetTags()); parent->SetIntTagValue(FT_SOURCES, uAllChildsSourceCount); parent->SetIntTagValue(FT_COMPLETE_SOURCES, uAllChildsCompleteSourceCount); if (uTrustValue > 0 && nPublishInfoTags > 0) uTrustValue = uTrustValue / nPublishInfoTags; parent->SetKadPublishInfo(((uDifferentNames & 0xFF) << 24) | ((uPublishersKnown & 0xFF) << 16) | ((uTrustValue & 0xFFFF) << 0)); // if all childs have the same AICH hash (or none), set the parent hash to it, otherwise clear it (see KademliaSearchKeyword) if (bHasMultipleAICHHashs || !bAICHHashValid) parent->GetFileIdentifier().ClearAICHHash(); else if (bAICHHashValid) parent->GetFileIdentifier().SetAICHHash(aichHash); } // recalculate spamrating DoSpamRating(parent, bClientResponse, false, false, false, dwFromUDPServerIP); // add the 'Availability' of the new search result entry to the total search result count for this search AddResultCount(parent->GetSearchID(), parent->GetFileHash(), uAvail, parent->IsConsideredSpam()); // update parent in GUI if (outputwnd && !m_MobilMuleSearch) outputwnd->UpdateSources(parent); if (bFound) delete toadd; return true; } } // no bounded result found yet -> add as parent to list toadd->SetListParent(NULL); UINT uAvail = 0; if (list->AddTail(toadd)) { UINT tempValue = 0; VERIFY( m_foundFilesCount.Lookup(toadd->GetSearchID(), tempValue) ); m_foundFilesCount.SetAt(toadd->GetSearchID(), tempValue + 1); // get the 'Availability' of this new search result entry if (bClientResponse) { // If this is a response from a client ("View Shared Files"), we set the "Availability" at least to 1. if (!toadd->GetIntTagValue(FT_SOURCES, uAvail) || uAvail==0) uAvail = 1; toadd->AddSources(uAvail); } else uAvail = toadd->GetIntTagValue(FT_SOURCES); } if (thePrefs.GetDebugSearchResultDetailLevel() >= 1) toadd->SetListExpanded(true); // calculate spamrating DoSpamRating(toadd, bClientResponse, false, false, false, dwFromUDPServerIP); // add the 'Availability' of this new search result entry to the total search result count for this search AddResultCount(toadd->GetSearchID(), toadd->GetFileHash(), uAvail, toadd->IsConsideredSpam()); // add parent in GUI if (outputwnd && !m_MobilMuleSearch) outputwnd->AddResult(toadd); return true; } CSearchFile* CSearchList::GetSearchFileByHash(const uchar* hash) const { for (POSITION pos = m_listFileLists.GetHeadPosition(); pos != NULL;) { const SearchListsStruct* listCur = m_listFileLists.GetNext(pos); for(POSITION pos2 = listCur->m_listSearchFiles.GetHeadPosition(); pos2 != NULL; ) { CSearchFile* sf = listCur->m_listSearchFiles.GetNext(pos2); if (!md4cmp(hash, sf->GetFileHash())) return sf; } } return NULL; } bool CSearchList::AddNotes(Kademlia::CEntry* entry, const uchar *hash) { bool flag = false; for (POSITION pos = m_listFileLists.GetHeadPosition(); pos != NULL;) { const SearchListsStruct* listCur = m_listFileLists.GetNext(pos); for(POSITION pos2 = listCur->m_listSearchFiles.GetHeadPosition(); pos2 != NULL; ) { CSearchFile* sf = listCur->m_listSearchFiles.GetNext(pos2); if (!md4cmp(hash, sf->GetFileHash())){ Kademlia::CEntry* entryClone = entry->Copy(); if(sf->AddNote(entryClone)) flag = true; else delete entryClone; } } } return flag; } void CSearchList::SetNotesSearchStatus(const uchar* pFileHash, bool bSearchRunning){ for (POSITION pos = m_listFileLists.GetHeadPosition(); pos != NULL;) { const SearchListsStruct* listCur = m_listFileLists.GetNext(pos); for(POSITION pos2 = listCur->m_listSearchFiles.GetHeadPosition(); pos2 != NULL; ) { CSearchFile* sf = listCur->m_listSearchFiles.GetNext(pos2); if (!md4cmp(pFileHash, sf->GetFileHash())) sf->SetKadCommentSearchRunning(bSearchRunning); } } } void CSearchList::AddResultCount(uint32 nSearchID, const uchar* hash, UINT nCount, bool bSpam) { // do not count already available or downloading files for the search result limit if (theApp.sharedfiles->GetFileByID(hash) || theApp.downloadqueue->GetFileByID(hash)) return; UINT tempValue = 0; VERIFY( m_foundSourcesCount.Lookup(nSearchID, tempValue) ); // spam files count as max 5 availability m_foundSourcesCount.SetAt(nSearchID, tempValue + ( (bSpam && thePrefs.IsSearchSpamFilterEnabled()) ? min(nCount, 5) : nCount) ); } // FIXME LARGE FILES void CSearchList::KademliaSearchKeyword(uint32 searchID, const Kademlia::CUInt128* fileID, LPCTSTR name, uint64 size, LPCTSTR type, UINT uKadPublishInfo , CArray<CAICHHash>& raAICHHashs, CArray<uint8>& raAICHHashPopularity , SSearchTerm* pQueriedSearchTerm, UINT numProperties, ...) { va_list args; va_start(args, numProperties); EUtf8Str eStrEncode = utf8strRaw; CSafeMemFile* temp = new CSafeMemFile(250); Kademlia::CKeyEntry verifierEntry; verifierEntry.m_uKeyID.SetValue(*fileID); uchar fileid[16]; fileID->ToByteArray(fileid); temp->WriteHash16(fileid); temp->WriteUInt32(0); // client IP temp->WriteUInt16(0); // client port // write tag list UINT uFilePosTagCount = (UINT)temp->GetPosition(); uint32 tagcount = 0; temp->WriteUInt32(tagcount); // dummy tag count, will be filled later // standard tags CTag tagName(FT_FILENAME, name); tagName.WriteTagToFile(temp, eStrEncode); tagcount++; verifierEntry.SetFileName(name); CTag tagSize(FT_FILESIZE, size, true); tagSize.WriteTagToFile(temp, eStrEncode); tagcount++; verifierEntry.m_uSize = size; if (type != NULL && type[0] != _T('\0')) { CTag tagType(FT_FILETYPE, type); tagType.WriteTagToFile(temp, eStrEncode); tagcount++; verifierEntry.AddTag(new Kademlia::CKadTagStr(TAG_FILETYPE, type)); } // additional tags while (numProperties-- > 0) { UINT uPropType = va_arg(args, UINT); LPCSTR pszPropName = va_arg(args, LPCSTR); LPVOID pvPropValue = va_arg(args, LPVOID); if (uPropType == 2 /*TAGTYPE_STRING*/) { if ((LPCTSTR)pvPropValue != NULL && ((LPCTSTR)pvPropValue)[0] != _T('\0')) { if (strlen(pszPropName) == 1) { CTag tagProp((uint8)*pszPropName, (LPCTSTR)pvPropValue); tagProp.WriteTagToFile(temp, eStrEncode); } else { CTag tagProp(pszPropName, (LPCTSTR)pvPropValue); tagProp.WriteTagToFile(temp, eStrEncode); } verifierEntry.AddTag(new Kademlia::CKadTagStr(pszPropName, (LPCTSTR)pvPropValue)); tagcount++; } } else if (uPropType == 3 /*TAGTYPE_UINT32*/) { if ((uint32)pvPropValue != 0) { CTag tagProp(pszPropName, (uint32)pvPropValue); tagProp.WriteTagToFile(temp, eStrEncode); tagcount++; verifierEntry.AddTag(new Kademlia::CKadTagUInt(pszPropName, (uint32)pvPropValue)); } } else { ASSERT(0); } } va_end(args); temp->Seek(uFilePosTagCount, SEEK_SET); temp->WriteUInt32(tagcount); temp->SeekToBegin(); if (pQueriedSearchTerm == NULL || verifierEntry.StartSearchTermsMatch(pQueriedSearchTerm)) { CSearchFile* tempFile = new CSearchFile(temp, eStrEncode == utf8strRaw, searchID, 0, 0, 0, true); tempFile->SetKadPublishInfo(uKadPublishInfo); // About the AICH hash: We received a list of possible AICH Hashs for this file and now have to deceide what to do // If it wasn't for backwards compability, the choice would be easy: Each different md4+aich+size is its own result, // but we can'T do this alone for the fact that for the next years we will always have publishers which don'T report // the AICH hash at all (which would mean ahving a different entry, which leads to double files in searchresults). So here is what we do for now: // If we have excactly 1 AICH hash and more than 1/3 of the publishers reported it, we set it as verified AICH hash for // the file (which is as good as using a ed2k link with an AICH hash attached). If less publishers reported it or if we // have multiple AICH hashes, we ignore them and use the MD4 only. // This isn't a perfect solution, but it makes sure not to open any new attack vectors (a wrong AICH hash means we cannot // download the file sucessfully) nor to confuse users by requiering them to select an entry out of several equal looking results. // Once the majority of nodes in the network publishes AICH hashes, this might get reworked to make the AICH hash more sticky if (raAICHHashs.GetCount() == 1 && raAICHHashPopularity.GetCount() == 1) { uint8 byPublishers = (uint8)((uKadPublishInfo & 0x00FF0000) >> 16); if ( byPublishers > 0 && raAICHHashPopularity[0] > 0 && byPublishers / raAICHHashPopularity[0] <= 3) { DEBUG_ONLY( DebugLog(_T("Received accepted AICH Hash for search result %s, %u out of %u Publishers, Hash: %s") , tempFile->GetFileName(), raAICHHashPopularity[0], byPublishers, raAICHHashs[0].GetString()) ); tempFile->GetFileIdentifier().SetAICHHash(raAICHHashs[0]); } else DEBUG_ONLY( DebugLog(_T("Received unaccepted AICH Hash for search result %s, %u out of %u Publishers, Hash: %s") , tempFile->GetFileName(), raAICHHashPopularity[0], byPublishers, raAICHHashs[0].GetString()) ); } else if (raAICHHashs.GetCount() > 1) DEBUG_ONLY( DebugLog(_T("Received multiple (%u) AICH Hashs for search result %s, ignoring AICH"), raAICHHashs.GetCount(), tempFile->GetFileName()) ); AddToList(tempFile); } else { DebugLogWarning(_T("Kad Searchresult failed sanitize check against search query, ignoring. (%s)"), name); } delete temp; } // default spam threshold = 60 #define SPAM_FILEHASH_HIT 100 #define SPAM_FULLNAME_HIT 80 #define SPAM_SMALLFULLNAME_HIT 50 #define SPAM_SIMILARNAME_HIT 60 #define SPAM_SMALLSIMILARNAME_HIT 40 #define SPAM_SIMILARNAME_NEARHIT 50 #define SPAM_SIMILARNAME_FARHIT 40 #define SPAM_SIMILARSIZE_HIT 10 #define SPAM_UDPSERVERRES_HIT 21 #define SPAM_UDPSERVERRES_NEARHIT 15 #define SPAM_UDPSERVERRES_FARHIT 10 #define SPAM_ONLYUDPSPAMSERVERS_HIT 30 #define SPAM_SOURCE_HIT 39 #define SPAM_HEURISTIC_BASEHIT 39 #define SPAM_HEURISTIC_MAXHIT 60 #define UDP_SPAMRATIO_THRESHOLD 50 void CSearchList::DoSpamRating(CSearchFile* pSearchFile, bool bIsClientFile, bool bMarkAsNoSpam, bool bRecalculateAll, bool bUpdate, uint32 dwFromUDPServerIP){ /* This spam filter uses two simple approaches to try to identify spam search results: 1 - detect general characteristics of fake results - not very reliable which are (each hit increases the score) * high availability from one udp server, but none from others * archive or programm + size between 0,1 and 10 MB * 100% complete sources together with high availability Appearently, those characteristics target for current spyware fake results, other fake results like videos and so on will not be detectable, because only the first point is more or less common for server fake results, which would produce too many false positives 2 - learn characteristics of files a user has marked as spam remembered data is: * FileHash (of course, a hit will always lead to a full score rating) * Equal filename * Equal or similar name after removing the search keywords and seperators (if search for "emule", "blubby!! emule foo.rar" is remembered as "blubby foo rar") * Similar size (+- 5% but max 5MB) as other spam files * Equal search source server (UDP only) * Equal initial source clients * Ratio (Spam / NotSpam) of UDP Servers Both detection methods add to the same score rating. bMarkAsNoSpam = true: Will remove all stored characteristics which would add to an postive spam score for this file */ ASSERT( (bRecalculateAll && bMarkAsNoSpam) || !bRecalculateAll ); if (!thePrefs.IsSearchSpamFilterEnabled()) return; if (!m_bSpamFilterLoaded) LoadSpamFilter(); int nSpamScore = 0; CString strDebug; bool bSureNegative = false; int nDbgFileHash, nDbgStrings, nDbgSize, nDbgServer, nDbgSources, nDbgHeuristic, nDbgOnlySpamServer; nDbgFileHash = nDbgStrings = nDbgSize = nDbgServer = nDbgSources = nDbgHeuristic = nDbgOnlySpamServer = 0; // 1- filehash bool bSpam = false; if (m_mapKnownSpamHashs.Lookup(CSKey(pSearchFile->GetFileHash()), bSpam)){ if (!bMarkAsNoSpam && bSpam){ nSpamScore += SPAM_FILEHASH_HIT; nDbgFileHash = SPAM_FILEHASH_HIT; } else if (bSpam) m_mapKnownSpamHashs.RemoveKey(CSKey(pSearchFile->GetFileHash())); else bSureNegative = true; } CSearchFile* pParent = NULL; if (pSearchFile->GetListParent() != NULL) pParent = pSearchFile->GetListParent(); else if (pSearchFile->GetListChildCount() > 0) pParent = pSearchFile; CSearchFile* pTempFile = (pSearchFile->GetListParent() != NULL) ? pSearchFile->GetListParent() : pSearchFile; if (!bSureNegative && bMarkAsNoSpam) m_mapKnownSpamHashs.SetAt(CSKey(pSearchFile->GetFileHash()), false); #ifndef _DEBUG else if (bSureNegative && !bMarkAsNoSpam) { #endif // 2-3 FileNames // consider also filenames of childs / parents / silblings and take the highest rating uint32 nHighestRating; if (pParent != NULL){ nHighestRating = GetSpamFilenameRatings(pParent, bMarkAsNoSpam); SearchList* list = GetSearchListForID(pParent->GetSearchID()); for (POSITION pos = list->GetHeadPosition(); pos != NULL; ) { const CSearchFile* pCurFile = list->GetNext(pos); if (pCurFile->GetListParent() == pParent){ uint32 nRating = GetSpamFilenameRatings(pCurFile, bMarkAsNoSpam); nHighestRating = max(nHighestRating, nRating); } } } else nHighestRating = GetSpamFilenameRatings(pSearchFile, bMarkAsNoSpam); nSpamScore += nHighestRating; nDbgStrings = nHighestRating; //4 - Sizes for (int i = 0; i < m_aui64KnownSpamSizes.GetCount(); i++){ if ((uint64)pSearchFile->GetFileSize() != 0 && _abs64((uint64)pSearchFile->GetFileSize() - m_aui64KnownSpamSizes[i]) < 5242880 && ((_abs64((uint64)pSearchFile->GetFileSize() - m_aui64KnownSpamSizes[i]) * 100) / (uint64)pSearchFile->GetFileSize()) < 5) { if (!bMarkAsNoSpam){ nSpamScore += SPAM_SIMILARSIZE_HIT; nDbgSize = SPAM_SIMILARSIZE_HIT; break; } else{ m_aui64KnownSpamSizes.RemoveAt(i); i--; } } } if (!bIsClientFile){ // only to skip some useless calculations //5 Servers for (int i = 0; i != pTempFile->GetServers().GetSize(); i++){ bool bFound = false; if (pTempFile->GetServers()[i].m_nIP != 0 && pTempFile->GetServers()[i].m_bUDPAnswer && m_mapKnownSpamServerIPs.Lookup(pTempFile->GetServers()[i].m_nIP, bFound)) { if (!bMarkAsNoSpam){ strDebug.AppendFormat(_T(" (Serverhit: %s)"), ipstr(pTempFile->GetServers()[i].m_nIP)); if (pSearchFile->GetServers().GetSize() == 1 && m_mapKnownSpamServerIPs.GetCount() <= 10){ // source only from one server nSpamScore += SPAM_UDPSERVERRES_HIT; nDbgServer = SPAM_UDPSERVERRES_HIT; } else if (pSearchFile->GetServers().GetSize() == 1){ // source only from one server but the users seems to be a bit careless with the mark as spam option // and has already added a lot UDP servers. To avoid false positives, we give a lower rating nSpamScore += SPAM_UDPSERVERRES_NEARHIT; nDbgServer = SPAM_UDPSERVERRES_NEARHIT; } else{ // file was given by more than one server, lowest spam rating for server hits nSpamScore += SPAM_UDPSERVERRES_FARHIT; nDbgServer = SPAM_UDPSERVERRES_FARHIT; } break; } else m_mapKnownSpamServerIPs.RemoveKey(pTempFile->GetServers()[i].m_nIP); } } // partial heuristic - only udp spamservers // has this file at least one server as origin which is not rated for spam or UDP // or not a result from a server at all bool bNormalServerWithoutCurrentPresent = (pTempFile->GetServers().GetSize() == 0); bool bNormalServerPresent = (pTempFile->GetServers().GetSize() == 0); for (int i = 0; i != pTempFile->GetServers().GetSize(); i++){ UDPServerRecord* pRecord = NULL; if (!bMarkAsNoSpam && pTempFile->GetServers()[i].m_bUDPAnswer && m_aUDPServerRecords.Lookup(pTempFile->GetServers()[i].m_nIP, pRecord) && pRecord != NULL){ ASSERT( pRecord->m_nResults >= pRecord->m_nSpamResults ); int nRatio; if (pRecord->m_nResults >= pRecord->m_nSpamResults && pRecord->m_nResults != 0){ nRatio = (pRecord->m_nSpamResults * 100) / pRecord->m_nResults; } else nRatio = 100; if (nRatio < 50){ bNormalServerWithoutCurrentPresent |= (dwFromUDPServerIP != pTempFile->GetServers()[i].m_nIP); bNormalServerPresent = true; } } else if (!pTempFile->GetServers()[i].m_bUDPAnswer){ bNormalServerWithoutCurrentPresent = true; bNormalServerPresent = true; break; } else if (!bMarkAsNoSpam) ASSERT( pRecord != NULL ); } if (!bNormalServerPresent && !bMarkAsNoSpam){ nDbgOnlySpamServer = SPAM_ONLYUDPSPAMSERVERS_HIT; nSpamScore += SPAM_ONLYUDPSPAMSERVERS_HIT; strDebug += _T(" (AllSpamServers)"); } else if(!bNormalServerWithoutCurrentPresent && !bMarkAsNoSpam) strDebug += _T(" (AllSpamServersWoCurrent)"); // 7 Heuristic (UDP Results) uint32 nResponses = 0; VERIFY( m_ReceivedUDPAnswersCount.Lookup(pTempFile->GetSearchID(), nResponses) ); uint32 nRequests = 0; VERIFY( m_RequestedUDPAnswersCount.Lookup(pTempFile->GetSearchID(), nRequests) ); if (!bNormalServerWithoutCurrentPresent && (nResponses >= 3 || nRequests >= 5) && pTempFile->GetSourceCount() > 100) { // check if the one of the files sources are in the same ip subnet as a udp server // which indicates that the server is advertising its own files bool bSourceServer = false; for (int i = 0; i != pTempFile->GetServers().GetSize(); i++){ if (pTempFile->GetServers()[i].m_nIP != 0){ if ( (pTempFile->GetServers()[i].m_nIP & 0x00FFFFFF) == (pTempFile->GetClientID() & 0x00FFFFFF)){ bSourceServer = true; strDebug.AppendFormat(_T(" (Server: %s - Source: %s Hit)"), ipstr(pTempFile->GetServers()[i].m_nIP), ipstr(pTempFile->GetClientID())); break; } for (int j = 0; j != pTempFile->GetClients().GetSize(); j++){ if ( (pTempFile->GetServers()[i].m_nIP & 0x00FFFFFF) == (pTempFile->GetClients()[j].m_nIP & 0x00FFFFFF)){ bSourceServer = true; strDebug.AppendFormat(_T(" (Server: %s - Source: %s Hit)"), ipstr(pTempFile->GetServers()[i].m_nIP), ipstr(pTempFile->GetClients()[j].m_nIP)); break; } } } } if (((GetED2KFileTypeID(pTempFile->GetFileName()) == ED2KFT_PROGRAM || GetED2KFileTypeID(pTempFile->GetFileName()) == ED2KFT_ARCHIVE) && (uint64)pTempFile->GetFileSize() > 102400 && (uint64)pTempFile->GetFileSize() < 10485760 && !bMarkAsNoSpam) || bSourceServer) { nSpamScore += SPAM_HEURISTIC_MAXHIT; nDbgHeuristic = SPAM_HEURISTIC_MAXHIT; } else if (!bMarkAsNoSpam){ nSpamScore += SPAM_HEURISTIC_BASEHIT; nDbgHeuristic = SPAM_HEURISTIC_BASEHIT; } } } // 6 Sources bool bFound = false; if (IsValidSearchResultClientIPPort(pTempFile->GetClientID(), pTempFile->GetClientPort()) && !::IsLowID(pTempFile->GetClientID()) && m_mapKnownSpamSourcesIPs.Lookup(pTempFile->GetClientID(), bFound)) { if (!bMarkAsNoSpam){ strDebug.AppendFormat(_T(" (Sourceshit: %s)"), ipstr(pTempFile->GetClientID())); nSpamScore += SPAM_SOURCE_HIT; nDbgSources = SPAM_SOURCE_HIT; } else m_mapKnownSpamSourcesIPs.RemoveKey(pTempFile->GetClientID()); } else{ for (int i = 0; i != pTempFile->GetClients().GetSize(); i++){ if (pTempFile->GetClients()[i].m_nIP != 0 && m_mapKnownSpamSourcesIPs.Lookup(pTempFile->GetClients()[i].m_nIP, bFound)) { if (!bMarkAsNoSpam){ strDebug.AppendFormat(_T(" (Sources: %s)"), ipstr(pTempFile->GetClients()[i].m_nIP)); nSpamScore += SPAM_SOURCE_HIT; nDbgSources = SPAM_SOURCE_HIT; break; } else m_mapKnownSpamSourcesIPs.RemoveKey(pTempFile->GetClients()[i].m_nIP); } } } #ifndef _DEBUG } #endif if (!bMarkAsNoSpam){ if (nSpamScore > 0) DebugLog(_T("Spamrating Result: %u. Details: Hash: %u, Name: %u, Size: %u, Server: %u, Sources: %u, Heuristic: %u, OnlySpamServers: %u. %s Filename: %s") ,bSureNegative ? 0 : nSpamScore, nDbgFileHash, nDbgStrings, nDbgSize, nDbgServer, nDbgSources, nDbgHeuristic, nDbgOnlySpamServer, strDebug, pSearchFile->GetFileName()); } else{ DebugLog(_T("Marked file as No Spam, Old Rating: %u."), pSearchFile->GetSpamRating()); } bool bOldSpamStatus = pSearchFile->IsConsideredSpam(); pParent = NULL; if (pSearchFile->GetListParent() != NULL) pParent = pSearchFile->GetListParent(); else if (pSearchFile->GetListChildCount() > 0) pParent = pSearchFile; if (pParent != NULL){ pParent->SetSpamRating(bMarkAsNoSpam ? 0 : nSpamScore); SearchList* list = GetSearchListForID(pParent->GetSearchID()); for (POSITION pos = list->GetHeadPosition(); pos != NULL; ) { CSearchFile* pCurFile = list->GetNext(pos); if (pCurFile->GetListParent() == pParent) pCurFile->SetSpamRating( (bMarkAsNoSpam || bSureNegative) ? 0 : nSpamScore); } } else pSearchFile->SetSpamRating(bMarkAsNoSpam ? 0 : nSpamScore); // keep record about ratio of spam in UDP server results if (bOldSpamStatus != pSearchFile->IsConsideredSpam()){ for (int i = 0; i != pTempFile->GetServers().GetSize(); i++){ UDPServerRecord* pRecord = NULL; if (pTempFile->GetServers()[i].m_bUDPAnswer && m_aUDPServerRecords.Lookup(pTempFile->GetServers()[i].m_nIP, pRecord) && pRecord != NULL) { if (pSearchFile->IsConsideredSpam()) pRecord->m_nSpamResults++; else { ASSERT( pRecord->m_nSpamResults > 0 ); pRecord->m_nSpamResults--; } } } } else if (dwFromUDPServerIP != 0 && pSearchFile->IsConsideredSpam()){ // files was already spam, but a new server also gave it as result, add it to his spam stats UDPServerRecord* pRecord = NULL; if (m_aUDPServerRecords.Lookup(dwFromUDPServerIP, pRecord) && pRecord != NULL) pRecord->m_nSpamResults++; } if (bUpdate && outputwnd != NULL) outputwnd->UpdateSources((pParent != NULL) ? pParent : pSearchFile); if (bRecalculateAll) RecalculateSpamRatings(pSearchFile->GetSearchID(), false, true, bUpdate); } uint32 CSearchList::GetSpamFilenameRatings(const CSearchFile* pSearchFile, bool bMarkAsNoSpam){ for (int i = 0; i < m_astrKnownSpamNames.GetCount(); i++){ if (pSearchFile->GetFileName().CompareNoCase(m_astrKnownSpamNames[i]) == 0){ if (!bMarkAsNoSpam){ if (pSearchFile->GetFileName().GetLength() <= 10) return SPAM_SMALLFULLNAME_HIT; else return SPAM_FULLNAME_HIT; } else{ m_astrKnownSpamNames.RemoveAt(i); i--; } } } uint32 nResult = 0; if (!m_astrKnownSimilarSpamNames.IsEmpty() && !pSearchFile->GetNameWithoutKeyword().IsEmpty()){ for (int i = 0; i < m_astrKnownSimilarSpamNames.GetCount(); i++){ bool bRemove = false; if (pSearchFile->GetNameWithoutKeyword().Compare(m_astrKnownSimilarSpamNames[i]) == 0){ if (!bMarkAsNoSpam){ if (pSearchFile->GetNameWithoutKeyword().GetLength() <= 10) return SPAM_SMALLSIMILARNAME_HIT; else return SPAM_SIMILARNAME_HIT; } else bRemove = true; } else if (pSearchFile->GetNameWithoutKeyword().GetLength() > 10 && (abs(pSearchFile->GetNameWithoutKeyword().GetLength() - m_astrKnownSimilarSpamNames[i].GetLength()) == 0 || pSearchFile->GetNameWithoutKeyword().GetLength() / abs(pSearchFile->GetNameWithoutKeyword().GetLength() - m_astrKnownSimilarSpamNames[i].GetLength()) >= 3)) { uint32 nStringComp = LevenshteinDistance(pSearchFile->GetNameWithoutKeyword(), m_astrKnownSimilarSpamNames[i]); if (nStringComp != 0) nStringComp = pSearchFile->GetNameWithoutKeyword().GetLength() / nStringComp; if (nStringComp >= 3){ if (!bMarkAsNoSpam){ if (nStringComp >= 6) nResult = SPAM_SIMILARNAME_NEARHIT; else nResult = max(nResult, SPAM_SIMILARNAME_FARHIT); } else bRemove = true; } } if (bRemove){ m_astrKnownSimilarSpamNames.RemoveAt(i); i--; } } } return nResult; } SearchList* CSearchList::GetSearchListForID(uint32 nSearchID){ for (POSITION pos = m_listFileLists.GetHeadPosition(); pos != NULL; ) { SearchListsStruct* list = m_listFileLists.GetNext(pos); if (list->m_nSearchID == nSearchID) return &list->m_listSearchFiles; } SearchListsStruct* list = new SearchListsStruct; list->m_nSearchID = nSearchID; m_listFileLists.AddHead(list); return &list->m_listSearchFiles; } void CSearchList::SentUDPRequestNotification(uint32 nSearchID, uint32 dwServerIP){ if (nSearchID == m_nCurED2KSearchID){ m_RequestedUDPAnswersCount.SetAt(nSearchID, m_aCurED2KSentRequestsIPs.Add(dwServerIP) + 1); } else ASSERT( false ); } void CSearchList::MarkFileAsSpam(CSearchFile* pSpamFile, bool bRecalculateAll, bool bUpdate){ if (!m_bSpamFilterLoaded) LoadSpamFilter(); m_astrKnownSpamNames.Add(pSpamFile->GetFileName()); m_astrKnownSimilarSpamNames.Add(pSpamFile->GetNameWithoutKeyword()); m_mapKnownSpamHashs.SetAt(CSKey(pSpamFile->GetFileHash()), true); m_aui64KnownSpamSizes.Add((uint64)pSpamFile->GetFileSize()); if (IsValidSearchResultClientIPPort(pSpamFile->GetClientID(), pSpamFile->GetClientPort()) && !::IsLowID(pSpamFile->GetClientID())) { m_mapKnownSpamSourcesIPs.SetAt(pSpamFile->GetClientID(), true); } for (int i = 0; i != pSpamFile->GetClients().GetSize(); i++){; if (pSpamFile->GetClients()[i].m_nIP != 0){ m_mapKnownSpamSourcesIPs.SetAt(pSpamFile->GetClients()[i].m_nIP, true); } } for (int i = 0; i != pSpamFile->GetServers().GetSize(); i++){ if (pSpamFile->GetServers()[i].m_nIP != 0 && pSpamFile->GetServers()[i].m_bUDPAnswer){ m_mapKnownSpamServerIPs.SetAt(pSpamFile->GetServers()[i].m_nIP, true); } } if (bRecalculateAll) RecalculateSpamRatings(pSpamFile->GetSearchID(), true, false, bUpdate); else DoSpamRating(pSpamFile); if (bUpdate && outputwnd != NULL) outputwnd->UpdateSources(pSpamFile); } void CSearchList::RecalculateSpamRatings(uint32 nSearchID, bool bExpectHigher, bool bExpectLower, bool bUpdate){ ASSERT( !(bExpectHigher && bExpectLower) ); ASSERT( m_bSpamFilterLoaded ); SearchList* list = GetSearchListForID(nSearchID); for (POSITION pos = list->GetHeadPosition(); pos != NULL; ) { CSearchFile* pCurFile = list->GetNext(pos); // check only parents and only if we expect a status change if (pCurFile->GetListParent() == NULL && !(pCurFile->IsConsideredSpam() && bExpectHigher) && !(!pCurFile->IsConsideredSpam() && bExpectLower)) { DoSpamRating(pCurFile, false, false, false, false); if (bUpdate && outputwnd != NULL) outputwnd->UpdateSources(pCurFile); } } } void CSearchList::LoadSpamFilter(){ m_astrKnownSpamNames.RemoveAll(); m_astrKnownSimilarSpamNames.RemoveAll(); m_mapKnownSpamServerIPs.RemoveAll(); m_mapKnownSpamSourcesIPs.RemoveAll(); m_mapKnownSpamHashs.RemoveAll(); m_aui64KnownSpamSizes.RemoveAll(); int nDbgFileHashPos = 0; m_bSpamFilterLoaded = true; CString fullpath = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR); fullpath.Append(SPAMFILTER_FILENAME); CSafeBufferedFile file; CFileException fexp; if (!file.Open(fullpath,CFile::modeRead|CFile::osSequentialScan|CFile::typeBinary|CFile::shareDenyWrite, &fexp)){ if (fexp.m_cause != CFileException::fileNotFound){ CString strError(_T("Failed to load ") SPAMFILTER_FILENAME _T(" file")); TCHAR szError[MAX_CFEXP_ERRORMSG]; if (fexp.GetErrorMessage(szError, ARRSIZE(szError))){ strError += _T(" - "); strError += szError; } DebugLogError(_T("%s"), strError); } return; } setvbuf(file.m_pStream, NULL, _IOFBF, 16384); try { uint8 header = file.ReadUInt8(); if (header != MET_HEADER_I64TAGS){ file.Close(); DebugLogError(_T("Failed to load searchspam.met, invalid first byte")); return; } UINT RecordsNumber = file.ReadUInt32(); for (UINT i = 0; i < RecordsNumber; i++) { CTag tag(&file, false); switch (tag.GetNameID()){ case SP_FILEHASHSPAM: ASSERT( tag.IsHash() ); if (tag.IsHash()) m_mapKnownSpamHashs.SetAt(CSKey(tag.GetHash()), true); break; case SP_FILEHASHNOSPAM: ASSERT( tag.IsHash() ); if (tag.IsHash()){ m_mapKnownSpamHashs.SetAt(CSKey(tag.GetHash()), false); nDbgFileHashPos++; } break; case SP_FILEFULLNAME: ASSERT( tag.IsStr() ); if (tag.IsStr()) m_astrKnownSpamNames.Add(tag.GetStr()); break; case SP_FILESIMILARNAME: ASSERT( tag.IsStr() ); if (tag.IsStr()) m_astrKnownSimilarSpamNames.Add(tag.GetStr()); break; case SP_FILESOURCEIP: ASSERT( tag.IsInt() ); if (tag.IsInt()) m_mapKnownSpamSourcesIPs.SetAt(tag.GetInt(), true); break; case SP_FILESERVERIP: ASSERT( tag.IsInt() ); if (tag.IsInt()) m_mapKnownSpamServerIPs.SetAt(tag.GetInt(), true); break; case SP_FILESIZE: ASSERT( tag.IsInt64() ); if (tag.IsInt64()) m_aui64KnownSpamSizes.Add(tag.GetInt64()); break; case SP_UDPSERVERSPAMRATIO: ASSERT( tag.IsBlob() && tag.GetBlobSize() == 12); if (tag.IsBlob() && tag.GetBlobSize() == 12){ const BYTE* pBuffer = tag.GetBlob(); UDPServerRecord* pRecord = new UDPServerRecord; pRecord->m_nResults = PeekUInt32(&pBuffer[4]); pRecord->m_nSpamResults = PeekUInt32(&pBuffer[8]); m_aUDPServerRecords.SetAt(PeekUInt32(&pBuffer[0]), pRecord); int nRatio; if (pRecord->m_nResults >= pRecord->m_nSpamResults && pRecord->m_nResults != 0){ nRatio = (pRecord->m_nSpamResults * 100) / pRecord->m_nResults; } else nRatio = 100; DEBUG_ONLY(DebugLog(_T("UDP Server Spam Record: IP: %s, Results: %u, SpamResults: %u, Ratio: %u") , ipstr(PeekUInt32(&pBuffer[0])), pRecord->m_nResults, pRecord->m_nSpamResults, nRatio)); } break; default: ASSERT( false ); } } file.Close(); } catch(CFileException* error){ if (error->m_cause == CFileException::endOfFile) DebugLogError(_T("Failed to load searchspam.met, corrupt")); else{ TCHAR buffer[MAX_CFEXP_ERRORMSG]; error->GetErrorMessage(buffer, ARRSIZE(buffer)); DebugLogError(_T("Failed to load searchspam.met, %s"),buffer); } error->Delete(); return; } DebugLog(_T("Loaded search Spam Filter. Entries - ServerIPs: %u, SourceIPs, %u, Hashs: %u, PositiveHashs: %u, FileSizes: %u, FullNames: %u, SimilarNames: %u") , m_mapKnownSpamSourcesIPs.GetCount(), m_mapKnownSpamServerIPs.GetCount(), m_mapKnownSpamHashs.GetCount() - nDbgFileHashPos, nDbgFileHashPos , m_aui64KnownSpamSizes.GetCount(), m_astrKnownSpamNames.GetCount(), m_astrKnownSimilarSpamNames.GetCount()); } void CSearchList::SaveSpamFilter(){ if (!m_bSpamFilterLoaded) return; CString fullpath = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR); fullpath.Append(SPAMFILTER_FILENAME); CSafeBufferedFile file; CFileException fexp; if (!file.Open(fullpath, CFile::modeWrite|CFile::modeCreate|CFile::typeBinary|CFile::shareDenyWrite, &fexp)){ if (fexp.m_cause != CFileException::fileNotFound){ CString strError(_T("Failed to load ") SPAMFILTER_FILENAME _T(" file")); TCHAR szError[MAX_CFEXP_ERRORMSG]; if (fexp.GetErrorMessage(szError, ARRSIZE(szError))){ strError += _T(" - "); strError += szError; } DebugLogError(_T("%s"), strError); } return; } setvbuf(file.m_pStream, NULL, _IOFBF, 16384); uint32 nCount = 0; try{ file.WriteUInt8(MET_HEADER_I64TAGS); file.WriteUInt32(nCount); for (int i = 0; i < m_astrKnownSpamNames.GetCount(); i++){ CTag tag(SP_FILEFULLNAME, m_astrKnownSpamNames[i]); tag.WriteNewEd2kTag(&file, utf8strOptBOM); nCount++; } for (int i = 0; i < m_astrKnownSimilarSpamNames.GetCount(); i++){ CTag tag(SP_FILESIMILARNAME, m_astrKnownSimilarSpamNames[i]); tag.WriteNewEd2kTag(&file, utf8strOptBOM); nCount++; } for (int i = 0; i < m_aui64KnownSpamSizes.GetCount(); i++){ CTag tag(SP_FILESIZE, m_aui64KnownSpamSizes[i], true); tag.WriteNewEd2kTag(&file); nCount++; } POSITION pos = m_mapKnownSpamHashs.GetStartPosition(); while( pos != NULL ) { bool bSpam; CSKey key; m_mapKnownSpamHashs.GetNextAssoc(pos, key, bSpam); if (bSpam){ CTag tag(SP_FILEHASHSPAM, (BYTE*)key.m_key); tag.WriteNewEd2kTag(&file); } else{ CTag tag(SP_FILEHASHNOSPAM, (BYTE*)key.m_key); tag.WriteNewEd2kTag(&file); } nCount++; } pos = m_mapKnownSpamServerIPs.GetStartPosition(); while( pos != NULL ) { bool bTmp; uint32 dwIP; m_mapKnownSpamServerIPs.GetNextAssoc(pos, dwIP, bTmp); CTag tag(SP_FILESERVERIP, dwIP); tag.WriteNewEd2kTag(&file); nCount++; } pos = m_mapKnownSpamSourcesIPs.GetStartPosition(); while( pos != NULL ) { bool bTmp; uint32 dwIP; m_mapKnownSpamSourcesIPs.GetNextAssoc(pos, dwIP, bTmp); CTag tag(SP_FILESOURCEIP, dwIP); tag.WriteNewEd2kTag(&file); nCount++; } pos = m_aUDPServerRecords.GetStartPosition(); while( pos != NULL ) { UDPServerRecord* pRecord; uint32 dwIP; m_aUDPServerRecords.GetNextAssoc(pos, dwIP, pRecord); BYTE abyBuffer[12]; PokeUInt32(&abyBuffer[0], dwIP); PokeUInt32(&abyBuffer[4], pRecord->m_nResults); PokeUInt32(&abyBuffer[8], pRecord->m_nSpamResults); CTag tag(SP_UDPSERVERSPAMRATIO, sizeof(abyBuffer), abyBuffer); tag.WriteNewEd2kTag(&file); nCount++; } file.Seek(1, CFile::begin); file.WriteUInt32(nCount); file.Close(); } catch(CFileException* error){ TCHAR buffer[MAX_CFEXP_ERRORMSG]; error->GetErrorMessage(buffer, ARRSIZE(buffer)); DebugLogError(_T("Failed to save searchspam.met, %s"),buffer); error->Delete(); return; } DebugLog(_T("Stored searchspam.met, wrote %u records"), nCount); } void CSearchList::StoreSearches(){ // store open searches on shutdown to restore them on the next startup CString fullpath = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR); fullpath.Append(STOREDSEARCHES_FILENAME); CSafeBufferedFile file; CFileException fexp; if (!file.Open(fullpath, CFile::modeWrite|CFile::modeCreate|CFile::typeBinary|CFile::shareDenyWrite, &fexp)){ if (fexp.m_cause != CFileException::fileNotFound){ CString strError(_T("Failed to load ") STOREDSEARCHES_FILENAME _T(" file")); TCHAR szError[MAX_CFEXP_ERRORMSG]; if (fexp.GetErrorMessage(szError, ARRSIZE(szError))){ strError += _T(" - "); strError += szError; } DebugLogError(_T("%s"), strError); } return; } setvbuf(file.m_pStream, NULL, _IOFBF, 16384); uint16 nCount = 0; try{ file.WriteUInt8(MET_HEADER_I64TAGS); uint8 byVersion = STOREDSEARCHES_VERSION; file.WriteUInt8(byVersion); // count how many (if any) open searches we have which are GUI related POSITION pos; for (pos = m_listFileLists.GetHeadPosition(); pos != NULL; ){ SearchListsStruct* pSl = m_listFileLists.GetNext(pos); if (theApp.emuledlg->searchwnd->GetSearchParamsBySearchID(pSl->m_nSearchID) != NULL) nCount++; } file.WriteUInt16(nCount); if (nCount > 0){ POSITION pos; for (pos = m_listFileLists.GetTailPosition(); pos != NULL; ){ SearchListsStruct* pSl = m_listFileLists.GetPrev(pos); SSearchParams* pParams = theApp.emuledlg->searchwnd->GetSearchParamsBySearchID(pSl->m_nSearchID); if (pParams != NULL){ pParams->StorePartially(file); file.WriteUInt32(pSl->m_listSearchFiles.GetCount()); POSITION pos2; for (pos2 = pSl->m_listSearchFiles.GetHeadPosition(); pos2 != NULL;) pSl->m_listSearchFiles.GetNext(pos2)->StoreToFile(file); } } } file.Close(); } catch(CFileException* error){ TCHAR buffer[MAX_CFEXP_ERRORMSG]; error->GetErrorMessage(buffer, ARRSIZE(buffer)); DebugLogError(_T("Failed to save %s, %s"), STOREDSEARCHES_FILENAME, buffer); error->Delete(); return; } DebugLog(_T("Stored %u open search for restoring on next start"), nCount); } void CSearchList::LoadSearches(){ ASSERT( m_listFileLists.GetCount() == 0 ); CString fullpath = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR); fullpath.Append(STOREDSEARCHES_FILENAME); CSafeBufferedFile file; CFileException fexp; if (!file.Open(fullpath,CFile::modeRead|CFile::osSequentialScan|CFile::typeBinary|CFile::shareDenyWrite, &fexp)){ if (fexp.m_cause != CFileException::fileNotFound){ CString strError(_T("Failed to load ") STOREDSEARCHES_FILENAME _T(" file")); TCHAR szError[MAX_CFEXP_ERRORMSG]; if (fexp.GetErrorMessage(szError, ARRSIZE(szError))){ strError += _T(" - "); strError += szError; } DebugLogError(_T("%s"), strError); } return; } setvbuf(file.m_pStream, NULL, _IOFBF, 16384); try { uint8 header = file.ReadUInt8(); if (header != MET_HEADER_I64TAGS){ file.Close(); DebugLogError(_T("Failed to load %s, invalid first byte"), STOREDSEARCHES_FILENAME); return; } uint8 byVersion = file.ReadUInt8(); if (byVersion != STOREDSEARCHES_VERSION){ file.Close(); return; } uint32 nHighestKadSearchID = 0xFFFFFFFF; uint32 nHighestEd2kSearchID = 0xFFFFFFFF; uint16 nCount = file.ReadUInt16(); for (int i = 0; i < nCount; i++){ SSearchParams* pParams = new SSearchParams(file); uint32 nFileCount = file.ReadUInt32(); // backward compability fix for new automatic option if (pParams->eType == SearchTypeAutomatic) pParams->eType = SearchTypeEd2kServer; else if (pParams->eType == SearchTypeEd2kGlobal && pParams->dwSearchID < 0x80000000) pParams->eType = SearchTypeKademlia; if (pParams->eType == SearchTypeKademlia && (nHighestKadSearchID == 0xFFFFFFFF || nHighestKadSearchID < pParams->dwSearchID)){ ASSERT( pParams->dwSearchID < 0x80000000 ); nHighestKadSearchID = pParams->dwSearchID; } else if (pParams->eType != SearchTypeKademlia && (nHighestEd2kSearchID == 0xFFFFFFFF || nHighestEd2kSearchID < pParams->dwSearchID)){ ASSERT( pParams->dwSearchID >= 0x80000000 ); nHighestEd2kSearchID = pParams->dwSearchID; } // create the new tab CStringA strResultType = pParams->strFileType; if (strResultType == ED2KFTSTR_PROGRAM) strResultType.Empty(); NewSearch(NULL, strResultType, pParams->dwSearchID, pParams->eType, pParams->strExpression, false); bool bDeleteParams = false; if (theApp.emuledlg->searchwnd->CreateNewTab(pParams, false)){ m_foundFilesCount.SetAt(pParams->dwSearchID, 0); m_foundSourcesCount.SetAt(pParams->dwSearchID, 0); } else{ bDeleteParams = true; ASSERT( false ); } // fill the list with stored results for (uint32 j = 0; j < nFileCount; j++) { CSearchFile* toadd = new CSearchFile(&file, true, pParams->dwSearchID, 0, 0, NULL, pParams->eType == SearchTypeKademlia); AddToList(toadd, pParams->bClientSharedFiles); } if (bDeleteParams){ delete pParams; pParams = NULL; } } file.Close(); // adjust the start values for searchids in order to not reuse IDs of our loaded searches if (nHighestKadSearchID != 0xFFFFFFFF) Kademlia::CSearchManager::SetNextSearchID(nHighestKadSearchID + 1); if (nHighestEd2kSearchID != 0xFFFFFFFF) theApp.emuledlg->searchwnd->SetNextSearchID(max(nHighestEd2kSearchID + 1, 0x80000000)); } catch(CFileException* error){ if (error->m_cause == CFileException::endOfFile) DebugLogError(_T("Failed to load %s, corrupt"), STOREDSEARCHES_FILENAME); else{ TCHAR buffer[MAX_CFEXP_ERRORMSG]; error->GetErrorMessage(buffer, ARRSIZE(buffer)); DebugLogError(_T("Failed to load %s, %s"), STOREDSEARCHES_FILENAME, buffer); } error->Delete(); return; } }
[ "Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b", "[email protected]@dd569cc8-ff36-11de-bbca-1111db1fd05b" ]
[ [ [ 1, 514 ], [ 516, 574 ], [ 594, 653 ], [ 657, 661 ], [ 676, 712 ], [ 718, 836 ], [ 838, 927 ], [ 953, 1822 ] ], [ [ 515, 515 ], [ 575, 593 ], [ 654, 656 ], [ 662, 675 ], [ 713, 717 ], [ 837, 837 ], [ 928, 952 ] ] ]
78d90046d8550cd06e1c43a3db7b55b018a9ea9a
bdb1e38df8bf74ac0df4209a77ddea841045349e
/CapsuleSortor/Version 1.0 -2.0/CapsuleSortor-10-12-17/Remain/TTransRemain.cpp
ab6c5833910d9ca894e3bc6672587c7b2da31cf3
[]
no_license
Strongc/my001project
e0754f23c7818df964289dc07890e29144393432
07d6e31b9d4708d2ef691d9bedccbb818ea6b121
refs/heads/master
2021-01-19T07:02:29.673281
2010-12-17T03:10:52
2010-12-17T03:10:52
49,062,858
0
1
null
2016-01-05T11:53:07
2016-01-05T11:53:07
null
GB18030
C++
false
false
18,454
cpp
// TTransRemain.cpp: implementation of the TTransRemain class. // ////////////////////////////////////////////////////////////////////// #include "TTransRemain.h" #include "TImgProcess.h" #include "afxwin.h" #include "ttimediff.h" #include <sstream> #include "TToInteger.h" #include "SortObserver.h " #include "CapsuleProc.h" using namespace std; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// TTransRemain::TTransRemain(): m_whiteBlob(NULL), m_binIMG(NULL), m_rawIMG(NULL), m_minBoxIMG(NULL), m_blackBlob(NULL) { } TTransRemain::~TTransRemain() { } bool TTransRemain::RemainCapsule ( const TAlloc<PixelMem> &rawImg, const TImgDim &rawImgDim, TImage<PelGray8> &remain, RemainParam &remainParam, REMAINMODE remainMode, bool frontLight) { m_mode = remainMode; if(rawImgDim.bytesPerPixel == 3) { TImage<PelRGB24> rgb(rawImg, rawImgDim); if(frontLight) { TImgProcess::RGBToGray (rgb, m_rawImage); } else { TImgProcess::RGBToGray2(rgb, m_rawImage); } } else { m_rawImage.SetImage(rawImg.Base(), rawImgDim); } remain.SetZero(); try { TImgProcess::BinaryGray(m_rawImage, m_binImage, remainParam.binaryLowThres, remainParam.binaryUpThres); // m_sortObserver.ObserverIMG(SortObserver::MAll, m_cvbProfileImg); IMG minImage = NULL; FilterBoxMin( m_binIMG, remainParam.minBoxWidth, remainParam.minBoxWidth, remainParam.minBoxWidth/2, remainParam.minBoxWidth/2, minImage); unsigned char *pImage = NULL; PVPAT VPA = NULL; GetImageVPA ( minImage, 0, (void**)&pImage, &VPA); memcpy ( m_minBoxImage.Base(), pImage, m_minBoxImage.Width()*m_minBoxImage.Height()); ReleaseImage( minImage); TImgProcess::SobelFilter( m_rawImage, m_sobelImage); CapsuleProc::ObservedIMG(SortObserver::MEnh, m_sobelIMG); TImgProcess::AndGrayImg ( m_minBoxImage, m_sobelImage, m_andedImage); CapsuleProc::ObservedIMG(SortObserver::MAnd, m_andedIMG); } catch (...) { static int count = 0; CString txt; txt.Format("D:\\\n%d.txt", count); count++; FILE* pFile = NULL; fopen_s(&pFile, "D:\\CatchFile.txt", "wb"); fwrite(txt, sizeof(char), strlen(txt), pFile); fclose(pFile); return false; } try { WhiteBlob ( m_binIMG, m_whiteBlob); vector<RECT> rectSet = GetMouldRect(m_whiteBlob); ExcludeEmpty ( rectSet, remain.Height(), remain.Width()); CheckPosition ( m_andedImage, remain, rectSet, remainParam.radius); TImgProcess::AndGrayImg(m_rawImage, remain, remain); } catch (...) { static int count = 0; CString txt; txt.Format("D:\\\n%d.txt", count); count++; FILE* pFile = NULL; fopen_s(&pFile, "D:\\CatchFile1.txt", "wb"); fwrite(txt, sizeof(char), strlen(txt), pFile); fclose(pFile); return false; } return true; } void TTransRemain::ReInit(IMG &image) { size_t imgWidth = ImageWidth(image); size_t imgHeight = ImageHeight(image); TRect2D<int> bound(0, 0, imgWidth-1, imgHeight-1); m_rawImage.ReInit(bound); m_binImage.ReInit(bound); m_minBoxImage.ReInit(bound); m_sobelImage.ReInit(bound); m_andedImage.ReInit(bound); if (m_binIMG) { ReleaseImage(m_binIMG); } if (m_rawIMG) { ReleaseImage(m_rawIMG); } if (m_minBoxIMG) { ReleaseImage(m_minBoxIMG); } CreateImageFromPointer(m_binImage.Base(), m_binImage.Width()*m_binImage.Height(), m_binImage.Width(), m_binImage.Height(), 1, 8, 1, m_binImage.Width(), 1, NULL, NULL, NULL, m_binIMG); CreateImageFromPointer(m_rawImage.Base(), m_rawImage.Width()*m_rawImage.Height(), m_rawImage.Width(), m_rawImage.Height(), 1, 8, 1, m_rawImage.Width(), 1, NULL, NULL, NULL, m_rawIMG); CreateImageFromPointer(m_minBoxImage.Base(), m_minBoxImage.Width()*m_minBoxImage.Height(), m_minBoxImage.Width(), m_minBoxImage.Height(), 1, 8, 1, m_minBoxImage.Width(), 1, NULL, NULL, NULL, m_minBoxIMG ); CreateImageFromPointer(m_andedImage.Base(), m_andedImage.Width()*m_andedImage.Height(), m_andedImage.Width(), m_andedImage.Height(), 1, 8, 1, m_andedImage.Width(), 1, NULL, NULL, NULL, m_andedIMG ); CreateImageFromPointer(m_sobelImage.Base(), m_sobelImage.Width()*m_sobelImage.Height(), m_sobelImage.Width(), m_sobelImage.Height(), 1, 8, 1, m_sobelImage.Width(), 1, NULL, NULL, NULL, m_sobelIMG ); BlobInit(m_rawIMG, m_whiteBlob); BlobInit(m_rawIMG, m_blackBlob); } void TTransRemain::WhiteBlob(IMG &image, FBLOB &blob) { FBlobSetImage (blob, image, 0); FBlobSetObjectFeatureRange (blob, 128, 255); FBlobSetObjectTouchBorder (blob, FBLOB_BORDER_NONE); FBlobSetLimitArea (blob, 10, -1); FBlobSetLimitWidth (blob, 30, -1); FBlobSetSortMode (blob, FBLOB_SORT_POSX, 0, 0, 0, FBLOB_SORT_RISING); FBlobSetSkipBinarization (blob, TRUE); FBlobExec (blob); } RECT TTransRemain::RectNoBlack(IMG &image, TRect2D<int> &rect, IMG debugImage) { unsigned char *pImage = NULL; PVPAT VPA = NULL; GetImageVPA (image, 0, (void**)&pImage, &VPA); //const size_t rectWidth = rect.Width(); //const size_t rectHeight = rect.Height(); RECT resultRect = { 0, 0, 0, 0}; bool lineEmpty = false; for(int i = rect.x0() ; i < rect.x1(); ++i) { for (int j = rect.y0(); j < rect.y1(); ++j) { if (0 == *(VPA[i].XEntry + pImage + VPA[j].YEntry) ) { break; } //*(rawVPA[i].XEntry + pRawImage + rawVPA[j].YEntry) = 255; if (rect.y1() -1 == j) { lineEmpty = true; } } if (lineEmpty) { resultRect.left = rect.x0() + i; resultRect.top = rect.y0(); break; } } lineEmpty = false; for (int i = rect.x1()-1; i >rect.x0(); --i) { for (int j = rect.y0(); j < rect.y1(); ++j) { if ( 0 == *(VPA[i].XEntry + pImage + VPA[j].YEntry)) { break; } if ( rect.y1()-1 == j) { lineEmpty = true; } } if (lineEmpty) { resultRect.right = rect.x0() + i; resultRect.bottom = rect.y1(); break; } } return resultRect; } vector<RECT> TTransRemain::GetMouldRect(FBLOB& blob) { long blobCount = 0; FBlobGetNumBlobs(blob, blobCount); vector<RECT> rectSet; rectSet.clear(); RECT blobRect; memset(&blobRect, 0X00, sizeof(RECT)); for( int i = 0; i < blobCount; ++i) { long startX = 0, startY = 0, dX = 0, dY = 0; FBlobGetBoundingBox(blob, i, startX, startY, dX, dY); blobRect.left = startX; blobRect.top = startY; blobRect.right = startX+dX; blobRect.bottom = startY+dY; rectSet.push_back(blobRect); } return rectSet; } bool TTransRemain::IsEmpty(IMG &image, RECT rect) { IMG tempIMG = NULL; IMG maskIMG = NULL; CreateImageMap( m_rawIMG, rect.left, rect.top, rect.right, rect.bottom, rect.right-rect.left, rect.bottom-rect.top, tempIMG); CreateImageMap( m_minBoxIMG, rect.left, rect.top, rect.right, rect.bottom, rect.right-rect.left, rect.bottom-rect.top, maskIMG); const size_t imgWidth = ImageWidth(tempIMG); const size_t imgHeight = ImageHeight(tempIMG); IMG andedImage = NULL; AndImages ( tempIMG, maskIMG, andedImage); const size_t roiWidth = imgWidth/3; const size_t roiHeigh = imgHeight/2; const size_t roiXStart = imgWidth/3; const size_t roiYStart = imgHeight/4; IMG roiImg = NULL; CreateImageMap(andedImage, roiXStart, roiYStart, roiXStart+roiWidth, roiYStart+roiHeigh, roiWidth, roiHeigh, roiImg); bool isEmpty = BlackDetect(roiImg, roiWidth*roiHeigh/3); ReleaseImage(roiImg); ReleaseImage(andedImage); ReleaseImage(maskIMG); ReleaseImage(tempIMG); if (isEmpty) return false; else return true; } //ๅ‡บไบŽ้€Ÿๅบฆ่€ƒ่™‘ bool TTransRemain::IsEmpty1(IMG &image, RECT& rect, size_t maxHeight) { IMG tempIMG = NULL; IMG maskIMG = NULL; CreateImageMap( m_rawIMG, rect.left, rect.top, rect.right, rect.bottom, rect.right-rect.left, rect.bottom-rect.top, tempIMG); CreateImageMap( m_minBoxIMG, rect.left, rect.top, rect.right, rect.bottom, rect.right-rect.left, rect.bottom-rect.top, maskIMG); const size_t imgWidth = ImageWidth(tempIMG); const size_t imgHeight = ImageHeight(tempIMG); IMG andedImage = NULL; AndImages ( tempIMG, maskIMG, andedImage); size_t detectCount = 0; size_t indent = 1 ; for (int i = 1; i < 5; ++i) { RECT ROIRect = { indent, imgHeight*i/5, imgWidth-indent, imgHeight*i/5 + 20}; //RECT edgeRect = RectNoBlack(andedImage, ROIRect, tempIMG); if (EdgeJudge(andedImage, rect , ROIRect)) { detectCount++; } } ReleaseImage(andedImage); ReleaseImage(maskIMG); ReleaseImage(tempIMG); if (detectCount >= 3) { return false; } return true; } void TTransRemain::CheckPosition( TImage<unsigned char> &srcImage, TImage<unsigned char > &dstImage, vector<RECT> &rectSet, const size_t radius) { TBmpInfo info; info.Width (srcImage.Width()); info.Height (srcImage.Height()); info.AccordMem(); TBmpBoard bmpBoard; bmpBoard.SetBmpInfo(info); PixelMem *pPixel = bmpBoard.GetPixelBase(); memcpy(pPixel, dstImage.Base(), dstImage.Width() * dstImage.Height()); HDC memHDC = bmpBoard.GetMemDC(); ArcTemple uptemp = ArcCreator::CreateArc(radius, ArcTemple::eUpArc); ArcTemple downTemp = ArcCreator::CreateArc(radius, ArcTemple::eDownArc); TPoint2D<int> upCentre; TPoint2D<int> downCentre; for(size_t i = 0; i < rectSet.size(); ++i) { long upSpeciSide = rectSet[i].top + (rectSet[i].bottom - rectSet[i].top)/3; long downSpeciSide = rectSet[i].top + (rectSet[i].bottom - rectSet[i].top)*2/3; TRect2D<int> selectUpArea(rectSet[i].left, rectSet[i].top, rectSet[i].right-1, upSpeciSide); TRect2D<int> selectDownArea(rectSet[i].left, downSpeciSide, rectSet[i].right, rectSet[i].bottom); GetTopPos(srcImage, selectUpArea, upCentre, uptemp); if (!selectUpArea.Within(upCentre.x(), upCentre.y())) { upCentre = selectUpArea.Center(); } GetTopPos(srcImage, selectDownArea, downCentre, downTemp); if (!selectDownArea.Within(downCentre.x(), downCentre.y())) { downCentre = selectDownArea.Center(); } FillDest(dstImage, upCentre, downCentre, memHDC, radius); } memcpy(dstImage.Base(), pPixel, dstImage.Width()* dstImage.Height()); } void TTransRemain::GetTopPos( TImage<unsigned char> &image, TRect2D<int> &rect, TPoint2D<int> &centre, ArcTemple &temp) { ArcMatchor matchor; matchor.SetImage(image); matchor.GetMaxMatchPos(temp, rect, centre); } void TTransRemain::FillDest( TImage<unsigned char> &image, TPoint2D<int> &upCentre, TPoint2D<int> &downCentre, HDC &memHDC, const size_t radius) { CBrush bush; bush.CreateHatchBrush(HS_CROSS, RGB(255,255,255)); CRgn upRgn; upRgn.CreateEllipticRgn( upCentre.x()- radius, upCentre.y()-radius, upCentre.x()+ radius, upCentre.y()+radius); FillRgn(memHDC , upRgn, bush); CRgn downRgn; downRgn.CreateEllipticRgn( downCentre.x()-radius, downCentre.y()-radius, downCentre.x()+radius, downCentre.y()+radius); FillRgn(memHDC,downRgn, bush); CRgn midRgn; POINT midRect[4]; midRect[0].x = upCentre.x()-radius; midRect[0].y = upCentre.y(); midRect[1].x = downCentre.x()-radius; midRect[1].y = downCentre.y(); midRect[2].x = downCentre.x()+radius; midRect[2].y = downCentre.y(); midRect[3].x = upCentre.x()+radius; midRect[3].y = upCentre.y(); midRgn.CreatePolygonRgn(midRect, 4, ALTERNATE); FillRgn(memHDC, midRgn, bush); } bool TTransRemain::BlackDetect( IMG &image, const size_t sizeLimit) { //static FBLOB blob = FBlobCreate(image, 0); FBlobSetImage (m_blackBlob, image, 0); FBlobSetObjectFeatureRange (m_blackBlob, 0, 128); FBlobSetLimitArea (m_blackBlob, sizeLimit, -1); FBlobExec (m_blackBlob); long blobCount = 0; FBlobGetNumBlobs(m_blackBlob, blobCount); if (blobCount) return true; else return false; } void TTransRemain::ExcludeEmpty( vector<RECT> &rectSet, const int imgHeight, const int imgWidth) { //ๅ–ๅ‡นๆงฝ็š„ๆœ€ๅคง้ซ˜ๅบฆ int maxHeight = 0; for(size_t i = 0 ; i< rectSet.size(); ++i) { int dY = rectSet[i].bottom- rectSet[i].top; if (dY > maxHeight) { maxHeight = dY; } } //ๅŽปๆމไธŽ่พน็•ŒๆŽฅ่งฆ็š„ๅŒบๅŸŸ size_t rectCount = rectSet.size(); for(size_t i = 0; i < rectCount; ++i) { if (rectSet.at(i).left == 0||rectSet.at(i).right >= (imgWidth - 1)) { rectSet.erase(rectSet.begin() + i); rectCount--; i--; } } //ๅŽปๆމไธŽไธŠไธ‹่พน็•ŒๆŽฅ่งฆ็š„ๅŒบๅŸŸ rectCount = rectSet.size(); vector<RECT> zeroRect; for(size_t i = 0; i < rectCount; ++i) { if (rectSet.at(i).top == 0||rectSet.at(i).bottom >= (imgHeight - 1)) { zeroRect.push_back(rectSet.at(i)); rectSet.erase(rectSet.begin() + i); rectCount--; i--; } } //ๅŽปๆމ้“พๆฟ้—ด้—ด้š™็š„ๅŒบๅŸŸ rectCount = rectSet.size(); size_t zeroRectCount = zeroRect.size(); for(size_t i = 0; i < rectCount; ++i) { int centreX = (rectSet.at(i).left + rectSet.at(i).right)/2; for(size_t j = 0; j < zeroRectCount; ++j) { if (((rectSet.at(i).left>= zeroRect.at(j).left)&&(rectSet.at(i).left <= zeroRect.at(j).right))|| ((rectSet.at(i).right >= zeroRect.at(j).left)&&(rectSet.at(i).right <= zeroRect.at(j).right))|| ((centreX >= zeroRect.at(j).left)&&(centreX <= zeroRect.at(j).right))) { zeroRect[j].left = zeroRect[j].left>rectSet[i].left?rectSet[i].left:zeroRect[j].left; zeroRect[j].right = zeroRect[j].right>rectSet[i].right?zeroRect[j].right:rectSet[i].right; rectSet.erase(rectSet.begin() + i); rectCount--; i--; break; } } } //ๅŽปๆމไธŠไธ‹ๅŒน้…้”™่ฏฏ็š„ๅŒบๅŸŸ rectCount = rectSet.size(); for(size_t i = 0; i < rectCount; ++i) { int centreX = (rectSet.at(i).left + rectSet.at(i).right)/2; for(size_t j = i+1; j < rectCount; ++j) { RECT curRect = rectSet.at(i); RECT dstRect = rectSet.at(j); if (((curRect.left>= dstRect.left)&&(curRect.left <= dstRect.right))|| ((curRect.right >= dstRect.left)&&(curRect.right <= dstRect.right))|| ((dstRect.left >= curRect.left)&&(dstRect.left<= curRect.right))|| ((dstRect.right>=curRect.left)&&(dstRect.right<= curRect.right))|| ((centreX >= dstRect.left)&&(centreX <= dstRect.right))) { rectSet[j].left = rectSet[j].left >rectSet[i].left?rectSet[i].left:rectSet[j].left; rectSet[j].right = rectSet[j].right >rectSet[i].right?rectSet[j].right:rectSet[i].right; rectSet[j].top = rectSet[j].top >rectSet[i].top?rectSet[i].top:rectSet[j].top; rectSet[j].bottom = rectSet[j].bottom > rectSet[i].bottom?rectSet[j].bottom:rectSet[i].bottom; rectSet.erase(rectSet.begin() + i); rectCount--; i--; break; } } } //ๅŽปๆމๆฒกๆœ‰่ƒถๅ›Š็š„ๅ‡นๆงฝ็š„ๅŒบๅŸŸ rectCount = rectSet.size(); for(size_t i = 0; i < rectCount; ++i) { bool isEmpty = (m_mode == TTransRemain::TRANSMODE)? IsEmpty1(m_rawIMG, rectSet.at(i), maxHeight/10):IsEmpty(m_rawIMG, rectSet.at(i)); if (isEmpty) { rectSet.erase(rectSet.begin() + i); rectCount--; i--; } } } void TTransRemain::BlobInit ( IMG &image, FBLOB &blob) { if (blob) { ReleaseImage(blob); } blob = FBlobCreate(image, 0); FBlobSetImage(blob, image, 0); FBlobExec(blob); } bool TTransRemain::DynamicEdge( IMG &image, TArea &area, TEdgeResult &edgeResult, double &thres, double termValue) { const size_t density = 1000; const double stepLen = 0.3; TEdgeResult resArr[256]; RECT roi; roi.left = TToInteger::Floor(area.X0); roi.right = TToInteger::Floor(area.X2); roi.top = TToInteger::Floor(area.Y0); roi.bottom = TToInteger::Floor(area.Y1); //FillRect( image, roi); TCoordinateMap cm; InitCoordinateMap(cm); SetImageCoordinates (image, cm); SetImageOrigin(image, 0, 0); for (thres = 3.0f; thres < termValue; thres += stepLen) { long edgeCount = 0; if (CFindAllEdges(image, 0, density, area, thres, FALSE, 256, resArr, edgeCount)) { if ( 1 == edgeCount ) { return true; } } else { return false; } } return false; } bool TTransRemain::EdgeJudge ( IMG &image, RECT &rect, RECT &edgeRect ) { const double termValue = 15.0f; TArea area; TEdgeResult edgeResult; double thres; // SetArea( rect.left + edgeRect.left, rect.top + edgeRect.top, rect.left +edgeRect.right, rect.top +edgeRect.bottom, // (rect.left +edgeRect.left + rect.left + edgeRect.right)/2, rect.top + edgeRect.top, area); SetArea( edgeRect.left, edgeRect.top, edgeRect.left, edgeRect.bottom, (edgeRect.left + edgeRect.right)/2, edgeRect.top, area); if (DynamicEdge(image, area, edgeResult, thres, termValue)) return true; else { // SetArea( rect.left + edgeRect.right, rect.top + edgeRect.top, rect.left + edgeRect.right,rect.top + edgeRect.bottom, // (rect.left + edgeRect.left + rect.left + edgeRect.right)/2, rect.top + edgeRect.top, area); SetArea( edgeRect.right, edgeRect.top, edgeRect.right, edgeRect.bottom, (edgeRect.left + edgeRect.right)/2, edgeRect.top, area); if (DynamicEdge(image, area, edgeResult, thres, termValue)) return true; } return false; } void TTransRemain::SetArea ( int x0, int y0, int x1, int y1, int x2, int y2, TArea &area) { area.X0 = x0; area.X1 = x1; area.X2 = x2; area.Y0 = y0; area.Y1 = y1; area.Y2 = y2; } void TTransRemain::FillRect ( IMG &image, RECT &rect) { unsigned char *pImage = NULL; PVPAT VPA = NULL; GetImageVPA(image, 0, (void**)&pImage, &VPA); const size_t rectWidth = rect.right - rect.left; const size_t rectHeight = rect.bottom - rect.top; for (int i = rect.top; i < rect.bottom; ++i ) { for(int j = rect.left; j < rect.right; ++j) { *(VPA[j].XEntry + pImage + VPA[i].YEntry) = 255; } } }
[ "vincen.cn@66f52ff4-a261-11de-b161-9f508301ba8e" ]
[ [ [ 1, 637 ] ] ]
5df287954358099ea169ac8461f7f75e737193bd
b2184b7322d384ce5612c1fa480b4800f16646d1
/Src/Include/GLTools.cpp
8cb358c4b320c1eccd9651623180bf7b716571cb
[]
no_license
betner/3D-Scenegraph
a3bbc07866ad620fd2c481d8c8eea8cb8d37df67
fc0f870bf2385f9ed665f3d82cf324fde1e25936
refs/heads/master
2021-05-27T11:32:39.141183
2011-01-12T17:19:49
2011-01-12T17:19:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
51,858
cpp
/* * gltools.cpp * * Created by Richard Wright on 10/16/06. * OpenGL SuperBible, 5th Edition * */ /* Copyright (c) 2005-2010, Richard S. Wright Jr. 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 Richard S. Wright Jr. nor the names of other 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 "GLTools.h" #include "math3d.h" #include "GLTriangleBatch.h" #include <stdio.h> #include <assert.h> #include <stdarg.h> #ifdef linux #include <cstdlib> #endif #ifdef __APPLE__ #include <unistd.h> #endif // Windows #ifdef WIN32 #include <stdio.h> #include <stdlib.h> #endif /////////////////////////////////////////////////////////////////////////////// // Get the OpenGL version number void gltGetOpenGLVersion(GLint &nMajor, GLint &nMinor) { #ifndef OPENGL_ES glGetIntegerv(GL_MAJOR_VERSION, &nMajor); glGetIntegerv(GL_MINOR_VERSION, &nMinor); #else const char *szVersionString = (const char *)glGetString(GL_VERSION); if(szVersionString == NULL) { nMajor = 0; nMinor = 0; return; } // Get major version number. This stops at the first non numeric character nMajor = atoi(szVersionString); // Get minor version number. Start past the first ".", atoi terminates on first non numeric char. nMinor = atoi(strstr(szVersionString, ".")+1); #endif } /////////////////////////////////////////////////////////////////////////////// // This function determines if the named OpenGL Extension is supported // Returns 1 or 0 int gltIsExtSupported(const char *extension) { #ifndef OPENGL_ES GLint nNumExtensions; glGetIntegerv(GL_NUM_EXTENSIONS, &nNumExtensions); for(GLint i = 0; i < nNumExtensions; i++) if(strcmp(extension, (const char *)glGetStringi(GL_EXTENSIONS, i)) == 0) return 1; #else GLubyte *extensions = NULL; const GLubyte *start; GLubyte *where, *terminator; where = (GLubyte *) strchr(extension, ' '); if (where || *extension == '\0') return 0; extensions = (GLubyte *)glGetString(GL_EXTENSIONS); start = extensions; for (;;) { where = (GLubyte *) strstr((const char *) start, extension); if (!where) break; terminator = where + strlen(extension); if (where == start || *(where - 1) == ' ') { if (*terminator == ' ' || *terminator == '\0') return 1; } start = terminator; } #endif return 0; } ///////////////////////////////////////////////////////////////////////////////// // No-op on anything other than the Mac, sets the working directory to // the /Resources folder void gltSetWorkingDirectory(const char *szArgv) { #ifdef __APPLE__ static char szParentDirectory[255]; /////////////////////////////////////////////////////////////////////////// // Get the directory where the .exe resides char *c; strncpy( szParentDirectory, szArgv, sizeof(szParentDirectory) ); szParentDirectory[254] = '\0'; // Make sure we are NULL terminated c = (char*) szParentDirectory; while (*c != '\0') // go to end c++; while (*c != '/') // back up to parent c--; *c++ = '\0'; // cut off last part (binary name) /////////////////////////////////////////////////////////////////////////// // Change to Resources directory. Any data files need to be placed there chdir(szParentDirectory); #ifndef OPENGL_ES chdir("../Resources"); #endif #endif } // Draw a torus (doughnut) at z = fZVal... torus is in xy plane void gltMakeTorus(GLTriangleBatch& torusBatch, GLfloat majorRadius, GLfloat minorRadius, GLint numMajor, GLint numMinor) { double majorStep = 2.0f*M3D_PI / numMajor; double minorStep = 2.0f*M3D_PI / numMinor; int i, j; torusBatch.BeginMesh(numMajor * (numMinor+1) * 6); for (i=0; i<numMajor; ++i) { double a0 = i * majorStep; double a1 = a0 + majorStep; GLfloat x0 = (GLfloat) cos(a0); GLfloat y0 = (GLfloat) sin(a0); GLfloat x1 = (GLfloat) cos(a1); GLfloat y1 = (GLfloat) sin(a1); M3DVector3f vVertex[4]; M3DVector3f vNormal[4]; M3DVector2f vTexture[4]; for (j=0; j<=numMinor; ++j) { double b = j * minorStep; GLfloat c = (GLfloat) cos(b); GLfloat r = minorRadius * c + majorRadius; GLfloat z = minorRadius * (GLfloat) sin(b); // First point vTexture[0][0] = (float)(i)/(float)(numMajor); vTexture[0][1] = (float)(j)/(float)(numMinor); vNormal[0][0] = x0*c; vNormal[0][1] = y0*c; vNormal[0][2] = z/minorRadius; m3dNormalizeVector3(vNormal[0]); vVertex[0][0] = x0 * r; vVertex[0][1] = y0 * r; vVertex[0][2] = z; // Second point vTexture[1][0] = (float)(i+1)/(float)(numMajor); vTexture[1][1] = (float)(j)/(float)(numMinor); vNormal[1][0] = x1*c; vNormal[1][1] = y1*c; vNormal[1][2] = z/minorRadius; m3dNormalizeVector3(vNormal[1]); vVertex[1][0] = x1*r; vVertex[1][1] = y1*r; vVertex[1][2] = z; // Next one over b = (j+1) * minorStep; c = (GLfloat) cos(b); r = minorRadius * c + majorRadius; z = minorRadius * (GLfloat) sin(b); // Third (based on first) vTexture[2][0] = (float)(i)/(float)(numMajor); vTexture[2][1] = (float)(j+1)/(float)(numMinor); vNormal[2][0] = x0*c; vNormal[2][1] = y0*c; vNormal[2][2] = z/minorRadius; m3dNormalizeVector3(vNormal[2]); vVertex[2][0] = x0 * r; vVertex[2][1] = y0 * r; vVertex[2][2] = z; // Fourth (based on second) vTexture[3][0] = (float)(i+1)/(float)(numMajor); vTexture[3][1] = (float)(j+1)/(float)(numMinor); vNormal[3][0] = x1*c; vNormal[3][1] = y1*c; vNormal[3][2] = z/minorRadius; m3dNormalizeVector3(vNormal[3]); vVertex[3][0] = x1*r; vVertex[3][1] = y1*r; vVertex[3][2] = z; torusBatch.AddTriangle(vVertex, vNormal, vTexture); // Rearrange for next triangle memcpy(vVertex[0], vVertex[1], sizeof(M3DVector3f)); memcpy(vNormal[0], vNormal[1], sizeof(M3DVector3f)); memcpy(vTexture[0], vTexture[1], sizeof(M3DVector2f)); memcpy(vVertex[1], vVertex[3], sizeof(M3DVector3f)); memcpy(vNormal[1], vNormal[3], sizeof(M3DVector3f)); memcpy(vTexture[1], vTexture[3], sizeof(M3DVector2f)); torusBatch.AddTriangle(vVertex, vNormal, vTexture); } } torusBatch.End(); } ///////////////////////////////////////////////////////////////////////////////////////////////// // Make a sphere void gltMakeSphere(GLTriangleBatch& sphereBatch, GLfloat fRadius, GLint iSlices, GLint iStacks) { GLfloat drho = (GLfloat)(3.141592653589) / (GLfloat) iStacks; GLfloat dtheta = 2.0f * (GLfloat)(3.141592653589) / (GLfloat) iSlices; GLfloat ds = 1.0f / (GLfloat) iSlices; GLfloat dt = 1.0f / (GLfloat) iStacks; GLfloat t = 1.0f; GLfloat s = 0.0f; GLint i, j; // Looping variables sphereBatch.BeginMesh(iSlices * iStacks * 6); for (i = 0; i < iStacks; i++) { GLfloat rho = (GLfloat)i * drho; GLfloat srho = (GLfloat)(sin(rho)); GLfloat crho = (GLfloat)(cos(rho)); GLfloat srhodrho = (GLfloat)(sin(rho + drho)); GLfloat crhodrho = (GLfloat)(cos(rho + drho)); // Many sources of OpenGL sphere drawing code uses a triangle fan // for the caps of the sphere. This however introduces texturing // artifacts at the poles on some OpenGL implementations s = 0.0f; M3DVector3f vVertex[4]; M3DVector3f vNormal[4]; M3DVector2f vTexture[4]; for ( j = 0; j < iSlices; j++) { GLfloat theta = (j == iSlices) ? 0.0f : j * dtheta; GLfloat stheta = (GLfloat)(-sin(theta)); GLfloat ctheta = (GLfloat)(cos(theta)); GLfloat x = stheta * srho; GLfloat y = ctheta * srho; GLfloat z = crho; vTexture[0][0] = s; vTexture[0][1] = t; vNormal[0][0] = x; vNormal[0][1] = y; vNormal[0][2] = z; vVertex[0][0] = x * fRadius; vVertex[0][1] = y * fRadius; vVertex[0][2] = z * fRadius; x = stheta * srhodrho; y = ctheta * srhodrho; z = crhodrho; vTexture[1][0] = s; vTexture[1][1] = t - dt; vNormal[1][0] = x; vNormal[1][1] = y; vNormal[1][2] = z; vVertex[1][0] = x * fRadius; vVertex[1][1] = y * fRadius; vVertex[1][2] = z * fRadius; theta = ((j+1) == iSlices) ? 0.0f : (j+1) * dtheta; stheta = (GLfloat)(-sin(theta)); ctheta = (GLfloat)(cos(theta)); x = stheta * srho; y = ctheta * srho; z = crho; s += ds; vTexture[2][0] = s; vTexture[2][1] = t; vNormal[2][0] = x; vNormal[2][1] = y; vNormal[2][2] = z; vVertex[2][0] = x * fRadius; vVertex[2][1] = y * fRadius; vVertex[2][2] = z * fRadius; x = stheta * srhodrho; y = ctheta * srhodrho; z = crhodrho; vTexture[3][0] = s; vTexture[3][1] = t - dt; vNormal[3][0] = x; vNormal[3][1] = y; vNormal[3][2] = z; vVertex[3][0] = x * fRadius; vVertex[3][1] = y * fRadius; vVertex[3][2] = z * fRadius; sphereBatch.AddTriangle(vVertex, vNormal, vTexture); // Rearrange for next triangle memcpy(vVertex[0], vVertex[1], sizeof(M3DVector3f)); memcpy(vNormal[0], vNormal[1], sizeof(M3DVector3f)); memcpy(vTexture[0], vTexture[1], sizeof(M3DVector2f)); memcpy(vVertex[1], vVertex[3], sizeof(M3DVector3f)); memcpy(vNormal[1], vNormal[3], sizeof(M3DVector3f)); memcpy(vTexture[1], vTexture[3], sizeof(M3DVector2f)); sphereBatch.AddTriangle(vVertex, vNormal, vTexture); } t -= dt; } sphereBatch.End(); } //////////////////////////////////////////////////////////////////////////////////////// void gltMakeDisk(GLTriangleBatch& diskBatch, GLfloat innerRadius, GLfloat outerRadius, GLint nSlices, GLint nStacks) { // How much to step out each stack GLfloat fStepSizeRadial = outerRadius - innerRadius; if(fStepSizeRadial < 0.0f) // Dum dum... fStepSizeRadial *= -1.0f; fStepSizeRadial /= float(nStacks); GLfloat fStepSizeSlice = (3.1415926536f * 2.0f) / float(nSlices); diskBatch.BeginMesh(nSlices * nStacks * 6); M3DVector3f vVertex[4]; M3DVector3f vNormal[4]; M3DVector2f vTexture[4]; float fRadialScale = 1.0f / outerRadius; for(GLint i = 0; i < nStacks; i++) // Stacks { float theyta; float theytaNext; for(GLint j = 0; j < nSlices; j++) // Slices { float inner = innerRadius + (float(i)) * fStepSizeRadial; float outer = innerRadius + (float(i+1)) * fStepSizeRadial; theyta = fStepSizeSlice * float(j); if(j == (nSlices - 1)) theytaNext = 0.0f; else theytaNext = fStepSizeSlice * (float(j+1)); // Inner First vVertex[0][0] = cos(theyta) * inner; // X vVertex[0][1] = sin(theyta) * inner; // Y vVertex[0][2] = 0.0f; // Z vNormal[0][0] = 0.0f; // Surface Normal, same for everybody vNormal[0][1] = 0.0f; vNormal[0][2] = 1.0f; vTexture[0][0] = ((vVertex[0][0] * fRadialScale) + 1.0f) * 0.5f; vTexture[0][1] = ((vVertex[0][1] * fRadialScale) + 1.0f) * 0.5f; // Outer First vVertex[1][0] = cos(theyta) * outer; // X vVertex[1][1] = sin(theyta) * outer; // Y vVertex[1][2] = 0.0f; // Z vNormal[1][0] = 0.0f; // Surface Normal, same for everybody vNormal[1][1] = 0.0f; vNormal[1][2] = 1.0f; vTexture[1][0] = ((vVertex[1][0] * fRadialScale) + 1.0f) * 0.5f; vTexture[1][1] = ((vVertex[1][1] * fRadialScale) + 1.0f) * 0.5f; // Inner Second vVertex[2][0] = cos(theytaNext) * inner; // X vVertex[2][1] = sin(theytaNext) * inner; // Y vVertex[2][2] = 0.0f; // Z vNormal[2][0] = 0.0f; // Surface Normal, same for everybody vNormal[2][1] = 0.0f; vNormal[2][2] = 1.0f; vTexture[2][0] = ((vVertex[2][0] * fRadialScale) + 1.0f) * 0.5f; vTexture[2][1] = ((vVertex[2][1] * fRadialScale) + 1.0f) * 0.5f; // Outer Second vVertex[3][0] = cos(theytaNext) * outer; // X vVertex[3][1] = sin(theytaNext) * outer; // Y vVertex[3][2] = 0.0f; // Z vNormal[3][0] = 0.0f; // Surface Normal, same for everybody vNormal[3][1] = 0.0f; vNormal[3][2] = 1.0f; vTexture[3][0] = ((vVertex[3][0] * fRadialScale) + 1.0f) * 0.5f; vTexture[3][1] = ((vVertex[3][1] * fRadialScale) + 1.0f) * 0.5f; diskBatch.AddTriangle(vVertex, vNormal, vTexture); // Rearrange for next triangle memcpy(vVertex[0], vVertex[1], sizeof(M3DVector3f)); memcpy(vNormal[0], vNormal[1], sizeof(M3DVector3f)); memcpy(vTexture[0], vTexture[1], sizeof(M3DVector2f)); memcpy(vVertex[1], vVertex[3], sizeof(M3DVector3f)); memcpy(vNormal[1], vNormal[3], sizeof(M3DVector3f)); memcpy(vTexture[1], vTexture[3], sizeof(M3DVector2f)); diskBatch.AddTriangle(vVertex, vNormal, vTexture); } } diskBatch.End(); } // Draw a cylinder. Much like gluCylinder void gltMakeCylinder(GLTriangleBatch& cylinderBatch, GLfloat baseRadius, GLfloat topRadius, GLfloat fLength, GLint numSlices, GLint numStacks) { float fRadiusStep = (topRadius - baseRadius) / float(numStacks); GLfloat fStepSizeSlice = (3.1415926536f * 2.0f) / float(numSlices); M3DVector3f vVertex[4]; M3DVector3f vNormal[4]; M3DVector2f vTexture[4]; cylinderBatch.BeginMesh(numSlices * numStacks * 6); GLfloat ds = 1.0f / float(numSlices); GLfloat dt = 1.0f / float(numStacks); GLfloat s; GLfloat t; for (int i = 0; i < numStacks; i++) { if(i == 0) t = 0.0f; else t = float(i) * dt; float tNext; if(i == (numStacks - 1)) tNext = 1.0f; else tNext = float(i+1) * dt; float fCurrentRadius = baseRadius + (fRadiusStep * float(i)); float fNextRadius = baseRadius + (fRadiusStep * float(i+1)); float theyta; float theytaNext; float fCurrentZ = float(i) * (fLength / float(numStacks)); float fNextZ = float(i+1) * (fLength / float(numStacks)); float zNormal = 0.0f; if(!m3dCloseEnough(baseRadius - topRadius, 0.0f, 0.00001f)) { // Rise over run... zNormal = (baseRadius - topRadius); } for (int j = 0; j < numSlices; j++) { if(j == 0) s = 0.0f; else s = float(j) * ds; float sNext; if(j == (numSlices -1)) sNext = 1.0f; else sNext = float(j+1) * ds; theyta = fStepSizeSlice * float(j); if(j == (numSlices - 1)) theytaNext = 0.0f; else theytaNext = fStepSizeSlice * (float(j+1)); // Inner First vVertex[1][0] = cos(theyta) * fCurrentRadius; // X vVertex[1][1] = sin(theyta) * fCurrentRadius; // Y vVertex[1][2] = fCurrentZ; // Z vNormal[1][0] = vVertex[1][0]; // Surface Normal, same for everybody vNormal[1][1] = vVertex[1][1]; vNormal[1][2] = zNormal; m3dNormalizeVector3(vNormal[1]); vTexture[1][0] = s; // Texture Coordinates, I have no idea... vTexture[1][1] = t; // Outer First vVertex[0][0] = cos(theyta) * fNextRadius; // X vVertex[0][1] = sin(theyta) * fNextRadius; // Y vVertex[0][2] = fNextZ; // Z if(!m3dCloseEnough(fNextRadius, 0.0f, 0.00001f)) { vNormal[0][0] = vVertex[0][0]; // Surface Normal, same for everybody vNormal[0][1] = vVertex[0][1]; // For cones, tip is tricky vNormal[0][2] = zNormal; m3dNormalizeVector3(vNormal[0]); } else memcpy(vNormal[0], vNormal[1], sizeof(M3DVector3f)); vTexture[0][0] = s; // Texture Coordinates, I have no idea... vTexture[0][1] = tNext; // Inner second vVertex[3][0] = cos(theytaNext) * fCurrentRadius; // X vVertex[3][1] = sin(theytaNext) * fCurrentRadius; // Y vVertex[3][2] = fCurrentZ; // Z vNormal[3][0] = vVertex[3][0]; // Surface Normal, same for everybody vNormal[3][1] = vVertex[3][1]; vNormal[3][2] = zNormal; m3dNormalizeVector3(vNormal[3]); vTexture[3][0] = sNext; // Texture Coordinates, I have no idea... vTexture[3][1] = t; // Outer second vVertex[2][0] = cos(theytaNext) * fNextRadius; // X vVertex[2][1] = sin(theytaNext) * fNextRadius; // Y vVertex[2][2] = fNextZ; // Z if(!m3dCloseEnough(fNextRadius, 0.0f, 0.00001f)) { vNormal[2][0] = vVertex[2][0]; // Surface Normal, same for everybody vNormal[2][1] = vVertex[2][1]; vNormal[2][2] = zNormal; m3dNormalizeVector3(vNormal[2]); } else memcpy(vNormal[2], vNormal[3], sizeof(M3DVector3f)); vTexture[2][0] = sNext; // Texture Coordinates, I have no idea... vTexture[2][1] = tNext; cylinderBatch.AddTriangle(vVertex, vNormal, vTexture); // Rearrange for next triangle memcpy(vVertex[0], vVertex[1], sizeof(M3DVector3f)); memcpy(vNormal[0], vNormal[1], sizeof(M3DVector3f)); memcpy(vTexture[0], vTexture[1], sizeof(M3DVector2f)); memcpy(vVertex[1], vVertex[3], sizeof(M3DVector3f)); memcpy(vNormal[1], vNormal[3], sizeof(M3DVector3f)); memcpy(vTexture[1], vTexture[3], sizeof(M3DVector2f)); cylinderBatch.AddTriangle(vVertex, vNormal, vTexture); } } cylinderBatch.End(); } /////////////////////////////////////////////////////////////////////////////////////// // Make a cube, centered at the origin, and with a specified "radius" void gltMakeCube(GLBatch& cubeBatch, GLfloat fRadius ) { cubeBatch.Begin(GL_TRIANGLES, 36, 1); ///////////////////////////////////////////// // Top of cube cubeBatch.Normal3f(0.0f, fRadius, 0.0f); cubeBatch.MultiTexCoord2f(0, fRadius, fRadius); cubeBatch.Vertex3f(fRadius, fRadius, fRadius); cubeBatch.Normal3f(0.0f, fRadius, 0.0f); cubeBatch.MultiTexCoord2f(0, fRadius, 0.0f); cubeBatch.Vertex3f(fRadius, fRadius, -fRadius); cubeBatch.Normal3f(0.0f, fRadius, 0.0f); cubeBatch.MultiTexCoord2f(0, 0.0f, 0.0f); cubeBatch.Vertex3f(-fRadius, fRadius, -fRadius); cubeBatch.Normal3f(0.0f, fRadius, 0.0f); cubeBatch.MultiTexCoord2f(0, fRadius, fRadius); cubeBatch.Vertex3f(fRadius, fRadius, fRadius); cubeBatch.Normal3f(0.0f, fRadius, 0.0f); cubeBatch.MultiTexCoord2f(0, 0.0f, 0.0f); cubeBatch.Vertex3f(-fRadius, fRadius, -fRadius); cubeBatch.Normal3f(0.0f, fRadius, 0.0f); cubeBatch.MultiTexCoord2f(0, 0.0f, fRadius); cubeBatch.Vertex3f(-fRadius, fRadius, fRadius); //////////////////////////////////////////// // Bottom of cube cubeBatch.Normal3f(0.0f, -fRadius, 0.0f); cubeBatch.MultiTexCoord2f(0, 0.0f, 0.0f); cubeBatch.Vertex3f(-fRadius, -fRadius, -fRadius); cubeBatch.Normal3f(0.0f, -fRadius, 0.0f); cubeBatch.MultiTexCoord2f(0, fRadius, 0.0f); cubeBatch.Vertex3f(fRadius, -fRadius, -fRadius); cubeBatch.Normal3f(0.0f, -fRadius, 0.0f); cubeBatch.MultiTexCoord2f(0, fRadius, fRadius); cubeBatch.Vertex3f(fRadius, -fRadius, fRadius); cubeBatch.Normal3f(0.0f, -fRadius, 0.0f); cubeBatch.MultiTexCoord2f(0, 0.0f, fRadius); cubeBatch.Vertex3f(-fRadius, -fRadius, fRadius); cubeBatch.Normal3f(0.0f, -fRadius, 0.0f); cubeBatch.MultiTexCoord2f(0, 0.0f, 0.0f); cubeBatch.Vertex3f(-fRadius, -fRadius, -fRadius); cubeBatch.Normal3f(0.0f, -fRadius, 0.0f); cubeBatch.MultiTexCoord2f(0, fRadius, fRadius); cubeBatch.Vertex3f(fRadius, -fRadius, fRadius); /////////////////////////////////////////// // Left side of cube cubeBatch.Normal3f(-fRadius, 0.0f, 0.0f); cubeBatch.MultiTexCoord2f(0, fRadius, fRadius); cubeBatch.Vertex3f(-fRadius, fRadius, fRadius); cubeBatch.Normal3f(-fRadius, 0.0f, 0.0f); cubeBatch.MultiTexCoord2f(0, fRadius, 0.0f); cubeBatch.Vertex3f(-fRadius, fRadius, -fRadius); cubeBatch.Normal3f(-fRadius, 0.0f, 0.0f); cubeBatch.MultiTexCoord2f(0, 0.0f, 0.0f); cubeBatch.Vertex3f(-fRadius, -fRadius, -fRadius); cubeBatch.Normal3f(-fRadius, 0.0f, 0.0f); cubeBatch.MultiTexCoord2f(0, fRadius, fRadius); cubeBatch.Vertex3f(-fRadius, fRadius, fRadius); cubeBatch.Normal3f(-fRadius, 0.0f, 0.0f); cubeBatch.MultiTexCoord2f(0, 0.0f, 0.0f); cubeBatch.Vertex3f(-fRadius, -fRadius, -fRadius); cubeBatch.Normal3f(-fRadius, 0.0f, 0.0f); cubeBatch.MultiTexCoord2f(0, 0.0f, fRadius); cubeBatch.Vertex3f(-fRadius, -fRadius, fRadius); // Right side of cube cubeBatch.Normal3f(fRadius, 0.0f, 0.0f); cubeBatch.MultiTexCoord2f(0, 0.0f, 0.0f); cubeBatch.Vertex3f(fRadius, -fRadius, -fRadius); cubeBatch.Normal3f(fRadius, 0.0f, 0.0f); cubeBatch.MultiTexCoord2f(0, fRadius, 0.0f); cubeBatch.Vertex3f(fRadius, fRadius, -fRadius); cubeBatch.Normal3f(fRadius, 0.0f, 0.0f); cubeBatch.MultiTexCoord2f(0, fRadius, fRadius); cubeBatch.Vertex3f(fRadius, fRadius, fRadius); cubeBatch.Normal3f(fRadius, 0.0f, 0.0f); cubeBatch.MultiTexCoord2f(0, fRadius, fRadius); cubeBatch.Vertex3f(fRadius, fRadius, fRadius); cubeBatch.Normal3f(fRadius, 0.0f, 0.0f); cubeBatch.MultiTexCoord2f(0, 0.0f, fRadius); cubeBatch.Vertex3f(fRadius, -fRadius, fRadius); cubeBatch.Normal3f(fRadius, 0.0f, 0.0f); cubeBatch.MultiTexCoord2f(0, 0.0f, 0.0f); cubeBatch.Vertex3f(fRadius, -fRadius, -fRadius); // Front and Back // Front cubeBatch.Normal3f(0.0f, 0.0f, fRadius); cubeBatch.MultiTexCoord2f(0, fRadius, 0.0f); cubeBatch.Vertex3f(fRadius, -fRadius, fRadius); cubeBatch.Normal3f(0.0f, 0.0f, fRadius); cubeBatch.MultiTexCoord2f(0, fRadius, fRadius); cubeBatch.Vertex3f(fRadius, fRadius, fRadius); cubeBatch.Normal3f(0.0f, 0.0f, fRadius); cubeBatch.MultiTexCoord2f(0, 0.0f, fRadius); cubeBatch.Vertex3f(-fRadius, fRadius, fRadius); cubeBatch.Normal3f(0.0f, 0.0f, fRadius); cubeBatch.MultiTexCoord2f(0, 0.0f, fRadius); cubeBatch.Vertex3f(-fRadius, fRadius, fRadius); cubeBatch.Normal3f(0.0f, 0.0f, fRadius); cubeBatch.MultiTexCoord2f(0, 0.0f, 0.0f); cubeBatch.Vertex3f(-fRadius, -fRadius, fRadius); cubeBatch.Normal3f(0.0f, 0.0f, fRadius); cubeBatch.MultiTexCoord2f(0, fRadius, 0.0f); cubeBatch.Vertex3f(fRadius, -fRadius, fRadius); // Back cubeBatch.Normal3f(0.0f, 0.0f, -fRadius); cubeBatch.MultiTexCoord2f(0, fRadius, 0.0f); cubeBatch.Vertex3f(fRadius, -fRadius, -fRadius); cubeBatch.Normal3f(0.0f, 0.0f, -fRadius); cubeBatch.MultiTexCoord2f(0, 0.0f, 0.0f); cubeBatch.Vertex3f(-fRadius, -fRadius, -fRadius); cubeBatch.Normal3f(0.0f, 0.0f, -fRadius); cubeBatch.MultiTexCoord2f(0, 0.0f, fRadius); cubeBatch.Vertex3f(-fRadius, fRadius, -fRadius); cubeBatch.Normal3f(0.0f, 0.0f, -fRadius); cubeBatch.MultiTexCoord2f(0, 0.0f, fRadius); cubeBatch.Vertex3f(-fRadius, fRadius, -fRadius); cubeBatch.Normal3f(0.0f, 0.0f, -fRadius); cubeBatch.MultiTexCoord2f(0, fRadius, fRadius); cubeBatch.Vertex3f(fRadius, fRadius, -fRadius); cubeBatch.Normal3f(0.0f, 0.0f, -fRadius); cubeBatch.MultiTexCoord2f(0, fRadius, 0.0f); cubeBatch.Vertex3f(fRadius, -fRadius, -fRadius); cubeBatch.End(); } // Define targa header. This is only used locally. #pragma pack(1) typedef struct { GLbyte identsize; // Size of ID field that follows header (0) GLbyte colorMapType; // 0 = None, 1 = paletted GLbyte imageType; // 0 = none, 1 = indexed, 2 = rgb, 3 = grey, +8=rle unsigned short colorMapStart; // First colour map entry unsigned short colorMapLength; // Number of colors unsigned char colorMapBits; // bits per palette entry unsigned short xstart; // image x origin unsigned short ystart; // image y origin unsigned short width; // width in pixels unsigned short height; // height in pixels GLbyte bits; // bits per pixel (8 16, 24, 32) GLbyte descriptor; // image descriptor } TGAHEADER; #pragma pack(8) //////////////////////////////////////////////////////////////////// // Capture the current viewport and save it as a targa file. // Be sure and call SwapBuffers for double buffered contexts or // glFinish for single buffered contexts before calling this function. // Returns 0 if an error occurs, or 1 on success. // Does not work on the iPhone #ifndef OPENGL_ES GLint gltGrabScreenTGA(const char *szFileName) { FILE *pFile; // File pointer TGAHEADER tgaHeader; // TGA file header unsigned long lImageSize; // Size in bytes of image GLbyte *pBits = NULL; // Pointer to bits GLint iViewport[4]; // Viewport in pixels GLenum lastBuffer; // Storage for the current read buffer setting // Get the viewport dimensions glGetIntegerv(GL_VIEWPORT, iViewport); // How big is the image going to be (targas are tightly packed) lImageSize = iViewport[2] * 3 * iViewport[3]; // Allocate block. If this doesn't work, go home pBits = (GLbyte *)malloc(lImageSize); if(pBits == NULL) return 0; // Read bits from color buffer glPixelStorei(GL_PACK_ALIGNMENT, 1); glPixelStorei(GL_PACK_ROW_LENGTH, 0); glPixelStorei(GL_PACK_SKIP_ROWS, 0); glPixelStorei(GL_PACK_SKIP_PIXELS, 0); // Get the current read buffer setting and save it. Switch to // the front buffer and do the read operation. Finally, restore // the read buffer state glGetIntegerv(GL_READ_BUFFER, (GLint *)&lastBuffer); glReadBuffer(GL_FRONT); glReadPixels(0, 0, iViewport[2], iViewport[3], GL_BGR_EXT, GL_UNSIGNED_BYTE, pBits); glReadBuffer(lastBuffer); // Initialize the Targa header tgaHeader.identsize = 0; tgaHeader.colorMapType = 0; tgaHeader.imageType = 2; tgaHeader.colorMapStart = 0; tgaHeader.colorMapLength = 0; tgaHeader.colorMapBits = 0; tgaHeader.xstart = 0; tgaHeader.ystart = 0; tgaHeader.width = iViewport[2]; tgaHeader.height = iViewport[3]; tgaHeader.bits = 24; tgaHeader.descriptor = 0; // Do byte swap for big vs little endian #ifdef __APPLE__ LITTLE_ENDIAN_WORD(&tgaHeader.colorMapStart); LITTLE_ENDIAN_WORD(&tgaHeader.colorMapLength); LITTLE_ENDIAN_WORD(&tgaHeader.xstart); LITTLE_ENDIAN_WORD(&tgaHeader.ystart); LITTLE_ENDIAN_WORD(&tgaHeader.width); LITTLE_ENDIAN_WORD(&tgaHeader.height); #endif // Attempt to open the file pFile = fopen(szFileName, "wb"); if(pFile == NULL) { free(pBits); // Free buffer and return error return 0; } // Write the header fwrite(&tgaHeader, sizeof(TGAHEADER), 1, pFile); // Write the image data fwrite(pBits, lImageSize, 1, pFile); // Free temporary buffer and close the file free(pBits); fclose(pFile); // Success! return 1; } #endif //////////////////////////////////////////////////////////////////// // Allocate memory and load targa bits. Returns pointer to new buffer, // height, and width of texture, and the OpenGL format of data. // Call free() on buffer when finished! // This only works on pretty vanilla targas... 8, 24, or 32 bit color // only, no palettes, no RLE encoding. GLbyte *gltReadTGABits(const char *szFileName, GLint *iWidth, GLint *iHeight, GLint *iComponents, GLenum *eFormat) { FILE *pFile; // File pointer TGAHEADER tgaHeader; // TGA file header unsigned long lImageSize; // Size in bytes of image short sDepth; // Pixel depth; GLbyte *pBits = NULL; // Pointer to bits // Default/Failed values *iWidth = 0; *iHeight = 0; *eFormat = GL_RGB; *iComponents = GL_RGB; // Attempt to open the file pFile = fopen(szFileName, "rb"); if(pFile == NULL) return NULL; // Read in header (binary) fread(&tgaHeader, 18/* sizeof(TGAHEADER)*/, 1, pFile); // Do byte swap for big vs little endian #ifdef __APPLE__ LITTLE_ENDIAN_WORD(&tgaHeader.colorMapStart); LITTLE_ENDIAN_WORD(&tgaHeader.colorMapLength); LITTLE_ENDIAN_WORD(&tgaHeader.xstart); LITTLE_ENDIAN_WORD(&tgaHeader.ystart); LITTLE_ENDIAN_WORD(&tgaHeader.width); LITTLE_ENDIAN_WORD(&tgaHeader.height); #endif // Get width, height, and depth of texture *iWidth = tgaHeader.width; *iHeight = tgaHeader.height; sDepth = tgaHeader.bits / 8; // Put some validity checks here. Very simply, I only understand // or care about 8, 24, or 32 bit targa's. if(tgaHeader.bits != 8 && tgaHeader.bits != 24 && tgaHeader.bits != 32) return NULL; // Calculate size of image buffer lImageSize = tgaHeader.width * tgaHeader.height * sDepth; // Allocate memory and check for success pBits = (GLbyte*)malloc(lImageSize * sizeof(GLbyte)); if(pBits == NULL) return NULL; // Read in the bits // Check for read error. This should catch RLE or other // weird formats that I don't want to recognize if(fread(pBits, lImageSize, 1, pFile) != 1) { free(pBits); return NULL; } // Set OpenGL format expected switch(sDepth) { #ifndef OPENGL_ES case 3: // Most likely case *eFormat = GL_BGR; *iComponents = GL_RGB; break; #endif case 4: *eFormat = GL_BGRA; *iComponents = GL_RGBA; break; case 1: *eFormat = GL_LUMINANCE; *iComponents = GL_LUMINANCE; break; default: // RGB // If on the iPhone, TGA's are BGR, and the iPhone does not // support BGR without alpha, but it does support RGB, // so a simple swizzle of the red and blue bytes will suffice. // For faster iPhone loads however, save your TGA's with an Alpha! #ifdef OPENGL_ES for(int i = 0; i < lImageSize; i+=3) { GLbyte temp = pBits[i]; pBits[i] = pBits[i+2]; pBits[i+2] = temp; } #endif break; } // Done with File fclose(pFile); // Return pointer to image data return pBits; } /////////////////////////////////////////////////////////////////////////////// // This function opens the "bitmap" file given (szFileName), verifies that it is // a 24bit .BMP file and loads the bitmap bits needed so that it can be used // as a texture. The width and height of the bitmap are returned in nWidth and // nHeight. The memory block allocated and returned must be deleted with free(); // The returned array is an 888 BGR texture // These structures match the layout of the equivalent Windows specific structs // used by Win32 #pragma pack(1) struct RGB { GLbyte blue; GLbyte green; GLbyte red; GLbyte alpha; }; struct BMPInfoHeader { GLuint size; GLuint width; GLuint height; GLushort planes; GLushort bits; GLuint compression; GLuint imageSize; GLuint xScale; GLuint yScale; GLuint colors; GLuint importantColors; }; struct BMPHeader { GLushort type; GLuint size; GLushort unused; GLushort unused2; GLuint offset; }; struct BMPInfo { BMPInfoHeader header; RGB colors[1]; }; #pragma pack(8) GLbyte* gltReadBMPBits(const char *szFileName, int *nWidth, int *nHeight) { FILE* pFile; BMPInfo *pBitmapInfo = NULL; unsigned long lInfoSize = 0; unsigned long lBitSize = 0; GLbyte *pBits = NULL; // Bitmaps bits BMPHeader bitmapHeader; // Attempt to open the file pFile = fopen(szFileName, "rb"); if(pFile == NULL) return NULL; // File is Open. Read in bitmap header information fread(&bitmapHeader, sizeof(BMPHeader), 1, pFile); // Read in bitmap information structure lInfoSize = bitmapHeader.offset - sizeof(BMPHeader); pBitmapInfo = (BMPInfo *) malloc(sizeof(GLbyte)*lInfoSize); if(fread(pBitmapInfo, lInfoSize, 1, pFile) != 1) { free(pBitmapInfo); fclose(pFile); return false; } // Save the size and dimensions of the bitmap *nWidth = pBitmapInfo->header.width; *nHeight = pBitmapInfo->header.height; lBitSize = pBitmapInfo->header.imageSize; // If the size isn't specified, calculate it anyway if(pBitmapInfo->header.bits != 24) { free(pBitmapInfo); return false; } if(lBitSize == 0) lBitSize = (*nWidth * pBitmapInfo->header.bits + 7) / 8 * abs(*nHeight); // Allocate space for the actual bitmap free(pBitmapInfo); pBits = (GLbyte*)malloc(sizeof(GLbyte)*lBitSize); // Read in the bitmap bits, check for corruption if(fread(pBits, lBitSize, 1, pFile) != 1) { free(pBits); pBits = NULL; } // Close the bitmap file now that we have all the data we need fclose(pFile); return pBits; } // Rather than malloc/free a block everytime a shader must be loaded, // I will dedicate a single 4k page for reading in shaders. Thanks to // modern OS design, this page will be swapped out to disk later if never // used again after program initialization. Where-as mallocing different size // shader blocks could lead to heap fragmentation, which would actually be worse. //#define MAX_SHADER_LENGTH 8192 -> This is defined in gltools.h // BTW... this does make this function unsafe to use in two threads simultaneously // BTW BTW... personally.... I do this also to my own texture loading code - RSW static GLubyte shaderText[MAX_SHADER_LENGTH]; ////////////////////////////////////////////////////////////////////////// // Load the shader from the source text void gltLoadShaderSrc(const char *szShaderSrc, GLuint shader) { GLchar *fsStringPtr[1]; fsStringPtr[0] = (GLchar *)szShaderSrc; glShaderSource(shader, 1, (const GLchar **)fsStringPtr, NULL); } //////////////////////////////////////////////////////////////// // Load the shader from the specified file. Returns false if the // shader could not be loaded bool gltLoadShaderFile(const char *szFile, GLuint shader) { GLint shaderLength = 0; FILE *fp; // Open the shader file fp = fopen(szFile, "r"); if(fp != NULL) { // See how long the file is while (fgetc(fp) != EOF) shaderLength++; // Allocate a block of memory to send in the shader assert(shaderLength < MAX_SHADER_LENGTH); // make me bigger! if(shaderLength > MAX_SHADER_LENGTH) { fclose(fp); return false; } // Go back to beginning of file rewind(fp); // Read the whole file in if (shaderText != NULL) fread(shaderText, 1, shaderLength, fp); // Make sure it is null terminated and close the file shaderText[shaderLength] = '\0'; fclose(fp); } else return false; // Load the string gltLoadShaderSrc((const char *)shaderText, shader); return true; } ///////////////////////////////////////////////////////////////// // Load a pair of shaders, compile, and link together. Specify the complete // source text for each shader. After the shader names, specify the number // of attributes, followed by the index and attribute name of each attribute GLuint gltLoadShaderPairWithAttributes(const char *szVertexProg, const char *szFragmentProg, ...) { // Temporary Shader objects GLuint hVertexShader; GLuint hFragmentShader; GLuint hReturn = 0; GLint testVal; // Create shader objects hVertexShader = glCreateShader(GL_VERTEX_SHADER); hFragmentShader = glCreateShader(GL_FRAGMENT_SHADER); // Load them. If fail clean up and return null // Vertex Program if(gltLoadShaderFile(szVertexProg, hVertexShader) == false) { glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); fprintf(stderr, "The shader at %s could ot be found.\n", szVertexProg); return (GLuint)NULL; } // Fragment Program if(gltLoadShaderFile(szFragmentProg, hFragmentShader) == false) { glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); fprintf(stderr,"The shader at %s could not be found.\n", szFragmentProg); return (GLuint)NULL; } // Compile them both glCompileShader(hVertexShader); glCompileShader(hFragmentShader); // Check for errors in vertex shader glGetShaderiv(hVertexShader, GL_COMPILE_STATUS, &testVal); if(testVal == GL_FALSE) { char infoLog[1024]; glGetShaderInfoLog(hVertexShader, 1024, NULL, infoLog); fprintf(stderr, "The shader at %s failed to compile with the following error:\n%s\n", szVertexProg, infoLog); glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); return (GLuint)NULL; } // Check for errors in fragment shader glGetShaderiv(hFragmentShader, GL_COMPILE_STATUS, &testVal); if(testVal == GL_FALSE) { char infoLog[1024]; glGetShaderInfoLog(hFragmentShader, 1024, NULL, infoLog); fprintf(stderr, "The shader at %s failed to compile with the following error:\n%s\n", szFragmentProg, infoLog); glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); return (GLuint)NULL; } // Create the final program object, and attach the shaders hReturn = glCreateProgram(); glAttachShader(hReturn, hVertexShader); glAttachShader(hReturn, hFragmentShader); // Now, we need to bind the attribute names to their specific locations // List of attributes va_list attributeList; va_start(attributeList, szFragmentProg); // Iterate over this argument list char *szNextArg; int iArgCount = va_arg(attributeList, int); // Number of attributes for(int i = 0; i < iArgCount; i++) { int index = va_arg(attributeList, int); szNextArg = va_arg(attributeList, char*); glBindAttribLocation(hReturn, index, szNextArg); } va_end(attributeList); // Attempt to link glLinkProgram(hReturn); // These are no longer needed glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); // Make sure link worked too glGetProgramiv(hReturn, GL_LINK_STATUS, &testVal); if(testVal == GL_FALSE) { char infoLog[1024]; glGetProgramInfoLog(hReturn, 1024, NULL, infoLog); fprintf(stderr,"The programs %s and %s failed to link with the following errors:\n%s\n", szVertexProg, szFragmentProg, infoLog); glDeleteProgram(hReturn); return (GLuint)NULL; } // All done, return our ready to use shader program return hReturn; } ///////////////////////////////////////////////////////////////// // Load a pair of shaders, compile, and link together. Specify the complete // file path for each shader. Note, there is no support for // just loading say a vertex program... you have to do both. GLuint gltLoadShaderPair(const char *szVertexProg, const char *szFragmentProg) { // Temporary Shader objects GLuint hVertexShader; GLuint hFragmentShader; GLuint hReturn = 0; GLint testVal; // Create shader objects hVertexShader = glCreateShader(GL_VERTEX_SHADER); hFragmentShader = glCreateShader(GL_FRAGMENT_SHADER); // Load them. If fail clean up and return null if(gltLoadShaderFile(szVertexProg, hVertexShader) == false) { glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); return (GLuint)NULL; } if(gltLoadShaderFile(szFragmentProg, hFragmentShader) == false) { glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); return (GLuint)NULL; } // Compile them glCompileShader(hVertexShader); glCompileShader(hFragmentShader); // Check for errors glGetShaderiv(hVertexShader, GL_COMPILE_STATUS, &testVal); if(testVal == GL_FALSE) { glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); return (GLuint)NULL; } glGetShaderiv(hFragmentShader, GL_COMPILE_STATUS, &testVal); if(testVal == GL_FALSE) { glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); return (GLuint)NULL; } // Link them - assuming it works... hReturn = glCreateProgram(); glAttachShader(hReturn, hVertexShader); glAttachShader(hReturn, hFragmentShader); glLinkProgram(hReturn); // These are no longer needed glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); // Make sure link worked too glGetProgramiv(hReturn, GL_LINK_STATUS, &testVal); if(testVal == GL_FALSE) { glDeleteProgram(hReturn); return (GLuint)NULL; } return hReturn; } ///////////////////////////////////////////////////////////////// // Load a pair of shaders, compile, and link together. Specify the complete // file path for each shader. Note, there is no support for // just loading say a vertex program... you have to do both. GLuint gltLoadShaderPairSrc(const char *szVertexSrc, const char *szFragmentSrc) { // Temporary Shader objects GLuint hVertexShader; GLuint hFragmentShader; GLuint hReturn = 0; GLint testVal; // Create shader objects hVertexShader = glCreateShader(GL_VERTEX_SHADER); hFragmentShader = glCreateShader(GL_FRAGMENT_SHADER); // Load them. gltLoadShaderSrc(szVertexSrc, hVertexShader); gltLoadShaderSrc(szFragmentSrc, hFragmentShader); // Compile them glCompileShader(hVertexShader); glCompileShader(hFragmentShader); // Check for errors glGetShaderiv(hVertexShader, GL_COMPILE_STATUS, &testVal); if(testVal == GL_FALSE) { glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); return (GLuint)NULL; } glGetShaderiv(hFragmentShader, GL_COMPILE_STATUS, &testVal); if(testVal == GL_FALSE) { glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); return (GLuint)NULL; } // Link them - assuming it works... hReturn = glCreateProgram(); glAttachShader(hReturn, hVertexShader); glAttachShader(hReturn, hFragmentShader); glLinkProgram(hReturn); // These are no longer needed glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); // Make sure link worked too glGetProgramiv(hReturn, GL_LINK_STATUS, &testVal); if(testVal == GL_FALSE) { glDeleteProgram(hReturn); return (GLuint)NULL; } return hReturn; } ///////////////////////////////////////////////////////////////// // Load a pair of shaders, compile, and link together. Specify the complete // source code text for each shader. Note, there is no support for // just loading say a vertex program... you have to do both. GLuint gltLoadShaderPairSrcWithAttributes(const char *szVertexSrc, const char *szFragmentSrc, ...) { // Temporary Shader objects GLuint hVertexShader; GLuint hFragmentShader; GLuint hReturn = 0; GLint testVal; // Create shader objects hVertexShader = glCreateShader(GL_VERTEX_SHADER); hFragmentShader = glCreateShader(GL_FRAGMENT_SHADER); // Load them. gltLoadShaderSrc(szVertexSrc, hVertexShader); gltLoadShaderSrc(szFragmentSrc, hFragmentShader); // Compile them glCompileShader(hVertexShader); glCompileShader(hFragmentShader); // Check for errors glGetShaderiv(hVertexShader, GL_COMPILE_STATUS, &testVal); if(testVal == GL_FALSE) { glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); return (GLuint)NULL; } glGetShaderiv(hFragmentShader, GL_COMPILE_STATUS, &testVal); if(testVal == GL_FALSE) { glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); return (GLuint)NULL; } // Link them - assuming it works... hReturn = glCreateProgram(); glAttachShader(hReturn, hVertexShader); glAttachShader(hReturn, hFragmentShader); // List of attributes va_list attributeList; va_start(attributeList, szFragmentSrc); char *szNextArg; int iArgCount = va_arg(attributeList, int); // Number of attributes for(int i = 0; i < iArgCount; i++) { int index = va_arg(attributeList, int); szNextArg = va_arg(attributeList, char*); glBindAttribLocation(hReturn, index, szNextArg); } va_end(attributeList); glLinkProgram(hReturn); // These are no longer needed glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); // Make sure link worked too glGetProgramiv(hReturn, GL_LINK_STATUS, &testVal); if(testVal == GL_FALSE) { glDeleteProgram(hReturn); return (GLuint)NULL; } return hReturn; } ///////////////////////////////////////////////////////////////// // Check for any GL errors that may affect rendering // Check the framebuffer, the shader, and general errors bool gltCheckErrors(GLuint progName) { bool bFoundError = false; GLenum error = glGetError(); if (error != GL_NO_ERROR) { fprintf(stderr, "A GL Error has occured\n"); bFoundError = true; } #ifndef OPENGL_ES GLenum fboStatus = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); if(fboStatus != GL_FRAMEBUFFER_COMPLETE) { bFoundError = true; fprintf(stderr,"The framebuffer is not complete - "); switch (fboStatus) { case GL_FRAMEBUFFER_UNDEFINED: // Oops, no window exists? fprintf(stderr, "GL_FRAMEBUFFER_UNDEFINED\n"); break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: // Check the status of each attachment fprintf(stderr, "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT\n"); break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: // Attach at least one buffer to the FBO fprintf(stderr, "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT\n"); break; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: // Check that all attachments enabled via // glDrawBuffers exist in FBO fprintf(stderr, "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER\n"); break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: // Check that the buffer specified via // glReadBuffer exists in FBO fprintf(stderr, "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER\n"); break; case GL_FRAMEBUFFER_UNSUPPORTED: // Reconsider formats used for attached buffers fprintf(stderr, "GL_FRAMEBUFFER_UNSUPPORTED\n"); break; case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: // Make sure the number of samples for each // attachment is the same fprintf(stderr, "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE\n"); break; case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: // Make sure the number of layers for each // attachment is the same fprintf(stderr, "GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS\n"); break; } } #endif if (progName != 0) { glValidateProgram(progName); int iIsProgValid = 0; glGetProgramiv(progName, GL_VALIDATE_STATUS, &iIsProgValid); if(iIsProgValid == 0) { bFoundError = true; fprintf(stderr, "The current program(%d) is not valid\n", progName); } } return bFoundError; } /////////////////////////////////////////////////////////////////////////////////////////////////////// // Create a matrix that maps geometry to the screen. 1 unit in the x directionequals one pixel // of width, same with the y direction. void gltGenerateOrtho2DMat(GLuint screenWidth, GLuint screenHeight, M3DMatrix44f &orthoMatrix, GLBatch &screenQuad) { float right = (float)screenWidth; float left = 0.0f; float top = (float)screenHeight; float bottom = 0.0f; // set ortho matrix orthoMatrix[0] = (float)(2 / (right - left)); orthoMatrix[1] = 0.0; orthoMatrix[2] = 0.0; orthoMatrix[3] = 0.0; orthoMatrix[4] = 0.0; orthoMatrix[5] = (float)(2 / (top - bottom)); orthoMatrix[6] = 0.0; orthoMatrix[7] = 0.0; orthoMatrix[8] = 0.0; orthoMatrix[9] = 0.0; orthoMatrix[10] = (float)(-2 / (1.0 - 0.0)); orthoMatrix[11] = 0.0; orthoMatrix[12] = -1*(right + left) / (right - left); orthoMatrix[13] = -1*(top + bottom) / (top - bottom); orthoMatrix[14] = -1.0f; orthoMatrix[15] = 1.0; // set screen quad vertex array screenQuad.Reset(); screenQuad.Begin(GL_TRIANGLE_STRIP, 4, 1); screenQuad.Color4f(0.0f, 1.0f, 0.0f, 1.0f); screenQuad.MultiTexCoord2f(0, 0.0f, 0.0f); screenQuad.Vertex3f(0.0f, 0.0f, 0.0f); screenQuad.Color4f(0.0f, 1.0f, 0.0f, 1.0f); screenQuad.MultiTexCoord2f(0, 1.0f, 0.0f); screenQuad.Vertex3f((float)screenWidth, 0.0f, 0.0f); screenQuad.Color4f(0.0f, 1.0f, 0.0f, 1.0f); screenQuad.MultiTexCoord2f(0, 0.0f, 1.0f); screenQuad.Vertex3f(0.0f, (float)screenHeight, 0.0f); screenQuad.Color4f(0.0f, 1.0f, 0.0f, 1.0f); screenQuad.MultiTexCoord2f(0, 1.0f, 1.0f); screenQuad.Vertex3f((float)screenWidth, (float)screenHeight, 0.0f); screenQuad.End(); }
[ "[email protected]", "patrick@eeepaddy.(none)" ]
[ [ [ 1, 35 ], [ 39, 49 ], [ 56, 1422 ], [ 1424, 1425 ], [ 1427, 1427 ], [ 1429, 1431 ], [ 1433, 1435 ], [ 1437, 1452 ], [ 1454, 1474 ], [ 1476, 1486 ], [ 1488, 1622 ] ], [ [ 36, 38 ], [ 50, 55 ], [ 1423, 1423 ], [ 1426, 1426 ], [ 1428, 1428 ], [ 1432, 1432 ], [ 1436, 1436 ], [ 1453, 1453 ], [ 1475, 1475 ], [ 1487, 1487 ] ] ]
77abc569cc710150ff9aece6b5b290fffd8f1366
58ef4939342d5253f6fcb372c56513055d589eb8
/LemonPlayer_2nd/Source/LPData/inc/LPSetting.h
e2c7eadcf8289eea9166706a39a3b3bdaff874c9
[]
no_license
flaithbheartaigh/lemonplayer
2d77869e4cf787acb0aef51341dc784b3cf626ba
ea22bc8679d4431460f714cd3476a32927c7080e
refs/heads/master
2021-01-10T11:29:49.953139
2011-04-25T03:15:18
2011-04-25T03:15:18
50,263,327
0
0
null
null
null
null
UTF-8
C++
false
false
527
h
#ifndef LPSETTING_H_ #define LPSETTING_H_ #include <e32std.h> #include <e32base.h> #include "FileOperate.h" class LPSetting : public MFileOperateNotify { public: ~LPSetting(); static LPSetting* GetInstance(); public: virtual void FileWriteData(RFileWriteStream& aStream); virtual void FileReadData(RFileReadStream& aStream); private: void ConstructL(); void LoadDataL(); void SaveDataL(); private: static LPSetting* iInstance; CFileOperate* iOperate; }; #endif /*LPSETTING_H_*/
[ "zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494" ]
[ [ [ 1, 28 ] ] ]
61aac92fe964ce54cc09d07952a77d6b1545747c
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/wheel/MyWheelController/include/Probability.h
90699463fc2d0ba2074f50322a6c67fbefb0bbdc
[]
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
UTF-8
C++
false
false
294
h
#ifndef __Orz_Probability_h__ #define __Orz_Probability_h__ #include "WheelControllerConfig.h" #include "WheelEngineInterface.h" namespace Orz { class _OrzMyWheelControlleExport Probability { public: Probability(void); ~Probability(void); }; } #endif
[ [ [ 1, 23 ] ] ]
1da6a8e5780a281eedd4cdbd4ee2a40846e1d9a6
29c5bc6757634a26ac5103f87ed068292e418d74
/src/hook/Hook.cpp
6b661eb335f97660a4d5fd0da267fbd06a569dc4
[]
no_license
drivehappy/tlapi
d10bb75f47773e381e3ba59206ff50889de7e66a
56607a0243bd9d2f0d6fb853cddc4fce3e7e0eb9
refs/heads/master
2021-03-19T07:10:57.343889
2011-04-18T22:58:29
2011-04-18T22:58:29
32,191,364
5
0
null
null
null
null
UTF-8
C++
false
false
8,877
cpp
#include "Hook.h" using namespace TLAPI; // ----------------------------------------------------------------------- // // Meat of the code originally developed by dengus // Cleaned up - drivehappy // ----------------------------------------------------------------------- // PVOID TLAPI::HookGenerateEntry(PVOID address, PVOID out_ins, size_t* out_size) { ud u; ud_init(&u); ud_set_mode(&u,32); ud_set_input_buffer(&u,(uint8_t*)address,0x100); ud_set_pc(&u,(uint64_t)address); uint8_t*out = (uint8_t*)out_ins; size_t total_size=0; void*ret_addr = address; size_t size; // follow any jumps if the function starts with them for (int i=0;i<10;i++) { size = ud_decode(&u); if (!size) { xcept("hook entry %p; failed to decode instruction at %p",address,(void*)u.insn_offset); } ud_operand&op = u.operand[0]; if (u.mnemonic==UD_Ijmp) { ret_addr = (uint8_t*)(u.pc + (op.size==32?op.lval.sdword:op.size==16?op.lval.sword:op.lval.sbyte)); ud_set_input_buffer(&u,(uint8_t*)ret_addr,0x100); ud_set_pc(&u,(uint64_t)ret_addr); continue; } else break; } while (total_size<5) { // u already contains an instruction from the above loop total_size += size; // ud_translate_intel(&u); // printf(" %p :: %-16s %s\n",(void*)ud_insn_off(&u),ud_insn_hex(&u),ud_insn_asm(&u)); // any instructions we care about only have one operand ud_operand&op = u.operand[0]; // oh no, a relative jump. we must patch it up if (op.type==UD_OP_JIMM) { uint32_t addr = (uint32_t)(u.pc + (op.size==32?op.lval.sdword:op.size==16?op.lval.sword:op.lval.sbyte)); // check that the branch is not inside the entry // this routine will still generate invalid code if a function starts with, for instance, 74 00 // but that is extremely unlikely to happen if (addr<(uint32_t)ret_addr||addr>(uint32_t)ret_addr + total_size) { uint8_t*p = (uint8_t*)u.insn_offset; // to be sure it'll reach, we must patch them up to use 32-bit offsets if (op.size==32) { // just copy the opcode memcpy(out,p,size-4); out += size-4; } else if (op.size==16) { // remove the prefix, and copy the opcode memcpy(out,p,size-2-1); out += size-2-1; } else if (op.size==8) { uint8_t i = *p; if (i==0xeb) *out+= 0xe9; // jmp short is 0xeb, jmp near is 0xe9 else if (i>=0x70&&i<=0x7f) { // jcc // the conditional short jmp instructions are 0x70 - 0x7f // the conditional long jmp instructions are 0x80-0x8f (after the 2-byte prefix 0x0f) *out++ = 0x0f; *out++ = i+0x10; } else { xcept("hook entry %p: failed to convert instruction at %p from 8-bit relative branch to 32-bit",address,(void*)u.insn_offset); } // there are no 8-bit relative call instructions } *(uint32_t*)out = addr - (uint32_t)(out+4); out += 4; continue; } } memcpy(out,(void*)u.insn_offset,size); out += size; if (total_size<5) { if (u.mnemonic==UD_Iret || u.mnemonic==UD_Iiretw || u.mnemonic==UD_Ijmp) { // function end, but let's not give up quite yet... there should be some padding uint8_t*p = (uint8_t*)u.pc; while ((*p==0xcc||*p==0x00) && total_size<5) { total_size++; p++; } if (total_size>=5) break; // oh well... xcept("hook entry %p; function too small; ret or non-conditional branch found at %p",address,(void*)u.insn_offset); } size = ud_decode(&u); if (!size) { xcept("hook entry %p; failed to decode instruction at %p",address,(void*)u.insn_offset); } } } // and the jump back to the real function *out++ = 0xe9; *(uint32_t*)out = ((uint32_t)ret_addr + total_size) - (uint32_t)(out+4); out += 4; if (out_size) { *out_size = out - (uint8_t*)out_ins; } return ret_addr; } HookFunctionDef* TLAPI::HookNew(PVOID address, HookFunction pre, HookFunction post, u32 flags, u32 args) { HookFunctionDef *f = new HookFunctionDef; memset(f,0,sizeof(f)); f->address = address; f->pre = pre; f->post = post; f->flags = flags; f->args = args; uint8_t*p = (uint8_t*)VirtualAlloc(0,0x1000,MEM_RESERVE | MEM_COMMIT,PAGE_EXECUTE_READWRITE); f->entry = p; f->patch_address = HookGenerateEntry(address, f->entry, &f->entry_size); f->hook_code = (void*)(((uint32_t)(p+f->entry_size-1) & ~0xF) + 16); // align to 16 bytes f->hook_code_size = HookGenerate(f->hook_code,f); return f; } HookFunctionDef* TLAPI::Hook(PVOID address, HookFunction pre, HookFunction post, u32 flags, u32 args) { HookFunctionDef*f = HookNew(address,pre,post,flags,args); HookActivate(f); return f; } size_t TLAPI::HookGenerate(PVOID out, HookFunctionDef* f) { out_buf_ptr code_buf((unsigned char*)out); codegen gen(&code_buf); //gen.int3(); gen.add_rm_immx<32>(modrm_reg(badreg,esp),-(int)sizeof(HookStruct)); #define rm_h(r,o,...) modrm_dispx(r,-gen.esp_val - sizeof(HookStruct) + (offsetof(HookStruct, o) __VA_ARGS__),sib_nomul(esp)) for (int i=0;i<8;i++) { if (f->flags & HookFlag_Regs[i]) { gen.mov_rm_r<32>(rm_h((reg)i, _eax, +i*4)); } } gen.mov_r_rm<32>(modrm_dispx(eax, -gen.esp_val, sib_nomul(esp))); gen.mov_rm_r<32>(rm_h(eax, retaddress)); int r=2; for (int i=0;i<f->args;i++) { gen.mov_r_rm<32>(modrm_dispx((reg)r,-gen.esp_val + 4 + i*4,sib_nomul(esp))); gen.mov_rm_r<32>(rm_h((reg)r,arg[i])); gen.mov_rm_r<32>(rm_h((reg)r,ref_arg[i])); if (--r==-1) r=2; } if (f->pre) { gen.mov_rm_imm<8>(rm_h(badreg,calloriginal),1); if (-gen.esp_val==sizeof(HookStruct)) gen.mov_r_rm<32>(modrm_reg(eax,esp)); else gen.lea_r_rm<32>(rm_h(eax,ref_arg[0])); gen.push_imm32((uint32_t)f); if (-gen.esp_val==sizeof(HookStruct)) gen.push_r32(esp); else gen.push_r32(eax); gen.call_rel32((uint32_t)f->pre); gen.add_rm_immx<32>(modrm_reg(badreg,esp),8); gen.mov_r_rm<8>(rm_h(eax,calloriginal)); gen.test_rm_r<8>(modrm_reg(eax,eax)); gen.push_imm32(0); uint32_t*retaddr = (uint32_t*)(gen.c->addr()-4); for (int i=0;i<8;i++) { if (f->flags & HookFlag_Regs[i]) { gen.mov_r_rm<32>(rm_h((reg)i,_eax,+4*i)); } } gen.jnz_relx((uint32_t)f->entry); gen.mov_r_rm<32>(rm_h(eax,retval)); gen.add_rm_immx<32>(modrm_reg(badreg,esp),4 + (f->flags & HOOKFLAG_CALLEE_CLEANUP ? 4*f->args : 0)); while (gen.c->addr()%4) gen.nop(); *retaddr = (uint32_t)gen.c->addr(); } else { for (int i=0;i<8;i++) { if (f->flags & HookFlag_Regs[i]) { gen.mov_r_rm<32>(rm_h((reg)i,_eax,+4*i)); } } gen.call_rel32((uint32_t)f->entry); if (f->flags & HOOKFLAG_CALLEE_CLEANUP) { gen.esp_val += 4*f->args; } } if (f->post) { gen.mov_rm_r<32>(rm_h(eax,retval)); if (-gen.esp_val==sizeof(HookStruct)) gen.mov_r_rm<32>(modrm_reg(eax,esp)); else gen.lea_r_rm<32>(rm_h(eax,ref_arg[0])); gen.push_imm32((uint32_t)f); if (-gen.esp_val==sizeof(HookStruct)) gen.push_r32(esp); else gen.push_r32(eax); gen.call_rel32((uint32_t)f->post); gen.mov_r_rm<32>(rm_h(eax,retval)); } #undef rm_h gen.add_rm_immx<32>(modrm_reg(badreg, esp), -gen.esp_val); if (f->flags & HOOKFLAG_CALLEE_CLEANUP && f->args) gen.ret_imm16(f->args*4); else gen.ret(); return code_buf.c - code_buf.oc; } void TLAPI::HookDelete(HookFunctionDef* f) { if (f->hook_code) VirtualFree(f->hook_code,0,MEM_RELEASE); delete f; } void TLAPI::HookActivate(HookFunctionDef* f) { // patch up patch_address to jump to entry DWORD oldprot; if (!VirtualProtectEx(GetCurrentProcess(), f->patch_address, 0x100, PAGE_EXECUTE_READWRITE, &oldprot)) { //xcept("hook entry %p; VirtualProtectEx failed (error %d)",GetLastError()); } uint8_t*out = (uint8_t*)f->patch_address; *out++ = 0xe9; *(uint32_t*)out = (uint8_t*)f->hook_code - (out+4); out += 4; } void TLAPI::HookDeactivate(HookFunctionDef* f) { if (f->hook_code) { VirtualFree(f->hook_code, 0, MEM_RELEASE); } delete f; } void TLAPI::PatchJMP(uint32_t addr, uint32_t to) { uint8_t *p = (uint8_t*)addr; DWORD old; VirtualProtect(p, 5, PAGE_EXECUTE_READWRITE, &old); *p++ = 0xe9; *(uint32_t*)p = (uint8_t*)(to) - (p+4); } void TLAPI::PatchShortJMP(uint32_t addr, uint8_t to) { uint8_t *p = (uint8_t*)addr; DWORD old; VirtualProtect(p, 2, PAGE_EXECUTE_READWRITE, &old); *p++ = 0xeb; *p++ = to; }
[ "drivehappy@53ea644a-42e2-1498-a4e7-6aa81ae25522" ]
[ [ [ 1, 263 ] ] ]
5a16273327d55c3b9e62e727629e37d10f1edfa5
595820f3bb133f455252280a574023931a400660
/cac cau truc va bien toan cuc_TUNGNQ.cpp
e1deccbdcee80c6f0a606155d604cbaece1c50f9
[]
no_license
thinhhoanghuu/btlnhom3
3691b2debed870688cb5449fe8ee4660cfa96a4c
057bdfbf796f20ec8f7b29a8186a614b4e13cfb6
refs/heads/master
2020-12-24T20:43:00.249253
2007-11-07T17:59:39
2007-11-07T17:59:39
56,648,934
0
0
null
null
null
null
UTF-8
C++
false
false
316
cpp
typedef struct { char class_name[7]; char teacher[40]; char room_no[15]; char time[14]; int student_num; } class_information; typedef struct { char roll_no[7]; char full_name[40]; char birthday[11]; char address[50]; char class_name[7]; } student_information;
[ [ [ 1, 23 ] ] ]
4b45d8b6fcd4e8eaf4a34215badb19a3c0723fe5
5236606f2e6fb870fa7c41492327f3f8b0fa38dc
/nsrpc/src/p2p/SystemService.h
6c7e0e2c2b3640b473133d5f71a5bf8061c78db8
[]
no_license
jcloudpld/srpc
aa8ecf4ffc5391b7183b19d217f49fb2b1a67c88
f2483c8177d03834552053e8ecbe788e15b92ac0
refs/heads/master
2021-01-10T08:54:57.140800
2010-02-08T07:03:00
2010-02-08T07:03:00
44,454,693
0
0
null
null
null
null
UHC
C++
false
false
3,302
h
#ifndef NSRPC_SYSTEMSERVICE_H #define NSRPC_SYSTEMSERVICE_H #ifdef _MSC_VER # pragma once #endif #include <nsrpc/p2p/detail/P2pProtocol.h> #include <nsrpc/p2p/detail/P2pRpcTypes.h> #include <nsrpc/p2p/Group.h> #include <srpc/RpcP2p.h> namespace nsrpc { namespace detail { /** @addtogroup p2p * @{ */ /** * @struct RPeerInfo * Peer ์ •๋ณด */ struct RPeerInfo { PeerId peerId_; RAddresses addresses_; RP2pOptions p2pOptions_; RPeerInfo() : peerId_(invalidPeerId) {} RPeerInfo(PeerId peerId, const RAddresses& addresses, P2pOptions p2pOptions) : peerId_(peerId), addresses_(addresses), p2pOptions_(p2pOptions) {} template <typename Stream> void serialize(Stream& ostream) { ostream & peerId_ & addresses_ & p2pOptions_; } }; /// RPeerInfo list typedef srpc::RVector<RPeerInfo> RPeerInfos; /** * @class RpcSystemService * P2P ์‹œ์Šคํ…œ RPC ๋ฉ”์„ธ์ง€ */ class RpcSystemService { public: virtual ~RpcSystemService() {} /// ์—ฐ๊ฒฐ์„ ์š”์ฒญํ•œ๋‹ค DECLARE_SRPC_METHOD_4(RpcSystemService, rpcConnect, RAddresses, peerAddresses, RP2pOptions, p2pOptions, srpc::RShortString, sessionPassword, srpc::UInt32, sessionKey); /// ์—ฐ๊ฒฐ ์š”์ฒญ์— ๋Œ€ํ•œ ์‘๋‹ต์„ ํ•œ๋‹ค DECLARE_SRPC_METHOD_5(RpcSystemService, rpcConnected, RAddresses, peerAddresses, bool, isHost, RP2pProperty, p2pProperty, RP2pOptions, P2pOptions, RGroupMap, groups); /// ํ˜ธ์ŠคํŠธ์—๊ฒŒ ์ง์ ‘ ์—ฐ๊ฒฐ์„ ์š”์ฒญํ•œ๋‹ค DECLARE_SRPC_METHOD_1(RpcSystemService, rpcRequestConnectReversal, RAddresses, peerAddresses); /// ํ˜ธ์ŠคํŠธ๊ฐ€ ํ”ผ์–ด์—๊ฒŒ ์ง์ ‘ ์—ฐ๊ฒฐ์„ ์‹œ๋„ํ•œ๋‹ค DECLARE_SRPC_METHOD_2(RpcSystemService, rpcConnectReversal, RAddresses, PeerAddresses, RP2pOptions, p2pOptions); /// ์ƒˆ๋กœ์šด Peer๊ฐ€ ์ ‘์†ํ•˜์˜€๋‹ค. DECLARE_SRPC_METHOD_1(RpcSystemService, rpcNewPeerConnected, RPeerInfo, peerInfo); /// ํ˜„์žฌ ์„ธ์…˜์—์„œ ์ ‘์† ํ•ด์ œ๋ฅผ ์•Œ๋ฆฐ๋‹ค. DECLARE_SRPC_METHOD_0(RpcSystemService, rpcDisconnect); /// ํ•‘ ๋ฉ”์„ธ์ง€๋ฅผ ๋ณด๋‚ธ๋‹ค. DECLARE_SRPC_METHOD_0(RpcSystemService, rpcPing); /// ์‹ ๋ขฐ ๋ณด์žฅ ๋ฉ”์„ธ์ง€์— ๋Œ€ํ•œ ์‘๋‹ต(ack)๋ฅผ ๋ณด๋‚ธ๋‹ค. DECLARE_SRPC_METHOD_2(RpcSystemService, rpcAcknowledgement, SequenceNumber, sequenceNumber, PeerTime, sentTime); /// ํ˜ธ์ŠคํŠธ ๋งˆ์ด๊ทธ๋ ˆ์ด์…˜์ด ์ผ์–ด๋‚ฌ๋‹ค. DECLARE_SRPC_METHOD_0(RpcSystemService, rpcHostMigrated); /// ๊ทธ๋ฃน์ด ์ƒ์„ฑ๋˜์—ˆ์Œ์„ ์•Œ๋ฆฐ๋‹ค DECLARE_SRPC_METHOD_1(RpcSystemService, rpcGroupCreated, RGroupInfo, groupInfo); /// ๊ทธ๋ฃน์ด ํŒŒ๊ดด๋˜์—ˆ์Œ์„ ์•Œ๋ฆฐ๋‹ค DECLARE_SRPC_METHOD_1(RpcSystemService, rpcGroupDestroyed, RGroupId, groupId); /// ๊ทธ๋ฃน์— ์ฐธ์—ฌํ–ˆ์Œ์„ ์•Œ๋ฆฐ๋‹ค DECLARE_SRPC_METHOD_2(RpcSystemService, rpcGroupJoined, RGroupId, groupId, PeerId, peerId); /// ๊ทธ๋ฃน์—์„œ ํ‡ด์žฅํ–ˆ์Œ์„ ์•Œ๋ฆฐ๋‹ค DECLARE_SRPC_METHOD_2(RpcSystemService, rpcGroupLeft, RGroupId, groupId, PeerId, peerId); }; /** @} */ // addtogroup p2p } // namespace detail } // namespace nsrpc #endif // NSRPC_SYSTEMSERVICE_H
[ "kcando@6d7ccee0-1a3b-0410-bfa1-83648d9ec9a4" ]
[ [ [ 1, 121 ] ] ]
9eea027fdb0fa3a5112ecade078e7b8e25fd02ee
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/SMDK/Limn/LimnDW/LimnDW/BulkSplitter.cpp
616b6399ee87ec957e15cd1142d08d3f1d5c48cb
[]
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
10,878
cpp
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #include "stdafx.h" #define __BULKSPLITTER_CPP #include "bulksplitter.h" #include "limnstream.h" #pragma optimize("", off) #define DoDbg 0 /*x7*/ //==================================================================================== static MInOutDefStruct s_IODefs[]= { // Desc; Name; Id; Rqd; Max; CnId, FracHgt; Options; { "Feed", "Feed", 0, 1, 10, 0, 1.0f, MIO_In |MIO_Material }, { "Product0", "Prod0", 1, 1, 1, 0, 1.0f, MIO_Out|MIO_Material }, { "Product1", "Prod1", 2, 1, 4, 0, 1.0f, MIO_Out|MIO_Material }, { NULL }, }; static double Drw_BulkSplitter[] = { MDrw_Poly, -12,6, 12,2, 12,-2, 0,-6, -12,2, -12,6, MDrw_Poly, -12,4, 12,0, MDrw_Poly, -12,2, 12,-2, MDrw_End }; CLimn_ModelData_Common C_ModelParameters_DiamondWizard_BulkSplitter::sm_Common; //--------------------------------------------------------------------------- DEFINE_TRANSFER_UNIT(CBulkSplitter, "BulkSplitter", DLL_GroupName) void CBulkSplitter_UnitDef::GetOptions() { SetDefaultTag("EC"); SetDrawing("BulkSplitter", Drw_BulkSplitter); SetTreeDescription("LimnDW:BulkSplitter"); SetModelSolveMode(MSolveMode_Probal|MSolveMode_DynamicFlow|MSolveMode_DynamicFull); SetModelGroup(MGroup_General); }; //--------------------------------------------------------------------------- CBulkSplitter::CBulkSplitter(MUnitDefBase * pUnitDef, TaggedObject * pNd) : MBaseMethod(pUnitDef, pNd) { gs_DWCfg.Initialise(); m_DWParms.Initialise();//gs_DWCfg.nSGs()); m_LBtnDn = false; m_RBtnDn = false; } //--------------------------------------------------------------------------- void CBulkSplitter::Init() { SetIODefinition(s_IODefs); } //--------------------------------------------------------------------------- void CBulkSplitter::BuildDataFields() { m_DWParms.BuildDataFields(DD); } bool CBulkSplitter::ExchangeDataFields() { if (m_DWParms.ExchangeDataFields(DX)) return true; return false; } //--------------------------------------------------------------------------- void CBulkSplitter::EvalProducts() { try { //get handles to input and output streams... MStream QI; FlwIOs.AddMixtureIn_Id(QI, 0); MStream & Q0 = FlwIOs[FlwIOs.First[1]].Stream; MStream & Q1 = FlwIOs[FlwIOs.First[2]].Stream; //make outlet temperature and pressure same as input Q0.SetTP(QI.T, QI.P); Q1.SetTP(QI.T, QI.P); if (QI.IFExists<CLimnStream>()) { CLimnStream & LSIn = *QI.GetIF<CLimnStream>(); CLimnStream & LSO0 = *Q0.CreateIF<CLimnStream>(); CLimnStream & LSO1 = *Q1.CreateIF<CLimnStream>(); if (DoDbg) LSIn.Dump("In", DoDbg); LSIn.ConvertToMassForm(QI); LSO0.ConvertToMassForm(Q0); LSO1.ConvertToMassForm(Q1); if (DoDbg) LSIn.Dump("In", DoDbg); //m_DWParms.OversizeStreamID()=1; int Ret = _Model_DiamondWizard_BulkSplitter (gs_DWCfg.RowCount(), gs_DWCfg.ColCount(), m_DWParms.DataCount(), // int nParameters, 0, // int nReturns, CLimn_ModelData_Access(m_DWParms), NULL, // double* ModelReturn, LSIn.Data(), // double* CombinedFeed, LSO0.Data(), // double* Product1, LSO1.Data(), // double* Product2, NULL, // double* Product3, NULL, // double* Product4, NULL, // double* Product5, NULL // double* Product6 ); if (DoDbg) { LSO0.Dump("Product0", DoDbg); LSO1.Dump("Product1", DoDbg); } LSIn.ConvertToFracForm(QI); LSO0.ConvertToFracForm(Q0); LSO1.ConvertToFracForm(Q1); if (DoDbg) { LSO0.Dump("Product0", DoDbg); LSO1.Dump("Product1", DoDbg); } } //get display values... //dFeedQm = QI.MassFlow(); //dProdQm0 = QO0.MassFlow(); //dProdQm1 = QO1.MassFlow(); } catch (MMdlException &e) { Log.Message(MMsg_Error, e.Description); } catch (MFPPException &e) { e.ClearFPP(); Log.Message(MMsg_Error, e.Description); } catch (MSysException &e) { Log.Message(MMsg_Error, e.Description); } catch (...) { Log.Message(MMsg_Error, "Some Unknown Exception occured"); } } //==================================================================================== // Actions bool CBulkSplitter::GetModelAction(CMdlActionArray & Acts) { int IOCnt = FlwIOs.getCount(); if (IOCnt==3) { Acts.SetSize(0); //Acts.Add(CMdlAction(0, MAT_State, true, "Mass Split", 0)); //Acts.Add(CMdlAction(1, MAT_State, true, "Phase Split", 1)); //if (!bDoPhaseSplit) // { // double M1=FlwIOs[1].Stream.MassFlow(); // double M2=FlwIOs[2].Stream.MassFlow(); // double Split=(M1)/GTZ(M1+M2); // Acts.Add(CMdlAction(2, MAT_Value, !bDoPhaseSplit, "Split (%)", true, dRqdFracSplit*100, 0.0, 100.0, Split*100)); // } return true; } return false; }; bool CBulkSplitter::SetModelAction(CMdlAction & Act) { switch (Act.iIndex) { case 0: case 1: //bDoPhaseSplit=Act.iValue!=0; break; case 2: //dRqdFracSplit=Act.dValue*0.01; break; } return true; }; //==================================================================================== // Graphics bool CBulkSplitter::GetModelGraphic(CMdlGraphicArray & Grfs) { CMdlGraphic G0(0, MGT_Simple, true, "Split Graphic", 1); Grfs.SetSize(0); Grfs.SetAtGrow(0, G0); return true; }; bool CBulkSplitter::OperateModelGraphic(CMdlGraphicWnd & Wnd, CMdlGraphic & Grf) { const COLORREF White = COLORREF(RGB(255,255,255)); const COLORREF Black = COLORREF(RGB(0,0,0)); const COLORREF Blue = COLORREF(RGB(0,0,255)); const COLORREF Cyan = COLORREF(RGB(0,255,255)); const COLORREF Red = COLORREF(RGB(255,0,0)); const COLORREF Green = COLORREF(RGB(0,255,0)); switch (Wnd.m_eTask) { case MGT_Create: break; case MGT_Size: break; case MGT_Move: break; case MGT_EraseBkgnd: // Use Wnd.m_pDC; Wnd.m_bReturn = 0;// 1 if erased else 0 break; case MGT_Paint: { double Total=0; int IOCnt = FlwIOs.getCount(); if (IOCnt==3) { double M1=FlwIOs[1].Stream.MassFlow(); double M2=FlwIOs[2].Stream.MassFlow(); double Split=(M1)/GTZ(M1+M2); int charwide = Wnd.m_TextSize.x; int y0 = Wnd.m_ClientRect.top; int y1 = Wnd.m_TextSize.y+1; int y2 = Wnd.m_ClientRect.bottom; int x0 = Wnd.m_ClientRect.left; int xSplit = (int)(Split*Wnd.m_ClientRect.right); int x2 = Wnd.m_ClientRect.right; int y3 = 0; if (1)//!bDoPhaseSplit) { y3=y1; y1+=Wnd.m_TextSize.y; } Wnd.m_pPaintDC->FillSolidRect(CRect(x0,y1,xSplit,y2), Blue); Wnd.m_pPaintDC->FillSolidRect(CRect(xSplit,y1,x2,y2), Cyan); Wnd.m_pPaintDC->FillSolidRect(CRect(x0,y0,x2,y1), Black); Wnd.m_pPaintDC->SetTextColor(Green); CString S; //if (/*!bDoPhaseSplit &&*/ fabs(Split-dRqdFracSplit)>0.001) // S.Format("%.1f %% (Rqd:%.1f %%)", Split*100.0, dRqdFracSplit*100.0); //else S.Format("%.1f %%", Split*100.0); Wnd.m_pPaintDC->TextOut(x0,y0,S); //if (!bDoPhaseSplit) // { // CPen penWhite(PS_SOLID, 0, White); // CPen * oldPen=Wnd.m_pPaintDC->SelectObject(&penWhite); // CBrush brushRed(Red); // CBrush * oldBrush=Wnd.m_pPaintDC->SelectObject(&brushRed); // int xSplitRqd = (int)(dRqdFracSplit*Wnd.m_ClientRect.right); // POINT Arrow[] = // { // {xSplitRqd, y1}, // {xSplitRqd-charwide/2, y3}, // {xSplitRqd+charwide/2, y3}, // {xSplitRqd, y1}, // }; // Wnd.m_pPaintDC->Polygon(Arrow, sizeof(Arrow)/sizeof(Arrow[0])); // Wnd.m_pPaintDC->SelectObject(oldPen); // Wnd.m_pPaintDC->SelectObject(oldBrush); // } } else { int y0 = Wnd.m_ClientRect.top; int y2 = Wnd.m_ClientRect.bottom; int x0 = Wnd.m_ClientRect.left; int x2 = Wnd.m_ClientRect.right; Wnd.m_pPaintDC->FillSolidRect(CRect(x0,y0,x2,y2), Black); Wnd.m_pPaintDC->SetTextColor(Green); CString S; S.Format("Not Connected"); Wnd.m_pPaintDC->TextOut(x0,y0,S); } break; } case MGT_MouseMove: m_LBtnDn=(Wnd.m_MouseFlags & MK_LBUTTON); //if (m_LBtnDn && !bDoPhaseSplit) // { // m_MousePt=Wnd.m_MousePt; // dRqdFracSplit = (double)m_MousePt.x/Wnd.m_ClientRect.right; // Wnd.m_pWnd->RedrawWindow(0, 0, RDW_INVALIDATE|RDW_UPDATENOW); // } break; case MGT_LButtonDown: m_LBtnDn=true; //if (!bDoPhaseSplit) // { // m_MousePt=Wnd.m_MousePt; // dRqdFracSplit = (double)m_MousePt.x/Wnd.m_ClientRect.right; // Wnd.m_pWnd->RedrawWindow(0, 0, RDW_INVALIDATE|RDW_UPDATENOW); // } break; case MGT_LButtonUp: m_LBtnDn=false; break; case MGT_RButtonDown: m_RBtnDn=true; break; case MGT_RButtonUp: m_RBtnDn=false; break; } return true; }; //====================================================================================
[ [ [ 1, 342 ] ] ]