blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
8506a57c38942bc37edbcc096eea6f2a6cbf837b
17e1b436ba01206d97861ec9153943592002ecbe
/uppsrc/Web/httpcli_old.cpp
1594580089b99d2e7685f68fcd9bfba8f184a69a
[ "BSD-2-Clause" ]
permissive
ancosma/upp-mac
4c874e858315a5e68ea74fbb1009ea52e662eca7
5e40e8e31a3247e940e1de13dd215222a7a5195a
refs/heads/master
2022-12-22T17:04:27.008533
2010-12-30T16:38:08
2010-12-30T16:38:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,638
cpp
#include "Web.h" #pragma hdrstop NAMESPACE_UPP #define LLOG(x) // RLOG(x) #define LLOGBLOCK(x) // RLOGBLOCK(x) #define LDUMP(x) // RDUMP(x) HttpClient::HttpClient() { port = DEFAULT_PORT; timeout_msecs = DEFAULT_TIMEOUT_MSECS; max_header_size = DEFAULT_MAX_HEADER_SIZE; max_content_size = DEFAULT_MAX_CONTENT_SIZE; keepalive = false; std_headers = true; method = METHOD_GET; } HttpClient& HttpClient::URL(const char *u) { const char *t = u; while(*t && *t != '?') if(*t++ == '/' && *t == '/') { u = ++t; break; } t = u; while(*u && *u != ':' && *u != '/' && *u != '?') u++; host = String(t, u); port = DEFAULT_PORT; if(*u == ':') port = ScanInt(u + 1, &u); path = u; return *this; } HttpClient& HttpClient::Proxy(const char *p) { const char *t = p; while(*p && *p != ':') p++; proxy_host = String(t, p); proxy_port = 80; if(*p++ == ':' && IsDigit(*p)) proxy_port = ScanInt(p); return *this; } String HttpClient::ExecuteRedirect(int max_redirect, int retries, Gate2<int, int> progress) { int nredir = 0; for(;;) { if(progress(0, 0)) { aborted = true; return String::GetVoid(); } String data = Execute(progress); if(status_code >= 400 && status_code < 500) { error = status_line; return String::GetVoid(); } int r = 0; while(data.IsVoid()) { if(progress(0, 0)) { aborted = true; return String::GetVoid(); } if(++r >= retries) return String::GetVoid(); data = Execute(progress); } if(!IsRedirect()) return data; if(++nredir > max_redirect) { error = NFormat("Maximum number of redirections exceeded: %d", max_redirect); return String::GetVoid(); } URL(GetRedirectURL()); } } String HttpClient::ReadUntilProgress(char until, int start_time, int end_time, Gate2<int, int> progress) { String out; while(!socket.IsEof() && !socket.IsError()) { out.Cat(socket.Read(1000, 1000)); int f = out.Find('\n'); if(f >= 0) { socket.UnRead(out.Mid(f + 1)); out.Trim(f); return out; } int t = msecs(); if(t >= end_time) { socket.SetErrorText(NFormat(t_("%s:%d receiving headers timed out"), host, port)); break; } if(progress(msecs(start_time), end_time - start_time)) { aborted = true; break; } } return String::GetVoid(); } String HttpClient::Execute(Gate2<int, int> progress) { LLOGBLOCK("HttpClient::Execute"); int start_time = msecs(); int end_time = start_time + timeout_msecs; aborted = false; server_headers = Null; status_line = Null; status_code = 0; is_redirect = false; redirect_url = Null; if(socket.IsOpen() && IsError()) Close(); error = Null; bool use_proxy = !IsNull(proxy_host); String sock_host = (use_proxy ? proxy_host : host); int sock_port = (use_proxy ? proxy_port : port); LLOG("socket host = " << sock_host << ":" << sock_port); if(!socket.IsOpen() && !ClientSocket(socket, sock_host, sock_port, true, NULL, 0, false)) { error = Socket::GetErrorText(); return String::GetVoid(); } while(!socket.PeekWrite(1000)) { int time = msecs(); if(time >= end_time) { error = NFormat(t_("%s:%d: connecting to host timed out"), sock_host, sock_port); return String::GetVoid(); } if(progress(time - start_time, end_time - start_time)) { aborted = true; return String::GetVoid(); } } String request; switch(method) { case METHOD_GET: request << "GET "; break; case METHOD_POST: request << "POST "; break; default: NEVER(); // invalid method } String host_port = host; if(port != DEFAULT_PORT) host_port << ':' << port; String url; url << "http://" << host_port << Nvl(path, "/"); if(use_proxy) request << url; else request << Nvl(path, "/"); request << " HTTP/1.1\r\n"; if(std_headers) { request << "URL: " << url << "\r\n" << "Host: " << host_port << "\r\n" << "Connection: " << (keepalive ? "keep-alive" : "close") << "\r\n"; if(keepalive) request << "Keep-alive: 300\r\n"; // 5 minutes (?) request << "Accept: " << Nvl(accept, "*/*") << "\r\n"; request << "Accept-Encoding: gzip\r\n"; request << "Agent: " << Nvl(agent, "Ultimate++ HTTP client") << "\r\n"; if(method == METHOD_POST) request << "Content-Length: " << postdata.GetLength() << "\r\n"; } if(use_proxy && !IsNull(proxy_username)) request << "Proxy-Authorization: basic " << Base64Encode(proxy_username + ':' + proxy_password) << "\r\n"; if(!IsNull(username) || !IsNull(password)) request << "Authorization: basic " << Base64Encode(username + ":" + password) << "\r\n"; request << client_headers << "\r\n" << postdata; LLOG("host = " << host << ", port = " << port); LLOG("request: " << request); int written = 0; while(msecs() < end_time) { int nwrite = socket.WriteWait(request.GetIter(written), request.GetLength() - written, 1000); if(socket.IsError()) { error = Socket::GetErrorText(); return String::GetVoid(); } if((written += nwrite) >= request.GetLength()) break; if(progress(written, request.GetLength())) { aborted = true; return String::GetVoid(); } } if(written < request.GetLength()) { error = NFormat(t_("%s:%d: timed out sending request to server"), host, port); return String::GetVoid(); } status_line = ReadUntilProgress('\n', start_time, end_time, progress); if(socket.IsError()) { error = Socket::GetErrorText(); return String::GetVoid(); } if(status_line.GetLength() < 5 || MemICmp(status_line, "HTTP/", 5)) { error = NFormat(t_("%s:%d: invalid server response: %s"), host, port, status_line); return String::GetVoid(); } status_code = 0; const char *p = status_line.Begin() + 5; while(*p && *p != ' ') p++; if(*p == ' ' && IsDigit(*++p)) status_code = stou(p); is_redirect = (status_code >= 300 && status_code < 400); int content_length = -1; bool tc_chunked = false; bool ce_gzip = false; for(;;) { String line = ReadUntilProgress('\n', start_time, end_time, progress); if(socket.IsError()) { error = Socket::GetErrorText(); return String::GetVoid(); } for(p = line; *p && (byte)*p <= ' '; p++) ; const char *b = p, *e = line.End(); while(e > b && (byte)e[-1] < ' ') e--; if(b >= e) break; static const char cl[] = "content-length:"; static const char ce[] = "content-encoding:"; static const char te[] = "transfer-encoding:"; static const char lo[] = "location:"; static const int CL_LENGTH = sizeof(cl) - 1; static const int CE_LENGTH = sizeof(ce) - 1; static const int TE_LENGTH = sizeof(te) - 1; static const int LO_LENGTH = sizeof(lo) - 1; if(!MemICmp(p, cl, CL_LENGTH)) { for(p += CL_LENGTH; *p == ' '; p++) ; if(IsDigit(*p)) { content_length = minmax<int>(stou(p), 0, max_content_size); if(content_length > max_content_size) { error = NFormat(t_("%s:%d: maximum data length exceeded (%d B)"), host, port, max_content_size); return String::GetVoid(); } } } else if(!MemICmp(p, ce, CE_LENGTH)) { for(p += CE_LENGTH; *p == ' '; p++) ; static const char gzip[] = "gzip"; if(e - p == sizeof(gzip) - 1 && !memcmp(p, gzip, sizeof(gzip) - 1)) ce_gzip = true; } else if(!MemICmp(p, te, TE_LENGTH)) { for(p += TE_LENGTH; *p == ' '; p++) ; static const char ch[] = "chunked"; if(e - p == sizeof(ch) - 1 && !memcmp(p, ch, sizeof(ch) - 1)) tc_chunked = true; } else if(!MemICmp(p, lo, LO_LENGTH)) { for(p += LO_LENGTH; *p == ' '; p++) ; redirect_url = String(p, e); int q = redirect_url.Find('?'); int p = path.Find('?'); if(p >= 0 && q < 0) redirect_url.Cat(path.GetIter(p)); } if(server_headers.GetLength() + (e - b) + 2 > max_header_size) { error = NFormat(t_("%s:%d: maximum header length exceeded (%d B)"), host, port, max_header_size); return String::GetVoid(); } server_headers.Cat(b, int(e - b)); server_headers.Cat("\r\n"); } String chunked; String body; while(body.GetLength() < content_length || content_length < 0 || tc_chunked) { if(msecs(end_time) >= 0) { error = NFormat(t_("%s:%d: timed out when receiving server response"), host, port); return String::GetVoid(); } String part = socket.Read(1000); if(!part.IsEmpty()) { if(body.GetLength() + part.GetLength() > DEFAULT_MAX_CONTENT_SIZE) { error = NFormat(t_("Maximum content size exceeded: %d"), body.GetLength() + part.GetLength()); return tc_chunked ? chunked : body; } body.Cat(part); if(tc_chunked) for(;;) { const char *p = body.Begin(), *e = body.End(); while(p < e && *p != '\n') p++; if(p >= e) break; int nextline = int(p + 1 - body.Begin()); p = body.Begin(); int part_length = ctoi(*p); if((unsigned)part_length >= 16) { body.Remove(0, nextline); continue; } for(int i; (unsigned)(i = ctoi(*++p)) < 16; part_length = part_length * 16 + i) ; body.Remove(0, nextline); if(part_length <= 0) { p = body.Begin(); while(p < e - 2) if(*p == '\n' && (p[1] == '\n' || p[1] == '\r' && p[2] == '\n')) goto EXIT; else p++; while(socket.IsOpen() && !socket.IsError() && !socket.IsEof()) { if(msecs(end_time) >= 0) { error = NFormat("Timeout reading footer block (%d B).", body.GetLength()); goto EXIT; } if(body.GetLength() > 3) body.Remove(0, body.GetLength() - 3); String part = socket.Read(1000); body.Cat(part); const char *p = body; while(*p && !(*p == '\n' && (p[1] == '\n' || p[1] == '\r' && p[2] == '\n'))) p++; if(*p) goto EXIT; } break; } if(body.GetLength() >= part_length) { chunked.Cat(body, part_length); body.Remove(0, part_length); continue; } for(;;) { String part = socket.Read(-msecs(end_time)); if(part.IsEmpty()) { error = NFormat("Timeout reading Transfer-encoding: chunked block (%d B).", part_length); goto EXIT; } body.Cat(part); if(body.GetLength() >= part_length) { chunked.Cat(body, part_length); body.Remove(0, part_length); break; } if(progress(chunked.GetLength() + body.GetLength(), 0)) { aborted = true; return chunked; } } } } if(!socket.IsOpen() || socket.IsError() || socket.IsEof()) { if(socket.IsError()) error = Socket::GetErrorText(); else if(!tc_chunked && content_length > 0 && body.GetLength() < content_length) error = NFormat(t_("Partial input: %d out of %d"), body.GetLength(), content_length); break; } if(progress(chunked.GetLength() + body.GetLength(), max(content_length, 0))) { aborted = true; return tc_chunked ? chunked : body; } } EXIT: if(!keepalive || socket.IsError() || socket.IsEof()) Close(); if(ce_gzip) { body = GZDecompress(body); return body; } return tc_chunked ? chunked : body; } String HttpClientGet(String url, String proxy, String username, String password, String *server_headers, String *error, Gate2<int, int> progress, int timeout, int num_redirect, int retries) { HttpClient client; String out = client .URL(url) .User(username, password) .TimeoutMsecs(timeout) .Proxy(proxy) .ExecuteRedirect(num_redirect, progress, progress); if(server_headers) *server_headers = client.GetHeaders(); if(error) *error = client.GetError(); return out; } String HttpClientGet(String url, String proxy, String *server_headers, String *error, Gate2<int, int> progress, int timeout, int max_redirect, int retries) { return HttpClientGet(url, proxy, Null, Null, server_headers, error, progress, timeout, max_redirect, retries); } String HttpClientGet(String url, String username, String password, String *server_headers, String *error, Gate2<int, int> progress, int timeout, int num_redirect, int retries) { return HttpClientGet(url, Null, username, password, server_headers, error, progress, timeout, num_redirect, retries); } String HttpClientGet(String url, String *server_headers, String *error, Gate2<int, int> progress, int timeout, int max_redirect, int retries) { return HttpClientGet(url, Null, Null, Null, server_headers, error, progress, timeout, max_redirect, retries); } END_UPP_NAMESPACE
[ [ [ 1, 421 ] ] ]
ee8d4703d6db0f9ef744ad8037c21b802204446e
a7985fd90271731c73cab45029ee9a9903c8e1a2
/client/westley.hennigh_cs260/westley.hennigh_cs260/Client.cpp
830322b79994d28a581546a83380cde15f9d1ddd
[]
no_license
WestleyArgentum/cs260-networking
129039f7ad2a89b9350ddcac0cc50a17c6f74bf7
36d2d34400ad93906e2b4839278e4b33de28ae8b
refs/heads/master
2021-01-01T05:47:12.910324
2010-04-07T07:01:40
2010-04-07T07:01:40
32,187,121
0
0
null
null
null
null
UTF-8
C++
false
false
13,140
cpp
// Westley Hennigh // Client.cpp : the implementation of the client class. // CS260 Assignment 1 // Jan 26th 2010 #include <iostream> #include <algorithm> #include <fstream> #include <sstream> //need for getnameinfo() function #include "Ws2tcpip.h" //help the compiler figure out where winsock lives. You could //also add this to the linker but this means no //extra settings for the .csproj file //#pragma comment(lib, "ws2_32.lib") #include "Client.hpp" #include "Defines.hpp" #include "Window.hpp" Client* Client::client = NULL; Client::Client( std::string server_ip, unsigned port /*void (*callback_)(IMessage)*/ ) : ipAddress(server_ip), remote_port(port), lost_server(false) {} Client::Client(std::string text_file) : lost_server(false) { std::ifstream user_file(text_file.c_str()); // read in the ip, port and username info std::string line; unsigned place; // while there is more text and we have not read in the three values we need, read in lines for (unsigned val_read = 0; std::getline(user_file, line) && val_read <= 5; ) { if((place = line.find("IP: ")) != line.npos) { ipAddress = line.c_str() + place + sizeof("IP: ") - 1; // the ip address is everything after that place in the string (-1 for null) ++val_read; } else if((place = line.find("Port: ")) != line.npos) { std::stringstream value; // to extract the unsigned value << line.c_str() + place + sizeof("Port: ") - 1; // -1 for null value >> remote_port; ++val_read; } else if((place = line.find("Name: ")) != line.npos) { username = line.c_str() + place + sizeof("Name: ") - 1; // -1 for null ++val_read; } else if((place = line.find("Udp: ")) != line.npos) { std::stringstream value; // to extract the unsigned value << line.c_str() + place + sizeof("Udp: ") - 1; // -1 for null value >> udp_port; ++val_read; } else if((place = line.find("FileGo: ")) != line.npos) { path = line.c_str() + place + sizeof("FileGo: ") - 1; ++val_read; } //else //^! bad value, print error } } Client* Client::GetClient( std::string text_file ) { if (!client) client = new Client(text_file); return client; } Client* Client::GetClient() { return client; // well I could create one with bogus values but I should figure out a better solution } int Client::Connect(std::string username_) { int ret = 0; //start up winsock, asking for version 2.2 //our WSAData structure. This holds information about the version of winsock that we are using //not necessarily the version that we are requesting WSADATA wsaData; //let's start with zeroing wsaData, not a bad idea SecureZeroMemory(&wsaData, sizeof(wsaData)); //you must call this function to initialize winsock. You must call WSACleanup when you are finished. //this uses a reference counter, so for each call to WSAStartup, you must call WSACleanup or suffer //memory issues ret = WSAStartup(MAKEWORD(2,2), &wsaData); //check that WSAStartup was successful. if(ret != 0) { std::cout << "Error initializing winsock! Error was: " << ret << std::endl; return ret; } //a sockaddr_in specifies IP address and port information. the address family tells what the add //address used to bind to socket, holds port, IP, and address family struct sockaddr_in socketAddress; //address family- this identifies the addressing structure of this address structure. //for IP, it must always be set to AF_INET socketAddress.sin_family = AF_INET; //this is the port. remember, networks are in network-order, which is big-endian. we use htons() to ensure //that the number is in the correct "endian-ness" for the network regardless of what machine architecture we're on //for a local connection going out, pick 0 and winsock will assign a random port socketAddress.sin_port = 0; //htons(remote_port); //^? cant be remote_port, that would break everything when working on one machine //now we need to set the actual IP address. this is an in_addr struct for IPv4. for Ipv6, it's an in6_addr //it is represented as a ulong with each byte representing one part of the ip address. we can convert an address in //it's dot-notation (i.e. 192.168.1.1) to this format using the inet_addr() function, OR we can just use ADDR_ANY which //will cause this address to listen to any available network interface (machines may have more than one network card) //get host. hostent stores information about a host hostent* localhost; //gethostbyname- gets host information based on host name. //this allocates memory only once per host no matter how many times you call //gethostbyname(). //deprecated in favor of getaddrinfo //there are a lot of ways to do this localhost = gethostbyname(""); char* localIP; //this will give us the four-byte representation of our ip address. localIP = inet_ntoa(*(in_addr*)*localhost->h_addr_list); //let's use the address that we got from gethostbyname for our local endpoint socketAddress.sin_addr.s_addr = inet_addr(localIP); sockaddr_in remote; remote.sin_family = AF_INET; remote.sin_addr.s_addr = inet_addr(ipAddress.c_str()); remote.sin_port = htons(remote_port); //SOCKET clientSocket; //create a socket //this socket is not bound to anything, so all it is is an empty socket at this point //AF_INET- this means that we want an IP socket. If we wanted an IPv6 socket, we would use AF_INET6 //if we wanted to talk to an infrared port, we'd use AF_IRDA //bluetooth is AF_BTM //SOCK_STREAM - tells us the type of socket. SOCK_STREAM is two-way, reliable, connection-based byte streams //that can transmit OOB data. uses TCP. for UDP use SOCK_DGRAM, and for raw, use SOCK_RAW. there are others also //IPPROTO_TCP- tells us to use the TCP protocol. this parameter can only be used certain ways with //certain address family and type settings. if we wanted UDP, we would have had to set our type to SOCK_DGRAM //or we'll get an error. passing 0 means that we dont' care about the protocol and the socket can choose //NULL- we specified TCP, so we don't need this parameter, but it would contain protocol info normally. if //we enumerate all the protocols supported on this machine, we could pick one of them and pass it in here to get //an explicit protocol implementation. mostly, we don't care, but if we were using IPX (for example) then we would //care a lot //0- this is reserved, always set it to 0. //0- these are the options. normally the only one you'd care about is creating an overlapped socket for //use with IO ports. if you want to do that, send WSA_IO_OVERLAPPED here. more on that in a future demo clientSocket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0); //error checking if(clientSocket == INVALID_SOCKET) { int errorcode = WSAGetLastError(); std::cout << "Error on creating socket: " << errorcode << std::endl; return errorcode; } //so now we have a socket, and we have a sockaddr_in that describes an address and port, let's put them //together and send some data! //bind- binds a socket to an address. //clientSocket- the socket to bind //socketAddress- the address structure to bind, need to recast to sockaddr here //size of the sockaddr struct ret = bind(clientSocket, (sockaddr*)&socketAddress, sizeof(socketAddress)); if(ret == SOCKET_ERROR) { ret = WSAGetLastError(); return ret; } //now we have a socket and we can do something to it. let's connect to a server somewhere and //send some data //we're going to connect. for connection-oriented sockets (TCP) this will establish a connection. //for datagram sockets, it will only set up a default endpoint to send subsequent calls to SEND to //we're going connect to a remote host now. //clientSocket is the socket that we've created for this end of the connection //remote is the endpoint that we're connection to. We have to cast it as sockaddr for this //version of connect //we also pass the size of the sockaddr struct since this could potentially change based on //what type of address we're using ret = connect(clientSocket, (sockaddr*)&remote, sizeof(remote)); if(ret == SOCKET_ERROR) { ret = WSAGetLastError(); return ret; } // now we have a connection made, but the server will need to know our name. // wait for a query of that sort and then reply char buffer [STD_BUFF_SIZE]; ret = recv(clientSocket, buffer, STD_BUFF_SIZE, 0); IMessage* kitten = ConstructMessage(buffer); if(kitten->my_type == RequestForUsername_Msg) { UsernameMsg username_message; username_message.myname = username; ret = username_message.WriteOut(buffer); ret = send(clientSocket, buffer, ret, 0); } else { // the server is not behaving as expected (were not in the servers vec yet, // so we shouldnt get any other message) return -1; } delete kitten; // clean up! // now put the socket into non-blocking mode u_long val = 1; ioctlsocket(clientSocket, FIONBIO, &val); return 0; } int Client::ShutDown() { int ret = 0; //shutdown the socket //clientSocket- the socket to shut down //SD_SEND- how to shut it down. SD_SEND means that //you will no longer send over this socket. for TCP, it //also means that you will send a FIN packet once all //data has been received and acknowledged //you also have other options //SD_RECEIVE - no more receiving data. triggers a RST if //data is received after this is done //SD_BOTH- no more send and receive ret = shutdown(clientSocket, SD_SEND); if(ret == SOCKET_ERROR){ ret = WSAGetLastError(); return ret; } //clean up the socket. Technically, WSACleanup will do this for you //but it's good to get in the habit of closing your own sockets. ret = closesocket(clientSocket); if(ret == SOCKET_ERROR){ ret = WSAGetLastError(); return ret; } //don't forget to call this at the end. in total, call it as many times as you have called //WSAStartup() WSACleanup(); lost_server = true; return 0; } int Client::Send(IMessage& message_) { char buffer [STD_BUFF_SIZE]; int size = message_.WriteOut(buffer); return send(clientSocket, buffer, size + 1, 0); } IMessage* Client::Receive() { int ret; char buffer [STD_BUFF_SIZE]; // if we find data then make it into a nice message ret = recv(clientSocket, buffer, STD_BUFF_SIZE, 0); if(ret == SOCKET_ERROR) // check for error { if(WSAGetLastError() != WSAEWOULDBLOCK) { std::cout << "Error receiving data in accepting thread: " << WSAGetLastError() << std::endl; return NULL; } else // if it was return NULL; } else if(ret == 0) // means they are done playing around { // the server has shut down... lost_server = true; //^! this should be de-coupled SendMessage(SillyWindow::GetWindow()->output, WM_SETTEXT, 0, (LPARAM)"We are currently maintaining the server. Go away."); } // make the message (this is a good spot to check for errors) if (*reinterpret_cast<unsigned*>(buffer) > static_cast<unsigned>(ret)) { std::cout << "There was a problem receiving a message in the client..." << std::endl; } return ConstructMessage(buffer); } bool Client::StillConnected() { return !lost_server; } std::string Client::GetUsername() { return username; } //int Client::Run() //{ // int ret = 0; // // std::string SendBuffer; // std::string CommandBuffer; // we want to receive case insensitive commands from the prompt // char RecieveBuffer[MAX_LEN]; // // std::cout << "---------" << std::endl; // std::getline(std::cin, SendBuffer); // prime the buffer with their initial input so we can cin last in the loop and check quit before we network. // // // uppercase everything to check for commands // CommandBuffer = SendBuffer; // std::transform(CommandBuffer.begin(), CommandBuffer.end(), CommandBuffer.begin(), toupper); // // while (CommandBuffer != "QUIT") // { // // send the message ------- // ret = send(clientSocket, SendBuffer.c_str(), SendBuffer.size(), 0); // if(ret == SOCKET_ERROR) // { // ret = WSAGetLastError(); // return ret; // } // // ------------ // // // listen for a reply ------- // memset(RecieveBuffer, 0, MAX_LEN); // clear out the buffer // // ret = recv(clientSocket, RecieveBuffer, MAX_LEN, 0); // if(ret == SOCKET_ERROR) // { // ret = WSAGetLastError(); // return ret; // } // std::cout << std::string(RecieveBuffer) << std::endl << "---------" << std::endl; // print out what we got // // ------------ // // std::getline(std::cin, SendBuffer); // get some input from the user // // // uppercase everything to check for commands // CommandBuffer = SendBuffer; // std::transform(CommandBuffer.begin(), CommandBuffer.end(), CommandBuffer.begin(), toupper); // } // // return 0; //}
[ "[email protected]@1f2afcba-5144-80f4-e828-afee2f9acc6f", "knuxjr@1f2afcba-5144-80f4-e828-afee2f9acc6f", "westleyargentum@1f2afcba-5144-80f4-e828-afee2f9acc6f" ]
[ [ [ 1, 16 ], [ 18, 36 ], [ 38, 62 ], [ 68, 391 ] ], [ [ 17, 17 ] ], [ [ 37, 37 ], [ 63, 67 ] ] ]
be5567d8556f9a86fe4f7d508688338729eb28ac
f73eca356aba8cbc5c0cbe7527c977f0e7d6a116
/Glop/third_party/raknet/TransportInterface.h
f11d11d5714fa3b90fc79822bbfb5ec11a6ec7e9
[ "BSD-3-Clause" ]
permissive
zorbathut/glop
40737587e880e557f1f69c3406094631e35e6bb5
762d4f1e070ce9c7180a161b521b05c45bde4a63
refs/heads/master
2016-08-06T22:58:18.240425
2011-10-20T04:22:20
2011-10-20T04:22:20
710,818
1
0
null
null
null
null
UTF-8
C++
false
false
4,230
h
/// \file /// \brief Contains TransportInterface from which you can derive custom transport providers for ConsoleServer. /// /// This file is part of RakNet Copyright 2003 Kevin Jenkins. /// /// Usage of RakNet is subject to the appropriate license agreement. /// Creative Commons Licensees are subject to the /// license found at /// http://creativecommons.org/licenses/by-nc/2.5/ /// Single application licensees are subject to the license found at /// http://www.jenkinssoftware.com/SingleApplicationLicense.html /// Custom license users are subject to the terms therein. /// GPL license users are subject to 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. #ifndef __TRANSPORT_INTERFACE_H #define __TRANSPORT_INTERFACE_H #include "RakNetTypes.h" #include "Export.h" #include "RakMemoryOverride.h" #define REMOTE_MAX_TEXT_INPUT 2048 class CommandParserInterface; /// \brief Defines an interface that is used to send and receive null-terminated strings. /// In practice this is only used by the CommandParser system for for servers. class RAK_DLL_EXPORT TransportInterface : public RakNet::RakMemoryOverride { public: TransportInterface() {} virtual ~TransportInterface() {} /// Start the transport provider on the indicated port. /// \param[in] port The port to start the transport provider on /// \param[in] serverMode If true, you should allow incoming connections (I don't actually use this anywhere) /// \return Return true on success, false on failure. virtual bool Start(unsigned short port, bool serverMode)=0; /// Stop the transport provider. You can clear memory and shutdown threads here. virtual void Stop(void)=0; /// Send a null-terminated string to \a systemAddress /// If your transport method requires particular formatting of the outgoing data (e.g. you don't just send strings) you can do it here /// and parse it out in Receive(). /// \param[in] systemAddress The player to send the string to /// \param[in] data format specifier - same as RAKNET_DEBUG_PRINTF /// \param[in] ... format specification arguments - same as RAKNET_DEBUG_PRINTF virtual void Send( SystemAddress systemAddress, const char *data, ... )=0; /// Disconnect \a systemAddress . The binary address and port defines the SystemAddress structure. /// \param[in] systemAddress The player/address to disconnect virtual void CloseConnection( SystemAddress systemAddress )=0; /// Return a string. The string should be allocated and written to Packet::data . /// The byte length should be written to Packet::length . The player/address should be written to Packet::systemAddress /// If your transport protocol adds special formatting to the data stream you should parse it out before returning it in the packet /// and thus only return a string in Packet::data /// \return The packet structure containing the result of Receive, or 0 if no data is available virtual Packet* Receive( void )=0; /// Deallocate the Packet structure returned by Receive /// \param[in] The packet to deallocate virtual void DeallocatePacket( Packet *packet )=0; /// If a new system connects to you, you should queue that event and return the systemAddress/address of that player in this function. /// \return The SystemAddress/address of the system virtual SystemAddress HasNewConnection(void)=0; /// If a system loses the connection, you should queue that event and return the systemAddress/address of that player in this function. /// \return The SystemAddress/address of the system virtual SystemAddress HasLostConnection(void)=0; /// Your transport provider can itself have command parsers if the transport layer has user-modifiable features /// For example, your transport layer may have a password which you want remote users to be able to set or you may want /// to allow remote users to turn on or off command echo /// \return 0 if you do not need a command parser - otherwise the desired derivation of CommandParserInterface virtual CommandParserInterface* GetCommandParser(void)=0; protected: }; #endif
[ [ [ 1, 86 ] ] ]
d5a9189d8ae8650a6dbb851b91c81d5fdfac1214
677f7dc99f7c3f2c6aed68f41c50fd31f90c1a1f
/SolidSBCTestSDK/SolidSBCTestManager.cpp
a83d8d5e531837af047c382630ece168f8d0e0f8
[]
no_license
M0WA/SolidSBC
0d743c71ec7c6f8cfe78bd201d0eb59c2a8fc419
3e9682e90a22650e12338785c368ed69a9cac18b
refs/heads/master
2020-04-19T14:40:36.625222
2011-12-02T01:50:05
2011-12-02T01:50:05
168,250,374
0
0
null
null
null
null
UTF-8
C++
false
false
5,868
cpp
#include "stdafx.h" #include "SolidSBCTestManager.h" #include <stdio.h> using namespace std; CSolidSBCTestManager::CSolidSBCTestManager(void) { } CSolidSBCTestManager::~CSolidSBCTestManager(void) { //stop and delete all running tests for( std::vector<CSolidSBCTestThread*>::iterator iIter = m_vecRunningTests.begin(); iIter != m_vecRunningTests.end(); iIter++) { (*iIter)->StopThread(); delete (*iIter); (*iIter) = NULL; } m_vecRunningTests.clear(); //delete all dummy results for(std::map<std::string,CSolidSBCTestResult*>::iterator iIter = m_mapTestResultDataTypes.begin(); iIter != m_mapTestResultDataTypes.end(); iIter++) delete (*iIter).second; //delete all configs for tests for( SSBC_CONFIG_MAP_TYPE::iterator iIter = m_mapTestConfigs.begin(); iIter != m_mapTestConfigs.end(); iIter++) { delete (*iIter).second; } m_mapTestConfigs.clear(); //delete all remaining results for( SSBC_RESULT_MAP_TYPE::iterator iIter = m_mapTestResults.begin(); iIter != m_mapTestResults.end(); iIter++) { (*iIter).second.pResultMutex->Lock(); std::vector<CSolidSBCTestResult*>* pResultVector = (*iIter).second.pResults; if (pResultVector && pResultVector->size()) { std::vector<CSolidSBCTestResult*>::iterator iIterRes = pResultVector->begin(); for ( ; iIterRes != pResultVector->end(); iIterRes++ ) { CSolidSBCTestResult* pResult = (*iIterRes); if ( pResult ) delete pResult; } } delete pResultVector; (*iIter).second.pResultMutex->Unlock(); delete (*iIter).second.pResultMutex; } m_mapTestResults.clear(); } int CSolidSBCTestManager::GetTestNames(std::vector<std::string>& vecTestnames) { std::vector<SSBC_TESTNAME_FUNC_PAIR_TYPE>::iterator iIter; vecTestnames.clear(); vecTestnames.reserve(m_vecTestNames.size()); for( iIter = m_vecTestNames.begin(); iIter != m_vecTestNames.end(); iIter++) vecTestnames.push_back( (*iIter).first ); return (int)vecTestnames.size(); } void CSolidSBCTestManager::RegisterTest(AFX_THREADPROC pThreadFunc, CSolidSBCTestConfig* pTestConfig, CSolidSBCTestResult* pTestResult) { USES_CONVERSION; std::string sTestName = T2A(pTestConfig->GetTestName()); SSBC_RESULTS_CONTAINER resultContainer; resultContainer.pResultMutex = new CMutex(); resultContainer.pResults = new vector<CSolidSBCTestResult*>(); SSBC_TESTNAME_FUNC_PAIR_TYPE pairNameFunc(sTestName,pThreadFunc); m_vecTestNames.push_back(pairNameFunc); m_mapTestConfigs[sTestName] = pTestConfig; m_mapTestResults[sTestName] = resultContainer; m_mapTestResultDataTypes[sTestName] = pTestResult; } int CSolidSBCTestManager::StartTest(const std::string& sXML) { USES_CONVERSION; CString strXml = CString(A2T(sXML.c_str())); CString strTestName = CSolidSBCTestConfig::GetTestNameFromXML(strXml); if(strTestName == _T("")) return 1; AFX_THREADPROC threadFunc = GetThreadFuncByName(std::string(T2A(strTestName))); CSolidSBCTestThread* pThread = new CSolidSBCTestThread(std::string(T2A(strTestName)),threadFunc,m_mapTestResults[std::string(T2A(strTestName))]); if( !pThread ) return 1; CSolidSBCTestConfig* pConfig = m_mapTestConfigs[std::string(T2A(strTestName))]; pConfig->SetXml(A2T(sXML.c_str())); pThread->StartThread(pConfig); m_vecRunningTests.push_back(pThread); return 0; } int CSolidSBCTestManager::StopTest(const std::string& sTestName) { int nStopped = 0; while(1) { bool bTestFound = false; for( std::vector<CSolidSBCTestThread*>::iterator iIter = m_vecRunningTests.begin(); iIter != m_vecRunningTests.end(); iIter++) { if ( (*iIter) && ((*iIter)->GetTestName() == sTestName) ) { (*iIter)->StopThread(); delete (*iIter); (*iIter) = NULL; nStopped++; m_vecRunningTests.erase(iIter); bTestFound = true; break; } } if(!bTestFound) break; } return nStopped; } int CSolidSBCTestManager::GetTestResults(std::vector<CSolidSBCTestResult*>& vecResults) { int nSize = 0; std::vector<CSolidSBCTestResult*>* pResultVector = 0; for( SSBC_RESULT_MAP_TYPE::iterator iIter = m_mapTestResults.begin(); iIter != m_mapTestResults.end(); iIter++) { (*iIter).second.pResultMutex->Lock(); pResultVector = (*iIter).second.pResults; if ( pResultVector && pResultVector->size() ) { nSize += (int)pResultVector->size(); vecResults.insert( vecResults.end(), pResultVector->begin(), pResultVector->end() ); pResultVector->clear(); } (*iIter).second.pResultMutex->Unlock(); } return nSize; } CSolidSBCTestConfig* CSolidSBCTestManager::GetTestConfigByName( const std::string& sTestName ) { return m_mapTestConfigs[sTestName]; } void CSolidSBCTestManager::SetTestConfigByName( const std::string& sTestName, CSolidSBCTestConfig* pConfig ) { delete m_mapTestConfigs[sTestName]; m_mapTestConfigs[sTestName] = pConfig; } AFX_THREADPROC CSolidSBCTestManager::GetThreadFuncByName(const std::string& sTestName) { for( std::vector<SSBC_TESTNAME_FUNC_PAIR_TYPE>::iterator iIter = m_vecTestNames.begin(); iIter != m_vecTestNames.end(); iIter++) if ( (*iIter).first == sTestName ) return (*iIter).second; return NULL; } bool CSolidSBCTestManager::HasTestName( const std::string& sTestName ) { for( std::vector<SSBC_TESTNAME_FUNC_PAIR_TYPE>::iterator iIter = m_vecTestNames.begin(); iIter != m_vecTestNames.end(); iIter++) if ( (*iIter).first == sTestName ) return true; return false; } void CSolidSBCTestManager::GetCreateTableStatements(std::string& sStatement) { std::map<std::string,CSolidSBCTestResult*>::iterator iIter = m_mapTestResultDataTypes.begin(); for(; iIter != m_mapTestResultDataTypes.end(); iIter++) if( (*iIter).second != NULL ) sStatement += (*iIter).second->GetTestDBStructure(); }
[ "admin@bd7e3521-35e9-406e-9279-390287f868d3" ]
[ [ [ 1, 186 ] ] ]
ec17c1f6bae1fa2639f78c9a30dcdfe5efea568f
65c92f6c171a0565fe5275ecc48033907090d69d
/Client/Plugins/Course/Implementation/LessonTabTeacher.h
71f9f0718a66ee5da4c343db51cecff2b6d4a385
[]
no_license
freakyzoidberg/horus-edu
653ac573887d83a803ddff1881924ab82b46f5f6
2757766a6cb8c1f1a1b0a8e209700e6e3ccea6bc
refs/heads/master
2020-05-20T03:08:15.276939
2010-01-07T14:34:51
2010-01-07T14:34:51
32,684,226
0
0
null
null
null
null
UTF-8
C++
false
false
3,068
h
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Horus is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * Horus is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with Horus. If not, see <http://www.gnu.org/licenses/>. * * * * The orginal content of this material was realized as part of * * 'Epitech Innovative Project' www.epitech.eu * * * * You are required to preserve the names of the original authors * * of this content in every copy of this material * * * * Authors : * * - BERTHOLON Romain * * - GRANDEMANGE Adrien * * - LACAVE Pierre * * - LEON-BONNET Valentin * * - NANOUCHE Abderrahmane * * - THORAVAL Gildas * * - VIDAL Jeremy * * * * You are also invited but not required to send a mail to the original * * authors of this content in case of modification of this material * * * * Contact: [email protected] * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef LESSONTABTEACHER_H #define LESSONTABTEACHER_H #include <QWidget> #include "../../../../Common/PluginManager.h" class LessonTabTeacher : public QWidget { public: LessonTabTeacher(PluginManager *pluginManager); private: PluginManager *_pluginManager; }; #endif // LESSONTABTEACHER_H
[ "git@cb2ab776-01a4-11df-b136-7f7962f7bc17", "grande_a@cb2ab776-01a4-11df-b136-7f7962f7bc17" ]
[ [ [ 1, 34 ] ], [ [ 35, 51 ] ] ]
0db402c57aea9193caf2505b8c1c970f12fc852c
335783c9e5837a1b626073d1288b492f9f6b057f
/source/fbxcmd/ViewScene/texloaders.cpp
3ba0f8a8d24b5f3b82ca34d81b7987f3eb169b44
[ "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
20,003
cpp
#pragma once #include <stdio.h> #include <stdarg.h> #include <tchar.h> #include <math.h> #include <sys/stat.h> #include <fbxsdk.h> #ifdef WIN32 #include <windows.h> #endif #include "GL/glew.h" //#define GLUT_DISABLE_ATEXIT_HACK #if defined(__MACH__) #include <GLUT/glut.h> #else #include "GL/glut.h" #endif #include <fbxfilesdk/fbxfilesdk_nsuse.h> #include "Texture.h" #include "Common.h" #include "texloaders.h" #include "targa.h" #include "dds/Image.h" #include "dds/dds_api.h" #include "dds/DirectDrawSurface.h" #include "daostream.h" #include "ResourceManager.h" #include "../fbxcmd/Plugins/fbxcmn/KFbxLog.h" typedef char int8; typedef short int16; typedef int int32; typedef unsigned char byte; typedef unsigned char uint8; typedef unsigned short uint16; typedef unsigned int uint32; // sprintf for TSTR without having to worry about buffer size. KString FormatString(const char* format,...) { char buffer[512]; va_list args; va_start(args, format); int nChars = _vsnprintf(buffer, _countof(buffer), format, args); if (nChars != -1) { va_end(args); return KString((char*)buffer); } else { size_t Size = _vscprintf(format, args); KString text('\0', Size + 1); nChars = _vsnprintf(text.Buffer(), Size, format, args); va_end(args); return text; } } class IOStream { public: IOStream() : fh(NULL){} ~IOStream() { Close(); } void *&pdata() { return data; } void* data; FILE* fh; bool Open(const char *file, bool readonly, KError & lError) { if (fh) Close(); if (file == NULL && readonly) { fh = stdin; } else if (file == NULL && !readonly) { fh = stdout; } else { fh = fopen(file, readonly ? "rbS" : "wbS"); if (!fh) { KFbxLog::LogError( "Unable to open file: %s", file ); return false; } setvbuf(fh, NULL, _IOFBF, 0x8000); } return true; } bool Open(const wchar_t *file, bool readonly, KError & lError) { if (fh) Close(); if (file == NULL && readonly) { fh = stdin; } else if (file == NULL && !readonly) { fh = stdout; } else { fh = _wfopen(file, readonly ? L"rbS" : L"wbS"); if (!fh) { KFbxLog::LogError( "Unable to open file: %s", file); return false; } setvbuf(fh, NULL, _IOFBF, 0x8000); } return true; } void Close() { if (fh) { fclose(fh); fh = NULL; } } size_t Read(void *buf, size_t size, size_t count) { size_t n = (size_t)fread(buf, size, count, fh); int err = errno; if (!(n == count && err == 0)) { int t = Tell(); //ASSERT(n == count && err == 0); } return n; } size_t Read(void *buf, size_t count) { return Read(buf, 1, count); } size_t Write(const void *buf, size_t size, size_t count) { return (size_t)fwrite(buf, size, count, fh); } size_t Write(const void *buf, size_t count) { return Write(buf, 1, count); } int Seek(int whence, long offset) { return fseek(fh, offset, whence); } int Seek(long offset) { return fseek(fh, offset, SEEK_SET); } int Tell() { return ftell(fh); } int TellEnd() { struct _stat64 data; memset(&data, 0, sizeof(data)); _fstat64(_fileno(fh), &data); return int(data.st_size); } int TellRemain() { return (TellEnd() - Tell()); } bool Eof() const { return (feof(fh) != 0); } }; //************************************ // Method: loadTargaFile // FullName: loadTargaFile // Access: public static // Returns: bool // Qualifier: // Parameter: const KString & lFileName // Parameter: VSTexture * lTexture // Parameter: KError & lError //************************************ static bool loadTargaFile( const KString & lFileName, VSTexture * lTexture, KError & lError ) { tga_image lTGAImage; tga_result errcode = tga_read(&lTGAImage, lFileName.Buffer()); if (TGA_NOERR == errcode) { // Make sure the image is left to right if (tga_is_right_to_left(&lTGAImage)) tga_flip_horiz(&lTGAImage); // Make sure the image is bottom to top if (tga_is_top_to_bottom(&lTGAImage)) tga_flip_vert(&lTGAImage); // Make the image BGR 24 tga_convert_depth(&lTGAImage, 24); lTexture->mW = lTGAImage.width; lTexture->mH = lTGAImage.height; lTexture->internalformat = 3; lTexture->format = GL_BGR_EXT; lTexture->type = GL_UNSIGNED_BYTE; lTexture->mImageData = new unsigned char[lTGAImage.width*lTGAImage.height*lTGAImage.pixel_depth/8]; memcpy(lTexture->mImageData, lTGAImage.image_data, lTGAImage.width*lTGAImage.height*lTGAImage.pixel_depth/8); tga_free_buffers(&lTGAImage); return true; } else { //lError.SetLastError(errcode, tga_error(errcode) ); return false; } } //! Check whether a number is a power of two. bool isPowerOfTwo( unsigned int x ) { while ( ! ( x == 0 || x & 1 ) ) x = x >> 1; return ( x == 1 ); } //! Converts RLE-encoded data into pixel data. /*! * TGA in particular uses the PackBits format described at * http://en.wikipedia.org/wiki/PackBits and in the TGA spec. */ bool uncompressRLE( IDAOStream & f, int w, int h, int bytespp, uint8 * pixel ) { int size = (f.TellEnd() - f.Tell()); byte *data = new byte[ size ]; f.Read(data, sizeof(byte), size); int c = 0; // total pixel count int o = 0; // data offset bool ok = true; uint8 rl; // runlength - 1 while ( c < w * h && ok ) { rl = data[o++]; if ( rl & 0x80 ) // if RLE packet { uint8 px[8]; // pixel data in this packet (assume bytespp < 8) for ( int b = 0; b < bytespp; b++ ) px[b] = data[o++]; rl &= 0x7f; // strip RLE bit do { for ( int b = 0; b < bytespp; b++ ) *pixel++ = px[b]; // expand pixel data (rl+1) times } while ( ++c < w*h && rl-- > 0 ); } else { do { for ( int b = 0; b < bytespp; b++ ) *pixel++ = data[o++]; // write (rl+1) raw pixels } while ( ++c < w*h && rl-- > 0 ); } if ( o >= size ) ok = false; } delete [] data; return ok; } //! Convert pixels to RGBA /*! * \param data Pixels to convert * \param w Width of the image * \param h Height of the image * \param bytespp Number of bytes per pixel * \param mask Bitmask for pixel data * \param flipV Whether to flip the data vertically * \param flipH Whether to flip the data horizontally * \param pixl Pixels to output */ void convertToRGBA( const uint8 * data, int w, int h, int bytespp, const uint32 mask[], bool flipV, bool flipH, uint8 * pixl ) { memset( pixl, 0, w * h * 4 ); static const int rgbashift[4] = { 0, 8, 16, 24 }; for ( int a = 0; a < 4; a++ ) { if ( mask[a] ) { uint32 msk = mask[ a ]; int rshift = 0; while ( msk != 0 && ( msk & 0xffffff00 ) ) { msk = msk >> 1; rshift++; } int lshift = rgbashift[ a ]; while ( msk != 0 && ( ( msk & 0x80 ) == 0 ) ) { msk = msk << 1; lshift++; } msk = mask[ a ]; const uint8 * src = data; const uint32 inc = ( flipH ? -1 : 1 ); for ( int y = 0; y < h; y++ ) { uint32 * dst = (uint32 *) ( pixl + 4 * ( w * ( flipV ? h - y - 1 : y ) + ( flipH ? w - 1 : 0 ) ) ); if ( rshift == lshift ) { for ( int x = 0; x < w; x++ ) { *dst |= *( (const uint32 *) src ) & msk; dst += inc; src += bytespp; } } else { for ( int x = 0; x < w; x++ ) { *dst |= ( *( (const uint32 *) src ) & msk ) >> rshift << lshift; dst += inc; src += bytespp; } } } } else if ( a == 3 ) { uint32 * dst = (uint32 *) pixl; uint32 x = 0xff << rgbashift[ a ]; for ( int c = w * h; c > 0; c-- ) *dst++ |= x; } } } int texLoadRaw( IDAOStream & f, VSTexture * lTexture , int width, int height, int num_mipmaps , int bpp, int bytespp, const uint32 mask[] , bool flipV /*= false*/, bool flipH /*= false*/, bool rle /*= false*/ , KError & lError ) { lError.ClearLastError(); if ( bytespp * 8 != bpp || bpp > 32 || bpp < 8 ) { KFbxLog::LogError( "unsupported image depth %d / %d", bpp, bytespp ); return 0; } uint8 * data1 = new uint8[ width * height * 4 ]; uint8 * data2 = new uint8[ width * height * 4 ]; int w = width; int h = height; int m = 0; if ( m < num_mipmaps ) { w = width >> m; h = height >> m; if ( w == 0 ) w = 1; if ( h == 0 ) h = 1; if ( rle ) { if ( ! uncompressRLE( f, w, h, bytespp, data1 ) ) { //lError.SetLastError(1,"unexpected EOF" ); } } else if ( f.Read( (char *) data1, w * h * bytespp ) != w * h * bytespp ) { //lError.SetLastError(1,"unexpected EOF" ); } if ( -1 == lError.GetLastErrorID()) { convertToRGBA( data1, w, h, bytespp, mask, flipV, flipH, data2 ); lTexture->mH = h; lTexture->mW = w; lTexture->mImageData = data2; lTexture->internalformat = 4; lTexture->format = GL_RGBA; lTexture->type = GL_UNSIGNED_BYTE; data2 = NULL; ++m; } } delete [] data2 ; delete [] data1 ; return m; } int texLoadPal( IDAOStream & f, VSTexture * lTexture , int width, int height, int num_mipmaps, int bpp, int bytespp , const uint32 colormap[], bool flipV, bool flipH, bool rle , KError & lError ) { lError.ClearLastError(); if ( bpp != 8 || bytespp != 1 ) { KFbxLog::LogError( "unsupported image depth %d / %d", bpp, bytespp ); return 0; } uint8 * data = new uint8[ width * height * 1 ]; uint8 * pixl = new uint8[ width * height * 4 ]; int w = width; int h = height; int m = 0; while ( m < num_mipmaps ) { w = width >> m; h = height >> m; if ( w == 0 ) w = 1; if ( h == 0 ) h = 1; if ( rle ) { if ( ! uncompressRLE( f, w, h, bytespp, data ) ) { KFbxLog::LogError( "unsupported image depth %d / %d", bpp, bytespp ); } } else if ( f.Read( (char *) data, w * h * bytespp ) != w * h * bytespp ) { KFbxLog::LogError("unsupported image depth %d / %d", bpp, bytespp ); } if ( -1 == lError.GetLastErrorID()) { uint8 * src = data; for ( int y = 0; y < h; y++ ) { uint32 * dst = (uint32 *) ( pixl + 4 * ( w * ( flipV ? h - y - 1 : y ) + ( flipH ? w - 1 : 0 ) ) ); for ( int x = 0; x < w; x++ ) { *dst++ = colormap[*src++]; } } lTexture->mH = h; lTexture->mW = w; lTexture->mImageData = pixl; lTexture->internalformat = 4; lTexture->format = GL_RGBA; lTexture->type = GL_UNSIGNED_BYTE; pixl = NULL; ++m; } } delete [] pixl ; delete [] data ; return m; } // thanks nvidia for providing the source code to flip dxt images typedef struct { unsigned short col0, col1; unsigned char row[4]; } DXTColorBlock_t; typedef struct { unsigned short row[4]; } DXT3AlphaBlock_t; typedef struct { unsigned char alpha0, alpha1; unsigned char row[6]; } DXT5AlphaBlock_t; void SwapMem(void *byte1, void *byte2, int size) { unsigned char *tmp=(unsigned char *)malloc(sizeof(unsigned char)*size); memcpy(tmp, byte1, size); memcpy(byte1, byte2, size); memcpy(byte2, tmp, size); free(tmp); } inline void SwapChar( unsigned char * x, unsigned char * y ) { unsigned char z = *x; *x = *y; *y = z; } inline void SwapShort( unsigned short * x, unsigned short * y ) { unsigned short z = *x; *x = *y; *y = z; } void flipDXT1Blocks(DXTColorBlock_t *Block, int NumBlocks) { int i; DXTColorBlock_t *ColorBlock=Block; for(i=0;i<NumBlocks;i++) { SwapChar( &ColorBlock->row[0], &ColorBlock->row[3] ); SwapChar( &ColorBlock->row[1], &ColorBlock->row[2] ); ColorBlock++; } } void flipDXT3Blocks(DXTColorBlock_t *Block, int NumBlocks) { int i; DXTColorBlock_t *ColorBlock=Block; DXT3AlphaBlock_t *AlphaBlock; for(i=0;i<NumBlocks;i++) { AlphaBlock=(DXT3AlphaBlock_t *)ColorBlock; SwapShort( &AlphaBlock->row[0], &AlphaBlock->row[3] ); SwapShort( &AlphaBlock->row[1], &AlphaBlock->row[2] ); ColorBlock++; SwapChar( &ColorBlock->row[0], &ColorBlock->row[3] ); SwapChar( &ColorBlock->row[1], &ColorBlock->row[2] ); ColorBlock++; } } void flipDXT5Alpha(DXT5AlphaBlock_t *Block) { unsigned long *Bits, Bits0=0, Bits1=0; memcpy(&Bits0, &Block->row[0], sizeof(unsigned char)*3); memcpy(&Bits1, &Block->row[3], sizeof(unsigned char)*3); Bits=((unsigned long *)&(Block->row[0])); *Bits&=0xff000000; *Bits|=(unsigned char)(Bits1>>12)&0x00000007; *Bits|=(unsigned char)((Bits1>>15)&0x00000007)<<3; *Bits|=(unsigned char)((Bits1>>18)&0x00000007)<<6; *Bits|=(unsigned char)((Bits1>>21)&0x00000007)<<9; *Bits|=(unsigned char)(Bits1&0x00000007)<<12; *Bits|=(unsigned char)((Bits1>>3)&0x00000007)<<15; *Bits|=(unsigned char)((Bits1>>6)&0x00000007)<<18; *Bits|=(unsigned char)((Bits1>>9)&0x00000007)<<21; Bits=((unsigned long *)&(Block->row[3])); *Bits&=0xff000000; *Bits|=(unsigned char)(Bits0>>12)&0x00000007; *Bits|=(unsigned char)((Bits0>>15)&0x00000007)<<3; *Bits|=(unsigned char)((Bits0>>18)&0x00000007)<<6; *Bits|=(unsigned char)((Bits0>>21)&0x00000007)<<9; *Bits|=(unsigned char)(Bits0&0x00000007)<<12; *Bits|=(unsigned char)((Bits0>>3)&0x00000007)<<15; *Bits|=(unsigned char)((Bits0>>6)&0x00000007)<<18; *Bits|=(unsigned char)((Bits0>>9)&0x00000007)<<21; } void flipDXT5Blocks(DXTColorBlock_t *Block, int NumBlocks) { DXTColorBlock_t *ColorBlock=Block; DXT5AlphaBlock_t *AlphaBlock; int i; for(i=0;i<NumBlocks;i++) { AlphaBlock=(DXT5AlphaBlock_t *)ColorBlock; flipDXT5Alpha(AlphaBlock); ColorBlock++; SwapChar( &ColorBlock->row[0], &ColorBlock->row[3] ); SwapChar( &ColorBlock->row[1], &ColorBlock->row[2] ); ColorBlock++; } } void flipDXT( GLenum glFormat, int width, int height, unsigned char * image ) { int linesize, j; DXTColorBlock_t *top; DXTColorBlock_t *bottom; int xblocks=width/4; int yblocks=height/4; switch ( glFormat) { case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: linesize=xblocks*8; for(j=0;j<(yblocks>>1);j++) { top=(DXTColorBlock_t *)(image+j*linesize); bottom=(DXTColorBlock_t *)(image+(((yblocks-j)-1)*linesize)); flipDXT1Blocks(top, xblocks); flipDXT1Blocks(bottom, xblocks); SwapMem(bottom, top, linesize); } break; case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: linesize=xblocks*16; for(j=0;j<(yblocks>>1);j++) { top=(DXTColorBlock_t *)(image+j*linesize); bottom=(DXTColorBlock_t *)(image+(((yblocks-j)-1)*linesize)); flipDXT3Blocks(top, xblocks); flipDXT3Blocks(bottom, xblocks); SwapMem(bottom, top, linesize); } break; case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: linesize=xblocks*16; for(j=0;j<(yblocks>>1);j++) { top=(DXTColorBlock_t *)(image+j*linesize); bottom=(DXTColorBlock_t *)(image+(((yblocks-j)-1)*linesize)); flipDXT5Blocks(top, xblocks); flipDXT5Blocks(bottom, xblocks); SwapMem(bottom, top, linesize); } break; default: return; } } GLuint texLoadDXT( IDAOStream & f, VSTexture * lTexture , GLenum /*glFormat*/, int /*blockSize*/, uint32 /*width*/, uint32 /*height*/ , uint32 mipmaps, bool flipV , KError & lError ) { // load the pixels f.Seek(SEEK_SET, 0); int size = f.TellEnd() - f.Tell(); byte *bytes = new byte[ size ]; f.Read(bytes, sizeof(byte), size); GLuint m = 0; if ( m < mipmaps ) { // load face 0, mipmap m if ( Image * img = load_dds(bytes, size, 0, m) ) { // convert texture to OpenGL RGBA format unsigned int w = img->width(); unsigned int h = img->height(); GLubyte * pixels = new GLubyte[w * h * 4]; Color32 * src = img->pixels(); GLubyte * dst = pixels; //qWarning() << "flipV = " << flipV; for ( uint32 y = 0; y < h; y++ ) { for ( uint32 x = 0; x < w; x++ ) { *dst++ = src->r; *dst++ = src->g; *dst++ = src->b; *dst++ = src->a; src++; } } delete img; lTexture->mH = h; lTexture->mW = w; lTexture->mImageData = pixels; lTexture->internalformat = 4; lTexture->format = GL_RGBA; lTexture->type = GL_UNSIGNED_BYTE; pixels = NULL; ++m; } else { m = 0; } } delete [] bytes; return m; } //! Load a (possibly compressed) dds texture. GLuint texLoadDDS( IDAOStream & f, KString & texformat, VSTexture * lTexture, KError & lError ) { char tag[4]; f.Read(&tag[0], 4); DDSFormat ddsHeader; if ( strncmp( tag,"DDS ", 4 ) != 0 || f.Read((char *) &ddsHeader, sizeof(DDSFormat), 1) != 1 ) { KFbxLog::LogError( "not a DDS file" ); return 0; } texformat = "DDS"; if ( !( ddsHeader.dwFlags & DDSD_MIPMAPCOUNT ) ) ddsHeader.dwMipMapCount = 1; if ( ! ( isPowerOfTwo( ddsHeader.dwWidth ) && isPowerOfTwo( ddsHeader.dwHeight ) ) ) { KFbxLog::LogError("image dimensions must be power of two" ); return 0; } f.Seek(SEEK_SET, ddsHeader.dwSize + 4); if ( ddsHeader.ddsPixelFormat.dwFlags & DDPF_FOURCC ) { int blockSize = 8; GLenum glFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; switch( ddsHeader.ddsPixelFormat.dwFourCC ) { case FOURCC_DXT1: glFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; blockSize = 8; texformat += " (DXT1)"; break; case FOURCC_DXT3: glFormat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; blockSize = 16; texformat += " (DXT3)"; break; case FOURCC_DXT5: glFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; blockSize = 16; texformat += " (DXT5)"; break; default: KFbxLog::LogError( "unknown texture compression" ); return 0; } return texLoadDXT( f, lTexture , glFormat, blockSize, ddsHeader.dwWidth, ddsHeader.dwHeight, ddsHeader.dwMipMapCount, false , lError ); } else { texformat += " (RAW)"; if ( ddsHeader.ddsPixelFormat.dwRMask != 0 && ddsHeader.ddsPixelFormat.dwGMask == 0 && ddsHeader.ddsPixelFormat.dwBMask == 0 ) { // fixup greyscale ddsHeader.ddsPixelFormat.dwGMask = ddsHeader.ddsPixelFormat.dwRMask; ddsHeader.ddsPixelFormat.dwBMask = ddsHeader.ddsPixelFormat.dwRMask; } return texLoadRaw( f, lTexture , ddsHeader.dwWidth, ddsHeader.dwHeight , ddsHeader.dwMipMapCount, ddsHeader.ddsPixelFormat.dwBPP, ddsHeader.ddsPixelFormat.dwBPP / 8 , &ddsHeader.ddsPixelFormat.dwRMask , false, false, false , lError ); } } //************************************ // Method: LoadTexture // FullName: LoadTexture // Access: public // Returns: extern bool // Qualifier: // Parameter: const KString & lFileName // Parameter: VSTexture * lTexture // Parameter: KError & lError //************************************ extern bool LoadTexture( const KString & lFileName, VSTexture * lTexture, KError & lError ) { _tstring fname = ResourceManager::FindFile( _tstring(lFileName) ); _tstring lExt = fname.substr(fname.size()-4); if (_tcsicmp(lExt.c_str(), ".tga") == 0) { return loadTargaFile(lFileName, lTexture, lError); } else if (_tcsicmp(lExt.c_str(), ".dds") == 0) { DAOStreamPtr stream = ResourceManager::OpenStream( lFileName ); if (!stream.isNull() ) { KString format; return texLoadDDS( *stream, format, lTexture, lError ) > 0; } KFbxLog::LogWarn( "File could not found: %s", lFileName.Buffer() ); return false; } else { fname.erase( fname.size()-4 ); fname.append(".dds"); DAOStreamPtr stream = ResourceManager::OpenStream( fname.c_str() ); if (!stream.isNull() ) { KString format; return texLoadDDS( *stream, format, lTexture, lError ) > 0; } KFbxLog::LogWarn( "File could not found: %s", lFileName.Buffer() ); return false; } KFbxLog::LogError( "Unknown file extension" ); return false; }
[ "tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792" ]
[ [ [ 1, 852 ] ] ]
9f46535f28556dba4febb1230b432afe48c1c717
45229380094a0c2b603616e7505cbdc4d89dfaee
/wavelets/facedetector_src/src/cvLib/annetwork.h
73bef8e1ba0d33f844cf5c3180f32f1d211a80ad
[]
no_license
xcud/msrds
a71000cc096723272e5ada7229426dee5100406c
04764859c88f5c36a757dbffc105309a27cd9c4d
refs/heads/master
2021-01-10T01:19:35.834296
2011-11-04T09:26:01
2011-11-04T09:26:01
45,697,313
1
2
null
null
null
null
UTF-8
C++
false
false
2,270
h
#ifndef ANNetwork_h #define ANNetwork_h #include "vec2d.h" class AnnLayer; class vec2D; class ANNetwork { public: ANNetwork(const wchar_t* fname); ~ANNetwork(); inline int status() const; //get loading status inline int activation_function() const; //for last layer inline unsigned int dimension() const; //input vec dimension inline unsigned int output_size() const; void saveWs(bool file = false) const; //save W matrices void classify(const float* ivec, float* ovec) const; //run network private: int m_status; //0 OK; -1 file not found; 1 random weights float m_nrule; //learning rule 0.2 float m_alpha; //momentum 0.7 int m_actfun[2]; //activation function for input and output layers vector<unsigned int> m_neurons; //neurons per layer vector<AnnLayer *> m_layers; //layers vec2D* m_input_vec; //input[1,:] = (input[1,:]+add[1,:]) * mul[1,:] vec2D* m_add_vec; //normalization vectors vec2D* m_mul_vec; //normalization vectors void init_weights(unsigned int rseed) const; //randomize weights //unintended functions ANNetwork(const ANNetwork& ann); const ANNetwork& operator=(const ANNetwork& ann); }; inline int ANNetwork::status() const { return m_status; } inline int ANNetwork::activation_function() const { return m_actfun[1]; } inline unsigned int ANNetwork::dimension() const { if (m_neurons.size() > 0) return m_neurons[0]; else return 0; } inline unsigned int ANNetwork::output_size() const { if (m_neurons.size() > 0) return m_neurons[m_neurons.size()-1]; else return 0; } #endif /* file format 3 40 10 1 [defaults] 1 activation function 0-linear, 1-sigmoid [input norm] weights ... */
[ "perpet99@cc61708c-8d4c-0410-8fce-b5b73d66a671" ]
[ [ [ 1, 93 ] ] ]
2307ad988c6693555c05e8c2cb659e89d06d03b5
138a353006eb1376668037fcdfbafc05450aa413
/source/NewtonSDK/customJoints/CustomWormGear.h
cd9d17a21bf26ce5fb5f8068ea828a275f12883d
[]
no_license
sonicma7/choreopower
107ed0a5f2eb5fa9e47378702469b77554e44746
1480a8f9512531665695b46dcfdde3f689888053
refs/heads/master
2020-05-16T20:53:11.590126
2009-11-18T03:10:12
2009-11-18T03:10:12
32,246,184
0
0
null
null
null
null
UTF-8
C++
false
false
1,456
h
//******************************************************************** // Newton Game dynamics // copyright 2000-2004 // By Julio Jerez // VC: 6.0 // simple demo list vector class with iterators //******************************************************************** // CustomWormGear.h: interface for the CustomWormGear class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_CustomWormGear_H__B631F556_B7D7_F85ECF3E9ADE__INCLUDED_) #define AFX_CustomWormGear_H__B631F556_B7D7_F85ECF3E9ADE__INCLUDED_ #include "NewtonCustomJoint.h" // this joint is for used in conjustion with Hinge of other spherical joints // is is usefull for stablishing synchronization between the phase angle otr the // relaltive angular velocity of two spining disk according to the law of gears // velErro = -(W0 * r0 + W1 * r1) // where w0 and W1 are teh angular velocity // r0 and r1 are teh radius of teh spinning disk class CustomWormGear: public NewtonCustomJoint { public: CustomWormGear(dFloat gearRatio, const dVector& rotationalPin, const dVector& linearPin, NewtonBody* rotationalBody, NewtonBody* linearBody); virtual ~CustomWormGear(); protected: virtual void SubmitConstrainst (); dMatrix m_localMatrix0; dMatrix m_localMatrix1; dFloat m_gearRatio; }; #endif // !defined(AFX_CustomWormGear_H__B631F556_468B_4331_B7D7_F85ECF3E9ADE__INCLUDED_)
[ "Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e" ]
[ [ [ 1, 43 ] ] ]
a5d0a569e8fefef832b8ac563a3d54c348125f97
658129adb8f10b4cccdb2e432430d67c0977d37e
/cpp/cs311/profs_examples/fibo6.cpp
f349664db62b259aa91df3d51d861fc9d5f70b6c
[]
no_license
amiel/random-useless-scripts
e2d473940bdb968ad0f8d31514654b79a760edd4
166195329bc93c780d7c8fd088d93e3a697062a0
refs/heads/master
2020-12-24T13:21:37.358940
2009-03-29T06:08:26
2009-03-29T06:14:02
140,835
1
1
null
null
null
null
UTF-8
C++
false
false
5,890
cpp
// fibo6.cpp // Glenn G. Chappell // 10 Nov 2006 // // For CS 311 // Computing Fibonacci Numbers // Version #6: Recursion Eliminated // // This program is based on fibo1.cpp. // Recursion has been eliminated using // the technique described in class. #include <iostream> using std::cout; using std::endl; #include <stack> // for std::stack /* Original function fibo, from fibo1.cpp: int fibo(int n) { // Base case if (n <= 1) return n; // Recursive case return fibo(n-2) + fibo(n-1); } Modified version used as the basis of this code: int fibo(int n) { int v1, v2; // Base case if (n <= 1) return n; // Recursive call #1 v1 = fibo(n-2); // Recursive call #2 v2 = fibo(n-1); // Return the result return v1 + v2; } */ // struct FiboStackFrame // "Stack frame" - holds local vars for function fibo. // In a structure so that they can be saved on a stack. struct FiboStackFrame { int n; // parameter int v1; // result of recursive call #1 int v2; // result of recursive call #2 int returnValue; // value to return int returnAddr; // return address: // 0: outside world (return from function) // 1: recursive call #1 (return to label1) // 2: recursive call #2 (return to label2) }; // fibo // Given n, returns F(n) (the nth Fibonacci number). // F(0) = 0. F(1) = 1. For n >= 2, F(n) = F(n-2) + F(n-1). // Pre: // n >= 0. // F(n) is a valid int value. // Note: For 32-bit signed int's, preconditions hold for 0 <= n <= 46. // Post: // Return value is F(n). // No-Throw Guarantee int fibo(int n) { // ************************************* // LOCAL VARIABLES // ************************************* int tmp; // Temp value - holds an int during stack op's std::stack<FiboStackFrame> s; // Stack, used to eliminate recursion // Top of stack holds current local variables // and place for return value // ************************************* // Set up stack frame. // // ORIGINAL CODE: // int fibo(int n) // { // int v1, v2; // ************************************* s.push(FiboStackFrame()); // make new stack frame s.top().n = n; // set parameter s.top().returnAddr = 0; // set return address (called by outside world) // ************************************* // BEGIN LOOP // while (true) loop used for recursion // elimination. // ************************************* while (true) { // ************************************* // ORIGINAL CODE: // // Base case // if (n <= 1) // return n; // ************************************* if (s.top().n <= 1) { // Do "return n;" s.top().returnValue = s.top().n; if (s.top().returnAddr == 0) // called by outside world { tmp = s.top().returnValue; s.pop(); return tmp; } if (s.top().returnAddr == 1) // called by recursive call #1 { goto label1; } if (s.top().returnAddr == 2) // called by recursive call #2 { goto label2; } } // ************************************* // ORIGINAL CODE: // // Recursive call #1 // v1 = fibo(n-2); // ************************************* tmp = s.top().n - 2; s.push(FiboStackFrame()); // make new stack frame s.top().n = tmp; // set parameter s.top().returnAddr = 1; // set return address (recursive call #1) continue; // Do "recursive call" label1: // Place to return to tmp = s.top().returnValue; s.pop(); s.top().v1 = tmp; // put returned value in v1 // ************************************* // ORIGINAL CODE: // // Recursive call #2 // v2 = fibo(n-1); // ************************************* tmp = s.top().n - 1; s.push(FiboStackFrame()); // make new stack frame s.top().n = tmp; // set parameter s.top().returnAddr = 2; // set return address (recursive call #2) continue; // Do "recursive call" label2: // Place to return to tmp = s.top().returnValue; s.pop(); s.top().v2 = tmp; // put returned value in v2 // ************************************* // ORIGINAL CODE: // // Return the result // return v1 + v2; // ************************************* s.top().returnValue = s.top().v1 + s.top().v2; if (s.top().returnAddr == 0) // called by outside world { tmp = s.top().returnValue; s.pop(); return tmp; } if (s.top().returnAddr == 1) // called by recursive call #1 { goto label1; } if (s.top().returnAddr == 2) // called by recursive call #2 { goto label2; } // ************************************* // END LOOP // while (true) loop used for recursion // elimination. // ************************************* } } // main // From fibo1.cpp int main() { cout << "Fibonacci Numbers" << endl; cout << endl; for (int i = 0; i < 50; ++i) { cout << i << ": " << fibo(i) << endl; } }
[ [ [ 1, 207 ] ] ]
f608cccc549382128fa10ab1b4d9121a6577f38c
74d531abb9fda8dc621c5d8376eb10ec4ef19568
/src/main.cpp
d3b14c58d59d97f0930bee4e87576f6393bf22d1
[]
no_license
aljosaosep/xsoko
e207d6ec8de3196029e569e7765424a399a50f04
c52440ecee65dc2f3f38d996936e65b3ff3b8b5e
refs/heads/master
2021-01-10T14:27:04.644013
2009-09-02T20:39:53
2009-09-02T20:39:53
49,592,571
0
0
null
null
null
null
UTF-8
C++
false
false
1,987
cpp
/* * codename: xSoko * Copyright (C) Aljosa Osep, Jernej Skrabec, Jernej Halozan 2008 <[email protected], [email protected], [email protected]> * * xSoko project 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. * * xSoko project 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/>. */ /* * Codename: xSoko * File: main.cpp * * Summary: * Game entry point * * Author: Aljosa Osep 2007 * Changes: * Aljosa May 28 2008 * Jernej October 5 2008 */ #ifdef _WINDOWS #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif #include <cstdlib> #include "level.h" #include "game.h" #include "messages.h" #include "input.h" #include "renderer/renderer.h" using namespace PacGame::GameClasses; using namespace PacGame::RenderMaschine; #ifdef _WINDOWS int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) #else int main(int argc, char *argv[]) #endif { // game and window creation PGame pacgame(800, 600, "xSoko project"); // game initialization if(!pacgame.initGame()) { PacGame::Messages::initMessage("game", false); return -1; } //PGuiSession* guiSession = new PGuiSession(800,600); PGameSession* gameSession = new PGameSession(); // loads session pacgame.loadSession(gameSession); // run game pacgame.run(); delete gameSession; return 0; }
[ "aljosa.osep@d77d96cf-bc4d-0410-95e8-7f58e8f99bdb", "jernej.skrabec@d77d96cf-bc4d-0410-95e8-7f58e8f99bdb", "jernej.halozan@d77d96cf-bc4d-0410-95e8-7f58e8f99bdb" ]
[ [ [ 1, 28 ], [ 30, 30 ], [ 37, 37 ], [ 39, 41 ], [ 43, 43 ], [ 45, 45 ], [ 53, 62 ], [ 65, 65 ], [ 67, 69 ] ], [ [ 29, 29 ], [ 31, 34 ], [ 47, 49 ], [ 51, 51 ], [ 63, 64 ], [ 66, 66 ], [ 70, 71 ] ], [ [ 35, 36 ], [ 38, 38 ], [ 42, 42 ], [ 44, 44 ], [ 46, 46 ], [ 50, 50 ], [ 52, 52 ], [ 72, 73 ] ] ]
8b414df4ae0d5358c9c8e1285284742342da9812
15732b8e4190ae526dcf99e9ffcee5171ed9bd7e
/GeneratedFiles/Release/moc_tab.cpp
cd08ce5693356f729710c7a317706ce050546587
[]
no_license
clovermwliu/whutnetsim
d95c07f77330af8cefe50a04b19a2d5cca23e0ae
924f2625898c4f00147e473a05704f7b91dac0c4
refs/heads/master
2021-01-10T13:10:00.678815
2010-04-14T08:38:01
2010-04-14T08:38:01
48,568,805
0
0
null
null
null
null
UTF-8
C++
false
false
3,771
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'tab.h' ** ** Created: Wed Feb 3 11:15:16 2010 ** by: The Qt Meta Object Compiler version 59 (Qt 4.3.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../INC/tab.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'tab.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 59 #error "This file was generated using the moc from 4.3.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif static const uint qt_meta_data_TabItem[] = { // content: 1, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0 // eod }; static const char qt_meta_stringdata_TabItem[] = { "TabItem\0" }; const QMetaObject TabItem::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_TabItem, qt_meta_data_TabItem, 0 } }; const QMetaObject *TabItem::metaObject() const { return &staticMetaObject; } void *TabItem::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_TabItem)) return static_cast<void*>(const_cast< TabItem*>(this)); return QWidget::qt_metacast(_clname); } int TabItem::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } static const uint qt_meta_data_FirstTab[] = { // content: 1, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0 // eod }; static const char qt_meta_stringdata_FirstTab[] = { "FirstTab\0" }; const QMetaObject FirstTab::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_FirstTab, qt_meta_data_FirstTab, 0 } }; const QMetaObject *FirstTab::metaObject() const { return &staticMetaObject; } void *FirstTab::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_FirstTab)) return static_cast<void*>(const_cast< FirstTab*>(this)); return QWidget::qt_metacast(_clname); } int FirstTab::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } static const uint qt_meta_data_SecondTab[] = { // content: 1, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0 // eod }; static const char qt_meta_stringdata_SecondTab[] = { "SecondTab\0" }; const QMetaObject SecondTab::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_SecondTab, qt_meta_data_SecondTab, 0 } }; const QMetaObject *SecondTab::metaObject() const { return &staticMetaObject; } void *SecondTab::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_SecondTab)) return static_cast<void*>(const_cast< SecondTab*>(this)); return QWidget::qt_metacast(_clname); } int SecondTab::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; }
[ "pengelmer@f37e807c-cba8-11de-937e-2741d7931076" ]
[ [ [ 1, 144 ] ] ]
71bfed01afd863d6f41755b9e46bf976950de1ca
fa609a5b5a0e7de3344988a135b923a0f655f59e
/Source/tokens/Break.h
54002fca44dd05c7c5df51f13d892d703aa7782f
[ "MIT" ]
permissive
Sija/swift
3edfd70e1c8d9d54556862307c02d1de7d400a7e
dddedc0612c0d434ebc2322fc5ebded10505792e
refs/heads/master
2016-09-06T09:59:35.416041
2007-08-30T02:29:30
2007-08-30T02:29:30
null
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
1,047
h
/** * Swift Parser Library * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2007 Sijawusz Pur Rahnama * @copyright Copyright (c) 2007 Paweł Złomaniec * @version $Revision: 90 $ * @modifiedby $LastChangedBy: ursus6 $ * @lastmodified $Date: 2007-08-06 11:41:22 +0200 (Pn, 06 sie 2007) $ */ #pragma once #ifndef __SWIFT_BREAK_TOKEN_H__ #define __SWIFT_BREAK_TOKEN_H__ #include "../iSection.h" namespace Swift { namespace Tokens { class BreakException : public SwiftException { public: BreakException() : SwiftException("Invalid use of break") { } }; class Break: public iSection { public: static iSection* __stdcall getInstance(class iBlock* parent) { return new Break; } public: inline String output() { throw BreakException(); } }; SWIFT_REGISTER_TOKEN(Break, "break"); }} #endif // __SWIFT_BREAK_TOKEN_H__
[ [ [ 1, 43 ] ] ]
fa52943b8a480695af95aefa3197f3172db55a70
12ea67a9bd20cbeed3ed839e036187e3d5437504
/winxgui/GuiLib/GuiLib/GuiMDIFrame.cpp
324f3d58a3b5b63dc9a00cda51c5d595e10dfcb9
[]
no_license
cnsuhao/winxgui
e0025edec44b9c93e13a6c2884692da3773f9103
348bb48994f56bf55e96e040d561ec25642d0e46
refs/heads/master
2021-05-28T21:33:54.407837
2008-09-13T19:43:38
2008-09-13T19:43:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,320
cpp
/**************************************************************************** * * * GuiToolKit * * (MFC extension) * * Created by Francisco Campos G. www.beyondata.com [email protected] * *--------------------------------------------------------------------------* * * * This program is free software;so you are free to use it any of your * * applications (Freeware, Shareware, Commercial),but leave this header * * intact. * * * * These files are provided "as is" without warranty of any kind. * * * * GuiToolKit is forever FREE CODE !!!!! * * * *--------------------------------------------------------------------------* * Created by: Francisco Campos G. * * Bug Fixes and improvements : (Add your name) * * -Francisco Campos * * -Serge Koroleuve * * * ****************************************************************************/ #include "stdafx.h" #include "GuiMDIFrame.h" #include "GuiMiniFrame.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CGuiMDIFrame IMPLEMENT_DYNCREATE(CGuiMDIFrame, CMDIFrameWnd) CGuiMDIFrame::CGuiMDIFrame() { sProfile = AfxGetAppName(); sProfile.Replace(_T(' '), _T('_')); m_StyleDisplay=GUISTYLE_XP; m_InitClass=TRUE; } CGuiMDIFrame::~CGuiMDIFrame() { } BEGIN_MESSAGE_MAP(CGuiMDIFrame, CMDIFrameWnd) //{{AFX_MSG_MAP(CGuiMDIFrame) // NOTE - the ClassWizard will add and remove mapping macros here. ON_COMMAND(ID_FILE_PRINT_PREVIEW, OnFilePrintPreview) ON_WM_SYSCOLORCHANGE() //}}AFX_MSG_MAP END_MESSAGE_MAP() //************************************************************************** void CGuiMDIFrame::OnSysColorChange( ) { CMDIFrameWnd::OnSysColorChange( ); GuiDrawLayer::IsThemeXP(); } BOOL CGuiMDIFrame::PreTranslateMessage(MSG* pMsg) { if (m_wndMenuBar.TranslateFrameMessage(pMsg)) return TRUE; return CMDIFrameWnd::PreTranslateMessage(pMsg); } void CGuiMDIFrame::OnFilePrintPreview() { // TODO: Add your command handler code here } BOOL CGuiMDIFrame::PreCreateWindow(CREATESTRUCT& cs) { // Restore main window position CWinApp* pApp = AfxGetApp(); TCHAR szSection[256]; wsprintf(szSection, "%sMain", sProfile); // Restore main window position CWinApp* app = AfxGetApp(); int s, t, b, r, l; l =(int) pApp->GetProfileInt(szSection, _T("left"),10); t =(int) pApp->GetProfileInt(szSection, _T("top"),10); b =(int) pApp->GetProfileInt(szSection, _T("bottom"),400); r = (int)pApp->GetProfileInt(szSection, _T("right"),600); s = (int)pApp->GetProfileInt(szSection, _T("status"), SW_NORMAL); GuiDrawLayer::m_Style=(int)pApp->GetProfileInt(szSection, _T("Style"),GUISTYLE_XP); m_StyleDisplay=GuiDrawLayer::m_Style; // only restore if there is a previously saved position // restore the window's status app->m_nCmdShow = s; // restore the window's width and height cs.cx = r - l; cs.cy = b - t; // the following correction is needed when the taskbar is // at the left or top and it is not "auto-hidden" RECT workArea; SystemParametersInfo(SPI_GETWORKAREA, 0, &workArea, 0); l += workArea.left; t += workArea.top; // make sure the window is not completely out of sight int max_x = GetSystemMetrics(SM_CXSCREEN) - GetSystemMetrics(SM_CXICON); int max_y = GetSystemMetrics(SM_CYSCREEN) - GetSystemMetrics(SM_CYICON); cs.x = min(l, max_x); cs.y = min(t, max_y); return CMDIFrameWnd::PreCreateWindow(cs); } void CGuiMDIFrame::StyleDispl(DWORD dwDsp) { m_StyleDisplay=dwDsp; GuiDrawLayer::IsThemeXP(); GuiDrawLayer::m_Style=m_StyleDisplay; m_wndCool.StyleDispl(m_StyleDisplay); if(::IsWindow(m_MdiTabbed.GetSafeHwnd())) m_MdiTabbed.StyleDispl(m_StyleDisplay); m_wndStatusBar.StyleDispl(m_StyleDisplay); m_wndMenuBar.StyleDispl(m_StyleDisplay); m_wndToolBar.StyleDispl(m_StyleDisplay); m_dockTop->StyleDispl(m_StyleDisplay); m_dockLeft->StyleDispl(m_StyleDisplay); m_dockRight->StyleDispl(m_StyleDisplay); m_dockBottom->StyleDispl(m_StyleDisplay); m_NewMenu.StyleDispl(m_StyleDisplay); SendMessage(WM_NCPAINT); Invalidate(); UpdateWindow(); } BOOL CGuiMDIFrame::InitMDITabbed() { if(::IsWindow(m_MdiTabbed.GetSafeHwnd())) return TRUE; if (!m_MdiTabbed.Create(WS_VISIBLE|WS_CHILD,CRect(0,0,0,0),this,0x333)) return FALSE; if (::IsWindow(m_wndMenuBar.GetSafeHwnd())) m_wndMenuBar.SetTabbed(TRUE); return TRUE; } //************************************************************************* BOOL CGuiMDIFrame::PreCreateWindow(CREATESTRUCT& cs, UINT nIconID) { cs.lpszClass = AfxRegisterWndClass( 0, NULL, NULL, AfxGetApp()->LoadIcon(nIconID)); ASSERT(cs.lpszClass); return CMDIFrameWnd::PreCreateWindow(cs); } //************************************************************************* void CGuiMDIFrame::ShowHideBar(CGuiControlBar* pBar) { if (pBar->IsWindowVisible()) ShowControlBar(pBar, FALSE, FALSE); else ShowControlBar(pBar, TRUE, FALSE); } void CGuiMDIFrame::ShowHideBar(CControlBar* pBar) { if (pBar->IsWindowVisible()) ShowControlBar(pBar, FALSE, FALSE); else ShowControlBar(pBar, TRUE, FALSE); } //************************************************************************* void CGuiMDIFrame::EnableDocking(DWORD dwDockStyle) { ASSERT((dwDockStyle & ~ (CBRS_ALIGN_ANY | CBRS_FLOAT_MULTI)) == 0); m_pFloatingFrameClass = RUNTIME_CLASS(CMiniDockFrameWnd); CGuiDocBarExten* pDock; DWORD dwStyle = WS_CHILD| WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; DWORD dwstyle; DockSpecialBars(); pDock = new CGuiDocBarExten(); pDock->Create(this,dwStyle|CBRS_TOP, AFX_IDW_DOCKBAR_TOP); dwstyle = pDock->GetBarStyle(); dwstyle &= ~CBRS_BORDER_ANY; pDock->SetBarStyle(dwstyle); pDock = new CGuiDocBarExten(); pDock->Create(this, dwStyle|CBRS_BOTTOM, AFX_IDW_DOCKBAR_BOTTOM); dwstyle = pDock->GetBarStyle(); dwstyle &= ~CBRS_BORDER_ANY; pDock->SetBarStyle(dwstyle); pDock = new CGuiDocBarExten(); pDock->Create(this,dwStyle|CBRS_LEFT, AFX_IDW_DOCKBAR_LEFT); dwstyle = pDock->GetBarStyle(); dwstyle &= ~CBRS_BORDER_ANY; pDock->SetBarStyle(dwstyle); pDock = new CGuiDocBarExten(); pDock->Create(this,dwStyle|CBRS_RIGHT, AFX_IDW_DOCKBAR_RIGHT); dwstyle = pDock->GetBarStyle(); dwstyle &= ~CBRS_BORDER_ANY; pDock->SetBarStyle(dwstyle); m_pFloatingFrameClass = RUNTIME_CLASS(CGuiMiniFrame); } DWORD CGuiMDIFrame::CanDock(CRect rect, DWORD dwDockStyle, CDockBar** ppDockBar) { // dwDockStyle -- allowable styles of bar // don't allow to dock to floating unless multi is specified dwDockStyle &= CBRS_ALIGN_ANY|CBRS_FLOAT_MULTI; if (ppDockBar != NULL) *ppDockBar = NULL; POSITION pos = m_listControlBars.GetHeadPosition(); while (pos != NULL) { CDockBar* pDockBar = (CDockBar*)m_listControlBars.GetNext(pos); if (pDockBar->IsDockBar() && pDockBar->IsWindowVisible() && (pDockBar->m_dwStyle & dwDockStyle & CBRS_ALIGN_ANY) && (!pDockBar->m_bFloating || (dwDockStyle & pDockBar->m_dwStyle & CBRS_FLOAT_MULTI))) { CRect rectBar; pDockBar->GetWindowRect(&rectBar); if (rectBar.Width() == 0) rectBar.right++; if (rectBar.Height() == 0) rectBar.bottom++; if (rectBar.IntersectRect(rectBar, rect)) { if (ppDockBar != NULL) *ppDockBar = pDockBar; return pDockBar->m_dwStyle & dwDockStyle; } } } return 0; } void CGuiMDIFrame::DockSpecialBars() { DWORD dwStyle = WS_CHILD| WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; m_dockTop=new CGuiDocBarExtenEx(); m_dockTop->Create(this,dwStyle|CBRS_TOP,CBRS_ALIGN_TOP); DWORD dwstyle; dwstyle = m_dockTop->GetBarStyle(); dwstyle &= ~CBRS_BORDER_ANY; m_dockTop->SetBarStyle(dwstyle); m_dockBottom=new CGuiDocBarExtenEx(); m_dockBottom->Create(this,dwStyle|CBRS_BOTTOM,CBRS_ALIGN_BOTTOM); dwstyle = m_dockBottom->GetBarStyle(); dwstyle &= ~CBRS_BORDER_ANY; m_dockBottom->SetBarStyle(dwstyle); m_dockLeft=new CGuiDocBarExtenEx(); m_dockLeft->Create(this,dwStyle|CBRS_LEFT,CBRS_ALIGN_LEFT); dwstyle = m_dockLeft->GetBarStyle(); dwstyle &= ~CBRS_BORDER_ANY; m_dockLeft->SetBarStyle(dwstyle); m_dockRight=new CGuiDocBarExtenEx(); m_dockRight->Create(this,dwStyle|CBRS_RIGHT,CBRS_ALIGN_RIGHT); dwstyle = m_dockRight->GetBarStyle(); dwstyle &= ~CBRS_BORDER_ANY; m_dockRight->SetBarStyle(dwstyle); m_dockHideTop.Create(this,CBRS_ALIGN_TOP); m_dockHideBottom.Create(this,CBRS_ALIGN_BOTTOM); m_dockHideLeft.Create(this,CBRS_ALIGN_LEFT); m_dockHideRight.Create(this,CBRS_ALIGN_RIGHT); m_dockToolbarTop.Create(this,CBRS_ALIGN_TOP); m_dockToolbarBottom.Create(this,CBRS_ALIGN_BOTTOM); m_dockToolbarLeft.Create(this,CBRS_ALIGN_LEFT); m_dockToolbarRight.Create(this,CBRS_ALIGN_RIGHT); } ///////////////////////////////////////////////////////////////////////////// // CGuiMDIFrame message handlers //*********************************************************************** BOOL CGuiMDIFrame::DestroyWindow() { CWinApp* pApp = AfxGetApp(); sProfile = AfxGetAppName(); TCHAR szSection[256]; wsprintf(szSection, "%sMain", sProfile); WINDOWPLACEMENT wp; GetWindowPlacement(&wp); pApp->WriteProfileString(szSection, NULL, NULL); pApp->WriteProfileInt(szSection, _T("left"),(int) wp.rcNormalPosition.left); pApp->WriteProfileInt(szSection, _T("right"),(int) wp.rcNormalPosition.right); pApp->WriteProfileInt(szSection, _T("bottom"), (int)wp.rcNormalPosition.bottom); pApp->WriteProfileInt(szSection, _T("top"), (int)wp.rcNormalPosition.top); pApp->WriteProfileInt(szSection, _T("status"),(int) wp.showCmd); pApp->WriteProfileInt(szSection, _T("Style"),(int) GuiDrawLayer::m_Style); pApp->WriteProfileInt(szSection, _T("Theme"),(int) GuiDrawLayer::m_Theme); SaveBarState(sProfile); SavePosBar(sProfile); return CFrameWnd::DestroyWindow(); } void CGuiMDIFrame::SavePosBar(CString szBars) { POSITION pos = m_listControlBars.GetHeadPosition(); while (pos != NULL) { CGuiControlBar* pBar = (CGuiControlBar*) m_listControlBars.GetNext(pos); ASSERT(pBar != NULL); if (pBar->IsKindOf(RUNTIME_CLASS(CGuiControlBar))) pBar->SaveBar(szBars); } } void CGuiMDIFrame::LoadPosBar(CString szBars) { POSITION pos = m_listControlBars.GetHeadPosition(); while (pos != NULL) { CGuiControlBar* pBar = (CGuiControlBar*) m_listControlBars.GetNext(pos); ASSERT(pBar != NULL); if (pBar->IsKindOf(RUNTIME_CLASS(CGuiControlBar))) pBar->LoadStateBar(szBars); } } //*********************************************************************** BOOL CGuiMDIFrame::VerifyBarState(LPCTSTR lpszProfileName) { CDockState state; state.LoadState(lpszProfileName); for (int i = 0; i < state.m_arrBarInfo.GetSize(); i++) { CControlBarInfo* pInfo = (CControlBarInfo*)state.m_arrBarInfo[i]; ASSERT(pInfo != NULL); int nDockedCount = pInfo->m_arrBarID.GetSize(); if (nDockedCount > 0) { // dockbar for (int j = 0; j < nDockedCount; j++) { UINT nID = (UINT) pInfo->m_arrBarID[j]; if (nID == 0) continue; // row separator if (nID > 0xFFFF) nID &= 0xFFFF; // placeholder - get the ID if (GetControlBar(nID) == NULL) return FALSE; } } if (!pInfo->m_bFloating) // floating dockbars can be created later if (GetControlBar(pInfo->m_nBarID) == NULL) return FALSE; // invalid bar ID } return TRUE; } void CGuiMDIFrame::LoadBars() { if (VerifyBarState(sProfile)) { LoadBarState(sProfile); LoadPosBar(sProfile); } } void CGuiMDIFrame::OnUpdateFrameTitle(BOOL bAddToTitle) { // TODO: Add your specialized code here and/or call the base class CMDIFrameWnd::OnUpdateFrameTitle(bAddToTitle); if(::IsWindow(m_MdiTabbed.GetSafeHwnd())) m_MdiTabbed.UpdateWindows(); } int CGuiMDIFrame::InitMenu(UINT uIDMenu) { if (!m_wndMenuBar.CreateEx(this, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_SIZE_DYNAMIC ) || !m_wndMenuBar.LoadMenuBar(uIDMenu)) { TRACE0("Failed to create menubar\n"); return -1; // fail to create } m_NewMenu.LoadMenu(uIDMenu); m_wndCool.Install(this); m_wndCool.LoadToolbar(uIDMenu); return 0; } //int CGuiMDIFrame::InitMenu(UINT uIDMenu) int CGuiMDIFrame::InitStatusBar(UINT *indicators,int nSize) { if (!m_wndStatusBar.Create(this) || !m_wndStatusBar.SetIndicators(indicators, nSize)) { TRACE0("Failed to create status bar\n"); return -1; // fail to create } return 0; } int CGuiMDIFrame::InitToolBar(UINT uIDMenu) { if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC,CRect(0,0,0,0),uIDMenu) || !m_wndToolBar.LoadToolBar(uIDMenu)) { TRACE0("Failed to create toolbar\n"); return -1; // fail to create } // new code: Serge Koroleuve IMAGEINFO ii; m_wndToolBar.GetToolBarCtrl().GetImageList()->GetImageInfo(0, &ii); int cx = ii.rcImage.right - ii.rcImage.left; int cy = ii.rcImage.bottom - ii.rcImage.top; int nCount = m_wndToolBar.GetToolBarCtrl().GetImageList()->GetImageCount(); CImageList imageList; CBitmap bitmap; bitmap.LoadBitmap(uIDMenu); imageList.Create(cx, cy, ILC_COLORDDB|ILC_MASK, nCount, 0); imageList.Add(&bitmap, RGB(192,192,192)); m_wndToolBar.SendMessage(TB_SETIMAGELIST, 0, (LPARAM)imageList.m_hImageList); imageList.Detach(); bitmap.Detach(); // end of new code return 0; }
[ "xushiweizh@86f14454-5125-0410-a45d-e989635d7e98" ]
[ [ [ 1, 479 ] ] ]
46128b16e21fff25be1fea12cf5edf5e59bc2652
1a5b43c98479a5c44c6da4b01fa35af95c6d7bcd
/CFGGen/ForLoopFlowPoint.h
b818d1df0cb1c7c677382160d399d27b834f96bc
[]
no_license
eknowledger/mcfromc
827641a5f670d18ee2a7e1d8d76b783d37d33004
41b6ba1065b27a8468d3b70c3698cbcef0dc698b
refs/heads/master
2016-09-05T12:11:29.137266
2010-08-08T05:11:43
2010-08-08T05:11:43
34,752,799
0
0
null
null
null
null
UTF-8
C++
false
false
457
h
#pragma once #include "flowpoint.h" class ForLoopFlowPoint : public FlowPoint { public: ForLoopFlowPoint(SNode* node, std::string name, FlowPoint* incrementExpr); virtual ~ForLoopFlowPoint(void); FlowPoint* getIncrementExpression() { return m_incrementExpr; } virtual FlowPointType Type() { return FOR_LOOP_FLOW_POINT; } private: //the increment expression of the for loop declaration FlowPoint* m_incrementExpr; };
[ "man701@46565ccc-2a3b-0f42-2bc5-e45c9856c86c" ]
[ [ [ 1, 23 ] ] ]
cfc00fb57c6cb914dfbed988d9d3af277da140a0
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SEFoundation/SESharedArrays/SESharedArray.inl
c98f86295c2b63672f7db976b63feb8e5470afd3
[]
no_license
pizibing/swingengine
d8d9208c00ec2944817e1aab51287a3c38103bea
e7109d7b3e28c4421c173712eaf872771550669e
refs/heads/master
2021-01-16T18:29:10.689858
2011-06-23T04:27:46
2011-06-23T04:27:46
33,969,301
0
0
null
null
null
null
UTF-8
C++
false
false
7,095
inl
// Swing Engine Version 1 Source Code // Most of techniques in the engine are mainly based on David Eberly's // Wild Magic 4 open-source code.The author of Swing Engine learned a lot // from Eberly's experience of architecture and algorithm. // Several sub-systems are totally new,and others are re-implimented or // re-organized based on Wild Magic 4's sub-systems. // Copyright (c) 2007-2010. All Rights Reserved // // Eberly's permission: // Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2.1 of the License, or (at // your option) any later version. The license is available for reading at // the location: // http://www.gnu.org/copyleft/lgpl.html //---------------------------------------------------------------------------- template <class T> SESharedArray<T>::SESharedArray(int iCount, T* pArray) { m_iCount = iCount; m_pArray = pArray; } //---------------------------------------------------------------------------- template <class T> SESharedArray<T>::SESharedArray(const SESharedArray& rShared) { m_pArray = 0; *this = rShared; } //---------------------------------------------------------------------------- template <class T> SESharedArray<T>::~SESharedArray() { SE_DELETE[] m_pArray; } //---------------------------------------------------------------------------- template <class T> SESharedArray<T>& SESharedArray<T>::operator=(const SESharedArray& rShared) { SE_DELETE[] m_pArray; m_iCount = rShared.m_iCount; if( rShared.m_pArray ) { m_pArray = SE_NEW T[m_iCount]; for( int i = 0; i < m_iCount; i++ ) { m_pArray[i] = rShared.m_pArray[i]; } } else { m_pArray = 0; } return *this; } //---------------------------------------------------------------------------- template <class T> int SESharedArray<T>::GetCount() const { return m_iCount; } //---------------------------------------------------------------------------- template <class T> T* SESharedArray<T>::GetData() const { return m_pArray; } //---------------------------------------------------------------------------- template <class T> SESharedArray<T>::operator const T*() const { return m_pArray; } //---------------------------------------------------------------------------- template <class T> SESharedArray<T>::operator T*() { return m_pArray; } //---------------------------------------------------------------------------- template <class T> const T& SESharedArray<T>::operator[](int i) const { SE_ASSERT( 0 <= i && i < m_iCount ); return m_pArray[i]; } //---------------------------------------------------------------------------- template <class T> T& SESharedArray<T>::operator[](int i) { SE_ASSERT( 0 <= i && i < m_iCount ); return m_pArray[i]; } //---------------------------------------------------------------------------- template <class T> void SESharedArray<T>::SetActiveCount(int iActiveCount) { SE_ASSERT( iActiveCount >= 0 ); m_iCount = iActiveCount; } //---------------------------------------------------------------------------- template <class T> SEObject* SESharedArray<T>::Factory(SEStream& rStream) { SESharedArray<T>* pObject = SE_NEW SESharedArray<T>; SEStream::SELink* pLink = SE_NEW SEStream::SELink(pObject); pObject->Load(rStream, pLink); return pObject; } //---------------------------------------------------------------------------- template <class T> void SESharedArray<T>::InitializeFactory() { if( !ms_pFactory ) { ms_pFactory = SE_NEW SEStringHashTable<FactoryFunction>(FACTORY_MAP_SIZE); } ms_pFactory->Insert(TYPE.GetName(), (FactoryFunction)SESharedArray<T>::Factory); } //---------------------------------------------------------------------------- template <class T> bool SESharedArray<T>::RegisterFactory() { if( !ms_bStreamRegistered ) { SEMain::AddInitializer(SESharedArray<T>::InitializeFactory); ms_bStreamRegistered = true; } return ms_bStreamRegistered; } //---------------------------------------------------------------------------- template <class T> SEObject* SESharedArray<T>::GetObjectByName(const std::string& rName) { return SEObject::GetObjectByName(rName); } //---------------------------------------------------------------------------- template <class T> void SESharedArray<T>::GetAllObjectsByName(const std::string& rName, std::vector<SEObject*>& rObjects) { SEObject::GetAllObjectsByName(rName,rObjects); } //---------------------------------------------------------------------------- template <class T> SEObject* SESharedArray<T>::GetObjectByID(unsigned int uiID) { return SEObject::GetObjectByID(uiID); } //---------------------------------------------------------------------------- template <class T> void SESharedArray<T>::Load(SEStream& rStream, SEStream::SELink* pLink) { SE_BEGIN_DEBUG_STREAM_LOAD; SEObject::Load(rStream, pLink); rStream.Read(m_iCount); m_pArray = SE_NEW T[m_iCount]; rStream.Read(m_iCount, m_pArray); SE_END_DEBUG_STREAM_LOAD(SESharedArray<T>); } //---------------------------------------------------------------------------- template <class T> void SESharedArray<T>::Link(SEStream& rStream, SEStream::SELink* pLink) { SEObject::Link(rStream,pLink); } //---------------------------------------------------------------------------- template <class T> bool SESharedArray<T>::Register(SEStream& rStream) const { return SEObject::Register(rStream); } //---------------------------------------------------------------------------- template <class T> void SESharedArray<T>::Save(SEStream& rStream) const { SE_BEGIN_DEBUG_STREAM_SAVE; SEObject::Save(rStream); rStream.Write(m_iCount); rStream.Write(m_iCount, m_pArray); SE_END_DEBUG_STREAM_SAVE(SESharedArray<T>); } //---------------------------------------------------------------------------- template <class T> int SESharedArray<T>::GetDiskUsed(const SEStreamVersion& rVersion) const { return SEObject::GetDiskUsed(rVersion) + sizeof(m_iCount) + m_iCount*sizeof(T); } //---------------------------------------------------------------------------- template <class T> SEStringTree* SESharedArray<T>::SaveStrings(const char* pTitle) { SEStringTree* pTree = SE_NEW SEStringTree; // strings pTree->Append(Format(&TYPE, GetName().c_str())); // children pTree->Append(SEObject::SaveStrings()); pTree->Append(Format(pTitle, m_iCount, m_pArray)); return pTree; } //----------------------------------------------------------------------------
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 220 ] ] ]
22b8882aaf4dfe22db7aebe9878c787c72b3b60f
6630a81baef8700f48314901e2d39141334a10b7
/1.4/Testing/Cxx/swWxGuiTesting/swCREventCaptureManager.h
8445e2cd5b7aeb710f4c1bf24d43977484d37ed7
[]
no_license
jralls/wxGuiTesting
a1c0bed0b0f5f541cc600a3821def561386e461e
6b6e59e42cfe5b1ac9bca02fbc996148053c5699
refs/heads/master
2021-01-10T19:50:36.388929
2009-03-24T20:22:11
2009-03-26T18:51:24
623,722
1
0
null
null
null
null
ISO-8859-1
C++
false
false
5,101
h
/////////////////////////////////////////////////////////////////////////////// // Name: swWxGuiTesting/swCREventCaptureManager.h // Author: Reinhold Füreder // Created: 2004 // Copyright: (c) 2005 Reinhold Füreder // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// #ifndef SWCREVENTCAPTUREMANAGER_H #define SWCREVENTCAPTUREMANAGER_H #ifdef __GNUG__ #pragma interface "swCREventCaptureManager.h" #endif #include "Common.h" #include <list> #include "swCREventFilterInterface.h" namespace swTst { class CRLogInterface; class CRCapturedEvent; /*! \class CREventCaptureManager \brief Manages the event filtering for C&R capturing (Singleton pattern). */ class CREventCaptureManager : public CREventFilterInterface { public: /*! \fn static CREventCaptureManager * GetInstance () \brief Get single private instance (Singleton pattern). \return single private instance */ static CREventCaptureManager * GetInstance (); /*! \fn static void Destroy () \brief Threadsafe destruction of static singleton instance. */ static void Destroy (); /*! \fn virtual void IgnoreWindow (wxWindow *wdw) \brief Events from/on dialog used in capturing for user interaction must be ignored. \param wdw capturing dialog to ignore events from */ virtual void IgnoreWindow (wxWindow *wdw); /*! \fn virtual void On () \brief Switch on event capturing (called by CRCaptureControl class). */ virtual void On (); /*! \fn virtual void Off () \brief Switch off event capturing (called by CRCaptureControl class). */ virtual void Off (); /*! \fn virtual bool IsOn () const \brief Get status of event capturing switch. \return true, if event capturing is switched on */ virtual bool IsOn () const; /*! \var virtual void SetLogger (CRLogInterface *log) \brief Set logging target. \param log logging target */ virtual void SetLogger (CRLogInterface *log); // Implement CREventFilterInterface: /*! \fn virtual void FilterEvent (wxEvent &event) \brief Filter all events in capturing mode. \param event event to process */ virtual void FilterEvent (wxEvent &event); /*! \fn virtual void EmitPendingEvent () \brief Emit pending event, if existing. */ virtual void EmitPendingEvent (); protected: /*! \fn CREventCaptureManager () \brief Constructor */ CREventCaptureManager (); /*! \fn virtual ~CREventCaptureManager () \brief Destructor */ virtual ~CREventCaptureManager (); /*! \fn virtual bool CanIgnore (wxEvent &event) \brief Returns if given event must be ignored. That is, the event stems from the capturing dialog itself. \param event event to check for being ignored */ virtual bool CanIgnore (wxEvent &event); /*! \fn virtual wxString GetDescForUnsupportedEvent (wxEvent &event) const \brief Returns descriptive name for given event, if unsupported. \param event event to get descriptive name for \return descriptive name for given event, if unsupported; or empty string otherwise */ virtual wxString GetDescForUnsupportedEvent (wxEvent &event) const; /*! \fn virtual wxString GetEventDesc (wxEvent &event) const \brief Returns descriptive name for given event. \param event event to get descriptive name for \return descriptive name for given event */ virtual wxString GetEventDesc (wxEvent &event) const; /*! \fn virtual wxString GetEventDetails (wxEvent& event) const \brief Get descriptive string with event details. \param event event to get descriptive name for \return descriptive string with event details */ virtual wxString GetEventDetails (wxEvent& event) const; /*! \fn virtual void LogEventDetails (wxEvent& event, const wxString &prefix); \brief Log event details (only called for unsupported event). \param event event to log details for \param prefix logging output prefix */ virtual void LogEventDetails (wxEvent& event, const wxString &prefix); private: static CREventCaptureManager *ms_instance; wxWindow *m_ignoreWdw; bool m_isOn; wxEvent *m_event; CRLogInterface *m_log; std::ofstream *m_logStream; //typedef std::list< CRCapturedEvent * > EventList; //EventList m_eventList; CRCapturedEvent *m_pendingEvent; private: // No copy and assignment constructor: CREventCaptureManager (const CREventCaptureManager &rhs); CREventCaptureManager & operator= (const CREventCaptureManager &rhs); }; } // End namespace swTst #endif // SWCREVENTCAPTUREMANAGER_H
[ "john@64288482-8357-404e-ad65-de92a562ee98" ]
[ [ [ 1, 183 ] ] ]
d204082bfc82a7808a083dd14609af3e8c1d661d
1e01b697191a910a872e95ddfce27a91cebc57dd
/GrfRandomSeed.h
f7097d5ae4ff9b5647926bf19eee38bb811830a4
[]
no_license
canercandan/codeworker
7c9871076af481e98be42bf487a9ec1256040d08
a68851958b1beef3d40114fd1ceb655f587c49ad
refs/heads/master
2020-05-31T22:53:56.492569
2011-01-29T19:12:59
2011-01-29T19:12:59
1,306,254
7
5
null
null
null
null
IBM852
C++
false
false
1,556
h
/* "CodeWorker": a scripting language for parsing and generating text. Copyright (C) 1996-1997, 1999-2010 CÚdric Lemaire This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA To contact the author: [email protected] */ #ifndef _GrfRandomSeed_h_ #define _GrfRandomSeed_h_ #include "GrfCommand.h" namespace CodeWorker { class ExprScriptExpression; class GrfRandomSeed : public GrfCommand { private: ExprScriptExpression* _pSeed; public: GrfRandomSeed() : _pSeed(NULL) {} virtual ~GrfRandomSeed(); virtual const char* getFunctionName() const { return "randomSeed"; } inline void setSeed(ExprScriptExpression* pSeed) { _pSeed = pSeed; } virtual void compileCpp(CppCompilerEnvironment& theCompilerEnvironment) const; protected: virtual SEQUENCE_INTERRUPTION_LIST executeInternal(DtaScriptVariable& visibility); }; } #endif
[ "cedric.p.r.lemaire@28b3f5f3-d42e-7560-b87f-5f53cf622bc4" ]
[ [ [ 1, 49 ] ] ]
48a0c26ff88563c29d3915acceec628ead346700
6f7850c90ed97967998033df615d06eacfabd5fa
/common/my_num.h
17f28d3d2d565eb25ec04490ddb9e8772a5a4a05
[]
no_license
vi-k/whoisalive
1145b0af6a2a18e951533b00a2103b000abd570a
ae86c1982c1e97eeebc50ba54bf53b9b694078b6
refs/heads/master
2021-01-10T02:00:28.585126
2010-08-23T01:58:45
2010-08-23T01:58:45
44,526,120
0
0
null
null
null
null
UTF-8
C++
false
false
13,426
h
/* Быстрые функции преобразования чисел в строки и из строки В строку - свой алгоритм (первый придуманный алгоритм оказался быстрее itoa и, даже (!), Boost.Spirit.Karma (после создания его безопасной версии стал таким как последний). Из строки (to_signed, to_unsigned, to_real)- использую Boost.Spirit2 (ужасно медленно компилируется, поэтому шаблоны вынес в *.cpp (и чтоб они компилировались, а не игнорировались, включил функцию my_num_dummy, которая задействует все возможные варианты). ---------------------------------------- Функции преобразования числа в строку. Поддерживаемые типы: char, short, int, long, long long и их беззнаковые версии. ---------- template<class Char> size_t put( Char *buf, size_t buf_sz, type value, size_t decimals = 0); Преобразование числа value в буфер buf размером buf_sz. decimals - минимальное кол-во цифр. Возврат: размер полученной строки (без учёта завершающего нуля). ---------- template<class Char> std::basic_string<Char> to_str( type value, size_t decimals = 0); std::string to_string( type value, size_t decimals = 0); std::wstring to_wstring( type value, size_t decimals = 0); Преобразование числа value в строку. ---------------------------------------- Функции преобразования строки в число. Поддерживаемые типы: char, short, int, long, long long, их беззнаковые версии, float, double, long double. Используемые типы и их представление в названиях функций: char -> char uchar -> unsigned char short -> short ushort -> unsigned short int -> int uint -> unsigned int long -> long ulong -> unsigned long longlong -> long long ulonglong -> unsigned long long ---------- template<class Char> size_t get( Char *str, size_t str_sz, type &res); template<class Char> size_t get( const std::basic_string<Char> &str, type &res); Преобразование строки в число. В первом варианте, если размер строки не задан (== -1), он рассчитывается автоматически. Возврат: кол-во символов, считанных из буфера или строки; в res - полученное значение. ---------- template<class Char> type to_type_def( Char *str, size_t str_sz, type def); template<class Char> type to_type_def( const std::basic_string<Char> &str, type def); Преобразование строки в число. В случае ошибки разбора, возвращается def. В первом варианте, если размер строки не задан (== -1), он рассчитывается автоматически. ---------- template<class Char> bool try_to_type( Char *str, size_t str_sz, type &res); template<class Char> bool try_to_type( const std::basic_string<Char> &str, type &res); Попытка преобразования строки в число. При ошибке преобразования число в res не меняется. В первом варианте, если размер строки не задан (== -1), он рассчитывается автоматически. Возврат: успех преобразования, в res - полученное значение. */ #ifndef MY_NUM_H #define MY_NUM_H #include <cstddef> /* std::size_t */ #include <string> namespace my { namespace num { /* Функции преобразования целых чисел в строку */ /* Размер временного буфера для преобразований, хватит на 128 бит (39 сиволов без знака) */ #define NUM_TO_STR_BUF_SIZE 64 /* signed_to Алгоритм преобразования целого числа со знаком в строку. Ради производительности имеет ограничение - используется временный буфер размером NUM_TO_STR_BUF_SIZE байт (128 бит требует 39 байт). Напрямую использовать не рекомендуется, т.к. шаблон принимает любые типы и результат такого действия не предсказуем. */ template<class T, class Char> std::size_t put_signed(Char *buf, std::size_t buf_sz, T n, std::size_t decimals = 0) { static const Char sym[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; /* Результат сохраняем во временный буфер в обратном порядке */ Char tmp[NUM_TO_STR_BUF_SIZE]; Char *tmp_ptr = tmp; bool neg; /* Сохраняем знак. Операции проводим только с отрицательными числами. Логичнее было бы проводить с положительными, но не все отрицательные числа можно перевести в положительные - например, (char)-128 */ if ( (neg = n < 0) == false) n = -n; do { T nn = n / 10; *tmp_ptr++ = sym[ (nn<<3) + (nn<<1) - n ]; n = nn; } while (n); /* На данный момент во временном буфере хранится число в обратном порядке, без знака и без завершающего нуля */ /* Заполняем выходную строку. Отдельно, если не входим в ограничение размера (###), отдельно - если входим */ Char *ptr = buf; Char *end = buf + buf_sz; std::size_t tmp_sz = tmp_ptr - tmp; std::size_t zero_count = (decimals > tmp_sz ? decimals - tmp_sz : 0); if (tmp_sz + zero_count + neg >= buf_sz) { if (buf_sz != 0) { Char *last = buf + buf_sz - 1; while (ptr != last) *ptr++ = '#'; *ptr = 0; } } else { if (neg) *ptr++ = '-'; Char *zero_end = ptr + zero_count; while (ptr < zero_end) *ptr++ = '0'; while (tmp_ptr != tmp) *ptr++ = *--tmp_ptr; *ptr = 0; } return ptr - buf; } /* unsigned_to Алгоритм преобразования целого числа без знака в строку. Ради производительности имеет ограничение - используется временный буфер размером NUM_TO_STR_BUF_SIZE байт (128 бит требует 39 байт). Напрямую использовать не рекомендуется, т.к. шаблон принимает любые типы и результат такого действия не предсказуем. */ template<class T, class Char> std::size_t put_unsigned(Char *buf, std::size_t buf_sz, T n, std::size_t decimals = 0) { static const Char sym[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; /* Результат сохраняем во временный буфер в обратном порядке */ Char tmp[NUM_TO_STR_BUF_SIZE]; Char *tmp_ptr = tmp; do { T nn = n / 10; *tmp_ptr++ = sym[ n - (nn<<3) - (nn<<1) ]; n = nn; } while (n); /* На данный момент в буфере хранится число в обратном порядке, без завершающего нуля */ /* Заполняем выходную строку. Отдельно, если не входим в ограничение размера (###), отдельно - если входим */ Char *ptr = buf; Char *end = buf + buf_sz; std::size_t tmp_sz = tmp_ptr - tmp; std::size_t zero_count = (decimals > tmp_sz ? decimals - tmp_sz : 0); if (tmp_sz + zero_count >= buf_sz) { if (buf_sz != 0) { Char *last = buf + buf_sz - 1; while (ptr != last) *ptr++ = '#'; *ptr = 0; } } else { Char *zero_end = ptr + zero_count; while (ptr < zero_end) *ptr++ = '0'; while (tmp_ptr != tmp) *ptr++ = *--tmp_ptr; *ptr = 0; } return ptr - buf; } /* signed_to_str и unsigned_to_str Напрямую использовать не рекомендуется. */ template<class T, class Char> inline std::basic_string<Char> signed_to_str(T n, std::size_t decimals = 0) { Char buf[NUM_TO_STR_BUF_SIZE]; std::size_t sz = put_signed<T,Char>(buf, sizeof(buf) / sizeof(*buf), n, decimals); return std::basic_string<Char>(buf); } template<class T, class Char> inline std::basic_string<Char> unsigned_to_str(T n, std::size_t decimals = 0) { Char buf[NUM_TO_STR_BUF_SIZE]; std::size_t sz = put_unsigned<T,Char>(buf, sizeof(buf) / sizeof(*buf), n, decimals); return std::basic_string<Char>(buf); } #define DEF_NUM_TO_FUNCS(S,T)\ template<class Char>\ inline std::size_t put(Char *str, std::size_t size,\ T n, std::size_t decimals = 0)\ { return put_##S<T,Char>(str, size, n, decimals); }\ template<class Char>\ inline std::basic_string<Char> to_str(T n, std::size_t decimals = 0)\ { return S##_to_str<T,Char>(n, decimals); }\ inline std::string to_string(T n, std::size_t decimals = 0)\ { return to_str<char>(n, decimals); }\ inline std::wstring to_wstring(T n, std::size_t decimals = 0)\ { return to_str<wchar_t>(n, decimals); } DEF_NUM_TO_FUNCS(signed,char) DEF_NUM_TO_FUNCS(signed,short) DEF_NUM_TO_FUNCS(signed,int) DEF_NUM_TO_FUNCS(signed,long) DEF_NUM_TO_FUNCS(signed,long long) DEF_NUM_TO_FUNCS(unsigned,unsigned char) DEF_NUM_TO_FUNCS(unsigned,unsigned short) DEF_NUM_TO_FUNCS(unsigned,unsigned int) DEF_NUM_TO_FUNCS(unsigned,unsigned long) DEF_NUM_TO_FUNCS(unsigned,unsigned long long) /* Функции преобразования строки в число */ template<class Char, class Type> inline std::size_t get_signed(const Char *str, std::size_t str_sz, Type &res); template<class Char, class Type> inline Type to_signed_def(const Char *str, std::size_t str_sz, Type def); template<class Char, class Type> inline bool try_to_signed(const Char *str, std::size_t str_sz, Type &res); template<class Char, class Type> inline std::size_t get_unsigned(const Char *str, std::size_t str_sz, Type &res); template<class Char, class Type> inline Type to_unsigned_def(const Char *str, std::size_t str_sz, Type def); template<class Char, class Type> inline bool try_to_unsigned(const Char *str, std::size_t str_sz, Type &res); template<class Char, class Type> inline std::size_t get_real(const Char *str, std::size_t str_sz, Type &res); template<class Char, class Type> inline Type to_real_def(const Char *str, std::size_t str_sz, Type def); template<class Char, class Type> inline bool try_to_real(const Char *str, std::size_t str_sz, Type &res); #define DEF_TO_NUM_FUNCS(S,N,T)\ template<class Char>\ inline std::size_t get(const Char *str, std::size_t str_sz, T &res)\ { return get_##S<Char,T>(str, str_sz, res); }\ template<class Char>\ inline T to_##N##_def(const Char *str, std::size_t str_sz, T def)\ { return to_##S##_def<Char,T>(str, str_sz, def); }\ template<class Char>\ inline bool try_to_##N(const Char *str, std::size_t str_sz, T &res)\ { return try_to_##S<Char,T>(str, str_sz, res); }\ template<class Char>\ inline std::size_t get(const std::basic_string<Char> &str, T &res)\ { return get_##S<Char,T>(str.c_str(), str.size(), res); }\ template<class Char>\ inline T to_##N##_def(const std::basic_string<Char> &str, T def)\ { return to_##S##_def<Char,T>(str.c_str(), str.size(), def); }\ template<class Char>\ inline bool try_to_##N(const std::basic_string<Char> &str, T &res)\ { return try_to_##S<Char,T>(str.c_str(), str.size(), res); } DEF_TO_NUM_FUNCS(signed,char,char) DEF_TO_NUM_FUNCS(signed,short,short) DEF_TO_NUM_FUNCS(signed,int,int) DEF_TO_NUM_FUNCS(signed,long,long) DEF_TO_NUM_FUNCS(signed,longlong,long long) DEF_TO_NUM_FUNCS(unsigned,uchar,unsigned char) DEF_TO_NUM_FUNCS(unsigned,ushort,unsigned short) DEF_TO_NUM_FUNCS(unsigned,uint,unsigned int) DEF_TO_NUM_FUNCS(unsigned,ulong,unsigned long) DEF_TO_NUM_FUNCS(unsigned,ulonglong,unsigned long long) DEF_TO_NUM_FUNCS(real,float,float) DEF_TO_NUM_FUNCS(real,double,double) DEF_TO_NUM_FUNCS(real,long_double,long double) }} #endif
[ "victor dunaev ([email protected])", "[email protected]" ]
[ [ [ 1, 138 ], [ 140, 345 ], [ 347, 347 ], [ 350, 350 ], [ 353, 353 ], [ 357, 357 ], [ 360, 360 ], [ 363, 363 ], [ 367, 367 ], [ 370, 370 ], [ 373, 373 ], [ 378, 379 ], [ 381, 382 ], [ 384, 385 ], [ 387, 388 ], [ 390, 391 ], [ 393, 394 ], [ 401, 401 ], [ 407, 415 ] ], [ [ 139, 139 ], [ 346, 346 ], [ 348, 349 ], [ 351, 352 ], [ 354, 356 ], [ 358, 359 ], [ 361, 362 ], [ 364, 366 ], [ 368, 369 ], [ 371, 372 ], [ 374, 377 ], [ 380, 380 ], [ 383, 383 ], [ 386, 386 ], [ 389, 389 ], [ 392, 392 ], [ 395, 400 ], [ 402, 406 ] ] ]
139643a1ff43b561075af281fe954515637d2aa3
3182b05c41f13237825f1ee59d7a0eba09632cd5
/renderInstance/renderPassManager.cpp
72b6eecd8c0a3a488a5747e83806725cec4fb417
[]
no_license
adhistac/ee-client-2-0
856e8e6ce84bfba32ddd8b790115956a763eec96
d225fc835fa13cb51c3e0655cb025eba24a8cdac
refs/heads/master
2021-01-17T17:13:48.618988
2010-01-04T17:35:12
2010-01-04T17:35:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,610
cpp
//----------------------------------------------------------------------------- // Torque Shader Engine // Copyright (C) GarageGames.com, Inc. //----------------------------------------------------------------------------- #include "platform/platform.h" #include "renderInstance/renderPassManager.h" #include "materials/sceneData.h" #include "materials/matInstance.h" #include "materials/customMaterialDefinition.h" #include "materials/materialManager.h" #include "sceneGraph/sceneGraph.h" #include "sceneGraph/sceneObject.h" #include "gfx/primBuilder.h" #include "platform/profiler.h" #include "renderInstance/renderBinManager.h" #include "renderInstance/renderObjectMgr.h" #include "renderInstance/renderMeshMgr.h" #include "renderInstance/renderTranslucentMgr.h" #include "renderInstance/renderGlowMgr.h" #include "renderInstance/renderTerrainMgr.h" #include "core/util/safeDelete.h" #include "math/util/matrixSet.h" //const String IRenderable3D::InterfaceName("Render3D"); const F32 RenderPassManager::PROCESSADD_NONE = -1e30f; const F32 RenderPassManager::PROCESSADD_NORMAL = 0.5f; const RenderInstType RenderPassManager::RIT_Interior("Interior"); const RenderInstType RenderPassManager::RIT_Mesh("Mesh"); const RenderInstType RenderPassManager::RIT_Shadow("Shadow"); const RenderInstType RenderPassManager::RIT_Sky("Sky"); const RenderInstType RenderPassManager::RIT_Terrain("Terrain"); const RenderInstType RenderPassManager::RIT_Object("Object"); const RenderInstType RenderPassManager::RIT_ObjectTranslucent("ObjectTranslucent"); const RenderInstType RenderPassManager::RIT_Decal("Decal"); const RenderInstType RenderPassManager::RIT_Water("Water"); const RenderInstType RenderPassManager::RIT_Foliage("Foliage"); const RenderInstType RenderPassManager::RIT_Translucent("Translucent"); const RenderInstType RenderPassManager::RIT_Begin("Begin"); const RenderInstType RenderPassManager::RIT_Custom("Custom"); const RenderInstType RenderPassManager::RIT_Particle("Particle"); const RenderInstType RenderPassManager::RIT_Occluder("Occluder"); //***************************************************************************** // RenderInstance //***************************************************************************** void RenderInst::clear() { dMemset( this, 0, sizeof(RenderInst) ); } void MeshRenderInst::clear() { dMemset( this, 0, sizeof(MeshRenderInst) ); visibility = 1.0f; } void ParticleRenderInst::clear() { dMemset( this, 0, sizeof(ParticleRenderInst) ); } void ObjectRenderInst::clear() { userData = NULL; dMemset( this, 0, sizeof( ObjectRenderInst ) ); // The memset here is kinda wrong... it clears the // state initialized by the delegate constructor. // // This fixes it... but we probably need to have a // real constructor for RenderInsts. renderDelegate.clear(); } void OccluderRenderInst::clear() { dMemset( this, 0, sizeof(OccluderRenderInst) ); } //***************************************************************************** // Render Instance Manager //***************************************************************************** IMPLEMENT_CONOBJECT(RenderPassManager); RenderPassManager::RenderBinEventSignal& RenderPassManager::getRenderBinSignal() { static RenderBinEventSignal theSignal; return theSignal; } void RenderPassManager::initPersistFields() { } RenderPassManager::RenderPassManager() { mSceneManager = NULL; VECTOR_SET_ASSOCIATION( mRenderBins ); VECTOR_SET_ASSOCIATION( mAddBins ); #ifndef TORQUE_SHIPPING mAddInstCount = 0; mAddInstPassCount = 0; VECTOR_SET_ASSOCIATION( mAddBinInstCounts ); #endif mMatrixSet = reinterpret_cast<MatrixSet *>(dAligned_malloc(sizeof(MatrixSet), 16)); constructInPlace(mMatrixSet); } RenderPassManager::~RenderPassManager() { dAligned_free(mMatrixSet); // Any bins left need to be deleted. for ( U32 i=0; i<mRenderBins.size(); i++ ) { RenderBinManager *bin = mRenderBins[i]; // Clear the parent first, so that RenderBinManager::onRemove() // won't call removeManager() and break this loop. bin->setParentManager( NULL ); bin->deleteObject(); } } void RenderPassManager::_insertSort(Vector<RenderBinManager*>& list, RenderBinManager* mgr, bool renderOrder) { U32 i; for (i = 0; i < list.size(); i++) { bool renderCompare = mgr->getRenderOrder() < list[i]->getRenderOrder(); bool processAddCompare = mgr->getProcessAddOrder() < list[i]->getProcessAddOrder(); if ((renderOrder && renderCompare) || (!renderOrder && processAddCompare)) { list.insert(i); list[i] = mgr; return; } } list.push_back(mgr); } void RenderPassManager::addManager(RenderBinManager* mgr) { if ( !mgr->isProperlyAdded() ) mgr->registerObject(); AssertFatal( mgr->getParentManager() == NULL, "RenderPassManager::addManager() - Bin is still part of another pass manager!" ); mgr->setParentManager(this); _insertSort(mRenderBins, mgr, true); if ( mgr->getProcessAddOrder() != PROCESSADD_NONE ) _insertSort(mAddBins, mgr, false); } void RenderPassManager::removeManager(RenderBinManager* mgr) { AssertFatal( mgr->getParentManager() == this, "RenderPassManager::removeManager() - We do not own this bin!" ); mRenderBins.remove( mgr ); mAddBins.remove( mgr ); mgr->setParentManager( NULL ); } RenderBinManager* RenderPassManager::getManager(S32 i) const { if (i >= 0 && i < mRenderBins.size()) return mRenderBins[i]; else return NULL; } #ifndef TORQUE_SHIPPING void RenderPassManager::resetCounters() { mAddInstCount = 0; mAddInstPassCount = 0; mAddBinInstCounts.setSize( mRenderBins.size() ); dMemset( mAddBinInstCounts.address(), 0, mAddBinInstCounts.size() * sizeof( U32 ) ); // TODO: We need to expose the counts again. The difficulty // is two fold... // // First we need to track bins and not RITs... you can have // the same RIT in multiple bins, so we miss some if we did that. // // Second we have multiple RenderPassManagers, so we need to // either combine the results of all passes, show all the bins // and passes, or just one pass at a time. } #endif void RenderPassManager::addInst( RenderInst *inst ) { AssertFatal(inst != NULL, "doh, null instance"); PROFILE_SCOPE(SceneRenderPassManager_addInst); #ifndef TORQUE_SHIPPING mAddInstCount++; #endif // See what managers want to look at this instance. bool bHandled = false; #ifndef TORQUE_SHIPPING U32 i = 0; #endif for (Vector<RenderBinManager *>::iterator itr = mAddBins.begin(); itr != mAddBins.end(); itr++) { RenderBinManager *curBin = *itr; AssertFatal(curBin, "Empty render bin slot!"); // We may want to pass if the inst has been handled already to addElement? RenderBinManager::AddInstResult result = curBin->addElement(inst); #ifndef TORQUE_SHIPPING // Log some rendering stats if ( result != RenderBinManager::arSkipped ) { mAddInstPassCount++; if ( i < mAddBinInstCounts.size() ) mAddBinInstCounts[ i ]++; } i++; #endif switch (result) { case RenderBinManager::arAdded : bHandled = true; break; case RenderBinManager::arStop : bHandled = true; continue; break; default : // handle warning break; } } //AssertFatal(bHandled, "Instance without a render manager!"); } void RenderPassManager::sort() { PROFILE_SCOPE( RenderPassManager_Sort ); for (Vector<RenderBinManager *>::iterator itr = mRenderBins.begin(); itr != mRenderBins.end(); itr++) { AssertFatal(*itr, "Render manager invalid!"); (*itr)->sort(); } } void RenderPassManager::clear() { PROFILE_SCOPE( RenderPassManager_Clear ); mChunker.clear(); for (Vector<RenderBinManager *>::iterator itr = mRenderBins.begin(); itr != mRenderBins.end(); itr++) { AssertFatal(*itr, "Invalid render manager!"); (*itr)->clear(); } } void RenderPassManager::render(SceneState * state) { PROFILE_SCOPE( RenderPassManager_Render ); GFX->pushWorldMatrix(); MatrixF proj = GFX->getProjectionMatrix(); for (Vector<RenderBinManager *>::iterator itr = mRenderBins.begin(); itr != mRenderBins.end(); itr++) { RenderBinManager *curBin = *itr; AssertFatal(curBin, "Invalid render manager!"); getRenderBinSignal().trigger(curBin, state, true); curBin->render(state); getRenderBinSignal().trigger(curBin, state, false); } GFX->popWorldMatrix(); GFX->setProjectionMatrix( proj ); // Restore a clean state for subsequent rendering. GFX->disableShaders(); for(S32 i = 0; i < GFX->getNumSamplers(); ++i) GFX->setTexture(i, NULL); } void RenderPassManager::renderPass(SceneState * state) { PROFILE_SCOPE( RenderPassManager_RenderPass ); sort(); render(state); clear(); } GFXTextureObject *RenderPassManager::getDepthTargetTexture() { // If this is OpenGL, or something else has set the depth buffer, return the pointer if( mDepthBuff.isValid() ) { // If this is OpenGL, make sure the depth target matches up // with the active render target. Otherwise recreate. if( GFX->getAdapterType() == OpenGL ) { GFXTarget* activeRT = GFX->getActiveRenderTarget(); AssertFatal( activeRT, "Must be an active render target to call 'getDepthTargetTexture'" ); Point2I activeRTSize = activeRT->getSize(); if( mDepthBuff.getWidth() == activeRTSize.x && mDepthBuff.getHeight() == activeRTSize.y ) return mDepthBuff.getPointer(); } else return mDepthBuff.getPointer(); } if(GFX->getAdapterType() == OpenGL) { AssertFatal(GFX->getActiveRenderTarget(), "Must be an active render target to call 'getDepthTargetTexture'"); const Point2I rtSize = GFX->getActiveRenderTarget()->getSize(); mDepthBuff.set(rtSize.x, rtSize.y, GFXFormatD24S8, &GFXDefaultZTargetProfile, avar("%s() - mDepthBuff (line %d)", __FUNCTION__, __LINE__)); return mDepthBuff.getPointer(); } // Default return value return GFXTextureTarget::sDefaultDepthStencil; } void RenderPassManager::setDepthTargetTexture( GFXTextureObject *zTarget ) { mDepthBuff = zTarget; } const MatrixF* RenderPassManager::allocSharedXform( SharedTransformType stt ) { AssertFatal(stt == View || stt == Projection, "Bad shared transform type"); // Enable this to simulate non-shared transform performance //#define SIMULATE_NON_SHARED_TRANSFORMS #ifdef SIMULATE_NON_SHARED_TRANSFORMS return allocUniqueXform(stt == View ? mMatrixSet->getWorldToCamera() : mMatrixSet->getCameraToScreen()); #else return &(stt == View ? mMatrixSet->getWorldToCamera() : mMatrixSet->getCameraToScreen()); #endif } void RenderPassManager::assignSharedXform( SharedTransformType stt, const MatrixF &xfm ) { AssertFatal(stt == View || stt == Projection, "Bad shared transform type"); if(stt == View) mMatrixSet->setSceneView(xfm); else mMatrixSet->setSceneProjection(xfm); } // Script interface ConsoleMethod(RenderPassManager, getManagerCount, S32, 2, 2, "Returns the total number of bin managers." ) { TORQUE_UNUSED(argc); TORQUE_UNUSED(argv); return (S32) object->getManagerCount(); } ConsoleMethod( RenderPassManager, getManager, S32, 3, 3, "Get the manager at index." ) { TORQUE_UNUSED(argc); S32 objectIndex = dAtoi(argv[2]); if(objectIndex < 0 || objectIndex >= S32(object->getManagerCount())) { Con::printf("Set::getObject index out of range."); return -1; } return object->getManager(objectIndex)->getId(); } ConsoleMethod( RenderPassManager, addManager, void, 3, 3, "Add a manager." ) { TORQUE_UNUSED(argc); RenderBinManager* m; if (Sim::findObject<RenderBinManager>(argv[2], m)) object->addManager(m); else Con::errorf("Object %s does not exist or is not a RenderBinManager", argv[2]); } ConsoleMethod( RenderPassManager, removeManager, void, 3, 3, "Removes a manager by name." ) { TORQUE_UNUSED(argc); RenderBinManager* m; if (Sim::findObject<RenderBinManager>(argv[2], m)) object->removeManager(m); else Con::errorf("Object %s does not exist or is not a RenderBinManager", argv[2]); }
[ [ [ 1, 427 ] ] ]
3b01bc2f43692333942d6c6f68ff461acfe1ca92
eb7a57e7cf69b4f4f3ee1ecc46b12b24f8b094f8
/Kickapoo/Game.cpp
e8c846f3881ec6416826dae5c71e237d2d9ab8cd
[]
no_license
gosuwachu/polidea-igk-2011
93df514d4d3f2a89d23746e60b4011a3e7be9c01
03ec935846d106004288e13de77995a54eae5272
refs/heads/master
2021-01-23T11:49:59.847960
2011-03-27T20:30:51
2011-03-27T20:30:51
32,650,639
0
0
null
null
null
null
UTF-8
C++
false
false
7,110
cpp
#include "Common.h" #include "Game.h" Sound* g_fireSound = NULL; Sound* g_wallSound = NULL; static float _introTime = 0.0f; static float _fake; static float _selectionAlpha = 0.0f; static float _splashZeroElementY = 0.0f; static float _splashOneElementY = 600.0f; string _introText = "Jestes komendantem komisariatu policji w siedlcach :P. \nMusisz chronic premiera zamieszanego w afere EURO2012.\n Dajesz dajesz, nie ma lipy!."; RECT _introRect; RECT _screenMiddleRect; const float MaxRelativeTime = 10.0f; Game::Game(void) : state_(EGameState::Intro) , kryzys_("kryzys_logo.jpg") , crysis_("crysis.jpg") , selection_("gfx/wave.png") , gameScreen_("gfx/splash_main.png") , zero_("gfx/splash_0.png") , one_("gfx/splash_1.png") , map(NULL) ,routePlaner(NULL), street("gfx/road.png"), street_corner("gfx/road2.png"), street_cross("gfx/road3.png"), street_cross3("gfx/road4.png"), tank1("models/tank1.x"), grass("gfx/grass.png"), ap_b("models/ap_b3.x"), ap_c("models/ap_c.x"), ap_d("models/ap_d.x"), vip("models/vip.x"), police("models/car.x"), tower("models/tower.x"), hangar("models/hangar_mesh.x"), ringa("gfx/circle_yellow.png"), ringb("gfx/circle_red.png"), ringc("gfx/circle_blue.png") { g_Game = this; loadLevel(); changeState(EGameState::Intro); explosionSound = g_Audio()->loadSound("sfx/explosion.wav"); g_fireSound = g_Audio()->loadSound("sfx/fire.wav"); pickSound = g_Audio()->loadSound("sfx/pick.wav"); g_wallSound = g_Audio()->loadSound("sfx/wall.wav"); background = g_Audio()->loadSound("sfx/background.mp3", true); backgroundMusicStarted = true; typingSound = g_Audio()->loadSound("sfx/typing.wav"); //! Create intro //! Fade In [0.0f - 1.0f] //! Wave it and FadeOut [1.0f - 2.0f] //! Fade In Game Screen [2.0f - 3.0f] //! Type text [3.0f - 3.0f + textLength * 0.1f] if(state_ == EGameState::Intro) { float totalTime = 3 + _introText.size() * 0.1f + 3; AnimationSequenceScalar* introTimeLine = new AnimationSequenceScalar(_introTime, 0.0f, totalTime, totalTime); AnimationSequenceActivator* startGame = new AnimationSequenceActivator( MakeDelegate(this, &Game::startGame) ); introTimeLine->setNext(startGame); AnimationSequence::add(introTimeLine); } //! intro font RECT tmp={5, 460, g_Window()->getWidth(), g_Window()->getHeight()}; _introRect = tmp; introFont_ = new Font(); introFont_->create("Comic Sans MS", 40, 0, false, &_introRect); introFont_->setTextColor(D3DCOLOR_RGBA(127, 100, 0, 255)); RECT screenMiddle ={g_Window()->getWidth() * 0.25f, g_Window()->getHeight()*0.5f, g_Window()->getWidth() * 0.25f + g_Window()->getWidth(), g_Window()->getHeight() * 0.25f + g_Window()->getHeight()}; _screenMiddleRect = screenMiddle; } void Game::loadLevel() { delete map; map = NULL; map = Map::load("map0.bmp"); // TODO: map->setupGroups(); delete routePlaner; routePlaner = new RoutePlaner(); } Game::~Game(void) { delete introFont_; } void Game::changeState(EGameState::TYPE state) { state_ = state; if(state_ == EGameState::Running) { map->setupGroups(); g_Audio()->play(g_Game->background, 1.0, false, 1000); } } void Game::startGame() { loadLevel(); changeState(EGameState::RoutePlaning); } void Game::update() { float dt = g_Timer()->getFrameTime(); if(state_ == EGameState::Intro) { } else if(state_ == EGameState::RoutePlaning) { if (routePlaner) routePlaner->update(); } else if(state_ == EGameState::Running) { if(map) map->update(); for(int i = 0; i < maxLevels_; ++i) { if(GetKeyState('1' + i) & 0x80) { loadLevel(); return; } } if(g_Input()->buttonClicked(0)) { /*D3DXVECTOR3 p = map->cameraPosition; p.y = 10; //Fire* fire = new Fire( p); //g_ParticleSystem()->spawn(fire); Bullet* bullet = new Bullet(BulletType::BULLET_Rocket); bullet->position.x = p.x; bullet->position.y = p.y; bullet->velocity = D3DXVECTOR2(RandomFloat(0, 1), RandomFloat(0, 1)); map->bullets.push_back(bullet);*/ } else if(g_Input()->buttonClicked(1)) { D3DXVECTOR3 p = map->cameraPosition; p.y = 0; Nova* nova = new Nova(p, 0.3f, 2); g_ParticleSystem()->spawn(nova); } } } void Game::draw() { if(state_ == EGameState::Intro) { if(_introTime < 1.0f) { getDevice()->SetTexture(0, crysis_.getTexture()); g_Renderer()->drawRect(0, 0, g_Window()->getWidth(), g_Window()->getHeight(), D3DCOLOR_ARGB((int)(_introTime * 255.0f),255,255,255)); } else //! Wave it and FadeOut [1.0f - 2.0f] if(_introTime < 2.0f) { getDevice()->SetTexture(0, crysis_.getTexture()); g_Renderer()->drawRect(0, 0, g_Window()->getWidth(), g_Window()->getHeight(), D3DCOLOR_ARGB((int)((2.0f - _introTime) * 255.0f),255,255,255)); getDevice()->SetTexture(0, kryzys_.getTexture()); g_Renderer()->drawRect(0, 0, g_Window()->getWidth(), g_Window()->getHeight(), D3DCOLOR_ARGB((int)((_introTime - 1.0f ) * 255.0f),255,255,255)); } else //! Fade In Game Screen [2.0f - 3.0f] if(_introTime < 3.0f) { getDevice()->SetTexture(0, gameScreen_.getTexture()); g_Renderer()->drawRect(0, 0, g_Window()->getWidth(), g_Window()->getHeight(), D3DCOLOR_ARGB((int)((_introTime - 2.0f) * 255.0f),255,255,255)); getDevice()->SetTexture(0, zero_.getTexture()); g_Renderer()->drawRect(0, _splashZeroElementY, g_Window()->getWidth(), g_Window()->getHeight(), D3DCOLOR_ARGB(255,255,255,255)); } else //! Type text [3.0f - 3.0f + textLength * 0.1f] //! and change 2010 into 2110 { static int typeChar = 0; getDevice()->SetTexture(0, gameScreen_.getTexture()); g_Renderer()->drawRect(0, 0, g_Window()->getWidth(), g_Window()->getHeight(), D3DCOLOR_ARGB(255,255,255,255)); string typedText; int currentLength = (int)((_introTime - 3.0f) * 10.0f); typedText.assign(_introText.c_str(), currentLength); introFont_->write(typedText.c_str()); float totalTime = 3 + _introText.size() * 0.1f; if(currentLength > typeChar && _introTime <= totalTime) { typeChar = currentLength; if(typedText[typedText.length() - 1] != ' ') g_Audio()->play(typingSound); } if(_splashOneElementY > 0.0f) { float speed = 600.0f / 1.5f; _splashZeroElementY -= speed * g_Timer()->getFrameTime(); _splashOneElementY -= speed * g_Timer()->getFrameTime(); }; getDevice()->SetTexture(0, zero_.getTexture()); g_Renderer()->drawRect(0, _splashZeroElementY, g_Window()->getWidth(), g_Window()->getHeight(), D3DCOLOR_ARGB(255,255,255,255)); getDevice()->SetTexture(0, one_.getTexture()); g_Renderer()->drawRect(0, _splashOneElementY, g_Window()->getWidth(), g_Window()->getHeight(), D3DCOLOR_ARGB(255,255,255,255)); } } else if(state_ == EGameState::RoutePlaning) { if(routePlaner) routePlaner->draw(); } else { if(map) map->draw(); } }
[ "[email protected]@6b609280-a7e5-20d7-3a34-d6fd9d7be190", "[email protected]@6b609280-a7e5-20d7-3a34-d6fd9d7be190", "[email protected]@6b609280-a7e5-20d7-3a34-d6fd9d7be190", "[email protected]@6b609280-a7e5-20d7-3a34-d6fd9d7be190" ]
[ [ [ 1, 19 ], [ 21, 26 ], [ 29, 30 ], [ 45, 46 ], [ 48, 49 ], [ 51, 57 ], [ 59, 75 ], [ 77, 84 ], [ 86, 94 ], [ 98, 110 ], [ 113, 118 ], [ 120, 127 ], [ 134, 135 ], [ 138, 229 ], [ 235, 240 ] ], [ [ 20, 20 ], [ 27, 28 ], [ 85, 85 ], [ 95, 97 ], [ 128, 133 ], [ 136, 137 ], [ 230, 234 ] ], [ [ 31, 44 ], [ 47, 47 ], [ 50, 50 ] ], [ [ 58, 58 ], [ 76, 76 ], [ 111, 112 ], [ 119, 119 ] ] ]
269979f7b44b839bbbef0b9d0e34e5ed51040392
4f89f1c71575c7a5871b2a00de68ebd61f443dac
/lib/boost/gil/extension/io_new/detail/io.hpp
fb9601b8046c1b85c8d0d208c7b32944d22a0d4d
[]
no_license
inayatkh/uniclop
1386494231276c63eb6cdbe83296cdfd0692a47c
487a5aa50987f9406b3efb6cdc656d76f15957cb
refs/heads/master
2021-01-10T09:43:09.416338
2009-09-03T16:26:15
2009-09-03T16:26:15
50,645,836
0
0
null
null
null
null
UTF-8
C++
false
false
4,182
hpp
/* Copyright 2007-2008 Christian Henning, Andreas Pokorny Use, modification and distribution are subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt). */ /*************************************************************************************************/ #ifndef BOOST_GIL_EXTENSION_IO_IO_HPP_INCLUDED #define BOOST_GIL_EXTENSION_IO_IO_HPP_INCLUDED //////////////////////////////////////////////////////////////////////////////////////// /// \file /// \brief /// \author Christian Henning, Andreas Pokorny \n /// /// \date 2007-2008 \n /// //////////////////////////////////////////////////////////////////////////////////////// /*! * \page iobackend Adding a new io backend * \section Overview of backend requirements * To add support for a new IO backend the following is required: * - a format tag, to identify the image format, derived from boost::gil::format_tag * - boolean meta function is_supported<PixelType,FormatTag> must be implemented for * the new format tag * - explicit specialisation of image_read_info<FormatTag> must be provided, containing * runtime information available before/at reading the image * - explicit specialisation of image_write_info<FormatTag> must be provided, containing * runtime encoding parameters for writing an image * - An image reader must be specialized: * \code * template<typename IODevice, typename ConversionPolicy> * struct boost::gil::detail::reader<IODevice,FormatTag,ConversionPolicy> * { * reader( IODevice & device ) * reader( IODevice & device, typename ConversionPolicy::color_converter_type const& cc ) * image_read_info<FormatTag> get_info(); * template<typename Image> * void read_image( Image &, point_t const& top_left ); * template<typename View> * void read_view( View &, point_t const& top_left ); * }; * \endcode * - An image writer must be specialized: * \code * \template <typename IODevice> * struct boost::gil::detail::writer<IODevice,FormatTag> * { * writer( IODevice & device ) * template<typename View> * void apply( View const&, point_t const& top_left ); * template<typename View> * void apply( View const&, point_t const& top_left, image_write_info<FormatTag> const& ); * }; * \endcode * * Or instead of the items above implement overloads of read_view, read_and_convert_view, read_image, * read_and_convert_image, write_view and read_image_info. * * \section ConversionPolicy Interface of the ConversionPolicy * There are two different conversion policies in use, when reading images: * read_and_convert<ColorConverter> and read_and_no_convert. ColorConverter * can be a user defined color converter. * * \code * struct ConversionPolicy * { * template<typename InputIterator,typename OutputIterator> * void read( InputIterator in_begin, InputIterator in_end, * OutputIterator out_end ); * }; * \endcode * * Methods like read_view and read_image are supposed to bail out with an * exception instead of converting the image * * \section IODevice Concept of IO Device * A Device is simply an object used to read and write data to and from a stream. * The IODevice was added as a template paramter to be able to replace the file_name * access functionality. This is only an interim solution, as soon as boost provides * a good IO library, interfaces/constraints provided by that library could be used. * * \code * concept IODevice * { * void IODevice::read( unsigned char* data, int count ); * void IODevice::write( unsigned char* data, int count ); * void IODevice::seek(long count, int whence); * void IODevice::flush(); * }; * \endcode * * For the time being a boolean meta function must be specialized: * \code * namespace boost{namespace gil{namespace detail{ * template<typename Device> * struct detail::is_input_device; * }}} * \endcode * */ #endif // BOOST_GIL_EXTENSION_IO_IO_HPP_INCLUDED
[ "rodrigo.benenson@gmailcom" ]
[ [ [ 1, 106 ] ] ]
70e2fb84251442c1357868973a51d24b08262832
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/kernelhwsrv/base/validation/f32/sfsrv/src/T_FileData.cpp
183ed3b761b6ffa00317680b186d8d94bc10b9f3
[]
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
7,489
cpp
/* * Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ /** @test @internalComponent This contains CT_FileData */ // User includes #include "T_FileData.h" /*@{*/ /// Parameters _LIT(KFile, "file"); _LIT(KUParamName, "name"); _LIT(KRFsName, "RFs"); _LIT(KFileMode, "file_mode"); _LIT(KDataWrite, "datawrite"); // FileMode _LIT(KEFileShareExclusive, "EFileShareExclusive"); _LIT(KEFileShareReadersOnly, "EFileShareReadersOnly"); _LIT(KEFileShareAny, "EFileShareAny"); _LIT(KEFileShareReadersOrWriters, "EFileShareReadersOrWriters"); _LIT(KEFileStream, "EFileStream"); _LIT(KEFileStreamText, "EFileStreamText"); _LIT(KEFileRead, "EFileRead"); _LIT(KEFileWrite, "EFileWrite"); _LIT(KEFileReadAsyncAll, "EFileReadAsyncAll"); /// Commands _LIT(KCmdNew, "new"); _LIT(KCmdClose, "Close"); _LIT(KCmdDestructor, "~"); _LIT(KCmdOpen, "Open"); _LIT(KCmdCreate, "Create"); _LIT(KCmdWrite, "Write"); /*@}*/ CT_FileData* CT_FileData::NewL() /** * Two phase constructor */ { CT_FileData* ret = new (ELeave) CT_FileData(); CleanupStack::PushL(ret); ret->ConstructL(); CleanupStack::Pop(ret); return ret; } CT_FileData::CT_FileData() /** * Protected constructor. First phase construction */ : iFile(NULL) { } void CT_FileData::ConstructL() /** * Protected constructor. Second phase construction */ { } CT_FileData::~CT_FileData() /** * Destructor. */ { DoCleanup(); } void CT_FileData::DoCleanup() /** * Contains cleanup implementation */ { //Deleting RFile. if(iFile != NULL) { INFO_PRINTF1(_L("Deleting current RFile")); delete iFile; iFile = NULL; } } TAny* CT_FileData::GetObject() /** * Return a pointer to the object that the data wraps * * @return pointer to the object that the data wraps */ { return iFile; } TBool CT_FileData::DoCommandL(const TTEFFunction& aCommand, const TTEFSectionName& aSection, const TInt /*aAsyncErrorIndex*/) /** * Process a command read from the ini file * * @param aCommand the command to process * @param aSection the entry in the ini file requiring the command to be processed * * @return ETrue if the command is processed */ { TBool retVal = ETrue; if (aCommand == KCmdNew) { TRAPD(err,DoCmdNewL()); if ( err!=KErrNone ) { ERR_PRINTF2(_L("new error %d"), err); SetError(err); } } else if (aCommand == KCmdDestructor) { DoCmdDestructor(); } else if (aCommand == KCmdOpen) { DoCmdOpenL(aSection); } else if (aCommand == KCmdWrite) { DoCmdWriteL(aSection); } else if (aCommand == KCmdClose) { DoCmdClose(); } else if (aCommand == KCmdCreate) { DoCmdCreateL(aSection); } else { retVal = EFalse; } return retVal; } void CT_FileData::DoCmdNewL() /** Creates new RFile class instance */ { //Deletes previous RFile class instance if it was already created. DoCleanup(); INFO_PRINTF1(_L("Create new RFile class instance")); // do create iFile = new (ELeave) RFile(); } void CT_FileData::DoCmdDestructor() /** Destroy RFile the object */ { DoCleanup(); } void CT_FileData::DoCmdOpenL(const TDesC& aSection) //Opens files { RFs* rfsObject=NULL; TPtrC rfsObjectName; TBool dataOk=GET_MANDATORY_STRING_PARAMETER(KRFsName(), aSection, rfsObjectName); if ( dataOk ) { rfsObject=(RFs*)GetDataObjectL(rfsObjectName); } TPtrC filePath; if ( !GET_MANDATORY_STRING_PARAMETER(KFile(), aSection, filePath) ) { dataOk=EFalse; } TFileMode fileMode = EFileShareAny; if ( !GetFileMode(KFileMode, aSection, fileMode) ) { ERR_PRINTF2(_L("Open() error reading parameter. %S"), &KFileMode()); SetBlockResult(EFail); dataOk=EFalse; } if ( dataOk ) { if (rfsObject) { TInt err = iFile->Open(*rfsObject, filePath, fileMode); if ( err!=KErrNone ) { ERR_PRINTF2(_L("Open() Error:%d"), err); SetError(err); } } else { ERR_PRINTF1(_L("RFs object is NULL")); SetBlockResult(EFail); } } } void CT_FileData::DoCmdWriteL(const TDesC& aSection) //Write data to file { TPtrC data; if(GET_MANDATORY_STRING_PARAMETER(KDataWrite, aSection, data)) { //convert 16 bit to 8 HBufC8* buffer8 = NULL; TRAPD (err, buffer8 = HBufC8::NewL( data.Length() )); if (err == KErrNone) { buffer8->Des().Copy(data); err = iFile->Write(buffer8->Des()); if(err == KErrNone) { INFO_PRINTF1(_L("Write() data OK")); } else { ERR_PRINTF2(_L("Write() Error :% d"), err); SetError(err); } delete buffer8; buffer8 = NULL; } } else { ERR_PRINTF2(_L("Write() error reading parameter. %S"), &KDataWrite()); } } void CT_FileData::DoCmdClose() { INFO_PRINTF1(_L("Closing RFile")); iFile->Close(); } void CT_FileData::DoCmdCreateL(const TDesC& aSection) { RFs* rfsObject=NULL; TPtrC rfsObjectName; TBool dataOk=GET_MANDATORY_STRING_PARAMETER(KRFsName, aSection, rfsObjectName); if ( dataOk ) { rfsObject=(RFs*)GetDataObjectL(rfsObjectName); } // Gets name of file from ini file. TPtrC name; if ( !GET_MANDATORY_STRING_PARAMETER(KUParamName(), aSection, name) ) { dataOk=EFalse; } TFileMode fileMode = EFileShareAny; if ( !GetFileMode(KFileMode, aSection, fileMode) ) { ERR_PRINTF2(_L("Create() error reading parameter. %S"), &KFileMode()); SetBlockResult(EFail); dataOk=EFalse; } if ( dataOk ) { // Creates and opens a new file for writing. if (rfsObject) { TInt err = iFile->Create(*rfsObject, name, fileMode); if ( err!=KErrNone ) { ERR_PRINTF2(_L("Create(), error create() = %d"), err); SetError(err); } } else { ERR_PRINTF1(_L("RFs object is NULL")); SetBlockResult(EFail); } } } TBool CT_FileData::GetFileMode(const TDesC& aParameterName, const TDesC& aSection, TFileMode& aFileMode) { TPtrC modeStr; TBool ret=GET_MANDATORY_STRING_PARAMETER(aParameterName, aSection, modeStr); if ( ret ) { if (modeStr == KEFileShareExclusive) { aFileMode = EFileShareExclusive; } else if (modeStr == KEFileShareReadersOnly) { aFileMode = EFileShareReadersOnly; } else if (modeStr == KEFileShareAny) { aFileMode = EFileShareAny; } else if (modeStr == KEFileShareReadersOrWriters) { aFileMode = EFileShareReadersOrWriters; } else if (modeStr == KEFileStream) { aFileMode = EFileStream; } else if (modeStr == KEFileStreamText) { aFileMode = EFileStreamText; } else if (modeStr == KEFileRead) { aFileMode = EFileRead; } else if (modeStr == KEFileWrite) { aFileMode = EFileWrite; } else if (modeStr == KEFileReadAsyncAll) { aFileMode = EFileReadAsyncAll; } else { ret = EFalse; } } return ret; }
[ "none@none" ]
[ [ [ 1, 358 ] ] ]
10dfed70c5243059f53bdd6bd79b4fd79d17e4b6
3ee2800b8b236c0796fac991c31e9997a391ea10
/src/r_main.c
c0d9b993870054cff4b055522d13136a49192903
[]
no_license
febret/omegadoom
9f8c071abb97ff0eadb5fac6ab9bcaac4e77d17e
9501a0cc5b7f7de4fa2dc8cc08abccf089c84ced
refs/heads/master
2021-01-10T22:28:40.825790
2011-11-18T17:30:29
2011-11-18T17:30:29
32,113,402
0
0
null
null
null
null
UTF-8
C++
false
false
17,638
c
/* Emacs style mode select -*- C++ -*- *----------------------------------------------------------------------------- * * * PrBoom: a Doom port merged with LxDoom and LSDLDoom * based on BOOM, a modified and improved DOOM engine * Copyright (C) 1999 by * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman * Copyright (C) 1999-2000 by * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze * Copyright 2005, 2006 by * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko * * 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. * * DESCRIPTION: * Rendering main loop and setup functions, * utility functions (BSP, geometry, trigonometry). * See tables.c, too. * *-----------------------------------------------------------------------------*/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "doomstat.h" #include "d_net.h" #include "w_wad.h" #include "r_main.h" #include "r_things.h" #include "r_plane.h" #include "r_bsp.h" #include "r_draw.h" #include "m_bbox.h" #include "r_sky.h" #include "v_video.h" #include "lprintf.h" #include "st_stuff.h" #include "i_main.h" #include "i_system.h" #include "g_game.h" #include "r_demo.h" #include "r_fps.h" #include "OMEGA/OMEGA_interface.h" // Fineangles in the SCREENWIDTH wide window. #define FIELDOFVIEW 2048 // killough: viewangleoffset is a legacy from the pre-v1.2 days, when Doom // had Left/Mid/Right viewing. +/-ANG90 offsets were placed here on each // node, by d_net.c, to set up a L/M/R session. int viewangleoffset; int validcount = 1; // increment every time a check is made const lighttable_t *fixedcolormap; int centerx, centery; fixed_t centerxfrac, centeryfrac; fixed_t viewheightfrac; //e6y: for correct clipping of things fixed_t projection; // proff 11/06/98: Added for high-res fixed_t projectiony; fixed_t viewx, viewy, viewz; angle_t viewangle; fixed_t viewcos, viewsin; player_t *viewplayer; extern lighttable_t **walllights; static mobj_t *oviewer; // // precalculated math tables // angle_t clipangle; // The viewangletox[viewangle + FINEANGLES/4] lookup // maps the visible view angles to screen X coordinates, // flattening the arc to a flat projection plane. // There will be many angles mapped to the same X. int viewangletox[FINEANGLES/2]; // The xtoviewangleangle[] table maps a screen pixel // to the lowest viewangle that maps back to x ranges // from clipangle to -clipangle. angle_t xtoviewangle[MAX_SCREENWIDTH+1]; // killough 2/8/98 // killough 3/20/98: Support dynamic colormaps, e.g. deep water // killough 4/4/98: support dynamic number of them as well int numcolormaps; const lighttable_t *(*c_zlight)[LIGHTLEVELS][MAXLIGHTZ]; const lighttable_t *(*zlight)[MAXLIGHTZ]; const lighttable_t *fullcolormap; const lighttable_t **colormaps; // killough 3/20/98, 4/4/98: end dynamic colormaps int extralight; // bumped light from gun blasts // // R_PointOnSide // Traverse BSP (sub) tree, // check point against partition plane. // Returns side 0 (front) or 1 (back). // // killough 5/2/98: reformatted // PUREFUNC int R_PointOnSide(fixed_t x, fixed_t y, const node_t *node) { if (!node->dx) return x <= node->x ? node->dy > 0 : node->dy < 0; if (!node->dy) return y <= node->y ? node->dx < 0 : node->dx > 0; x -= node->x; y -= node->y; // Try to quickly decide by looking at sign bits. if ((node->dy ^ node->dx ^ x ^ y) < 0) return (node->dy ^ x) < 0; // (left is negative) return FixedMul(y, node->dx>>FRACBITS) >= FixedMul(node->dy>>FRACBITS, x); } // killough 5/2/98: reformatted PUREFUNC int R_PointOnSegSide(fixed_t x, fixed_t y, const seg_t *line) { fixed_t lx = line->v1->x; fixed_t ly = line->v1->y; fixed_t ldx = line->v2->x - lx; fixed_t ldy = line->v2->y - ly; if (!ldx) return x <= lx ? ldy > 0 : ldy < 0; if (!ldy) return y <= ly ? ldx < 0 : ldx > 0; x -= lx; y -= ly; // Try to quickly decide by looking at sign bits. if ((ldy ^ ldx ^ x ^ y) < 0) return (ldy ^ x) < 0; // (left is negative) return FixedMul(y, ldx>>FRACBITS) >= FixedMul(ldy>>FRACBITS, x); } // // R_PointToAngle // To get a global angle from cartesian coordinates, // the coordinates are flipped until they are in // the first octant of the coordinate system, then // the y (<=x) is scaled and divided by x to get a // tangent (slope) value which is looked up in the // tantoangle[] table. The +1 size of tantoangle[] // is to handle the case when x==y without additional // checking. // // killough 5/2/98: reformatted, cleaned up #include <math.h> angle_t R_PointToAngle(fixed_t x, fixed_t y) { static fixed_t oldx, oldy; static angle_t oldresult; x -= viewx; y -= viewy; if ( /* !render_precise && */ // e6y: here is where "slime trails" can SOMETIMES occur #ifdef GL_DOOM (V_GetMode() != VID_MODEGL) && #endif (x < INT_MAX/4 && x > -INT_MAX/4 && y < INT_MAX/4 && y > -INT_MAX/4) ) { // old R_PointToAngle return (x || y) ? x >= 0 ? y >= 0 ? (x > y) ? tantoangle[SlopeDiv(y,x)] : // octant 0 ANG90-1-tantoangle[SlopeDiv(x,y)] : // octant 1 x > (y = -y) ? 0-tantoangle[SlopeDiv(y,x)] : // octant 8 ANG270+tantoangle[SlopeDiv(x,y)] : // octant 7 y >= 0 ? (x = -x) > y ? ANG180-1-tantoangle[SlopeDiv(y,x)] : // octant 3 ANG90 + tantoangle[SlopeDiv(x,y)] : // octant 2 (x = -x) > (y = -y) ? ANG180+tantoangle[ SlopeDiv(y,x)] : // octant 4 ANG270-1-tantoangle[SlopeDiv(x,y)] : // octant 5 0; } // R_PointToAngleEx merged into R_PointToAngle // e6y: The precision of the code above is abysmal so use the CRT atan2 function instead! if (oldx != x || oldy != y) { oldx = x; oldy = y; oldresult = (int)(atan2(y, x) * ANG180/M_PI); } return oldresult; } angle_t R_PointToAngle2(fixed_t viewx, fixed_t viewy, fixed_t x, fixed_t y) { return (y -= viewy, (x -= viewx) || y) ? x >= 0 ? y >= 0 ? (x > y) ? tantoangle[SlopeDiv(y,x)] : // octant 0 ANG90-1-tantoangle[SlopeDiv(x,y)] : // octant 1 x > (y = -y) ? 0-tantoangle[SlopeDiv(y,x)] : // octant 8 ANG270+tantoangle[SlopeDiv(x,y)] : // octant 7 y >= 0 ? (x = -x) > y ? ANG180-1-tantoangle[SlopeDiv(y,x)] : // octant 3 ANG90 + tantoangle[SlopeDiv(x,y)] : // octant 2 (x = -x) > (y = -y) ? ANG180+tantoangle[ SlopeDiv(y,x)] : // octant 4 ANG270-1-tantoangle[SlopeDiv(x,y)] : // octant 5 0; } // // R_InitTextureMapping // // killough 5/2/98: reformatted static void R_InitTextureMapping (void) { register int i,x; fixed_t focallength; // Use tangent table to generate viewangletox: // viewangletox will give the next greatest x // after the view angle. // // Calc focallength // so FIELDOFVIEW angles covers SCREENWIDTH. focallength = FixedDiv(centerxfrac, finetangent[FINEANGLES/4+FIELDOFVIEW/2]); for (i=0 ; i<FINEANGLES/2 ; i++) { int t; if (finetangent[i] > FRACUNIT*2) t = -1; else if (finetangent[i] < -FRACUNIT*2) t = viewwidth+1; else { t = FixedMul(finetangent[i], focallength); t = (centerxfrac - t + FRACUNIT-1) >> FRACBITS; if (t < -1) t = -1; else if (t > viewwidth+1) t = viewwidth+1; } viewangletox[i] = t; } // Scan viewangletox[] to generate xtoviewangle[]: // xtoviewangle will give the smallest view angle // that maps to x. for (x=0; x<=viewwidth; x++) { for (i=0; viewangletox[i] > x; i++) ; xtoviewangle[x] = (i<<ANGLETOFINESHIFT)-ANG90; } // Take out the fencepost cases from viewangletox. for (i=0; i<FINEANGLES/2; i++) if (viewangletox[i] == -1) viewangletox[i] = 0; else if (viewangletox[i] == viewwidth+1) viewangletox[i] = viewwidth; clipangle = xtoviewangle[0]; } // // R_InitLightTables // #define DISTMAP 2 static void R_InitLightTables (void) { int i; // killough 4/4/98: dynamic colormaps c_zlight = malloc(sizeof(*c_zlight) * numcolormaps); // Calculate the light levels to use // for each level / distance combination. for (i=0; i< LIGHTLEVELS; i++) { int j, startmap = ((LIGHTLEVELS-1-i)*2)*NUMCOLORMAPS/LIGHTLEVELS; for (j=0; j<MAXLIGHTZ; j++) { // CPhipps - use 320 here instead of SCREENWIDTH, otherwise hires is // brighter than normal res int scale = FixedDiv ((320/2*FRACUNIT), (j+1)<<LIGHTZSHIFT); int t, level = startmap - (scale >>= LIGHTSCALESHIFT)/DISTMAP; if (level < 0) level = 0; else if (level >= NUMCOLORMAPS) level = NUMCOLORMAPS-1; // killough 3/20/98: Initialize multiple colormaps level *= 256; for (t=0; t<numcolormaps; t++) // killough 4/4/98 c_zlight[t][i][j] = colormaps[t] + level; } } } // // R_SetViewSize // Do not really change anything here, // because it might be in the middle of a refresh. // The change will take effect next refresh. // boolean setsizeneeded; int setblocks; void R_SetViewSize(int blocks) { setsizeneeded = true; setblocks = blocks; } // // R_ExecuteSetViewSize // void R_ExecuteSetViewSize (void) { int i; setsizeneeded = false; if (setblocks == 11) { scaledviewwidth = SCREENWIDTH; viewheight = SCREENHEIGHT; } // proff 09/24/98: Added for high-res else if (setblocks == 10) { scaledviewwidth = SCREENWIDTH; viewheight = SCREENHEIGHT-ST_SCALED_HEIGHT; } else { // proff 08/17/98: Changed for high-res scaledviewwidth = setblocks*SCREENWIDTH/10; viewheight = (setblocks*(SCREENHEIGHT-ST_SCALED_HEIGHT)/10) & ~7; } viewwidth = scaledviewwidth; viewheightfrac = viewheight<<FRACBITS;//e6y centery = viewheight/2; centerx = viewwidth/2; centerxfrac = centerx<<FRACBITS; centeryfrac = centery<<FRACBITS; projection = centerxfrac; // proff 11/06/98: Added for high-res projectiony = ((SCREENHEIGHT * centerx * 320) / 200) / SCREENWIDTH * FRACUNIT; R_InitBuffer (scaledviewwidth, viewheight); R_InitTextureMapping(); // psprite scales // proff 08/17/98: Changed for high-res pspritescale = FRACUNIT*viewwidth/320; pspriteiscale = FRACUNIT*320/viewwidth; // proff 11/06/98: Added for high-res pspriteyscale = (((SCREENHEIGHT*viewwidth)/SCREENWIDTH) << FRACBITS) / 200; // thing clipping for (i=0 ; i<viewwidth ; i++) screenheightarray[i] = viewheight; // planes for (i=0 ; i<viewheight ; i++) { // killough 5/2/98: reformatted fixed_t dy = D_abs(((i-viewheight/2)<<FRACBITS)+FRACUNIT/2); // proff 08/17/98: Changed for high-res yslope[i] = FixedDiv(projectiony, dy); } for (i=0 ; i<viewwidth ; i++) { fixed_t cosadj = D_abs(finecosine[xtoviewangle[i]>>ANGLETOFINESHIFT]); distscale[i] = FixedDiv(FRACUNIT,cosadj); } } // // R_Init // extern int screenblocks; void R_Init (void) { // CPhipps - R_DrawColumn isn't constant anymore, so must // initialise in code // current column draw function lprintf(LO_INFO, "\nR_LoadTrigTables: "); R_LoadTrigTables(); lprintf(LO_INFO, "\nR_InitData: "); R_InitData(); R_SetViewSize(screenblocks); lprintf(LO_INFO, "\nR_Init: R_InitPlanes "); R_InitPlanes(); lprintf(LO_INFO, "R_InitLightTables "); R_InitLightTables(); lprintf(LO_INFO, "R_InitSkyMap "); R_InitSkyMap(); lprintf(LO_INFO, "R_InitTranslationsTables "); R_InitTranslationTables(); lprintf(LO_INFO, "R_InitPatches "); R_InitPatches(); } // // R_PointInSubsector // // killough 5/2/98: reformatted, cleaned up subsector_t *R_PointInSubsector(fixed_t x, fixed_t y) { int nodenum = numnodes-1; // special case for trivial maps (single subsector, no nodes) if (numnodes == 0) return subsectors; while (!(nodenum & NF_SUBSECTOR)) nodenum = nodes[nodenum].children[R_PointOnSide(x, y, nodes+nodenum)]; return &subsectors[nodenum & ~NF_SUBSECTOR]; } // // R_SetupFrame // static void R_SetupFrame (player_t *player) { int cm; boolean NoInterpolate = paused || (menuactive && !demoplayback); viewplayer = player; if (player->mo != oviewer || NoInterpolate) { R_ResetViewInterpolation (); oviewer = player->mo; } tic_vars.frac = I_GetTimeFrac (); if (NoInterpolate) tic_vars.frac = FRACUNIT; R_InterpolateView (player, tic_vars.frac); extralight = player->extralight; viewsin = finesine[viewangle>>ANGLETOFINESHIFT]; viewcos = finecosine[viewangle>>ANGLETOFINESHIFT]; R_DoInterpolations(tic_vars.frac); // killough 3/20/98, 4/4/98: select colormap based on player status if (player->mo->subsector->sector->heightsec != -1) { const sector_t *s = player->mo->subsector->sector->heightsec + sectors; cm = viewz < s->floorheight ? s->bottommap : viewz > s->ceilingheight ? s->topmap : s->midmap; if (cm < 0 || cm > numcolormaps) cm = 0; } else cm = 0; fullcolormap = colormaps[cm]; zlight = c_zlight[cm]; if (player->fixedcolormap) { fixedcolormap = fullcolormap // killough 3/20/98: use fullcolormap + player->fixedcolormap*256*sizeof(lighttable_t); } else fixedcolormap = 0; validcount++; } int autodetect_hom = 0; // killough 2/7/98: HOM autodetection flag // // R_ShowStats // int rendered_visplanes, rendered_segs, rendered_vissprites; boolean rendering_stats; static void R_ShowStats(void) { //e6y #if 0 // requires abstraction e.g. src/*/i_system.c:I_GetTicks static unsigned int FPS_SavedTick = 0, FPS_FrameCount = 0; unsigned int tick = SDL_GetTicks(); FPS_FrameCount++; if(tick >= FPS_SavedTick + 1000) { doom_printf((V_GetMode() == VID_MODEGL) ?"Frame rate %d fps\nWalls %d, Flats %d, Sprites %d" :"Frame rate %d fps\nSegs %d, Visplanes %d, Sprites %d", 1000 * FPS_FrameCount / (tick - FPS_SavedTick), rendered_segs, rendered_visplanes, rendered_vissprites); FPS_SavedTick = tick; FPS_FrameCount = 0; } #else #define KEEPTIMES 10 static int keeptime[KEEPTIMES], showtime; int now = I_GetTime(); if (now - showtime > 35) { doom_printf((V_GetMode() == VID_MODEGL) ?"Frame rate %d fps\nWalls %d, Flats %d, Sprites %d" :"Frame rate %d fps\nSegs %d, Visplanes %d, Sprites %d", (35*KEEPTIMES)/(now - keeptime[0]), rendered_segs, rendered_visplanes, rendered_vissprites); showtime = now; } memmove(keeptime, keeptime+1, sizeof(keeptime[0]) * (KEEPTIMES-1)); keeptime[KEEPTIMES-1] = now; #endif //e6y } // // R_RenderView // void R_RenderPlayerView (player_t* player) { R_SetupFrame (player); // Clear buffers. R_ClearClipSegs (); R_ClearDrawSegs (); R_ClearPlanes (); R_ClearSprites (); rendered_segs = rendered_visplanes = 0; if (V_GetMode() == VID_MODEGL) { #ifdef GL_DOOM // proff 11/99: clear buffers gld_InitDrawScene(); if(!OMEGA_draw_overlay) { // proff 11/99: switch to perspective mode gld_StartDrawScene(); } #endif } else { if (autodetect_hom) { // killough 2/10/98: add flashing red HOM indicators unsigned char color=(gametic % 20) < 9 ? 0xb0 : 0; V_FillRect(0, viewwindowx, viewwindowy, viewwidth, viewheight, color); R_DrawViewBorder(); } } // The head node is the last node output. R_RenderBSPNode (numnodes-1); R_ResetColumnBuffer(); if (V_GetMode() != VID_MODEGL) R_DrawPlanes (); if (V_GetMode() != VID_MODEGL) { R_DrawMasked (); R_ResetColumnBuffer(); } if (V_GetMode() == VID_MODEGL) { #ifdef GL_DOOM if(!OMEGA_draw_overlay) { // proff 11/99: draw the scene gld_DrawScene(player); } // proff 11/99: finishing off gld_EndDrawScene(); #endif } if (rendering_stats) R_ShowStats(); R_RestoreInterpolations(); }
[ "[email protected]@2510cb4e-c5e7-ff21-45d9-53e416f016e0" ]
[ [ [ 1, 634 ] ] ]
56eae9f3cbbd174a6d12414fc4481ecb85933352
2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4
/OUAN/OUAN/Src/Graphics/RenderComponent/RenderComponentEntity.h
a14ec553f86b3fc27527320973b9a5d589fa61cd
[]
no_license
juanjmostazo/once-upon-a-night
9651dc4dcebef80f0475e2e61865193ad61edaaa
f8d5d3a62952c45093a94c8b073cbb70f8146a53
refs/heads/master
2020-05-28T05:45:17.386664
2010-10-06T12:49:50
2010-10-06T12:49:50
38,101,059
1
1
null
null
null
null
UTF-8
C++
false
false
4,534
h
#ifndef RenderComponentEntityH_H #define RenderComponentEntityH_H #include "RenderComponent.h" #include "../AnimationBlender/AnimationBlender.h" namespace OUAN { struct TTransitionData { std::string source; std::string target; AnimationBlender::TBlendingTransition blendType; float duration; //TODO: Allow definition of a map as well std::vector<std::string> sourceBlendMask; std::vector<std::string> targetBlendMask; }; typedef std::map<std::string,TTransitionData> TTransitionMap; struct TAnimationData { std::string name; bool loop; float timescale; TTransitionMap transitions; }; typedef std::map<std::string, TAnimationData> TAnimationStateMap; class RenderComponentEntity: public RenderComponent { private: Ogre::Entity * mEntity; AnimationBlender* mAnimationBlender; /// Map with the set of animation state pointers that are available for the entity, /// so they can be easily accessed. TAnimationStateMap mAnimations; /// This can be replaced with a mAnimations.empty() check bool mIsAnimated; std::vector<std::string> mDreamsMaterial; std::vector<std::string> mNightmaresMaterial; std::vector<std::string> mChangeWorldMaterial; Ogre::ColourValue mTintColour; std::map<int,std::string> mOldMaterials; public: RenderComponentEntity(const std::string& type=""); ~RenderComponentEntity(); void initAnimationBlender(const std::string& defaultAnimation); void destroyAnimationBlender(); bool isLoopingAnimation (const std::string& animationName); bool hasFinishedAnimation(const std::string& animationName); bool hasAnimationBlender() const; void changeAnimation(const std::string& anim); bool hasAnimation(const std::string& anim); void changeAnimation(const std::string& animation,AnimationBlender::TBlendingTransition transition, float duration, bool l=true, float timeScale=1.0); void setAnimationBlenderVertexKeyMap(const TKeyFrameMap& keyFrameMap); double getMaxBoundingBoxY(); Ogre::Entity * getEntity() const; void setEntity(Ogre::Entity *,bool existInDreams,bool existInNightmares); void setVisible(bool visible); bool isVisible(); void update(double elapsedTime); void initAnimations(std::vector<TRenderComponentEntityAnimParams> entityAnimParams); void setAnimationPosition(float pos); float getAnimationPosition() const; float getCurrentAnimationLength() const; Ogre::AnimationState* getCurrentAnimation() const; std::string getCurrentAnimationName() const; bool isAnimated() const; void attachGameObjectToBone(const std::string& boneName,GameObjectPtr gameObject); void detachGameObject(GameObjectPtr gameObject); void setMaterial(std::vector<std::string> & material); void setDreamsMaterials(); void setNightmaresMaterials(); void setChangeWorldMaterials(); void setChangeWorldFactor(double factor); void setNewMaterial(std::string material,bool existInDreams,bool existInNightmares); void applyTint(const Ogre::ColourValue& tintColour); void removeTint(); void setTintFactor(double tintFactor); bool isTintBeingApplied() const; void changeTexture(std::vector<std::string>& newTextures); //void prepareForNormalMapping(); }; class TRenderComponentEntityAnimParams: public TRenderComponentParameters{ public: TRenderComponentEntityAnimParams(); ~TRenderComponentEntityAnimParams(); std::string name; bool loop; float timescale; TTransitionMap transitions; }; class TRenderComponentSubEntityParameters: public TRenderComponentParameters { public: TRenderComponentSubEntityParameters(); ~TRenderComponentSubEntityParameters(); String material; bool visible; }; class TRenderComponentEntityParameters: public TRenderComponentParameters { public: TRenderComponentEntityParameters(); ~TRenderComponentEntityParameters(); String meshfile; bool castshadows; QueryFlags cameraCollisionType; bool prepareForNormalMapping; std::vector<TRenderComponentSubEntityParameters> tRenderComponentSubEntityParameters; std::vector<TRenderComponentEntityAnimParams> tRenderComponentEntityAnimParams; Ogre::uint8 queueID; bool mInitManualAnimations; std::string mManualAnimationName; std::string initialAnimation; std::string initialAnimationAlt; std::string initialAnimationAlt2; std::string initialAnimationAlt3; }; } #endif
[ "juanj.mostazo@1610d384-d83c-11de-a027-019ae363d039", "ithiliel@1610d384-d83c-11de-a027-019ae363d039", "wyern1@1610d384-d83c-11de-a027-019ae363d039" ]
[ [ [ 1, 4 ], [ 6, 8 ], [ 32, 35 ], [ 53, 57 ], [ 73, 73 ], [ 75, 75 ], [ 78, 78 ], [ 122, 139 ], [ 143, 143 ], [ 154, 157 ] ], [ [ 5, 5 ], [ 9, 19 ], [ 21, 31 ], [ 36, 45 ], [ 50, 52 ], [ 58, 64 ], [ 66, 70 ], [ 79, 82 ], [ 84, 90 ], [ 98, 98 ], [ 101, 121 ], [ 141, 141 ], [ 144, 144 ], [ 147, 152 ] ], [ [ 20, 20 ], [ 46, 49 ], [ 65, 65 ], [ 71, 72 ], [ 74, 74 ], [ 76, 77 ], [ 83, 83 ], [ 91, 97 ], [ 99, 100 ], [ 140, 140 ], [ 142, 142 ], [ 145, 146 ], [ 153, 153 ] ] ]
4778e4084499af339cab3de1f6d41612d650b2f9
4ed04c4f418f2404db1fb94363b30552623e53da
/TibiaTekBot Injected DLL/Core.cpp
b009cb81f562cdcb3f7185c67ba29341e5c462ee
[]
no_license
Cameri/tibiatekbot
5f8ff3629d0fd2153ee2657af193ba2bc7585411
f98695749224061ba13ab56e922efb8a971b6363
refs/heads/master
2020-05-25T12:05:39.437437
2009-05-29T23:46:21
2009-05-29T23:46:21
32,226,477
1
0
null
null
null
null
UTF-8
C++
false
false
20,153
cpp
#include "stdafx.h" #include <windows.h> #include <string> #include <list> #include "Constants.h" #include "Core.h" #include "Packet.h" #include "Battlelist.h" #ifdef _MANAGED #pragma managed(push, off) #endif using namespace std; #define MAX_TEXT 512 /* DisplayText. Credits for Displaying text goes to Stiju and Zionz. Thanks for the help!*/ Ctext texts[MAX_TEXT] = {0}; list<PlayerText> CreatureTexts; list<PlayerText> RemovedCreatures; //Used to save creatures in screen list<PlayerText> AddedCreatures; //BLAddress BLConsts; int PlayerCount = 0; int n_text=0; char g_Text[1024] = ""; int g_Red = 0; int g_Green = 0; int g_Blue = 0; int g_X = 0; int g_Y = 0; int g_Font = 1; /*Address are loaded from Constants.xml file */ bool FirstTime = true; inline bool InGame(){ return (*Consts::INGAME == 8); } inline bool PopupOpened() { return (*Consts::POPUP == 11); } bool ComparePlayerText(PlayerText first, PlayerText second) { if(first.CreatureId == second.CreatureId) { return true; } else { return false; } } int KeyboardEntriesCount = 0; KeyboardEntry *KeyboardEntries = NULL; bool KeyboardEnabled = false; bool KeyboardSayMode = false; KeyboardModifier KeyboardModifiers; void MyPrintName(int nSurface, int nX, int nY, int nFont, int nRed, int nGreen, int nBlue, char* lpText, int nAlign) { list<PlayerText>::iterator it; //Displaying Original Text PrintText(nSurface, nX, nY, nFont, nRed, nGreen, nBlue, lpText, nAlign); //Write text above player //Removing Creatures from CreatureTexts if (RemovedCreatures.size() > 0) { list<PlayerText>::iterator rit; for(rit=RemovedCreatures.begin(); rit!=RemovedCreatures.end(); ++rit) { for(it=CreatureTexts.begin(); it!=CreatureTexts.end(); ) { if ((*rit).CreatureId == (*it).CreatureId) { free((*it).DisplayText); it = CreatureTexts.erase(it); } else { it++; } } } RemovedCreatures.clear(); } //Taking new ones to the CreatureTexts if (AddedCreatures.size() > 0) { CreatureTexts.splice(CreatureTexts.end(), AddedCreatures); } DWORD *EntityID = (DWORD*)(lpText - 4); //Displaying texts for(it=CreatureTexts.begin(); it!=CreatureTexts.end(); ++it) { if (*EntityID == (*it).CreatureId) { PrintText(0x01, nX + (*it).RelativeX, nY + (*it).RelativeY, (*it).TextFont, (*it).cR, (*it).cG, (*it).cB, (*it).DisplayText, 0x00); } } } void MyPrintFps(int nSurface, int nX, int nY, int nFont, int nRed, int nGreen, int nBlue, char* lpText, int nAlign) { bool *fps = (bool*)Consts::ptrShowFPS; if(*fps == true) { PrintText(nSurface, nX, nY, nFont, nRed, nGreen, nBlue, lpText, nAlign); nY += 12; } for(int i=0; i<MAX_TEXT; i++){ if(!texts[i].used) continue; strcpy(g_Text,texts[i].text); g_Blue = texts[i].b; g_Green = texts[i].g; g_Red = texts[i].r; g_Y = texts[i].y; g_X = texts[i].x; g_Font = texts[i].font; PrintText(0x01, g_X, g_Y, g_Font, g_Red, g_Green, g_Blue, g_Text, 0x00); //0x01 Surface, 0x00 Align } } DWORD HookCall(DWORD dwAddress, DWORD dwFunction) { DWORD dwOldProtect, dwNewProtect, dwOldCall, dwNewCall; BYTE callByte[5] = {0xE8, 0x00, 0x00, 0x00, 0x00}; dwNewCall = dwFunction - dwAddress - 5; memcpy(&callByte[1], &dwNewCall, 4); VirtualProtectEx(GetCurrentProcess(), (LPVOID)(dwAddress), 5, PAGE_READWRITE, &dwOldProtect); memcpy(&dwOldCall, (LPVOID)(dwAddress+1), 4); memcpy((LPVOID)(dwAddress), &callByte, 5); VirtualProtectEx(GetCurrentProcess(), (LPVOID)(dwAddress), 5, dwOldProtect, &dwNewProtect); return dwOldCall; } void UnhookCall(DWORD dwAddress, DWORD dwOldCall) { DWORD dwOldProtect, dwNewProtect; BYTE callByte[5] = {0xE8, 0x00, 0x00, 0x00, 0x00}; memcpy(&callByte[1], &dwOldCall, 4); VirtualProtectEx(GetCurrentProcess(), (LPVOID)(dwAddress), 5, PAGE_READWRITE, &dwOldProtect); memcpy((LPVOID)(dwAddress), &callByte, 5); VirtualProtectEx(GetCurrentProcess(), (LPVOID)(dwAddress), 5, dwOldProtect, &dwNewProtect); } void Nop(DWORD dwAddress, int size) { DWORD dwOldProtect, dwNewProtect; VirtualProtectEx(GetCurrentProcess(), (LPVOID)(dwAddress), size, PAGE_READWRITE, &dwOldProtect); memset((LPVOID)(dwAddress), 0x90, size); VirtualProtectEx(GetCurrentProcess(), (LPVOID)(dwAddress), size, dwOldProtect, &dwNewProtect); } void SetText(unsigned int TextNum, bool enabled, int nX, int nY, int nRed, int nGreen, int nBlue, int font, string lpText) { if(TextNum > MAX_TEXT-1){return;} if(font<1 || font >4){return;} if(nRed > 0xFF || nRed < 0){return;} if(nGreen > 0xFF || nGreen < 0){return;} if(nBlue > 0xFF || nBlue < 0){return;} if(lpText.empty()){return;} if (texts[TextNum].text != NULL) { free(texts[TextNum].text); texts[TextNum].text = NULL; } texts[TextNum].text = (char*)malloc((lpText.size()+1)*sizeof(char)); //REMEMBER TO FREE THIS! strcpy(texts[TextNum].text, lpText.c_str()); texts[TextNum].r=nRed; texts[TextNum].g=nGreen; texts[TextNum].b=nBlue; texts[TextNum].x=nX; texts[TextNum].y=nY; texts[TextNum].used = enabled; texts[TextNum].font = font; } void __declspec(noreturn) UninjectSelf(HMODULE Module) { __asm { push -2 push 0 push Module mov eax, TerminateThread push eax mov eax, FreeLibrary jmp eax } } LRESULT __stdcall WindowProc(HWND hWnd, int uMsg, WPARAM wParam, LPARAM lParam){ static int i; switch (uMsg) { case WM_CHAR: { /* if (wParam == 'q'){ int t = 0x000001; CallWindowProc(WndProc, hWnd, WM_KEYDOWN, VK_SHIFT, t); t=0x000001; CallWindowProc(WndProc, hWnd, WM_KEYDOWN, VK_F1, t ); t=0xc0000001; CallWindowProc(WndProc, hWnd, WM_KEYUP, VK_F1,t ); t=0xc0000001; CallWindowProc(WndProc, hWnd, WM_KEYUP, VK_SHIFT, t); return 0; }*/ if (KeyboardEnabled && InGame() && !PopupOpened()) { if (!KeyboardSayMode){ switch(wParam) { case 0x0D: // ENTER { KeyboardSayMode = true; return 0; } case 0x02: case 0x03: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0B: case 0x0C: case 0x0E: case 0x0F: case 0x12: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x1A: case 0x1B: break; default: return 0; } } } } break; case WM_KEYUP: { switch (wParam){ case VK_CONTROL: KeyboardModifiers = (KeyboardModifier)(KeyboardModifiers & !KMCtrl); break; case VK_SHIFT: KeyboardModifiers = (KeyboardModifier)(KeyboardModifiers & !KMShift); break; case VK_MENU: KeyboardModifiers = (KeyboardModifier)(KeyboardModifiers & !KMAlt); break; } } break; case WM_KEYDOWN: { /* if (wParam == 'q'){ int t = 0x2A0001; CallWindowProc(WndProc, hWnd, WM_KEYDOWN, VK_SHIFT, t); t=0x3b0001; CallWindowProc(WndProc, hWnd, WM_KEYDOWN, VK_F1, t ); t=0xc03b0001; CallWindowProc(WndProc, hWnd, WM_KEYUP, VK_F1,t ); t=0xc02a0001; CallWindowProc(WndProc, hWnd, WM_KEYUP, VK_SHIFT, t); return 0; }*/ /*if (wParam == VK_F1){ char output[256]; FILE *fp = fopen("c:/test.txt","a+"); sprintf(output, "wParam=%x,lParam=%x\n", wParam, lParam); fprintf(fp, output); fclose(fp); break; //CallWindowProc(WndProc, hWnd, uMsg, wParam, lParam ); }*/ switch (wParam){ case VK_CONTROL: KeyboardModifiers = (KeyboardModifier)(KeyboardModifiers | KMCtrl); break; case VK_SHIFT: KeyboardModifiers = (KeyboardModifier)(KeyboardModifiers | KMShift); break; case VK_MENU: KeyboardModifiers = (KeyboardModifier)(KeyboardModifiers | KMAlt); break; } if (KeyboardEnabled && InGame() && !PopupOpened()){ if (KeyboardSayMode){ if (wParam == VK_ESCAPE){ KeyboardSayMode = false; return 0; } else if(wParam == VK_RETURN) { KeyboardSayMode = false; break; } } else { for (i=0;i<KeyboardEntriesCount;i++){ if (KeyboardEntries[i].OldVirtualKey == wParam && ((KeyboardModifier)(KeyboardEntries[i].OldModifier & 0x7) == KeyboardModifiers)){ if (KeyboardEntries[i].Kind == KEKPressKey){ if ((KeyboardEntries[i].NewModifier & KMCtrl) == KMCtrl) CallWindowProc(WndProc, hWnd, WM_KEYDOWN, VK_CONTROL, 0x00000001); if ((KeyboardEntries[i].NewModifier & KMShift) == KMShift) CallWindowProc(WndProc, hWnd, WM_KEYDOWN, VK_SHIFT, 0x00000001); if ((KeyboardEntries[i].NewModifier & KMAlt) == KMAlt) CallWindowProc(WndProc, hWnd, WM_KEYDOWN, VK_MENU, 0x00000001); CallWindowProc(WndProc, hWnd, WM_KEYDOWN, KeyboardEntries[i].NewVirtualKey, 0x00000001); CallWindowProc(WndProc, hWnd, WM_KEYUP, KeyboardEntries[i].NewVirtualKey, 0xC0000001); if ((KeyboardEntries[i].NewModifier & KMCtrl) == KMCtrl) CallWindowProc(WndProc, hWnd, WM_KEYUP, VK_CONTROL, 0xC0000001); if ((KeyboardEntries[i].NewModifier & KMShift) == KMShift) CallWindowProc(WndProc, hWnd, WM_KEYUP, VK_SHIFT, 0xC0000001); if ((KeyboardEntries[i].NewModifier & KMAlt) == KMAlt) CallWindowProc(WndProc, hWnd, WM_KEYUP, VK_MENU, 0xC0000001); } break; } } return 0; } } } break; } return CallWindowProc(WndProc, hWnd, uMsg, wParam, lParam ); } void PipeOnRead(){ int position=0; WORD len = 0; len = Packet::ReadWord(Buffer, &position); BYTE PacketID = Packet::ReadByte(Buffer, &position); switch (PacketID){ case 1: // Set Constant { string ConstantName = Packet::ReadString(Buffer, &position); if (ConstantName == "ptrInGame"){ Consts::INGAME = (const unsigned int*)Packet::ReadDWord(Buffer, &position); } else if (ConstantName == "ptrWASDPopup") { Consts::POPUP = (const unsigned int*)Packet::ReadDWord(Buffer, &position); } else if (ConstantName == "TibiaWindowHandle") { TibiaWindowHandle = (HWND)Packet::ReadDWord(Buffer, &position); } else if (ConstantName == "ptrBattlelistBegin") { Consts::ptrBattlelistBegin = (unsigned int*)Packet::ReadDWord(Buffer, &position); } else if (ConstantName == "ptrPrintName") { Consts::ptrPrintName = (DWORD)Packet::ReadDWord(Buffer, &position); } else if (ConstantName == "ptrPrintFPS") { Consts::ptrPrintFPS = (DWORD)Packet::ReadDWord(Buffer, &position); } else if (ConstantName == "ptrShowFPS") { Consts::ptrShowFPS = (DWORD)Packet::ReadDWord(Buffer, &position); } else if (ConstantName == "ptrPrintTextFunc") { PrintText = (_PrintText*)Packet::ReadDWord(Buffer, &position); } else if (ConstantName == "BLMax") { Consts::BLMax = (const int)Packet::ReadDWord(Buffer, &position); } else if (ConstantName == "BLDist") { Consts::BLDist = (const int)Packet::ReadDWord(Buffer, &position); } else if (ConstantName == "BLNameOffset") { Consts::BLNameOffset = (const int)Packet::ReadDWord(Buffer, &position); } else if (ConstantName == "BLLocationOffset") { Consts::BLLocationOffset = (const int)Packet::ReadDWord(Buffer, &position); } else if (ConstantName == "BLOnScreenOffset") { Consts::BLOnScreenOffset = (unsigned int)Packet::ReadDWord(Buffer, &position); } else if (ConstantName == "BLHPPercentOffset") { Consts::BLHPPercentOffset = (unsigned int)Packet::ReadDWord(Buffer, &position); } else if (ConstantName == "ptrCharX") { Consts::ptrCharX = (unsigned int*)Packet::ReadDWord(Buffer, &position); } else if (ConstantName == "ptrCharY") { Consts::ptrCharY = (unsigned int*)Packet::ReadDWord(Buffer, &position); } else if (ConstantName == "ptrCharZ") { Consts::ptrCharZ = (unsigned int*)Packet::ReadDWord(Buffer, &position); } else if (ConstantName == "ptrNopFPS") { Consts::ptrNopFPS = (DWORD)Packet::ReadDWord(Buffer, &position); } else if (ConstantName == "ptrCharacterID") { Consts::ptrCharacterID = (unsigned int*)Packet::ReadDWord(Buffer, &position); } } break; case 2: // Hook WND_PROC { BYTE Hook = Packet::ReadByte(Buffer, &position); if (Hook){ WndProc = (WNDPROC)SetWindowLongPtr(TibiaWindowHandle, GWLP_WNDPROC, (LONG)WindowProc); } else { SetWindowLongPtr(TibiaWindowHandle, GWLP_WNDPROC, (LONG)WndProc); } } break; case 3: // Testing { //Battlelist BL; //BL.Reset(); //if (Battlelist::FindByName(&BL, "Seymour")) { PlayerText Creature = {0}; Creature.cB = 0x55; Creature.cG = 0x55; Creature.cR = 0xFF; Creature.CreatureId = *Consts::ptrCharacterID;//(int)BL.ID(); Creature.DisplayText = "PWNS"; Creature.RelativeX = 0; Creature.RelativeY = -10; Creature.TextFont = 1; AddedCreatures.push_back(Creature); //} } break; case 4: // DisplayText { int TextId = Packet::ReadByte(Buffer, &position); int PosX = Packet::ReadWord(Buffer, &position); int PosY = Packet::ReadWord(Buffer, &position); int ColorRed = Packet::ReadWord(Buffer, &position); int ColorGreen = Packet::ReadWord(Buffer, &position); int ColorBlue = Packet::ReadWord(Buffer, &position); int Font = Packet::ReadWord(Buffer, &position); string Text = Packet::ReadString(Buffer, &position); //char *lpText = (char*)malloc((Text.size()+1)*sizeof(char)); //strcpy(lpText, Text.c_str()); SetText(TextId, true, PosX, PosY, ColorRed, ColorGreen, ColorBlue, Font, Text); } break; case 5: //RemoveText { int TextId = Packet::ReadByte(Buffer, &position); if(TextId < MAX_TEXT) { texts[TextId].used = false; if (texts[TextId].text != NULL) { free(texts[TextId].text); texts[TextId].text = NULL; } } } break; case 6: //Remove All { int i; for(i=0; i<MAX_TEXT; i++){ texts[i].used = false; if (texts[i].text != NULL) { free(texts[i].text); texts[i].text = NULL; } } } break; case 7: //Inject Display { BYTE Inject = Packet::ReadByte(Buffer, &position); if(Inject) { /* Testing that every constant have a value */ if(!Consts::ptrPrintFPS || !Consts::ptrPrintName || !Consts::ptrShowFPS) { MessageBoxA(0, "Error. All the constant doesn't contain a value", "Error", 0); break; } HookCall(Consts::ptrPrintName, (DWORD)&MyPrintName); HookCall(Consts::ptrPrintFPS, (DWORD)&MyPrintFps); Nop(Consts::ptrNopFPS, 6); //Showing the FPS all the time.. } else { //TODO Restore Calls } } break; case 8: // Keyboard Enable/Disable { BYTE enabled = Packet::ReadByte(Buffer, &position); KeyboardEnabled = (enabled == 1); KeyboardSayMode = false; } break; case 9: // Keyboard Populate VK Entries { int entries = Packet::ReadDWord(Buffer, &position); if (KeyboardEntries){ delete [] KeyboardEntries; } KeyboardEntries = new KeyboardEntry[entries]; int i; for (i=0;i<entries;i++){ KeyboardEntries[i].Kind = (KeyboardEntryKind)Packet::ReadByte(Buffer, &position); KeyboardEntries[i].NewVirtualKey = Packet::ReadByte(Buffer, &position); KeyboardEntries[i].OldVirtualKey = Packet::ReadByte(Buffer, &position); KeyboardEntries[i].NewModifier = (KeyboardModifier)Packet::ReadByte(Buffer, &position); KeyboardEntries[i].OldModifier = (KeyboardModifier)Packet::ReadByte(Buffer, &position); } KeyboardEntriesCount = entries; } break; case 0xA: //Set Text Above Creature { int Id = Packet::ReadDWord(Buffer, &position); int nX = Packet::ReadWord(Buffer, &position); int nY = Packet::ReadWord(Buffer, &position); int Pos = Packet::ReadWord(Buffer, &position); int ColorR = Packet::ReadWord(Buffer, &position); int ColorG = Packet::ReadWord(Buffer, &position); int ColorB = Packet::ReadWord(Buffer, &position); int TxtFont = Packet::ReadWord(Buffer, &position); string Text = Packet::ReadString(Buffer, &position); char *lpText = (char*)calloc(Text.size() + 1, sizeof(char)); strcpy(lpText, Text.c_str()); PlayerText Creature = {0}; Creature.cB = ColorB; Creature.cG = ColorG; Creature.cR = ColorR; Creature.CreatureId = Id; Creature.DisplayText = lpText; Creature.RelativeX = nX; if (Pos) { Creature.RelativeY = nY; } else { Creature.RelativeY = -nY; } Creature.TextFont = TxtFont; AddedCreatures.push_back(Creature); } break; case 0xB: //Remove Text Above Creature { int Id = Packet::ReadDWord(Buffer, &position); PlayerText RCreature = {0}; RCreature.CreatureId = Id; RemovedCreatures.push_back(RCreature); } break; case 0xC: //Update Text Above Creature { int ID = Packet::ReadDWord(Buffer, &position); int PosX = Packet::ReadWord(Buffer, &position); int PosY = Packet::ReadWord(Buffer, &position); int Dir = Packet::ReadWord(Buffer, &position); string NewText = Packet::ReadString(Buffer, &position); char *lpNewText = (char*)calloc(NewText.size() + 1, sizeof(char)); char *OldText; strcpy(lpNewText, NewText.c_str()); list<PlayerText>::iterator newit; if (!Dir) { PosY = -PosY; } for(newit = CreatureTexts.begin(); newit != CreatureTexts.end(); ++newit) { /*char asd[205], dsa[205]; sprintf(asd, "ID: %d X: %d Y: %d", newit->CreatureId, newit->RelativeX, newit->RelativeY); sprintf(dsa, "ID: %d X: %d Y: %d", ID, PosX, PosY); MessageBoxA(0, asd, "List", 0); MessageBoxA(0, dsa, "Packet", 0);*/ if (newit->CreatureId == ID && newit->RelativeX == PosX && newit->RelativeY == PosY) { OldText = newit->DisplayText; strcpy(OldText, ""); newit->DisplayText = lpNewText; free(OldText); break; } } } break; } } void PipeThreadProc(HMODULE Module){ DWORD br; if (WaitNamedPipeA(PipeName.c_str(), NMPWAIT_WAIT_FOREVER)) { PipeHandle = CreateFileA(PipeName.c_str(), GENERIC_READ | GENERIC_WRITE , 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); PipeConnected = PipeHandle > 0; if (!PipeConnected){ MessageBoxA(0, "Pipe connection failed!", "TibiaTekBot Injected DLL - Fatal Error", MB_ICONERROR); return; } else { do { EnterCriticalSection(&PipeReadCriticalSection); if (!ReadFile(PipeHandle, Buffer, 1024, &br, NULL)) break; PipeOnRead(); LeaveCriticalSection(&PipeReadCriticalSection); } while (true); } } else { MessageBoxA(0, "Failed waiting for pipe, maybe pipe is not ready?.", "TibiaTekBot Injected DLL - Fatal Error", 0); } } extern "C" bool APIENTRY DllMain (HMODULE hModule, DWORD reason, LPVOID reserved){ switch (reason){ case DLL_PROCESS_ATTACH: { hMod = hModule; string CmdArgs = GetCommandLineA(); int pos = CmdArgs.find("-pipe:"); PipeName = "\\\\.\\pipe\\ttb" + CmdArgs.substr(pos + 6, 5); InitializeCriticalSection(&PipeReadCriticalSection); PipeConnected=false; PipeThread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)PipeThreadProc, hMod, NULL, NULL); } break; case DLL_PROCESS_DETACH: { TerminateThread(PipeThread, EXIT_SUCCESS); DeleteCriticalSection(&PipeReadCriticalSection); } break; } return true; }
[ "cameri2005@33ddfa00-593a-0410-b0c9-7b4335ea722e", "Cameri2005@33ddfa00-593a-0410-b0c9-7b4335ea722e", "oskari.virtanen@33ddfa00-593a-0410-b0c9-7b4335ea722e" ]
[ [ [ 1, 2 ], [ 5, 7 ], [ 9, 13 ], [ 15, 15 ], [ 23, 23 ], [ 36, 36 ], [ 39, 42 ], [ 51, 56 ], [ 59, 60 ], [ 183, 196 ], [ 198, 327 ], [ 329, 331 ], [ 335, 336 ], [ 340, 340 ], [ 342, 342 ], [ 344, 344 ], [ 346, 346 ], [ 348, 348 ], [ 358, 358 ], [ 360, 368 ], [ 370, 370 ], [ 372, 372 ], [ 374, 374 ], [ 379, 381 ], [ 384, 384 ], [ 387, 387 ], [ 389, 390 ], [ 392, 392 ], [ 413, 421 ], [ 430, 430 ], [ 432, 432 ], [ 469, 493 ], [ 564, 565 ], [ 572, 572 ], [ 584, 584 ], [ 587, 590 ], [ 594, 594 ], [ 603, 603 ], [ 610, 610 ], [ 612, 612 ] ], [ [ 3, 3 ], [ 14, 14 ], [ 197, 197 ], [ 328, 328 ], [ 332, 334 ], [ 337, 339 ], [ 341, 341 ], [ 343, 343 ], [ 345, 345 ], [ 382, 383 ], [ 385, 386 ], [ 388, 388 ], [ 391, 391 ], [ 393, 393 ], [ 409, 410 ], [ 563, 563 ], [ 566, 571 ], [ 573, 583 ], [ 585, 586 ], [ 591, 593 ], [ 597, 600 ], [ 604, 609 ], [ 611, 611 ] ], [ [ 4, 4 ], [ 8, 8 ], [ 16, 22 ], [ 24, 35 ], [ 37, 38 ], [ 43, 50 ], [ 57, 58 ], [ 61, 182 ], [ 347, 347 ], [ 349, 357 ], [ 359, 359 ], [ 369, 369 ], [ 371, 371 ], [ 373, 373 ], [ 375, 378 ], [ 394, 408 ], [ 411, 412 ], [ 422, 429 ], [ 431, 431 ], [ 433, 468 ], [ 494, 562 ], [ 595, 596 ], [ 601, 602 ] ] ]
f7f39791df9b2e8513559d0f9391880f101d2b04
7209e143b701bf83b10f09f334ea7bf7b08d790b
/src/zbuilding.cpp
92b05f68ec6f029f1f77de7fcf3fcc81abf69237
[]
no_license
sebhd/zod
755356b11efb2c7cd861b04e09ccf5ba1ec7ac2e
396e2231334af7eada1b41af5aaff065b6235e94
refs/heads/master
2018-12-28T09:04:04.762895
2011-09-30T08:48:16
2011-09-30T08:48:16
2,469,497
5
0
null
null
null
null
UTF-8
C++
false
false
15,953
cpp
#include "zbuilding.h" #include "zfont_engine.h" #include "zcannon.h" ZSDL_Surface ZBuilding::level_img[MAX_BUILDING_LEVELS]; ZSDL_Surface ZBuilding::exhaust[13]; ZSDL_Surface ZBuilding::little_exhaust[4]; ZBuilding::ZBuilding(ZTime *ztime_, ZSettings *zsettings_, planet_type palette_) : ZObject(ztime_, zsettings_) { object_name = "building"; destroyed = false; palette = palette_; level = 0; m_object_type = BUILDING_OBJECT; bot = -1; boid = -1; can_be_destroyed = false; zone_ownage = 0; attacked_by_explosives = true; do_base_rerender = true; //default build_state = BUILDING_SELECT; //some defaults unit_create_x = 32; unit_create_y = 32; unit_move_x = 32; unit_move_y = 112; //more defaults effects_box.x = 16; effects_box.y = 16; effects_box.w = 32; effects_box.h = 32; max_effects = 8; show_time = -1; //show_time_img = NULL; } ZBuilding::~ZBuilding() { //no memory leaks for (vector<EStandard*>::iterator i = extra_effects.begin(); i != extra_effects.begin(); i++) delete *i; extra_effects.clear(); } void ZBuilding::Init() { int i; char filename[500]; for (i = 0; i < MAX_BUILDING_LEVELS; i++) { sprintf(filename, "assets/buildings/level_%d.bmp", i + 1); level_img[i].LoadBaseImage(filename); // = IMG_Load_Error(filename); } for (i = 0; i < 13; i++) { sprintf(filename, "assets/buildings/exhaust_%d.png", i); exhaust[i].LoadBaseImage(filename); // = IMG_Load_Error(filename); } for (i = 0; i < 4; i++) { sprintf(filename, "assets/buildings/little_exhaust_%d.png", i); little_exhaust[i].LoadBaseImage(filename); // = IMG_Load_Error(filename); } } int ZBuilding::GetBuildState() { //if (gameCore->IsUnitLimitReached()[owner]) { if (unit_limit_reached[owner]) { return BUILDING_PAUSED; } else { return build_state; } } int ZBuilding::GetLevel() { return level; } void ZBuilding::ChangePalette(planet_type palette_) { palette = palette_; } void ZBuilding::ReRenderBase() { do_base_rerender = true; } bool ZBuilding::SetBuildingDefaultProduction() { unsigned char ot, oid; if (bot == (unsigned char) -1 && boid == (unsigned char) -1 && build_state == BUILDING_SELECT) { if (buildlist->GetFirstUnitInBuildList(m_object_id, level, ot, oid)) return SetBuildingProduction(ot, oid); else return false; } else return false; } bool ZBuilding::SetBuildingProduction(unsigned char ot, unsigned char oid) { double &the_time = ztime->ztime; if (owner == NULL_TEAM) return false; //produces units? if (!ProducesUnits()) return false; //we already building it? if (ot == bot && oid == boid) return false; //is this unit available to be produced here? if (!buildlist->UnitInBuildList(m_object_id, level, ot, oid)) return false; //set this building to be producing this unit //with the correct building time bot = ot; boid = oid; build_state = BUILDING_BUILDING; binit_time = the_time; RecalcBuildTime(); //bfinal_time = binit_time + buildlist->UnitBuildTime(bot, boid); //add to queue list? if (!queue_list.size()) AddBuildingQueue(ot, oid); return true; } void ZBuilding::SetBuildList(ZBuildList *buildlist_) { buildlist = buildlist_; } bool ZBuilding::AddBuildingQueue(unsigned char ot, unsigned char oid, bool push_to_front) { if (owner == NULL_TEAM) { printf("Owner is NULL_TEAM\n"); return false; } //produces units? if (!ProducesUnits()) { printf("Building does not produce units"); return false; } //already maxed out? if (queue_list.size() >= MAX_QUEUE_ITEMS) { printf("Queue list is full"); return false; } //is this unit available to be produced here? if (!buildlist->UnitInBuildList(m_object_id, level, ot, oid)) { printf("Unit cannot be produced here"); return false; } //printf("ZBuilding::AddBuildingQueue::adding %d %d\n", ot, oid); //add it.. if (push_to_front) queue_list.insert(queue_list.begin(), ZBProductionUnit(ot, oid)); else queue_list.push_back(ZBProductionUnit(ot, oid)); return true; } bool ZBuilding::CancelBuildingQueue(int list_i, unsigned char ot, unsigned char oid) { if (owner == NULL_TEAM) return false; //produces units? if (!ProducesUnits()) return false; //list_i ok? if (list_i < 0) return false; if (list_i >= queue_list.size()) return false; //ot and oid match? if (ot != queue_list[list_i].ot) return false; if (oid != queue_list[list_i].oid) return false; //erase it queue_list.erase(queue_list.begin() + list_i); return true; } void ZBuilding::CreateBuildingQueueData(char *&data, int &size) { int queue_amount; char *message; data = NULL; size = 0; //produces units? if (!ProducesUnits()) return; queue_amount = queue_list.size(); //make mem size = 8 + (queue_amount * sizeof(ZBProductionUnit)); data = message = (char*) malloc(size); //push header, the ref id of this object and the number of waypoints ((int*) message)[0] = ref_id; ((int*) message)[1] = queue_amount; //populate message += 8; for (vector<ZBProductionUnit>::iterator j = queue_list.begin(); j != queue_list.end(); j++) { memcpy(message, &(*j), sizeof(ZBProductionUnit)); message += sizeof(ZBProductionUnit); } } void ZBuilding::ProcessBuildingQueueData(char *data, int size) { int expected_packet_size; int queue_amount; int data_ref_id; ZObject *our_object; //produces units? if (!ProducesUnits()) return; //does it hold the header info? if (size < 8) return; //get header data_ref_id = ((int*) data)[0]; queue_amount = ((int*) data)[1]; expected_packet_size = 8 + (queue_amount * sizeof(ZBProductionUnit)); //should we toss this bad data? if (size != expected_packet_size) return; //not our ref_id... ? if (ref_id != data_ref_id) { printf("ZBuilding::ProcessBuildingQueueData::ref_id's do not match %d vs %d\n", ref_id, data_ref_id); return; } //clear list queue_list.clear(); //begin the push data += 8; for (int i = 0; i < queue_amount; i++) { ZBProductionUnit new_unit; memcpy(&new_unit, data, sizeof(ZBProductionUnit)); //add if (!AddBuildingQueue(new_unit.ot, new_unit.oid, false)) printf("ZBuilding::ProcessBuildingQueueData::could not add unit %d:%d %d\n", i, new_unit.ot, new_unit.oid); data += sizeof(ZBProductionUnit); } //debug //printf("ZBuilding::ProcessBuildingQueueData::queue list now %d:", queue_list.size()); //for(vector<ZBProductionUnit>::iterator j=queue_list.begin(); j!=queue_list.end();j++) // printf("%d %d, ", j->ot, j->oid); //printf("\n"); } bool ZBuilding::StopBuildingProduction(bool clear_queue_list) { if (bot == (unsigned char) -1 && boid == (unsigned char) -1 && build_state == BUILDING_SELECT) return false; build_state = BUILDING_SELECT; bot = -1; boid = -1; //also clear the queue_list if (clear_queue_list) queue_list.clear(); return true; } void ZBuilding::CreateBuiltCannonData(char *&data, int &size) { size = 8 + built_cannon_list.size(); data = (char*) malloc(size); *(int*) (data) = ref_id; *(int*) (data + 4) = built_cannon_list.size(); for (int i = 0; i < built_cannon_list.size(); i++) { *(char*) (data + 8 + i) = built_cannon_list[i]; //printf("storing cannon:%d\n", built_cannon_list[i]); } } void ZBuilding::ProcessSetBuiltCannonData(char *data, int size) { int cannon_amt; //bad data? if (size < 8) return; cannon_amt = *(int*) (data + 4); //bad data? if (size - 8 != cannon_amt) return; //set cannon placement list built_cannon_list.clear(); for (int i = 0; i < cannon_amt; i++) { built_cannon_list.push_back(*(unsigned char*) (data + 8 + i)); //printf("client cannon:%d\n", built_cannon_list[i]); } } void ZBuilding::CreateBuildingStateData(char *&data, int &size) { double &the_time = ztime->ztime; size = sizeof(set_building_state_packet); data = (char*) malloc(size); set_building_state_packet *pi = (set_building_state_packet*) data; pi->ref_id = ref_id; pi->state = build_state; pi->ot = bot; pi->oid = boid; pi->prod_time = bfinal_time - binit_time; pi->init_offset = binit_time - the_time; } void ZBuilding::ProcessSetBuildingStateData(char *data, int size) { double &the_time = ztime->ztime; set_building_state_packet *pi = (set_building_state_packet*) data; ZObject *obj; //good packet? if (size != sizeof(set_building_state_packet)) return; //haha. if (ref_id != pi->ref_id) return; build_state = pi->state; bot = pi->ot; boid = pi->oid; binit_time = the_time + pi->init_offset; bfinal_time = binit_time + pi->prod_time; } double ZBuilding::PercentageProduced(double &the_time) { double the_percentage; the_percentage = (the_time - binit_time) / (bfinal_time - binit_time); if (the_percentage < 0) the_percentage = 0; if (the_percentage > 1) the_percentage = 1; return the_percentage; } double ZBuilding::ProductionTimeLeft(double &the_time) { double time_left; time_left = bfinal_time - the_time; if (time_left < 0) time_left = 0; return time_left; } bool ZBuilding::GetBuildingCreationPoint(int &x, int &y) { x = loc.x + unit_create_x; y = loc.y + unit_create_y; return true; } bool ZBuilding::GetBuildingCreationMovePoint(int &x, int &y) { x = loc.x + unit_move_x; y = loc.y + unit_move_y; return true; } bool ZBuilding::BuildUnit(double &the_time, unsigned char &ot, unsigned char &oid) { if (bot == (unsigned char) -1) return false; if (boid == (unsigned char) -1) return false; if (build_state == BUILDING_SELECT) return false; if (owner == NULL_TEAM) return false; if (the_time >= bfinal_time && !unit_limit_reached[owner]) { //if (the_time >= bfinal_time && !gameCore->IsUnitLimitReached()[owner]) { ot = bot; oid = boid; return true; } return false; } bool ZBuilding::StoreBuiltCannon(unsigned char oid) { //already full? if (built_cannon_list.size() >= MAX_STORED_CANNONS) return false; printf("cannon stored\n"); built_cannon_list.push_back(oid); return true; } int ZBuilding::CannonsInZone(ZOLists &ols) { //the zbuilding version starts with built_cannon_list.size() int cannons_found = built_cannon_list.size(); for (vector<ZObject*>::iterator i = ols.object_list->begin(); i != ols.object_list->end(); i++) { if (this != *i && connected_zone == (*i)->GetConnectedZone()) { unsigned char ot, oid; (*i)->GetObjectID(ot, oid); //collect in cannons that other buildings have not yet placed ZBuilding* building = dynamic_cast<ZBuilding*>(*i); if (building) { cannons_found += building->GetBuiltCannonList().size(); } ZCannon* cannon = dynamic_cast<ZCannon*>(*i); if (cannon) { cannons_found++; } } } return cannons_found; } bool ZBuilding::RemoveStoredCannon(unsigned char oid) { //find it for (vector<unsigned char>::iterator i = built_cannon_list.begin(); i != built_cannon_list.end(); i++) if (oid == *i) { built_cannon_list.erase(i); return true; } return false; } bool ZBuilding::HaveStoredCannon(unsigned char oid) { //find it for (vector<unsigned char>::iterator i = built_cannon_list.begin(); i != built_cannon_list.end(); i++) { if (oid == *i) { return true; } } return false; } void ZBuilding::ResetProduction() { double &the_time = ztime->ztime; if (queue_list.size()) { unsigned char ot, oid; ot = queue_list.begin()->ot; oid = queue_list.begin()->oid; //take this off the list queue_list.erase(queue_list.begin()); //clear current production StopBuildingProduction(false); //start new SetBuildingProduction(ot, oid); } else { StopBuildingProduction(); } //before queue list //binit_time = the_time; //RecalcBuildTime(); } bool ZBuilding::GetBuildUnit(unsigned char &ot, unsigned char &oid) { ot = bot; oid = boid; return true; } void ZBuilding::ResetShowTime(int new_time) { int minutes, seconds; char message[50]; if (new_time == show_time) return; show_time_img.Unload(); //if(show_time_img) //{ // SDL_FreeSurface(show_time_img); // show_time_img = NULL; //} if (new_time > -1) { show_time = new_time; //setup these numbers seconds = new_time % 60; new_time /= 60; minutes = new_time % 60; sprintf(message, "%d:%02d", minutes, seconds); show_time_img.LoadBaseImage(ZFontEngine::GetFont(GREEN_BUILDING_FONT).Render(message)); } } void ZBuilding::SetOwner(team_type owner_) { owner = owner_; do_base_rerender = true; } vector<unsigned char> &ZBuilding::GetBuiltCannonList() { return built_cannon_list; } void ZBuilding::SetLevel(int level_) { level = level_; } void ZBuilding::DoDeathEffect(bool do_fire_death, bool do_missile_death) { do_base_rerender = true; } void ZBuilding::DoReviveEffect() { do_base_rerender = true; //no memory leaks for (vector<EStandard*>::iterator i = extra_effects.begin(); i != extra_effects.begin(); i++) delete *i; extra_effects.clear(); } void ZBuilding::ProcessBuildingsEffects(double &the_time) { double damage_percent; int should_effects; bool effects_added = false; for (vector<EStandard*>::iterator i = extra_effects.begin(); i != extra_effects.end(); i++) (*i)->Process(); damage_percent = 1.0 * health / max_health; if (damage_percent > 1) damage_percent = 1; if (damage_percent < 0) damage_percent = 0; should_effects = max_effects * (1 - damage_percent); //if(should_effects) printf("should_effects:%d size:%d\n", should_effects, extra_effects.size()); for (int i = extra_effects.size(); i < should_effects; i++) { int ex, ey; int choice; ex = loc.x + effects_box.x + (rand() % effects_box.w); ey = loc.y + effects_box.y + (rand() % effects_box.h); choice = rand() % 100; if (choice < 10) extra_effects.push_back(new EStandard(ztime, ex, ey, EDEATH_BIG_SMOKE)); else if (choice < 20) extra_effects.push_back(new EStandard(ztime, ex, ey, EDEATH_SMALL_FIRE_SMOKE)); else if (choice < 50) extra_effects.push_back(new EStandard(ztime, ex, ey, EDEATH_FIRE)); else extra_effects.push_back(new EStandard(ztime, ex, ey, EDEATH_LITTLE_FIRE)); effects_added = true; } //sort effects if (effects_added) sort(extra_effects.begin(), extra_effects.end(), sort_estandards_func); } bool ZBuilding::ResetBuildTime(float zone_ownage_) { if (zone_ownage_ == zone_ownage) return false; zone_ownage = zone_ownage_; if (zone_ownage > 1) zone_ownage = 1; if (zone_ownage < 0) zone_ownage = 0; return RecalcBuildTime(); } bool ZBuilding::RecalcBuildTime() { double bfinal_time_old; double build_time; bfinal_time_old = bfinal_time; //calc if (!buildlist) return false; if (bot == (unsigned char) -1) return false; if (boid == (unsigned char) -1) return false; if (build_state == BUILDING_SELECT) return false; //base time build_time = BuildTimeModified(buildlist->UnitBuildTime(bot, boid)); //do effect from zone ownage //build_time = build_time - (build_time * 0.5 * zone_ownage); //do effect from building health //build_time += BuildTimeIncrease(build_time);//build_time * (1.25 * (1.0 - (1.0 * health / max_health))); bfinal_time = binit_time + build_time; return bfinal_time_old != bfinal_time; } double ZBuilding::BuildTimeModified(double base_build_time) { base_build_time -= base_build_time * 0.5 * zone_ownage; base_build_time += base_build_time * (1.25 * (1.0 - (1.0 * health / max_health))); return base_build_time; }
[ "sebastian@T61p" ]
[ [ [ 1, 680 ] ] ]
c21cd026b83295c6e73f2c756ab0172075619b31
b5ad65ebe6a1148716115e1faab31b5f0de1b493
/src/AranIk_Test/BwOpenGlWindow.cpp
bb3c7357df8fb6a9b6eeb52e5bb006268a1c030b
[]
no_license
gasbank/aran
4360e3536185dcc0b364d8de84b34ae3a5f0855c
01908cd36612379ade220cc09783bc7366c80961
refs/heads/master
2021-05-01T01:16:19.815088
2011-03-01T05:21:38
2011-03-01T05:21:38
1,051,010
1
0
null
null
null
null
UTF-8
C++
false
false
22,885
cpp
#include "BwPch.h" #include "BwOpenGlWindow.h" #include "BwAppContext.h" #include <IL/il.h> #if _MSC_VER #define snprintf _snprintf #endif static void SelectGraphicObject(BwAppContext& ac, const float mousePx, const float mousePy); static void RenderScene(const BwAppContext& ac); static void RenderHud(const BwAppContext& ac); BwOpenGlWindow::BwOpenGlWindow(int x, int y, int w, int h, const char *l, BwAppContext& ac) : Fl_Gl_Window(x, y, w, h, l) , m_ac(ac) , m_drag(false) , m_cam_r(10.0) , m_cam_phi(0) , m_cam_dphi(0) , m_cam_theta(0) , m_cam_dtheta(0) , m_screenshot_fbyf(false) { sides = overlay_sides = 3; m_ac.windowWidth = w; m_ac.windowHeight = h; m_ac.avd.Width = m_ac.windowWidth; m_ac.avd.Height = m_ac.windowHeight; m_cam_cen[0] = 1; m_cam_cen[1] = 1; m_cam_cen[2] = 0; } BwOpenGlWindow::~BwOpenGlWindow() { } void BwOpenGlWindow::setCamCen(double cx, double cy, double cz) { m_cam_cen[0] = cx; m_cam_cen[1] = cy; m_cam_cen[2] = cz; } void BwOpenGlWindow::resize( int x, int y, int w, int h ) { m_ac.windowWidth = w; m_ac.windowHeight = h; m_ac.avd.Width = m_ac.windowWidth; m_ac.avd.Height = m_ac.windowHeight; //printf("Resized OpenGL widget size is %d x %d.\n", m_ac.windowWidth, m_ac.windowHeight); Fl_Gl_Window::resize(x, y, w, h); } void pym_sphere_to_cartesian(double *c, double r, double phi, double theta) { c[0] = r*sin(theta)*sin(phi); c[1] = -r*sin(theta)*cos(phi); c[2] = r*cos(theta); } static void pym_cross3(double *u, const double *const a, const double *const b) { u[0] = a[1]*b[2] - a[2]*b[1]; u[1] = a[2]*b[0] - a[0]*b[2]; u[2] = a[0]*b[1] - a[1]*b[0]; } void pym_up_dir_from_sphere(double *u, const double *const cam_car, double r, double phi, double theta) { const double left[3] = { -cos(phi), -sin(phi), 0 }; const double look_dir[3] = { -cam_car[0]/r, -cam_car[1]/r, -cam_car[2]/r }; pym_cross3(u, look_dir, left); } void PymLookUpLeft(double *look, double *up, double *left, double r, double phi, double theta) { double cam_car[3]; pym_sphere_to_cartesian(cam_car, r, phi, theta); left[0] = -cos(phi); left[1] = -sin(phi); left[2] = 0; look[0] = -cam_car[0]/r; look[1] = -cam_car[1]/r; look[2] = -cam_car[2]/r; pym_cross3(up, look, left); } void BwOpenGlWindow::draw() { // the valid() property may be used to avoid reinitializing your // GL transformation for each redraw: if (!valid()) { valid(1); glLoadIdentity(); glViewport(0, 0, w(), h()); } if (m_ac.activeCam) { //m_cam_r = ArnVec3Length(m_ac.activeCam->getCameraData().pos); m_cam_r = 5; double rc_cam_r = m_cam_r; double rc_cam_phi = m_cam_phi + m_cam_dphi; double rc_cam_theta = m_cam_theta + m_cam_dtheta; double rc_cam_cen[3]; rc_cam_cen[0] = m_cam_cen[0]; rc_cam_cen[1] = m_cam_cen[1]; rc_cam_cen[2] = m_cam_cen[2]; double cam_car[3]; /* Cartesian coordinate of cam */ double up_dir[3]; double right_dir[3]; double cam_car_nor[3]; pym_sphere_to_cartesian(cam_car, rc_cam_r, rc_cam_phi, rc_cam_theta); /* printf("cam_car = %lf %lf %lf\n", */ /* cam_car[0], cam_car[1], cam_car[2]); */ pym_up_dir_from_sphere(up_dir, cam_car, rc_cam_r, rc_cam_phi, rc_cam_theta); cam_car_nor[0] = cam_car[0] / m_cam_r; cam_car_nor[1] = cam_car[1] / m_cam_r; cam_car_nor[2] = cam_car[2] / m_cam_r; pym_cross3(right_dir, up_dir, cam_car_nor); ArnMatrix cam_mat( right_dir[0], up_dir[0], cam_car_nor[0], rc_cam_cen[0]+cam_car[0], right_dir[1], up_dir[1], cam_car_nor[1], rc_cam_cen[1]+cam_car[1], right_dir[2], up_dir[2], cam_car_nor[2], rc_cam_cen[2]+cam_car[2], 0, 0, 0, 1); m_ac.activeCam->setLocalXform(cam_mat); } RenderScene(m_ac); /* Check for error conditions. */ GLenum gl_error = glGetError(); if( gl_error != GL_NO_ERROR ) { fprintf( stderr, "ARAN: OpenGL error: %s\n", gluErrorString(gl_error) ); abort(); } } void BwOpenGlWindow::handle_push() { const int mouseX = Fl::event_x(); const int mouseY = Fl::event_y(); m_dragX = mouseX; m_dragY = mouseY; m_drag = true; SelectGraphicObject(m_ac, float(mouseX), float(m_ac.avd.Height - mouseY) // Note that Y-coord flipped. ); if (m_ac.sgPtr) { ArnMatrix modelview, projection; glGetFloatv(GL_MODELVIEW_MATRIX, reinterpret_cast<GLfloat*>(modelview.m)); modelview = modelview.transpose(); glGetFloatv(GL_PROJECTION_MATRIX, reinterpret_cast<GLfloat*>(projection.m)); projection = projection.transpose(); ArnVec3 origin, direction; ArnMakePickRay(&origin, &direction, float(mouseX), float(m_ac.avd.Height - mouseY), &modelview, &projection, &m_ac.avd); ArnNode* firstNode = m_ac.sgPtr->findFirstNodeOfType(NDT_RT_MESH); ArnMesh* mesh = reinterpret_cast<ArnMesh*>(firstNode); if (mesh) { bool bHit = false; unsigned int faceIdx = 0; ArnIntersectGl(mesh, &origin, &direction, &bHit, &faceIdx, 0, 0, 0, 0, 0); if (bHit) printf("Hit on Face %u of mesh %s\n", faceIdx, mesh->getName()); } } } void BwOpenGlWindow::handle_release() { m_drag = false; m_cam_phi += m_cam_dphi; m_cam_theta += m_cam_dtheta; m_cam_dphi = 0; m_cam_dtheta = 0; } void BwOpenGlWindow::handle_drag() { const int dx = Fl::event_x() - m_dragX; const int dy = Fl::event_y() - m_dragY; m_cam_dphi = -(double)dx/200; m_cam_dtheta = -(double)dy/200; redraw(); } void BwOpenGlWindow::handle_move() { mousePosition.first = Fl::event_x(); mousePosition.second = Fl::event_y(); // printf("%d %d\n", mousePosition.first, mousePosition.second); if (m_ac.bPanningButtonDown) { int dx = mousePosition.first - m_ac.panningStartPoint.first; int dy = mousePosition.second - m_ac.panningStartPoint.second; const float aspectRatio = (float)m_ac.windowWidth / m_ac.windowHeight; const float d1 = -(2.0f * m_ac.orthoViewDistance * aspectRatio / m_ac.windowWidth) * dx; const float d2 = -(-2.0f * m_ac.orthoViewDistance / m_ac.windowHeight) * dy; if (m_ac.viewMode == VM_TOP) { m_ac.dPanningCenter[0] = d1; m_ac.dPanningCenter[1] = d2; } else if (m_ac.viewMode == VM_RIGHT) { m_ac.dPanningCenter[1] = d1; m_ac.dPanningCenter[2] = d2; } else if (m_ac.viewMode == VM_BACK) { m_ac.dPanningCenter[0] = d1; m_ac.dPanningCenter[2] = d2; } //printf("%f %f\n", m_ac.dPanningCenter.first, m_ac.dPanningCenter.second); redraw(); } } void BwOpenGlWindow::handle_mousewheel() { if (m_ac.viewMode == VM_TOP || m_ac.viewMode == VM_RIGHT || m_ac.viewMode == VM_BACK) { if (Fl::event_dy() > 0) { ++m_ac.orthoViewDistance; redraw(); } else if (Fl::event_dy() < 0) { if (m_ac.orthoViewDistance > 1) --m_ac.orthoViewDistance; redraw(); } } } int BwOpenGlWindow::handle_keydown() { int key = Fl::event_key(); if (key == 65307) // ESC key return 0; if (key == 32) { // SPACE key if (!m_ac.bPanningButtonDown) { m_ac.bPanningButtonDown = true; m_ac.panningStartPoint = mousePosition; } } //redraw(); return 0; } int BwOpenGlWindow::handle_keyup() { int key = Fl::event_key(); if (key == FL_Escape) // ESC key return 0; if (key < 256) m_ac.bHoldingKeys[key] = true; if (key == ' ') {// SPACE key if (m_ac.bPanningButtonDown) { m_ac.bPanningButtonDown = false; m_ac.panningCenter[0] += m_ac.dPanningCenter[0]; m_ac.panningCenter[1] += m_ac.dPanningCenter[1]; m_ac.panningCenter[2] += m_ac.dPanningCenter[2]; m_ac.dPanningCenter[0] = 0; m_ac.dPanningCenter[1] = 0; m_ac.dPanningCenter[2] = 0; redraw(); } } else if (key == FL_KP + '7') { m_ac.viewMode = VM_TOP; //printf(" View mode set to top.\n"); redraw(); return 1; } else if (key == FL_KP + '3') { m_ac.viewMode = VM_RIGHT; //printf(" View mode set to left.\n"); redraw(); return 1; } else if (key == FL_KP + '1') { m_ac.viewMode = VM_BACK; //printf(" View mode set to front.\n"); redraw(); return 1; } else if (key == FL_KP + '4') { m_ac.viewMode = VM_CAMERA; //printf(" View mode set to camera.\n"); redraw(); return 1; } else if (key == '[') { ArnSkeleton *skel = dynamic_cast<ArnSkeleton *>(m_ac.sgPtr->getSceneRoot()->findFirstNodeOfType(NDT_RT_SKELETON)); assert(skel); ARNTRACK_DESC desc; skel->getAnimCtrl()->GetTrackDesc(0, &desc); skel->getAnimCtrl()->SetTrackEnable(0, desc.Enable ? FALSE : TRUE); return 1; } else if (key == ']') { ArnSkeleton *skel = dynamic_cast<ArnSkeleton *>(m_ac.sgPtr->getSceneRoot()->findFirstNodeOfType(NDT_RT_SKELETON)); assert(skel); ARNTRACK_DESC desc; skel->getAnimCtrl()->GetTrackDesc(1, &desc); skel->getAnimCtrl()->SetTrackEnable(1, desc.Enable ? FALSE : TRUE); return 1; } return 0; } int BwOpenGlWindow::handle( int eventType ) { if (eventType == FL_PUSH) { handle_push(); return 1; } else if (eventType == FL_RELEASE) { handle_release(); return 1; } else if (eventType == FL_DRAG) { handle_drag(); return 1; } else if (eventType == FL_ENTER) { take_focus(); return 1; } else if (eventType == FL_FOCUS) { return 1; } else if (eventType == FL_UNFOCUS) { return 1; } else if (eventType == FL_MOVE) { handle_move(); return 1; } else if (eventType == FL_MOUSEWHEEL) { handle_mousewheel(); return 1; } else if (eventType == FL_KEYDOWN) { return handle_keydown(); } else if (eventType == FL_KEYUP) { return handle_keyup(); } return Fl_Gl_Window::handle(eventType); } ////////////////////////////////////////////////////////////////////////// static void SelectGraphicObject(BwAppContext& ac, const float mousePx, const float mousePy) { if (!ac.sgPtr || !ac.activeCam) return; HitRecord buff[16]; GLint hits, view[4]; /* This choose the buffer where store the values for the selection data */ glSelectBuffer(4*16, reinterpret_cast<GLuint*>(buff)); /* This retrieve info about the viewport */ glGetIntegerv(GL_VIEWPORT, view); /* Switching in selecton mode */ glRenderMode(GL_SELECT); /* Clearing the name's stack. This stack contains all the info about the objects */ glInitNames(); /* Now fill the stack with one element (or glLoadName will generate an error) */ glPushName(0); /* Now modify the vieving volume, restricting selection area around the cursor */ glMatrixMode(GL_PROJECTION); glPushMatrix(); float origProjMat[16]; glGetFloatv(GL_PROJECTION_MATRIX, origProjMat); glLoadIdentity(); /* restrict the draw to an area around the cursor */ const GLdouble pickingAroundFactor = 1.0; gluPickMatrix(mousePx, mousePy, pickingAroundFactor, pickingAroundFactor, view); /* your original projection matrix */ glMultMatrixf(origProjMat); /* Draw the objects onto the screen */ glMatrixMode(GL_MODELVIEW); /* draw only the names in the stack, and fill the array */ glFlush(); // Rendering routine START ArnSceneGraphRenderGl(ac.sgPtr.get(), true); foreach (ArnIkSolver* ikSolver, ac.ikSolvers) { TreeDraw(*ikSolver->getTree(), ac.drawing_options[do_joint], ac.drawing_options[do_endeffector], ac.drawing_options[do_joint_axis], ac.drawing_options[do_root_node]); } // Rendering routine END /* Do you remeber? We do pushMatrix in PROJECTION mode */ glMatrixMode(GL_PROJECTION); glPopMatrix(); /* get number of objects drawed in that area and return to render mode */ hits = glRenderMode(GL_RENDER); glMatrixMode(GL_MODELVIEW); /* Print a list of the objects */ printf("---------------------\n"); for (GLint h = 0; h < hits; ++h) { if (buff[h].contents) // Zero means that ray hit on bounding box area. { const ArnNode* node = ac.sgPtr->getConstNodeById(buff[h].contents); if (node) { const ArnNode* parentNode = node->getParent(); const char* name = node->getName(); if (strlen(name) == 0) name = "<Unnamed>"; if (parentNode) { const char* parentName = parentNode->getName(); if (strlen(parentName) == 0) parentName = "<Unnamed>"; printf("[Object 0x%p ID %d %s (Parent Object 0x%p ID %d %s)]\n", node, node->getObjectId(), name, parentNode, parentNode->getObjectId(), parentName); } else { printf("[Object 0x%p ID %d %s]\n", node, node->getObjectId(), name); } const ArnMesh* mesh = dynamic_cast<const ArnMesh*>(parentNode); if (mesh) { ArnVec3 dim; mesh->getBoundingBoxDimension(&dim, true); printf("Mesh Dimension: "); dim.printFormatString(); } } foreach (ArnIkSolver* ikSolver, ac.ikSolvers) { Node* node = ikSolver->getNodeByObjectId(buff[h].contents); if (node) { printf("[Object 0x%p ID %d %s] Endeffector=%d\n", node, node->getObjectId(), node->getName(), node->isEndeffector()); /* if (ac.bHoldingKeys[SDLK_LSHIFT]) { ikSolver->reconfigureRoot(node); } else { if (node->isEndeffector()) { ikSolver->setSelectedEndeffector(node); } } */ } } } } } static void RenderGrid(const BwAppContext& ac, const float gridCellSize, const int gridCellCount, const float gridColor[3], const float thickness) { glColor3fv(gridColor); glPushAttrib(GL_ENABLE_BIT); glDisable(GL_LIGHTING); // subgrid glLineWidth(thickness); glBegin(GL_LINES); const float v1 = gridCellCount * gridCellSize; for (int i = -gridCellCount; i <= gridCellCount; ++i) { const float v2 = gridCellSize * i; switch (ac.viewMode) { case VM_UNKNOWN: case VM_CAMERA: case VM_TOP: // X direction glVertex3f(-v1, v2, 0); glVertex3f( v1, v2, 0); // Y direction glVertex3f(v2, -v1, 0); glVertex3f(v2, v1, 0); break; case VM_RIGHT: // Y direction glVertex3f(0, -v1, v2); glVertex3f(0, v1, v2); // Z direction glVertex3f(0, v2, -v1); glVertex3f(0, v2, v1); break; case VM_BACK: // X direction glVertex3f(-v1, 0, v2); glVertex3f( v1, 0, v2); // Z direction glVertex3f(v2, 0, -v1); glVertex3f(v2, 0, v1); break; default: break; } } glEnd(); glPopAttrib(); } static void RenderScene(const BwAppContext& ac) { glClearColor( 0.5, 0.5, 0.5, 1.0 ); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Set modelview and projection matrices here if (ac.viewMode == VM_CAMERA || ac.viewMode == VM_UNKNOWN) { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); if (ac.activeCam) { ArnConfigureViewportProjectionMatrixGl(&ac.avd, ac.activeCam); ArnConfigureViewMatrixGl(ac.activeCam); } } else if (ac.viewMode == VM_TOP || ac.viewMode == VM_RIGHT || ac.viewMode == VM_BACK) { static float eye[3], at[3], up[3]; if (ac.viewMode == VM_TOP) { eye[0] = ac.panningCenter[0] + ac.dPanningCenter[0]; eye[1] = ac.panningCenter[1] + ac.dPanningCenter[1]; eye[2] = 100.0f; at[0] = eye[0]; at[1] = eye[1]; at[2] = 0; up[0] = 0; up[1] = 1.0f; up[2] = 0; } else if (ac.viewMode == VM_RIGHT) { eye[0] = 100.0f; eye[1] = ac.panningCenter[1] + ac.dPanningCenter[1]; eye[2] = ac.panningCenter[2] + ac.dPanningCenter[2]; at[0] = 0; at[1] = eye[1]; at[2] = eye[2]; up[0] = 0; up[1] = 0; up[2] = 1.0f; } else if (ac.viewMode == VM_BACK) { eye[0] = ac.panningCenter[0] + ac.dPanningCenter[0]; eye[1] = -100.0f; eye[2] = ac.panningCenter[2] + ac.dPanningCenter[2]; at[0] = eye[0]; at[1] = 0; at[2] = eye[2]; up[0] = 0; up[1] = 0; up[2] = 1.0f; } glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(eye[0], eye[1], eye[2], at[0], at[1], at[2], up[0], up[1], up[2]); glMatrixMode(GL_PROJECTION); glLoadIdentity(); const float aspectRatio = (float)ac.windowWidth / ac.windowHeight; const float viewDistance = (float)ac.orthoViewDistance; glOrtho(-viewDistance*aspectRatio, viewDistance*aspectRatio, -viewDistance, viewDistance, 0, 10000); glMatrixMode(GL_MODELVIEW); } if (ac.activeLight) { ArnConfigureLightGl(0, ac.activeLight); } glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //glBlendFunc(GL_ONE_MINUS_DST_ALPHA,GL_DST_ALPHA); glBindTexture(GL_TEXTURE_2D, 0); if (ac.drawing_options[do_grid]) { const static float gridColor[3] = { 0.4f, 0.4f, 0.4f }; RenderGrid(ac, 0.5f, 10, gridColor, 0.5f); RenderGrid(ac, 2.5f, 2, gridColor, 1.0f); } // Render skeletons under control of IK solver foreach (ArnIkSolver* ikSolver, ac.ikSolvers) { glPushMatrix(); TreeDraw(*ikSolver->getTree(), ac.drawing_options[do_joint], ac.drawing_options[do_endeffector], ac.drawing_options[do_joint_axis], ac.drawing_options[do_root_node]); glPopMatrix(); } // Render the main scene graph glPushMatrix(); { if (ac.sgPtr) { ArnSceneGraphRenderGl(ac.sgPtr.get(), true); } } glPopMatrix(); // Render COM indicator and contact points of a biped. glPushAttrib(GL_DEPTH_BUFFER_BIT); glDisable(GL_DEPTH_TEST); { if (ac.trunk) { ArnVec3 netContactForce; const unsigned int contactCount = ac.swPtr->getContactCount(); // Calculate the net contact force and render the individual contact force for (unsigned int i = 0; i < contactCount; ++i) { ArnVec3 contactPos, contactForce; ac.swPtr->getContactPosition(i, &contactPos); ac.swPtr->getContactForce1(i, &contactForce); netContactForce += contactForce; // Accumulate contact forces // Render the individual contact force and contact point glPushMatrix(); { glTranslatef(contactPos.x, contactPos.y, contactPos.z); if (ac.drawing_options[do_contact]) { ArnSetupBasicMaterialGl(&ArnConsts::ARNCOLOR_YELLOW); ArnRenderSphereGl(0.025, 16, 16); } if (ac.drawing_options[do_contact_force]) { glPushAttrib(GL_ENABLE_BIT); glEnable(GL_COLOR_MATERIAL); glBegin(GL_LINES); glColor3f(1, 0, 0); glVertex3f(0, 0, 0); glColor3f(1, 0, 0); glVertex3f(contactForce.x, contactForce.y, contactForce.z); glEnd(); glPopAttrib(); } // TODO: Contact forces in the second direction. Should be zero. ac.swPtr->getContactForce2(i, &contactForce); //assert(contactForce == ArnConsts::ARNVEC3_ZERO); } glPopMatrix(); } glPushMatrix(); const ArnVec3& bipedComPos = *ac.bipedComPos.rbegin(); glTranslatef(bipedComPos.x, bipedComPos.y, bipedComPos.z); ArnSetupBasicMaterialGl(&ArnConsts::ARNCOLOR_GREEN); ArnRenderSphereGl(0.025, 16, 16); // COM indicator glPopMatrix(); } /* foreach (const ArnVec3& isect, ac.isects) { glPushMatrix(); glTranslatef(isect.x, isect.y, isect.z); ArnSetupBasicMaterialGl(&ArnConsts::ARNCOLOR_WHITE); ArnRenderSphereGl(0.025, 16, 16); glPopMatrix(); } */ } glPopAttrib(); } static void RenderHud(const BwAppContext& ac) { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); const double aspect = (double)ac.windowWidth / ac.windowHeight; glOrtho(-0.5 * aspect, 0.5 * aspect, -0.5, 0.5, 0, 1); glMatrixMode(GL_MODELVIEW); glPushAttrib(GL_DEPTH_BUFFER_BIT | GL_LIGHTING_BIT | GL_LINE_BIT | GL_POINT_BIT); glLineWidth(1); glPointSize(4); glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glPushMatrix(); glLoadIdentity(); glTranslatef(0.1f, 0, 0); glScalef(0.2, 0.2, 1); // Origin indicator ArnDrawAxesGl(0.5f); // Support polygon if (ac.supportPolygon.size()) { glBegin(GL_LINE_LOOP); foreach (const ArnVec3& v, ac.supportPolygon) { glColor3f(0, 0, 0); glVertex2f(v.x, v.y); } glEnd(); glBegin(GL_POINTS); foreach (const ArnVec3& contactPos, ac.isects) { glVertex2f(contactPos.x, contactPos.y); } glEnd(); } // Mass map if (ac.bipedComPos.size()) { const float devi = BwAppContext::massMapDeviation; const ArnVec3& comPos = *ac.bipedComPos.rbegin(); glEnable(GL_DEPTH_TEST); glBindTexture(GL_TEXTURE_2D, ac.massMapTex); glBegin(GL_QUADS); glTexCoord2f(0, 0); glColor4f(1, 1, 1, 1); glVertex2f(comPos.x - devi, comPos.y - devi); glTexCoord2f(1, 0); glColor4f(1, 1, 1, 1); glVertex2f(comPos.x + devi, comPos.y - devi); glTexCoord2f(1, 1); glColor4f(1, 1, 1, 1); glVertex2f(comPos.x + devi, comPos.y + devi); glTexCoord2f(0, 1); glColor4f(1, 1, 1, 1); glVertex2f(comPos.x - devi, comPos.y + devi); glEnd(); glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_DEPTH_TEST); glBegin(GL_LINE_LOOP); glColor4f(1, 1, 1, 1); glVertex2f(comPos.x - devi, comPos.y - devi); glColor4f(1, 1, 1, 1); glVertex2f(comPos.x + devi, comPos.y - devi); glColor4f(1, 1, 1, 1); glVertex2f(comPos.x + devi, comPos.y + devi); glColor4f(1, 1, 1, 1); glVertex2f(comPos.x - devi, comPos.y + devi); glEnd(); } // COM glDisable(GL_DEPTH_TEST); glBegin(GL_POINTS); float trail = 0; const float trailDiff = 1.0f / ac.bipedComPos.size(); foreach (const ArnVec3& comPos, ac.bipedComPos) { glColor4f(1, 0, 0, trail); glVertex2f(comPos.x, comPos.y); trail += trailDiff; } glEnd(); glPopMatrix(); glPopAttrib(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); }
[ [ [ 1, 759 ] ] ]
881fe24a639ca2cd76a54f7b473fabf1585747ce
78af025c564e5a348fd268e2f398a79a9b76d7d1
/src/iPhoneToday/CConfiguracion.h
7330a69bb6ec2150c36fc6499862f67edb1fbe54
[]
no_license
tronikos/iphonetoday
c2482f527299f315440a1afa1df72ab8e4f68154
d2ba13d97df16270c61642b2f477af8480c6abdf
refs/heads/master
2021-01-01T18:22:46.483398
2011-05-14T05:20:58
2011-05-14T05:20:58
32,228,280
1
0
null
null
null
null
UTF-8
C++
false
false
5,684
h
#pragma once #include "CConfigurationScreen.h" #include "CListaPantalla.h" #include "GraphicFunctions.h" #include "xmlWrapper.h" typedef struct SpecialIconSettings { TCHAR facename[LF_FACESIZE]; INT height; INT width; INT weight; COLORREF color; RECT offset; } SpecialIconSettings; typedef struct BubbleSettings { TCHAR image[MAX_PATH]; INT x; INT y; INT width; INT height; SpecialIconSettings sis; } BubbleSettings; typedef struct OutOfScreenSettings { BOOL stop; UINT stopAt; BOOL wrap; TCHAR exec[MAX_PATH]; } OutOfScreenSettings; class CConfiguracion { public: CConfiguracion(void); ~CConfiguracion(void); void calculaConfiguracion(CListaPantalla *listaPantallas, int width, int height); BOOL loadXMLIcons2(CListaPantalla *listaPantallas); void loadIconsImages(HDC *hDC, CListaPantalla *listaPantallas); void loadIconImage(HDC *hDC, CIcono *icono, SCREEN_TYPE screen_type); void loadImages(HDC *hDC); void loadBackground(HDC *hDC); void loadBackgrounds(HDC *hDC); void loadSounds(); BOOL loadXMLIcons(CListaPantalla *listaPantallas); void defaultValues(); BOOL AutoScale(); BOOL loadXMLConfig(); BOOL saveXMLConfig(); BOOL saveXMLIcons(CListaPantalla *listaPantallas); BOOL saveXMLScreenIcons(TiXmlElement *pElemScreen, CPantalla *pantalla); void getAbsolutePath(LPTSTR pszDest, size_t cchDest, LPCTSTR pszSrc, LPCTSTR pszDir); void getAbsolutePath(LPTSTR pszDest, size_t cchDest, LPCTSTR pszSrc); void getRelativePath(LPTSTR pszDest, size_t cchDest, LPCTSTR pszSrc); BOOL hasTimestampChanged(); TCHAR pathExecutableDir[MAX_PATH]; // Path of executable's directory TCHAR pathSettingsXML[MAX_PATH]; // Path of settings.xml TCHAR pathIconsXML[MAX_PATH]; // Path of icons.xml TCHAR pathIconsXMLDir[MAX_PATH]; // Path of the directory where icons.xml resides TCHAR pathIconsDir[MAX_PATH]; // Path of the icons directory FILETIME lastModifiedSettingsXML; FILETIME lastModifiedIconsXML; UINT altoPantalla; UINT altoPantallaMax; UINT anchoPantalla; CIcono *pressedIcon; CIcono *bubbleNotif; CIcono *bubbleState; CIcono *bubbleAlarm; CIcono *fondoPantalla; CIcono *backMainScreen; CIcono *backBottomBar; CIcono *backTopBar; RECT circlesBarRect; int circlesDistAdjusted; // Variables from XML // Screens CConfigurationScreen *mainScreenConfig; CConfigurationScreen *bottomBarConfig; CConfigurationScreen *topBarConfig; // Circles UINT circlesDiameter; INT circlesDiameterActivePerc; UINT circlesDiameterMax; INT circlesDistance; INT circlesOffset; BOOL circlesAlignTop; COLORREF circlesColorActive; COLORREF circlesColorInactive; COLORREF circlesColorOuter; BOOL circlesSingleTap; BOOL circlesDoubleTap; // Header TCHAR headerTextFacename[LF_FACESIZE]; UINT headerTextSize; UINT headerTextColor; UINT headerTextWeight; UINT headerOffset; UINT headerTextShadow; BOOL headerTextRoundRect; // Background UINT fondoTransparente; COLORREF fondoColor; BOOL fondoEstatico; float fondoFactor; BOOL fondoFitWidth; BOOL fondoFitHeight; BOOL fondoCenter; BOOL fondoTile; TCHAR strFondoPantalla[MAX_PATH]; // Movement UINT moveThreshold; UINT velMaxima; UINT velMinima; UINT refreshTime; UINT factorMovimiento; UINT verticalScroll; UINT freestyleScroll; // Special icons SpecialIconSettings dow; // DayOfWeek BOOL dowUseLocale; TCHAR diasSemana[7][16]; SpecialIconSettings dom; // DayOfMonth SpecialIconSettings clck; // Clock BOOL clckShowAMPM; BOOL clock12Format; SpecialIconSettings alrm; // Alarm BOOL alrmShowAMPM; SpecialIconSettings batt; // Battery BOOL battShowAC; BOOL battShowPercentage; TCHAR battChargingSymbol[2]; SpecialIconSettings vol; // Volume BOOL volShowPercentage; SpecialIconSettings meml; // Memory load BOOL memlShowPercentage; SpecialIconSettings memf; // Memory free BOOL memfShowMB; UINT memOSUsedKB; SpecialIconSettings memu; // Memory used BOOL memuShowMB; SpecialIconSettings psig; // Signal strength BOOL psigShowPercentage; SpecialIconSettings wsig; // Wifi signal strength BOOL wsigShowdBm; // Bubbles BubbleSettings bubble_notif; BubbleSettings bubble_state; BubbleSettings bubble_alarm; // Animation UINT animationEffect; COLORREF animationColor; UINT animationDuration; UINT animationDelay; BOOL launchAppAtBeginningOfAnimation; // OnLaunchIcon BOOL closeOnLaunchIcon; BOOL minimizeOnLaunchIcon; UINT vibrateOnLaunchIcon; TCHAR soundOnLaunchIcon[MAX_PATH]; BYTE* soundOnLaunchIcon_bytes; TCHAR runTool[MAX_PATH]; // OnPressIcon TCHAR pressed_icon[MAX_PATH]; TCHAR pressed_sound[MAX_PATH]; BYTE* pressed_sound_bytes; // OnChangeScreen TCHAR change_screen_sound[MAX_PATH]; BYTE* change_screen_sound_bytes; // General UINT notifyTimer; BOOL updateWhenInactive; UINT ignoreRotation; UINT ignoreMinimize; UINT disableRightClick; UINT disableRightClickDots; UINT fullscreen; UINT neverShowTaskBar; UINT noWindowTitle; UINT showExit; UINT textQuality; UINT textQualityInIcons; UINT autoShowKeyboardOnTextboxFocus; UINT soundsEnabled; // Today item height (Portrait|Landscape) UINT heightP; UINT heightL; // Out of screen OutOfScreenSettings ooss_left; OutOfScreenSettings ooss_right; OutOfScreenSettings ooss_up; OutOfScreenSettings ooss_down; // Transparency UINT alphaBlend; BOOL alphaOnBlack; UINT alphaThreshold; BOOL transparentBMP; BOOL useMask; UINT lastConfiguredAtWidth; UINT lastConfiguredAtHeight; };
[ [ [ 1, 230 ] ] ]
ba2655ab764b5bc5d25e58eb5dc3549aa4806314
b5ad65ebe6a1148716115e1faab31b5f0de1b493
/maxsdk2008/include/expr.h
6cbd49871ccc3830e97879190b1904f876323c7c
[]
no_license
gasbank/aran
4360e3536185dcc0b364d8de84b34ae3a5f0855c
01908cd36612379ade220cc09783bc7366c80961
refs/heads/master
2021-05-01T01:16:19.815088
2011-03-01T05:21:38
2011-03-01T05:21:38
1,051,010
1
0
null
null
null
null
UTF-8
C++
false
false
20,425
h
/********************************************************************** *< FILE: expr.h DESCRIPTION: expression object include file. CREATED BY: Don Brittain HISTORY: *> Copyright (c) 1994, All Rights Reserved. **********************************************************************/ #ifndef _EXPR_H_ #define _EXPR_H_ #include "maxheap.h" #include "export.h" #define SCALAR_EXPR 1 #define VECTOR_EXPR 3 #define SCALAR_VAR SCALAR_EXPR #define VECTOR_VAR VECTOR_EXPR class Expr; typedef int (*ExprFunc)(Expr *e, float f); class DllExport Inst: public MaxHeapOperators { public: ExprFunc func; float sVal; }; class ExprVar: public MaxHeapOperators { public: TSTR name; int type; int regNum; }; MakeTab(float); MakeTab(Point3); MakeTab(Inst); MakeTab(ExprVar); /*! \sa Class Point3, <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_expression_types.html">List of Expression Types</a>, <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_expression_variable_types.html">List of Expression Variable Types</a>, <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_expression_return_codes.html">List of Expression Return Codes</a>, <a href="ms-its:3dsmaxsdk.chm::/ui_character_strings.html">Character Strings</a>.\n\n \par Description: This class may be used by developers to parse mathematical expressions. The expression is created as a character string using a straightforward syntax. Expressions consist of operators (+, -, *, /, etc.), literal constants (numbers like 180, 2.718, etc.), variables (single floating point values or vector (<b>Point3</b>) values), and functions (mathematical functions that take one ore more arguments and return a result). The return value from the expression may be a floating point value or a vector. There are many built in functions, operators and constants available for use.\n\n All methods of this class are implemented by the system.\n\n Developers wishing to use these APIs should #include <b>/MAXSDK/INCLUDE/EXPRLIB.H</b> and should link to <b>/MAXSDK/LIB/EXPR.LIB</b>.\n\n Sample code using these APIs is shown below, and is also available as part of the expression controller in <b>/MAXSDK/SAMPLES/CONTROLLERS/EXPRCTRL.CPP</b>.\n\n Variables may be defined and used in expressions. Variable names are case sensitive, and must begin with a letter of the alphabet, but may include numbers. They may be any length. To create a named variable, you use the method <b>defVar()</b>. This takes a name and returns a register number. Defining the variable creates storage space in a list of variables maintained by the parser, and the register number is used as an array index into the variable value arrays passed into the expression evaluation method (<b>eval()</b>).\n\n To use the variable in an expression just use its name. For example if you define a variable named <b>radius</b>, you can use it in an expression like: <b>2*pi*radius</b>. To give the variable a value, you define two arrays of variables and pass them to the evaluation method (<b>eval()</b>). There is one array for scalar variables, and one for vector variables. You pass these arrays along with the number of variables in each list. See the sample code below for an example.\n\n The order of calling the methods of this class to evaluate an expression is as follows:\n\n Declare an expression instance (<b>Expr expr;</b>)\n\n Define the expression (<b>char e1[] = "2*pi*radius";</b>).\n\n Define any variables (<b>expr.defVar(SCALAR_VAR, _T("radius"));</b>)\n\n Load the expression (<b>expr.load(e1);</b>)\n\n Evaluate the expression (<b>expr.eval(...);</b>)\n\n There are no restrictions on the use of white space in expressions -- it may be used freely to make expressions more readable. In certain instances, white space should be used to ensure non-ambiguous parsing. For example, the <b>x</b> operator is used for to compute the cross product of two vectors. If a developer has several vectors: <b>Vec</b>, <b>Axis</b> and <b>xAxis</b> and wanted to compute the cross product, <b>VecxAxis</b> is ambiguous while <b>Vec x Axis</b> is not.\n\n All the necessary information to evaluate an expression is completely stored within an expression object. For example, if you are passed a pointer to an expression object for which some variables have been defined that you knew the value of, you could get all the information you needed from the expression object to completely evaluate the expression. This includes the expression string, variable names, variable types, and variable register indices.\n\n For complete documentation of the built in functions please refer to the 3ds Max User's Guide under Using Expression Controllers. Below is an overview of the operators, constants and functions that are available: \par Expression Operators: <b>Scalar Operators</b>\n\n Operator Use Meaning\n\n <b>+</b> p+q addition\n\n <b>-</b> p-q subtraction\n\n <b>-</b> -p additive inverse\n\n <b>*</b> p*q multiplication\n\n <b>/</b> p/q division\n\n <b>^</b> p^q power (p to the power of q)\n\n <b>**</b> p**q same as p^q\n\n <b>Boolean Operators</b>\n\n <b>=</b> p=q equal to\n\n <b>\<</b> p\<q less than\n\n <b>\></b> p\>q greater than\n\n <b>\<=</b> p\<=q less than or equal to\n\n <b>\>=</b> p\>=q greater than or equal to\n\n <b>|</b> p|q logical OR\n\n <b>\&</b> p\&q logical AND\n\n <b>Vector Operators</b>\n\n <b>+</b> V+W addition\n\n <b>-</b> V-W subtraction\n\n <b>*</b> p*V scalar multiplication\n\n V*p "\n\n <b>*</b> V*W dot product\n\n <b>x</b> VxW cross product\n\n <b>/</b> V/p scalar division\n\n <b>.</b> V.x first component (X)\n\n <b>.</b> V.y second component (Y)\n\n <b>.</b> V.z third component (Z) \par Built-In Constants: <b>pi</b> 3.1415...\n\n <b>e</b> 2.7182...\n\n <b>TPS</b> 4800 (ticks per second) \par Expression Functions: <b>Trigonometric Functions</b>\n\n The angles are specified and returned in degrees.\n\n <b>sin(p)</b> sine\n\n <b>cos(p)</b> cosine\n\n <b>tan(p)</b> tangent\n\n <b>asin(p)</b> arc sine\n\n <b>acos(p)</b> arc cosine\n\n <b>atan(p)</b> arc tangent\n\n <b>Hyperbolic Functions</b>\n\n <b>sinh(p)</b> hyperbolic sine\n\n <b>cosh(p)</b> hyperbolic cosine\n\n <b>tanh(p)</b> hyperbolic tangent\n\n <b>Conversion between Radians and Degrees</b>\n\n <b>radToDeg(p)</b> takes p in radians and returns the same angle in degrees\n\n <b>degToRad(p)</b> takes p in degrees and returns the same angle in radians\n\n <b>Rounding Functions</b>\n\n <b>ceil(p)</b> smallest integer greater than or equal to p.\n\n <b>floor(p)</b> largest integer less than or equal to p.\n\n <b>Standard Calculations</b>\n\n <b>ln(p)</b> natural (base e) logarithm\n\n <b>log(p)</b> common (base 10) logarithm\n\n <b>exp(p)</b> exponential function -- exp(e) = e^p\n\n <b>pow(p, q)</b> p to the power of q -- p^q\n\n <b>sqrt(p)</b> square root\n\n <b>abs(p)</b> absolute value\n\n <b>min(p, q)</b> minimum -- returns p or q depending on which is smaller\n\n <b>max(p, q)</b> maximum -- returns p or q depending on which is larger\n\n <b>mod(p, q)</b> remainder of p divided by q\n\n <b>Conditional</b>\n\n <b>if (p, q, r)</b> works like the common spreadsheet "if" -- if p is nonzero\n\n then "if" returns q, otherwise r.\n\n <b>Vector Handling</b>\n\n <b>length(V)</b> the length of V\n\n <b>unit(V)</b> returns a unit vector in the same direction as V.\n\n <b>comp(V, I)</b> i-th component, where I=0, 1, or 2.\n\n comp([5,6,7],1) = 6\n\n <b>Special Animation Functions</b>\n\n <b>noise(p, q, r)</b> 3D noise -- returns a randomly generated position.\n\n p, q, and r are random values used as a seed. \par Sample Code: The following code shows how the expression parser can be used. This code evaluates several expressions and displays the results in a dialog box. Both scalar and vector variables are used. One expression contains an error to show how error handling is done.\n\n \code void Utility::TestExpr() { // Declare an expression instance and variable storage Expr expr; float sRegs[2]; // Must be at least getVarCount(SCALAR_VAR); Point3 vRegs[2]; // Must be at least getVarCount(VECTOR_VAR); float ans[3]; int status; // Define a few expressions char e0[] = "2+2"; char e1[] = "2.0 * pi * radius"; char e2[] = "[1,1,0] + axis"; char e3[] = "[sin(90.0), sin(radToDeg(0.5*pi)), axis.z]"; char e4[] = "2+2*!@#$%"; // Bad expression // Define variables int radiusReg = expr.defVar(SCALAR_VAR, _T("radius")); int axisReg = expr.defVar(VECTOR_VAR, _T("axis")); // Set the variable values sRegs[radiusReg] = 50.0f; vRegs[axisReg] = Point3(0.0f, 0.0f, 1.0f); // Get the number of each we have defined so far int sCount = expr.getVarCount(SCALAR_VAR); int vCount = expr.getVarCount(VECTOR_VAR); // Load and evaluate expression "e0" if (status = expr.load(e0)) HandleLoadError(status, expr); else { status = expr.eval(ans, sCount, sRegs, vCount, vRegs); if (status != EXPR_NORMAL) HandleEvalError(status, expr); else DisplayExprResult(expr, ans); } // Load and evaluate expression "e1" if (status = expr.load(e1)) HandleLoadError(status, expr); else { status = expr.eval(ans, sCount, sRegs, vCount, vRegs); if (status != EXPR_NORMAL) HandleEvalError(status, expr); else DisplayExprResult(expr, ans); } // Load and evaluate expression "e2" if (status = expr.load(e2)) HandleLoadError(status, expr); else { status = expr.eval(ans, sCount, sRegs, vCount, vRegs); if (status != EXPR_NORMAL) HandleEvalError(status, expr); else DisplayExprResult(expr, ans); } // Load and evaluate expression "e3" if (status = expr.load(e3)) HandleLoadError(status, expr); else { status = expr.eval(ans, sCount, sRegs, vCount, vRegs); if (status != EXPR_NORMAL) HandleEvalError(status, expr); else DisplayExprResult(expr, ans); } // Load and evaluate expression "e4" if (status = expr.load(e4)) HandleLoadError(status, expr); else { status = expr.eval(ans, sCount, sRegs, vCount, vRegs); if (status != EXPR_NORMAL) HandleEvalError(status, expr); else DisplayExprResult(expr, ans); } } // Display the expression and the result void Utility::DisplayExprResult(Expr expr, float *ans) { TCHAR msg[128]; if (expr.getExprType() == SCALAR_EXPR) { _stprintf(msg, _T("Answer to \"%s\" is %.1f"), expr.getExprStr(), *ans); Message(msg, _T("Expression Result")); } else { _stprintf(msg, _T("Answer to \"%s\" is [%.1f, %.1f, %.1f]"), expr.getExprStr(), ans[0], ans[1], ans[2]); Message(msg, _T("Expression Result")); } } // Display the load error message void Utility::HandleLoadError(int status, Expr expr) { TCHAR msg[128]; if(status == EXPR_INST_OVERFLOW) { _stprintf(_T("Inst stack overflow: %s"), expr.getProgressStr()); Message(msg, _T("Error")); } else if (status == EXPR_UNKNOWN_TOKEN) { _stprintf(msg, _T("Unknown token: %s"), expr.getProgressStr()); Message(msg, _T("Error")); } else { _stprintf(msg, _T("Cannot parse \"%s\". Error begins at last char of: %s"), expr.getExprStr(), expr.getProgressStr()); Message(msg, _T("Error")); } } // Display the evaluation error message void Utility::HandleEvalError(int status, Expr expr) { TCHAR msg[128]; _stprintf(msg, _T("Can't parse expression \"%s\""), expr.getExprStr()); Message(msg, _T("Error")); } // Display the specified message and title in a dialog box void Utility::Message(TCHAR *msg, TCHAR *title) { MessageBox(ip->GetMAXHWnd(), (LPCTSTR) msg, (LPCTSTR) title, MB_ICONINFORMATION|MB_OK); } \endcode */ class Expr: public MaxHeapOperators { public: /*! \remarks Constructor. Internal data structures are initialized as empty. */ Expr() { sValStk = vValStk = instStk = nextScalar = nextVector = 0; } /*! \remarks Destructor. Any currently defined variables are deleted. */ ~Expr() { deleteAllVars(); } /*! \remarks This method is used to load an expression for parsing. An error code is returned indicating if the expression was loaded. A successfully loaded expression is then ready for evaluation with the <b>eval()</b> method. \par Parameters: <b>char *s</b>\n\n The expression to load. \return See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_expression_return_codes.html">List of Expression Return Codes</a>. */ DllExport int load(char *s); /*! \remarks This method is used to evaluate the expression loaded using <b>load()</b>. It returns either a scalar or vector result. \par Parameters: <b>float *ans</b>\n\n The numeric result of the expression is returned here, i.e. the answer . For scalar values this is a pointer to a single float. For vector values, <b>ans[0] is x, ans[1] = y, ans[2] = z</b>. You can determine which type of result is returned using the method <b>getExprType()</b>.\n\n <b>int sRegCt</b>\n\n The number of items in the <b>sRegs</b> array of scalar variables.\n\n <b>float *sRegs</b>\n\n Array of scalar variables.\n\n <b>int vRegCt=0</b>\n\n The number of items in the <b>vRegs</b> array of vector variables.\n\n <b>Point3 *vRegs=NULL</b>\n\n Array of vector variables. \return See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_expression_return_codes.html">List of Expression Return Codes</a>. */ DllExport int eval(float *ans, int sRegCt, float *sRegs, int vRegCt=0, Point3 *vRegs=NULL); /*! \remarks Returns the type of expression. See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_expression_types.html">List of Expression Types</a>. */ int getExprType(void) { return exprType; } /*! \remarks Returns a pointer to the currently loaded expression string. */ TCHAR * getExprStr(void) { return origStr; } /*! \remarks If there was an error parsing the expression, this method returns a string showing what portion of the expression was parsed before the error occurred. */ TCHAR * getProgressStr(void){ return progressStr; } /*! \remarks Defines a named variable that may be used in an expression. \par Parameters: <b>int type</b>\n\n The type of variable. See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_expression_variable_types.html">List of Expression Variable Types</a>.\n\n <b>MCHAR *name</b>\n\n The name of the variable. This name must begin with a letter, may include numbers and may be any length. \return The register number (into the <b>sRegs</b> or <b>vRegs</b> array passed to <b>eval()</b>) of the variable. */ DllExport int defVar(int type, TCHAR *name); /*! \remarks This method returns the number of variables defined of the specified type. When you call <b>eval()</b> on an expression, you must make sure that the variable arrays (<b>sRegs</b> and <b>vRegs</b>) are at least the size returned from this method. \par Parameters: <b>int type</b>\n\n See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_expression_variable_types.html">List of Expression Variable Types</a>. */ DllExport int getVarCount(int type); /*! \remarks Returns the name of the variable whose index is passed, or NULL if the variable could not be found. \par Parameters: <b>int type</b>\n\n The type the variable. See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_expression_variable_types.html">List of Expression Variable Types</a>.\n\n <b>int i</b>\n\n The register number of the variable. */ DllExport TCHAR * getVarName(int type, int i); /*! \remarks When you define a variable with <b>defVar()</b>, you get a back a register number. If your code is set up in such a way that saving that register number is not convenient in the block of code that defines it, you can use this method later on to find out what that return value had been. For example, one piece of code might have:\n\n <b>expr-\>defVar(SCALAR_VAR, "a"); // not saving return value...</b>\n\n <b>expr-\>defVar(SCALAR_VAR, "b");</b>\n\n and then right before evaluating the expression, you might have some code such as:\n\n <b>for(i = 0; i \< expr-\>getVarCount(SCALAR_VAR); i++)</b>\n\n <b>if(_tcscmp("a", expr-\>getVarName(SCALAR_VAR, i) == 0)</b>\n\n <b>aRegNum = expr-\>getVarRegNum(SCALAR_VAR, i);</b>\n\n Of course, this is a bit contrived -- most real examples would probably have tables to store the variable names, register numbers, etc. and thus would not need to call this method. It is available however, and this makes the expression object self-contained in that everything you need to evaluate an expression with variables (other than the variable values themselves) is stored by the expression object. \par Parameters: <b>int type</b>\n\n See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_expression_variable_types.html">List of Expression Variable Types</a>.\n\n <b>int i</b>\n\n The variable index returned from the method <b>defVar()</b>. \return The register index for the variable whose type and index are passed. */ DllExport int getVarRegNum(int type, int i); /*! \remarks Deletes all the variables from the list maintained by the expression. \return TRUE if the variables were deleted; otherwise FALSE. */ DllExport BOOL deleteAllVars(); /*! \remarks Deletes the variable whose name is passed from the list maintained by the expression. Register numbers never get reassigned, even if a variable gets deleted. For example, if you delete variables 0-9, and keep variable 10, you're going to need to pass in an array of size at least 11 to the <b>eval()</b> method, even though the first 10 slots are unused. \par Parameters: <b>MCHAR *name</b>\n\n The name of the variable to delete. \return TRUE if the variable was deleted; otherwise FALSE (the name was not found). */ DllExport BOOL deleteVar(TCHAR *name); // pseudo-private: (only to be used by the "instruction" functions void setExprType(int type) { exprType = type; } void pushInst(ExprFunc fn, float f) { if(instStk >= inst.Count()) inst.SetCount(instStk+30); inst[instStk].func = fn; inst[instStk++].sVal = f; } void pushSVal(float f) { if(sValStk>=sVal.Count())sVal.SetCount(sValStk+10);sVal[sValStk++]=f; } float popSVal() { return sVal[--sValStk]; } void pushVVal(Point3 &v) { if(vValStk>=vVal.Count())vVal.SetCount(vValStk+10);vVal[vValStk++]=v; } Point3 & popVVal() { return vVal[--vValStk]; } int getSRegCt(void) { return sRegCt; } float getSReg(int index) { return sRegPtr[index]; } int getVRegCt(void) { return vRegCt; } Point3 & getVReg(int index) { return vRegPtr[index]; } ExprVarTab vars; // named variables private: TCHAR * exprPtr; // pointer to current str pos during parsing TCHAR * exprStr; // ptr to original expression string to parse TSTR origStr; // original expression string that was loaded TSTR progressStr; // string to hold part of expr successfully parsed int sRegCt; // actual number of scalar registers passed to "eval" float *sRegPtr; // pointer to the scalar register array int vRegCt; // actual number of vector registers passed to "eval" Point3 *vRegPtr; // pointer to the vector register array int exprType; // expression type: SCALAR_EXPR or VECTOR_EXPR (set by load) int sValStk; // scalar value stack floatTab sVal; int vValStk; // vector value stack Point3Tab vVal; int instStk; // instruction stack InstTab inst; int nextScalar; // next scalar slot int nextVector; // next vector slot friend int yylex(); friend int yyerror(char *); }; #define EXPR_NORMAL 0 #define EXPR_INST_OVERFLOW -1 // instruction stack overflow during parsing #define EXPR_UNKNOWN_TOKEN -2 // unknown function, const, or reg during parsing #define EXPR_TOO_MANY_VARS -3 // value stack overflow #define EXPR_TOO_MANY_REGS -4 // register array overflow, or reg number too big #define EXPR_CANT_EVAL -5 // function can't be evaluated with given arg #define EXPR_CANT_PARSE -6 // expression can't be parsed (syntactically) #endif // _EXPR_H_
[ [ [ 1, 491 ] ] ]
c71c22114f805ef9c564fff1c3fc5ca590c21ede
56aae5e46371c17fd01fc19295a4f495fc7f9688
/uart_qt/posix_qextserialport.cpp
ee7ab2504240febe2e2f808a5e09de00d4f62f5a
[]
no_license
stesen/vi
b9aa4ee5439fef49b945503ffa284546ac6b6199
9608ad1b1a8c2a2f0a6a33481b3e2f04cbc5a878
refs/heads/master
2016-09-06T07:42:35.822003
2011-03-11T10:06:35
2011-03-11T10:06:35
1,467,486
0
0
null
null
null
null
UTF-8
C++
false
false
38,296
cpp
/*! \class Posix_QextSerialPort \version 1.0.0 \author Stefan Sander \author Michal Policht A cross-platform serial port class. This class encapsulates the POSIX portion of QextSerialPort. The user will be notified of errors and possible portability conflicts at run-time by default - this behavior can be turned off by defining _TTY_NOWARN_ (to turn off all warnings) or _TTY_NOWARN_PORT_ (to turn off portability warnings) in the project. Note that _TTY_NOWARN_ will also turn off portability warnings. */ #include <stdio.h> #include "posix_qextserialport.h" /*! \fn Posix_QextSerialPort::Posix_QextSerialPort() Default constructor. Note that the name of the device used by a QextSerialPort constructed with this constructor will be determined by #defined constants, or lack thereof - the default behavior is the same as _TTY_LINUX_. Possible naming conventions and their associated constants are: \verbatim Constant Used By Naming Convention ---------- ------------- ------------------------ _TTY_WIN_ Windows COM1, COM2 _TTY_IRIX_ SGI/IRIX /dev/ttyf1, /dev/ttyf2 _TTY_HPUX_ HP-UX /dev/tty1p0, /dev/tty2p0 _TTY_SUN_ SunOS/Solaris /dev/ttya, /dev/ttyb _TTY_DIGITAL_ Digital UNIX /dev/tty01, /dev/tty02 _TTY_FREEBSD_ FreeBSD /dev/ttyd0, /dev/ttyd1 _TTY_LINUX_ Linux /dev/ttyS0, /dev/ttyS1 <none> Linux /dev/ttyS0, /dev/ttyS1 \endverbatim This constructor assigns the device name to the name of the first port on the specified system. See the other constructors if you need to open a different port. */ Posix_QextSerialPort::Posix_QextSerialPort() : QextSerialBase() { Posix_File=new QFile(); } /*! \fn Posix_QextSerialPort::Posix_QextSerialPort(const Posix_QextSerialPort&) Copy constructor. */ Posix_QextSerialPort::Posix_QextSerialPort(const Posix_QextSerialPort& s) : QextSerialBase(s.port) { setOpenMode(s.openMode()); port = s.port; Settings.BaudRate=s.Settings.BaudRate; Settings.DataBits=s.Settings.DataBits; Settings.Parity=s.Settings.Parity; Settings.StopBits=s.Settings.StopBits; Settings.FlowControl=s.Settings.FlowControl; lastErr=s.lastErr; Posix_File=new QFile(); Posix_File=s.Posix_File; memcpy(&Posix_Timeout, &s.Posix_Timeout, sizeof(struct timeval)); memcpy(&Posix_Copy_Timeout, &s.Posix_Copy_Timeout, sizeof(struct timeval)); memcpy(&Posix_CommConfig, &s.Posix_CommConfig, sizeof(struct termios)); } /*! \fn Posix_QextSerialPort::Posix_QextSerialPort(const QString & name) Constructs a serial port attached to the port specified by name. name is the name of the device, which is windowsystem-specific, e.g."COM1" or "/dev/ttyS0". */ Posix_QextSerialPort::Posix_QextSerialPort(const QString & name, QextSerialBase::QueryMode mode) : QextSerialBase(name) { Posix_File=new QFile(); setQueryMode(mode); init(); } /*! \fn Posix_QextSerialPort::Posix_QextSerialPort(const PortSettings& settings) Constructs a port with default name and specified settings. */ Posix_QextSerialPort::Posix_QextSerialPort(const PortSettings& settings, QextSerialBase::QueryMode mode) : QextSerialBase() { setBaudRate(settings.BaudRate); setDataBits(settings.DataBits); setParity(settings.Parity); setStopBits(settings.StopBits); setFlowControl(settings.FlowControl); Posix_File=new QFile(); setTimeout(settings.Timeout_Millisec); setQueryMode(mode); init(); } /*! \fn Posix_QextSerialPort::Posix_QextSerialPort(const QString & name, const PortSettings& settings) Constructs a port with specified name and settings. */ Posix_QextSerialPort::Posix_QextSerialPort(const QString & name, const PortSettings& settings, QextSerialBase::QueryMode mode) : QextSerialBase(name) { setBaudRate(settings.BaudRate); setDataBits(settings.DataBits); setParity(settings.Parity); setStopBits(settings.StopBits); setFlowControl(settings.FlowControl); Posix_File=new QFile(); setTimeout(settings.Timeout_Millisec); setQueryMode(mode); init(); } /*! \fn Posix_QextSerialPort& Posix_QextSerialPort::operator=(const Posix_QextSerialPort& s) Override the = operator. */ Posix_QextSerialPort& Posix_QextSerialPort::operator=(const Posix_QextSerialPort& s) { setOpenMode(s.openMode()); port = s.port; Settings.BaudRate=s.Settings.BaudRate; Settings.DataBits=s.Settings.DataBits; Settings.Parity=s.Settings.Parity; Settings.StopBits=s.Settings.StopBits; Settings.FlowControl=s.Settings.FlowControl; lastErr=s.lastErr; Posix_File=s.Posix_File; memcpy(&Posix_Timeout, &(s.Posix_Timeout), sizeof(struct timeval)); memcpy(&Posix_Copy_Timeout, &(s.Posix_Copy_Timeout), sizeof(struct timeval)); memcpy(&Posix_CommConfig, &(s.Posix_CommConfig), sizeof(struct termios)); return *this; } void Posix_QextSerialPort::init() { if (queryMode() == QextSerialBase::EventDriven) qWarning("POSIX doesn't have event driven mechanism implemented yet"); } /*! \fn Posix_QextSerialPort::~Posix_QextSerialPort() Standard destructor. */ Posix_QextSerialPort::~Posix_QextSerialPort() { if (isOpen()) { close(); } Posix_File->close(); delete Posix_File; } /*! \fn void Posix_QextSerialPort::setBaudRate(BaudRateType baudRate) Sets the baud rate of the serial port. Note that not all rates are applicable on all platforms. The following table shows translations of the various baud rate constants on Windows(including NT/2000) and POSIX platforms. Speeds marked with an * are speeds that are usable on both Windows and POSIX. \note BAUD76800 may not be supported on all POSIX systems. SGI/IRIX systems do not support BAUD1800. \verbatim RATE Windows Speed POSIX Speed ----------- ------------- ----------- BAUD50 110 50 BAUD75 110 75 *BAUD110 110 110 BAUD134 110 134.5 BAUD150 110 150 BAUD200 110 200 *BAUD300 300 300 *BAUD600 600 600 *BAUD1200 1200 1200 BAUD1800 1200 1800 *BAUD2400 2400 2400 *BAUD4800 4800 4800 *BAUD9600 9600 9600 BAUD14400 14400 9600 *BAUD19200 19200 19200 *BAUD38400 38400 38400 BAUD56000 56000 38400 *BAUD57600 57600 57600 BAUD76800 57600 76800 *BAUD115200 115200 115200 BAUD128000 128000 115200 BAUD256000 256000 115200 \endverbatim */ void Posix_QextSerialPort::setBaudRate(BaudRateType baudRate) { LOCK_MUTEX(); if (Settings.BaudRate!=baudRate) { switch (baudRate) { case BAUD14400: Settings.BaudRate=BAUD9600; break; case BAUD56000: Settings.BaudRate=BAUD38400; break; case BAUD76800: #ifndef B76800 Settings.BaudRate=BAUD57600; #else Settings.BaudRate=baudRate; #endif break; case BAUD128000: case BAUD256000: Settings.BaudRate=BAUD115200; break; default: Settings.BaudRate=baudRate; break; } } if (isOpen()) { switch (baudRate) { /*50 baud*/ case BAUD50: TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows does not support 50 baud operation."); #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B50; #else cfsetispeed(&Posix_CommConfig, B50); cfsetospeed(&Posix_CommConfig, B50); #endif break; /*75 baud*/ case BAUD75: TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows does not support 75 baud operation."); #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B75; #else cfsetispeed(&Posix_CommConfig, B75); cfsetospeed(&Posix_CommConfig, B75); #endif break; /*110 baud*/ case BAUD110: #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B110; #else cfsetispeed(&Posix_CommConfig, B110); cfsetospeed(&Posix_CommConfig, B110); #endif break; /*134.5 baud*/ case BAUD134: TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows does not support 134.5 baud operation."); #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B134; #else cfsetispeed(&Posix_CommConfig, B134); cfsetospeed(&Posix_CommConfig, B134); #endif break; /*150 baud*/ case BAUD150: TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows does not support 150 baud operation."); #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B150; #else cfsetispeed(&Posix_CommConfig, B150); cfsetospeed(&Posix_CommConfig, B150); #endif break; /*200 baud*/ case BAUD200: TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows does not support 200 baud operation."); #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B200; #else cfsetispeed(&Posix_CommConfig, B200); cfsetospeed(&Posix_CommConfig, B200); #endif break; /*300 baud*/ case BAUD300: #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B300; #else cfsetispeed(&Posix_CommConfig, B300); cfsetospeed(&Posix_CommConfig, B300); #endif break; /*600 baud*/ case BAUD600: #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B600; #else cfsetispeed(&Posix_CommConfig, B600); cfsetospeed(&Posix_CommConfig, B600); #endif break; /*1200 baud*/ case BAUD1200: #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B1200; #else cfsetispeed(&Posix_CommConfig, B1200); cfsetospeed(&Posix_CommConfig, B1200); #endif break; /*1800 baud*/ case BAUD1800: TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows and IRIX do not support 1800 baud operation."); #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B1800; #else cfsetispeed(&Posix_CommConfig, B1800); cfsetospeed(&Posix_CommConfig, B1800); #endif break; /*2400 baud*/ case BAUD2400: #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B2400; #else cfsetispeed(&Posix_CommConfig, B2400); cfsetospeed(&Posix_CommConfig, B2400); #endif break; /*4800 baud*/ case BAUD4800: #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B4800; #else cfsetispeed(&Posix_CommConfig, B4800); cfsetospeed(&Posix_CommConfig, B4800); #endif break; /*9600 baud*/ case BAUD9600: #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B9600; #else cfsetispeed(&Posix_CommConfig, B9600); cfsetospeed(&Posix_CommConfig, B9600); #endif break; /*14400 baud*/ case BAUD14400: TTY_WARNING("Posix_QextSerialPort: POSIX does not support 14400 baud operation. Switching to 9600 baud."); #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B9600; #else cfsetispeed(&Posix_CommConfig, B9600); cfsetospeed(&Posix_CommConfig, B9600); #endif break; /*19200 baud*/ case BAUD19200: #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B19200; #else cfsetispeed(&Posix_CommConfig, B19200); cfsetospeed(&Posix_CommConfig, B19200); #endif break; /*38400 baud*/ case BAUD38400: #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B38400; #else cfsetispeed(&Posix_CommConfig, B38400); cfsetospeed(&Posix_CommConfig, B38400); #endif break; /*56000 baud*/ case BAUD56000: TTY_WARNING("Posix_QextSerialPort: POSIX does not support 56000 baud operation. Switching to 38400 baud."); #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B38400; #else cfsetispeed(&Posix_CommConfig, B38400); cfsetospeed(&Posix_CommConfig, B38400); #endif break; /*57600 baud*/ case BAUD57600: #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B57600; #else cfsetispeed(&Posix_CommConfig, B57600); cfsetospeed(&Posix_CommConfig, B57600); #endif break; /*76800 baud*/ case BAUD76800: TTY_PORTABILITY_WARNING("Posix_QextSerialPort Portability Warning: Windows and some POSIX systems do not support 76800 baud operation."); #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); #ifdef B76800 Posix_CommConfig.c_cflag|=B76800; #else TTY_WARNING("Posix_QextSerialPort: Posix_QextSerialPort was compiled without 76800 baud support. Switching to 57600 baud."); Posix_CommConfig.c_cflag|=B57600; #endif //B76800 #else //CBAUD #ifdef B76800 cfsetispeed(&Posix_CommConfig, B76800); cfsetospeed(&Posix_CommConfig, B76800); #else TTY_WARNING("Posix_QextSerialPort: Posix_QextSerialPort was compiled without 76800 baud support. Switching to 57600 baud."); cfsetispeed(&Posix_CommConfig, B57600); cfsetospeed(&Posix_CommConfig, B57600); #endif //B76800 #endif //CBAUD break; /*115200 baud*/ case BAUD115200: #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B115200; #else cfsetispeed(&Posix_CommConfig, B115200); cfsetospeed(&Posix_CommConfig, B115200); #endif break; /*128000 baud*/ case BAUD128000: TTY_WARNING("Posix_QextSerialPort: POSIX does not support 128000 baud operation. Switching to 115200 baud."); #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B115200; #else cfsetispeed(&Posix_CommConfig, B115200); cfsetospeed(&Posix_CommConfig, B115200); #endif break; /*256000 baud*/ case BAUD256000: TTY_WARNING("Posix_QextSerialPort: POSIX does not support 256000 baud operation. Switching to 115200 baud."); #ifdef CBAUD Posix_CommConfig.c_cflag&=(~CBAUD); Posix_CommConfig.c_cflag|=B115200; #else cfsetispeed(&Posix_CommConfig, B115200); cfsetospeed(&Posix_CommConfig, B115200); #endif break; } tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig); } UNLOCK_MUTEX(); } /*! \fn void Posix_QextSerialPort::setDataBits(DataBitsType dataBits) Sets the number of data bits used by the serial port. Possible values of dataBits are: \verbatim DATA_5 5 data bits DATA_6 6 data bits DATA_7 7 data bits DATA_8 8 data bits \endverbatim \note This function is subject to the following restrictions: \par 5 data bits cannot be used with 2 stop bits. \par 8 data bits cannot be used with space parity on POSIX systems. */ void Posix_QextSerialPort::setDataBits(DataBitsType dataBits) { LOCK_MUTEX(); if (Settings.DataBits!=dataBits) { if ((Settings.StopBits==STOP_2 && dataBits==DATA_5) || (Settings.StopBits==STOP_1_5 && dataBits!=DATA_5) || (Settings.Parity==PAR_SPACE && dataBits==DATA_8)) { } else { Settings.DataBits=dataBits; } } if (isOpen()) { switch(dataBits) { /*5 data bits*/ case DATA_5: if (Settings.StopBits==STOP_2) { TTY_WARNING("Posix_QextSerialPort: 5 Data bits cannot be used with 2 stop bits."); } else { Settings.DataBits=dataBits; Posix_CommConfig.c_cflag&=(~CSIZE); Posix_CommConfig.c_cflag|=CS5; tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig); } break; /*6 data bits*/ case DATA_6: if (Settings.StopBits==STOP_1_5) { TTY_WARNING("Posix_QextSerialPort: 6 Data bits cannot be used with 1.5 stop bits."); } else { Settings.DataBits=dataBits; Posix_CommConfig.c_cflag&=(~CSIZE); Posix_CommConfig.c_cflag|=CS6; tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig); } break; /*7 data bits*/ case DATA_7: if (Settings.StopBits==STOP_1_5) { TTY_WARNING("Posix_QextSerialPort: 7 Data bits cannot be used with 1.5 stop bits."); } else { Settings.DataBits=dataBits; Posix_CommConfig.c_cflag&=(~CSIZE); Posix_CommConfig.c_cflag|=CS7; tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig); } break; /*8 data bits*/ case DATA_8: if (Settings.StopBits==STOP_1_5) { TTY_WARNING("Posix_QextSerialPort: 8 Data bits cannot be used with 1.5 stop bits."); } else { Settings.DataBits=dataBits; Posix_CommConfig.c_cflag&=(~CSIZE); Posix_CommConfig.c_cflag|=CS8; tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig); } break; } } UNLOCK_MUTEX(); } /*! \fn void Posix_QextSerialPort::setParity(ParityType parity) Sets the parity associated with the serial port. The possible values of parity are: \verbatim PAR_SPACE Space Parity PAR_MARK Mark Parity PAR_NONE No Parity PAR_EVEN Even Parity PAR_ODD Odd Parity \endverbatim \note This function is subject to the following limitations: \par POSIX systems do not support mark parity. \par POSIX systems support space parity only if tricked into doing so, and only with fewer than 8 data bits. Use space parity very carefully with POSIX systems. */ void Posix_QextSerialPort::setParity(ParityType parity) { LOCK_MUTEX(); if (Settings.Parity!=parity) { if (parity==PAR_MARK || (parity==PAR_SPACE && Settings.DataBits==DATA_8)) { } else { Settings.Parity=parity; } } if (isOpen()) { switch (parity) { /*space parity*/ case PAR_SPACE: if (Settings.DataBits==DATA_8) { TTY_PORTABILITY_WARNING("Posix_QextSerialPort: Space parity is only supported in POSIX with 7 or fewer data bits"); } else { /*space parity not directly supported - add an extra data bit to simulate it*/ Posix_CommConfig.c_cflag&=~(PARENB|CSIZE); switch(Settings.DataBits) { case DATA_5: Settings.DataBits=DATA_6; Posix_CommConfig.c_cflag|=CS6; break; case DATA_6: Settings.DataBits=DATA_7; Posix_CommConfig.c_cflag|=CS7; break; case DATA_7: Settings.DataBits=DATA_8; Posix_CommConfig.c_cflag|=CS8; break; case DATA_8: break; } tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig); } break; /*mark parity - WINDOWS ONLY*/ case PAR_MARK: TTY_WARNING("Posix_QextSerialPort: Mark parity is not supported by POSIX."); break; /*no parity*/ case PAR_NONE: Posix_CommConfig.c_cflag&=(~PARENB); tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig); break; /*even parity*/ case PAR_EVEN: Posix_CommConfig.c_cflag&=(~PARODD); Posix_CommConfig.c_cflag|=PARENB; tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig); break; /*odd parity*/ case PAR_ODD: Posix_CommConfig.c_cflag|=(PARENB|PARODD); tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig); break; } } UNLOCK_MUTEX(); } /*! \fn void Posix_QextSerialPort::setStopBits(StopBitsType stopBits) Sets the number of stop bits used by the serial port. Possible values of stopBits are: \verbatim STOP_1 1 stop bit STOP_1_5 1.5 stop bits STOP_2 2 stop bits \endverbatim \note This function is subject to the following restrictions: \par 2 stop bits cannot be used with 5 data bits. \par POSIX does not support 1.5 stop bits. */ void Posix_QextSerialPort::setStopBits(StopBitsType stopBits) { LOCK_MUTEX(); if (Settings.StopBits!=stopBits) { if ((Settings.DataBits==DATA_5 && stopBits==STOP_2) || stopBits==STOP_1_5) {} else { Settings.StopBits=stopBits; } } if (isOpen()) { switch (stopBits) { /*one stop bit*/ case STOP_1: Settings.StopBits=stopBits; Posix_CommConfig.c_cflag&=(~CSTOPB); tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig); break; /*1.5 stop bits*/ case STOP_1_5: TTY_WARNING("Posix_QextSerialPort: 1.5 stop bit operation is not supported by POSIX."); break; /*two stop bits*/ case STOP_2: if (Settings.DataBits==DATA_5) { TTY_WARNING("Posix_QextSerialPort: 2 stop bits cannot be used with 5 data bits"); } else { Settings.StopBits=stopBits; Posix_CommConfig.c_cflag|=CSTOPB; tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig); } break; } } UNLOCK_MUTEX(); } /*! \fn void Posix_QextSerialPort::setFlowControl(FlowType flow) Sets the flow control used by the port. Possible values of flow are: \verbatim FLOW_OFF No flow control FLOW_HARDWARE Hardware (RTS/CTS) flow control FLOW_XONXOFF Software (XON/XOFF) flow control \endverbatim \note FLOW_HARDWARE may not be supported on all versions of UNIX. In cases where it is unsupported, FLOW_HARDWARE is the same as FLOW_OFF. */ void Posix_QextSerialPort::setFlowControl(FlowType flow) { LOCK_MUTEX(); if (Settings.FlowControl!=flow) { Settings.FlowControl=flow; } if (isOpen()) { switch(flow) { /*no flow control*/ case FLOW_OFF: Posix_CommConfig.c_cflag&=(~CRTSCTS); Posix_CommConfig.c_iflag&=(~(IXON|IXOFF|IXANY)); tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig); break; /*software (XON/XOFF) flow control*/ case FLOW_XONXOFF: Posix_CommConfig.c_cflag&=(~CRTSCTS); Posix_CommConfig.c_iflag|=(IXON|IXOFF|IXANY); tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig); break; case FLOW_HARDWARE: Posix_CommConfig.c_cflag|=CRTSCTS; Posix_CommConfig.c_iflag&=(~(IXON|IXOFF|IXANY)); tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig); break; } } UNLOCK_MUTEX(); } /*! \fn void Posix_QextSerialPort::setTimeout(ulong sec); Sets the read and write timeouts for the port to millisec milliseconds. Note that this is a per-character timeout, i.e. the port will wait this long for each individual character, not for the whole read operation. This timeout also applies to the bytesWaiting() function. \note POSIX does not support millisecond-level control for I/O timeout values. Any timeout set using this function will be set to the next lowest tenth of a second for the purposes of detecting read or write timeouts. For example a timeout of 550 milliseconds will be seen by the class as a timeout of 500 milliseconds for the purposes of reading and writing the port. However millisecond-level control is allowed by the select() system call, so for example a 550-millisecond timeout will be seen as 550 milliseconds on POSIX systems for the purpose of detecting available bytes in the read buffer. */ void Posix_QextSerialPort::setTimeout(long millisec) { LOCK_MUTEX(); Settings.Timeout_Millisec = millisec; Posix_Copy_Timeout.tv_sec = millisec / 1000; Posix_Copy_Timeout.tv_usec = millisec % 1000; if (isOpen()) { tcgetattr(Posix_File->handle(), &Posix_CommConfig); Posix_CommConfig.c_cc[VTIME] = millisec/100; tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig); } UNLOCK_MUTEX(); } /*! \fn bool Posix_QextSerialPort::open(OpenMode mode) Opens the serial port associated to this class. This function has no effect if the port associated with the class is already open. The port is also configured to the current settings, as stored in the Settings structure. */ bool Posix_QextSerialPort::open(OpenMode mode) { LOCK_MUTEX(); if (mode == QIODevice::NotOpen) return isOpen(); if (!isOpen()) { /*open the port*/ Posix_File->setFileName(port); //qDebug("Trying to open File"); if (Posix_File->open(QIODevice::ReadWrite|QIODevice::Unbuffered)) { //qDebug("Opened File succesfully"); /*set open mode*/ QIODevice::open(mode); /*configure port settings*/ tcgetattr(Posix_File->handle(), &Posix_CommConfig); /*set up other port settings*/ Posix_CommConfig.c_cflag|=CREAD|CLOCAL; Posix_CommConfig.c_lflag&=(~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG)); Posix_CommConfig.c_iflag&=(~(INPCK|IGNPAR|PARMRK|ISTRIP|ICRNL|IXANY)); Posix_CommConfig.c_oflag&=(~OPOST); Posix_CommConfig.c_cc[VMIN]=0; Posix_CommConfig.c_cc[VINTR] = _POSIX_VDISABLE; Posix_CommConfig.c_cc[VQUIT] = _POSIX_VDISABLE; Posix_CommConfig.c_cc[VSTART] = _POSIX_VDISABLE; Posix_CommConfig.c_cc[VSTOP] = _POSIX_VDISABLE; Posix_CommConfig.c_cc[VSUSP] = _POSIX_VDISABLE; setBaudRate(Settings.BaudRate); setDataBits(Settings.DataBits); setParity(Settings.Parity); setStopBits(Settings.StopBits); setFlowControl(Settings.FlowControl); // setTimeout(Settings.Timeout_Sec, Settings.Timeout_Millisec); setTimeout(10); //changed by APAUL tcsetattr(Posix_File->handle(), TCSAFLUSH, &Posix_CommConfig); } else { //qDebug("Could not open File! Error code : %d", Posix_File->error()); } } UNLOCK_MUTEX(); return isOpen(); } /*! \fn void Posix_QextSerialPort::close() Closes a serial port. This function has no effect if the serial port associated with the class is not currently open. */ void Posix_QextSerialPort::close() { LOCK_MUTEX(); Posix_File->close(); QIODevice::close(); UNLOCK_MUTEX(); } /*! \fn void Posix_QextSerialPort::flush() Flushes all pending I/O to the serial port. This function has no effect if the serial port associated with the class is not currently open. */ void Posix_QextSerialPort::flush() { LOCK_MUTEX(); if (isOpen()) { Posix_File->flush(); } UNLOCK_MUTEX(); } /*! \fn qint64 Posix_QextSerialPort::size() const This function will return the number of bytes waiting in the receive queue of the serial port. It is included primarily to provide a complete QIODevice interface, and will not record errors in the lastErr member (because it is const). This function is also not thread-safe - in multithreading situations, use Posix_QextSerialPort::bytesWaiting() instead. */ qint64 Posix_QextSerialPort::size() const { int numBytes; if (ioctl(Posix_File->handle(), FIONREAD, &numBytes)<0) { numBytes=0; } return (qint64)numBytes; } /*! \fn qint64 Posix_QextSerialPort::bytesAvailable() Returns the number of bytes waiting in the port's receive queue. This function will return 0 if the port is not currently open, or -1 on error. Error information can be retrieved by calling Posix_QextSerialPort::getLastError(). */ qint64 Posix_QextSerialPort::bytesAvailable() { LOCK_MUTEX(); if (isOpen()) { int bytesQueued; fd_set fileSet; FD_ZERO(&fileSet); FD_SET(Posix_File->handle(), &fileSet); /*on Linux systems the Posix_Timeout structure will be altered by the select() call. Make sure we use the right timeout values*/ //memcpy(&Posix_Timeout, &Posix_Copy_Timeout, sizeof(struct timeval)); Posix_Timeout = Posix_Copy_Timeout; int n=select(Posix_File->handle()+1, &fileSet, NULL, &fileSet, &Posix_Timeout); if (!n) { lastErr=E_PORT_TIMEOUT; UNLOCK_MUTEX(); return -1; } if (n==-1 || ioctl(Posix_File->handle(), FIONREAD, &bytesQueued)==-1) { translateError(errno); UNLOCK_MUTEX(); return -1; } lastErr=E_NO_ERROR; UNLOCK_MUTEX(); return bytesQueued + QIODevice::bytesAvailable(); } UNLOCK_MUTEX(); return 0; } /*! \fn void Posix_QextSerialPort::ungetChar(char) This function is included to implement the full QIODevice interface, and currently has no purpose within this class. This function is meaningless on an unbuffered device and currently only prints a warning message to that effect. */ void Posix_QextSerialPort::ungetChar(char) { /*meaningless on unbuffered sequential device - return error and print a warning*/ TTY_WARNING("Posix_QextSerialPort: ungetChar() called on an unbuffered sequential device - operation is meaningless"); } /*! \fn void Posix_QextSerialPort::translateError(ulong error) Translates a system-specific error code to a QextSerialPort error code. Used internally. */ void Posix_QextSerialPort::translateError(ulong error) { switch (error) { case EBADF: case ENOTTY: lastErr=E_INVALID_FD; break; case EINTR: lastErr=E_CAUGHT_NON_BLOCKED_SIGNAL; break; case ENOMEM: lastErr=E_NO_MEMORY; break; } } /*! \fn void Posix_QextSerialPort::setDtr(bool set) Sets DTR line to the requested state (high by default). This function will have no effect if the port associated with the class is not currently open. */ void Posix_QextSerialPort::setDtr(bool set) { LOCK_MUTEX(); if (isOpen()) { int status; ioctl(Posix_File->handle(), TIOCMGET, &status); if (set) { status|=TIOCM_DTR; } else { status&=~TIOCM_DTR; } ioctl(Posix_File->handle(), TIOCMSET, &status); } UNLOCK_MUTEX(); } /*! \fn void Posix_QextSerialPort::setRts(bool set) Sets RTS line to the requested state (high by default). This function will have no effect if the port associated with the class is not currently open. */ void Posix_QextSerialPort::setRts(bool set) { LOCK_MUTEX(); if (isOpen()) { int status; ioctl(Posix_File->handle(), TIOCMGET, &status); if (set) { status|=TIOCM_RTS; } else { status&=~TIOCM_RTS; } ioctl(Posix_File->handle(), TIOCMSET, &status); } UNLOCK_MUTEX(); } /*! \fn unsigned long Posix_QextSerialPort::lineStatus() returns the line status as stored by the port function. This function will retrieve the states of the following lines: DCD, CTS, DSR, and RI. On POSIX systems, the following additional lines can be monitored: DTR, RTS, Secondary TXD, and Secondary RXD. The value returned is an unsigned long with specific bits indicating which lines are high. The following constants should be used to examine the states of individual lines: \verbatim Mask Line ------ ---- LS_CTS CTS LS_DSR DSR LS_DCD DCD LS_RI RI LS_RTS RTS (POSIX only) LS_DTR DTR (POSIX only) LS_ST Secondary TXD (POSIX only) LS_SR Secondary RXD (POSIX only) \endverbatim This function will return 0 if the port associated with the class is not currently open. */ unsigned long Posix_QextSerialPort::lineStatus() { unsigned long Status=0, Temp=0; LOCK_MUTEX(); if (isOpen()) { ioctl(Posix_File->handle(), TIOCMGET, &Temp); if (Temp&TIOCM_CTS) { Status|=LS_CTS; } if (Temp&TIOCM_DSR) { Status|=LS_DSR; } if (Temp&TIOCM_RI) { Status|=LS_RI; } if (Temp&TIOCM_CD) { Status|=LS_DCD; } if (Temp&TIOCM_DTR) { Status|=LS_DTR; } if (Temp&TIOCM_RTS) { Status|=LS_RTS; } if (Temp&TIOCM_ST) { Status|=LS_ST; } if (Temp&TIOCM_SR) { Status|=LS_SR; } } UNLOCK_MUTEX(); return Status; } /*! \fn qint64 Posix_QextSerialPort::readData(char * data, qint64 maxSize) Reads a block of data from the serial port. This function will read at most maxSize bytes from the serial port and place them in the buffer pointed to by data. Return value is the number of bytes actually read, or -1 on error. \warning before calling this function ensure that serial port associated with this class is currently open (use isOpen() function to check if port is open). */ qint64 Posix_QextSerialPort::readData(char * data, qint64 maxSize) { LOCK_MUTEX(); int retVal=0; retVal=Posix_File->read(data, maxSize); if (retVal==-1) lastErr=E_READ_FAILED; UNLOCK_MUTEX(); return retVal; } /*! \fn qint64 Posix_QextSerialPort::writeData(const char * data, qint64 maxSize) Writes a block of data to the serial port. This function will write maxSize bytes from the buffer pointed to by data to the serial port. Return value is the number of bytes actually written, or -1 on error. \warning before calling this function ensure that serial port associated with this class is currently open (use isOpen() function to check if port is open). */ qint64 Posix_QextSerialPort::writeData(const char * data, qint64 maxSize) { LOCK_MUTEX(); int retVal=0; retVal=Posix_File->write(data, maxSize); if (retVal==-1) lastErr=E_WRITE_FAILED; UNLOCK_MUTEX(); return retVal; }
[ [ [ 1, 1131 ] ] ]
0c5b7cc628d47113c4d4d5fd09f85a19e2b04cf9
2b32433353652d705e5558e7c2d5de8b9fbf8fc3
/PTOC/PTOC/PARSER.CXX
263e54719a69bbb3677cc5111df66f5568dac0db
[]
no_license
smarthaert/d-edit
70865143db2946dd29a4ff52cb36e85d18965be3
41d069236748c6e77a5a457280846a300d38e080
refs/heads/master
2020-04-23T12:21:51.180517
2011-01-30T00:37:18
2011-01-30T00:37:18
35,532,200
0
0
null
null
null
null
UTF-8
C++
false
false
68,554
cxx
/* A Bison parser, made from parser.y with Bison version GNU Bison version 1.24 */ #define YYBISON 1 /* Identify Bison output. */ #define yyparse zzparse #define yylex zzlex #define yyerror zzerror #define yylval zzlval #define yychar zzchar #define yydebug zzdebug #define yynerrs zznerrs #define ARRAY 258 #define BEGIN 259 #define CASE 260 #define CONST 261 #define DO 262 #define DOTS 263 #define ELSE 264 #define END 265 #define FIL 266 #define FOR 267 #define FUNCTION 268 #define GOTO 269 #define IDENT 270 #define ICONST 271 #define IF 272 #define LABEL 273 #define LET 274 #define LOOPHOLE 275 #define OF 276 #define ORIGIN 277 #define OTHERWISE 278 #define PACKED 279 #define PROCEDURE 280 #define PROGRAM 281 #define RCONST 282 #define READ 283 #define RECORD 284 #define REPEAT 285 #define RETURN 286 #define SET 287 #define SCONST 288 #define THEN 289 #define TO 290 #define TYPE 291 #define UNTIL 292 #define VAR 293 #define WHILE 294 #define WITH 295 #define WRITE 296 #define EQ 297 #define NE 298 #define LT 299 #define LE 300 #define GT 301 #define GE 302 #define IN 303 #define PLUS 304 #define MINUS 305 #define OR 306 #define MOD 307 #define DIV 308 #define DIVR 309 #define MUL 310 #define AND 311 #define UPLUS 312 #define UMINUS 313 #define NOT 314 #line 1 "parser.y" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <malloc.h> #include "nmtbl.h" #include "token.h" #include "trnod.h" #include "util.h" static int zzcnv_table[] = { #define DEF_TOKEN(mnem, cat, cls, yacc) yacc, #include "token.dpp" }; void zzerror(char* text) { error(curr_token, "syntax error: %s", text); } #line 27 "parser.y" typedef union { token *tok; token_list *toks; node *n_node; tpd_node *n_tpd; block_node *n_block; stmt_node *n_stmt; decl_node *n_decl; expr_node *n_expr; expr_group_node *n_grp; write_param_node *n_wrtp; write_list_node *n_wrls; case_node *n_case; set_item_node *n_item; const_def_node *n_cdef; type_def_node *n_tdef; var_decl_node *n_vdcl; param_list_node *n_plist; idx_node *n_idx; field_list_node *n_fldls; variant_part_node *n_varp; selector_node *n_sel; variant_node *n_vari; compound_node *n_comp; import_list_node *n_imp; } YYSTYPE; #ifndef YYLTYPE typedef struct yyltype { int timestamp; int first_line; int first_column; int last_line; int last_column; char *text; } yyltype; #define YYLTYPE yyltype #endif #include <stdio.h> #ifndef __cplusplus #ifndef __STDC__ #define const #endif #endif #define YYFINAL 342 #define YYFLAG -32768 #define YYNTBASE 69 #define YYTRANSLATE(x) ((unsigned)(x) <= 314 ? yytranslate[x] : 138) static const char yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 46, 47, 2, 2, 43, 2, 42, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 44, 45, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 48, 2, 49, 50, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68 }; #if YYDEBUG != 0 static const short yyprhs[] = { 0, 0, 2, 4, 6, 9, 16, 18, 24, 25, 29, 33, 35, 38, 39, 42, 44, 46, 48, 50, 52, 54, 55, 59, 62, 68, 73, 80, 89, 94, 99, 102, 105, 107, 109, 114, 118, 120, 124, 126, 130, 131, 133, 134, 138, 140, 144, 149, 150, 152, 156, 160, 162, 166, 170, 174, 178, 182, 186, 190, 194, 198, 202, 206, 210, 214, 218, 222, 224, 227, 230, 233, 235, 239, 244, 248, 251, 256, 263, 265, 267, 269, 273, 275, 276, 278, 282, 284, 288, 290, 294, 296, 300, 302, 303, 307, 309, 313, 315, 319, 325, 329, 331, 335, 338, 339, 343, 347, 350, 351, 355, 359, 362, 363, 365, 369, 373, 379, 383, 389, 396, 405, 412, 421, 427, 428, 432, 434, 438, 441, 443, 445, 449, 451, 453, 455, 457, 459, 461, 463, 465, 467, 469, 471, 479, 487, 495, 499, 503, 506, 511, 516, 521, 522, 524, 526, 530, 536, 538, 542, 544, 548, 551, 553, 555, 560, 564, 566, 568, 571, 575 }; static const short yyrhs[] = { 70, 0, 71, 0, 72, 0, 75, 42, 0, 26, 15, 73, 45, 75, 42, 0, 76, 0, 26, 15, 73, 45, 76, 0, 0, 46, 74, 47, 0, 15, 43, 74, 0, 15, 0, 76, 79, 0, 0, 77, 76, 0, 98, 0, 100, 0, 103, 0, 106, 0, 111, 0, 110, 0, 0, 88, 19, 86, 0, 14, 16, 0, 5, 86, 21, 83, 10, 0, 17, 86, 34, 78, 0, 17, 86, 34, 78, 9, 78, 0, 12, 15, 19, 86, 35, 86, 7, 78, 0, 39, 86, 7, 78, 0, 30, 80, 37, 86, 0, 41, 82, 0, 28, 81, 0, 88, 0, 31, 0, 40, 92, 7, 78, 0, 16, 44, 78, 0, 79, 0, 4, 80, 10, 0, 78, 0, 78, 45, 80, 0, 0, 95, 0, 0, 46, 96, 47, 0, 84, 0, 84, 23, 78, 0, 84, 23, 78, 45, 0, 0, 85, 0, 85, 45, 84, 0, 92, 44, 78, 0, 87, 0, 86, 58, 86, 0, 86, 59, 86, 0, 86, 61, 86, 0, 86, 64, 86, 0, 86, 62, 86, 0, 86, 63, 86, 0, 86, 65, 86, 0, 86, 60, 86, 0, 86, 55, 86, 0, 86, 53, 86, 0, 86, 54, 86, 0, 86, 56, 86, 0, 86, 51, 86, 0, 86, 52, 86, 0, 86, 57, 86, 0, 88, 0, 58, 87, 0, 59, 87, 0, 68, 87, 0, 89, 0, 46, 92, 47, 0, 88, 46, 93, 47, 0, 88, 42, 15, 0, 88, 50, 0, 88, 48, 92, 49, 0, 20, 46, 117, 43, 86, 47, 0, 16, 0, 27, 0, 33, 0, 48, 90, 49, 0, 15, 0, 0, 91, 0, 91, 43, 90, 0, 86, 0, 86, 8, 86, 0, 86, 0, 86, 43, 92, 0, 94, 0, 94, 43, 93, 0, 86, 0, 0, 46, 92, 47, 0, 97, 0, 97, 43, 96, 0, 86, 0, 86, 44, 86, 0, 86, 44, 86, 44, 86, 0, 18, 99, 45, 0, 16, 0, 16, 43, 99, 0, 6, 101, 0, 0, 102, 45, 101, 0, 15, 51, 86, 0, 36, 104, 0, 0, 105, 45, 104, 0, 15, 51, 117, 0, 38, 107, 0, 0, 108, 0, 108, 45, 107, 0, 74, 44, 117, 0, 15, 22, 86, 44, 118, 0, 25, 15, 112, 0, 13, 15, 112, 44, 117, 0, 25, 15, 112, 45, 15, 45, 0, 13, 15, 112, 44, 117, 45, 15, 45, 0, 25, 15, 112, 45, 75, 45, 0, 13, 15, 112, 44, 117, 45, 75, 45, 0, 13, 15, 45, 75, 45, 0, 0, 46, 113, 47, 0, 114, 0, 114, 45, 113, 0, 38, 115, 0, 115, 0, 109, 0, 74, 44, 116, 0, 118, 0, 120, 0, 118, 0, 119, 0, 125, 0, 124, 0, 126, 0, 123, 0, 121, 0, 122, 0, 15, 0, 127, 3, 48, 130, 49, 21, 117, 0, 127, 3, 48, 128, 49, 21, 118, 0, 127, 3, 48, 128, 49, 21, 120, 0, 46, 74, 47, 0, 86, 8, 86, 0, 50, 117, 0, 127, 32, 21, 117, 0, 127, 29, 132, 10, 0, 127, 11, 21, 117, 0, 0, 24, 0, 129, 0, 129, 45, 128, 0, 15, 8, 15, 44, 117, 0, 131, 0, 131, 43, 130, 0, 118, 0, 86, 8, 86, 0, 133, 134, 0, 133, 0, 107, 0, 5, 135, 21, 136, 0, 15, 44, 117, 0, 117, 0, 137, 0, 137, 45, 0, 137, 45, 136, 0, 92, 44, 46, 132, 47, 0 }; #endif #if YYDEBUG != 0 static const short yyrline[] = { 0, 224, 229, 229, 231, 232, 237, 238, 244, 245, 247, 248, 250, 255, 256, 258, 258, 258, 258, 259, 259, 288, 289, 290, 291, 292, 293, 295, 297, 298, 299, 300, 301, 302, 303, 304, 305, 307, 309, 309, 310, 310, 312, 313, 315, 316, 327, 339, 340, 341, 343, 367, 368, 369, 370, 371, 372, 373, 375, 376, 378, 379, 380, 381, 382, 383, 384, 386, 387, 389, 391, 394, 395, 396, 397, 398, 399, 400, 402, 403, 404, 405, 406, 408, 409, 410, 412, 413, 415, 415, 417, 418, 420, 420, 423, 426, 426, 428, 429, 430, 472, 475, 476, 478, 481, 482, 484, 486, 489, 490, 492, 494, 497, 498, 499, 501, 502, 505, 508, 512, 515, 518, 521, 523, 526, 527, 529, 530, 532, 533, 533, 535, 537, 537, 543, 543, 543, 543, 543, 544, 544, 544, 546, 548, 551, 553, 556, 558, 561, 563, 565, 568, 570, 570, 572, 573, 575, 578, 578, 581, 582, 585, 588, 591, 593, 598, 599, 602, 603, 604, 606 }; static const char * const yytname[] = { "$","error","$undefined.","ARRAY", "BEGIN","CASE","CONST","DO","DOTS","ELSE","END","FIL","FOR","FUNCTION","GOTO", "IDENT","ICONST","IF","LABEL","LET","LOOPHOLE","OF","ORIGIN","OTHERWISE","PACKED", "PROCEDURE","PROGRAM","RCONST","READ","RECORD","REPEAT","RETURN","SET","SCONST", "THEN","TO","TYPE","UNTIL","VAR","WHILE","WITH","WRITE","'.'","','","':'","';'", "'('","')'","'['","']'","'^'","EQ","NE","LT","LE","GT","GE","IN","PLUS","MINUS", "OR","MOD","DIV","DIVR","MUL","AND","UPLUS","UMINUS","NOT","translation","input_file", "program","module","prog_param_list","ident_list","block","decl_part_list","decl_part", "statement","compoundst","sequence","actual_params","write_params","case_list", "case_items","case_item","expr","simple_expr","primary","constant","set_elem_list", "set_elem","expr_list","act_param_list","act_param","expr_group","write_list", "write_param","label_decl_part","label_list","const_def_part","const_def_list", "const_def","type_def_part","type_def_list","type_def","var_decl_part","var_decl_list", "var_decl","proc_decl","proc_fwd_decl","proc_def","formal_params","formal_param_list", "formal_param","param_decl","param_type","type","simple_type","array_type","conformant_array_type", "enum_type","range_type","pointer_type","set_type","record_type","file_type", "packed","conformant_indices","conformant_index","indices","index_spec","field_list", "fixed_part","variant_part","selector","variant_list","variant","" }; #endif static const short yyr1[] = { 0, 69, 70, 70, 71, 71, 72, 72, 73, 73, 74, 74, 75, 76, 76, 77, 77, 77, 77, 77, 77, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 79, 80, 80, 81, 81, 82, 82, 83, 83, 83, 84, 84, 84, 85, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 87, 87, 87, 87, 88, 88, 88, 88, 88, 88, 88, 89, 89, 89, 89, 89, 90, 90, 90, 91, 91, 92, 92, 93, 93, 94, 94, 95, 96, 96, 97, 97, 97, 98, 99, 99, 100, 101, 101, 102, 103, 104, 104, 105, 106, 107, 107, 107, 108, 108, 109, 109, 110, 110, 111, 111, 111, 112, 112, 113, 113, 114, 114, 114, 115, 116, 116, 117, 117, 117, 117, 117, 117, 117, 117, 118, 119, 120, 120, 121, 122, 123, 124, 125, 126, 127, 127, 128, 128, 129, 130, 130, 131, 131, 132, 132, 133, 134, 135, 135, 136, 136, 136, 137 }; static const short yyr2[] = { 0, 1, 1, 1, 2, 6, 1, 5, 0, 3, 3, 1, 2, 0, 2, 1, 1, 1, 1, 1, 1, 0, 3, 2, 5, 4, 6, 8, 4, 4, 2, 2, 1, 1, 4, 3, 1, 3, 1, 3, 0, 1, 0, 3, 1, 3, 4, 0, 1, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 2, 2, 2, 1, 3, 4, 3, 2, 4, 6, 1, 1, 1, 3, 1, 0, 1, 3, 1, 3, 1, 3, 1, 3, 1, 0, 3, 1, 3, 1, 3, 5, 3, 1, 3, 2, 0, 3, 3, 2, 0, 3, 3, 2, 0, 1, 3, 3, 5, 3, 5, 6, 8, 6, 8, 5, 0, 3, 1, 3, 2, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 7, 7, 7, 3, 3, 2, 4, 4, 4, 0, 1, 1, 3, 5, 1, 3, 1, 3, 2, 1, 1, 4, 3, 1, 1, 2, 3, 5 }; static const short yydefact[] = { 13, 104, 0, 0, 0, 0, 108, 112, 1, 2, 3, 0, 6, 13, 15, 16, 17, 18, 20, 19, 0, 103, 0, 124, 101, 0, 124, 8, 0, 107, 0, 11, 0, 111, 113, 4, 21, 12, 14, 0, 104, 13, 0, 0, 0, 100, 0, 0, 0, 152, 108, 0, 0, 152, 112, 0, 0, 0, 82, 78, 0, 0, 79, 40, 21, 33, 80, 0, 0, 42, 0, 83, 38, 36, 0, 32, 71, 78, 0, 0, 0, 106, 51, 67, 105, 0, 0, 0, 11, 0, 0, 0, 130, 0, 126, 129, 152, 102, 13, 0, 13, 82, 153, 0, 152, 0, 110, 134, 135, 140, 141, 139, 137, 136, 138, 0, 109, 0, 10, 115, 114, 0, 0, 23, 21, 0, 152, 0, 31, 41, 0, 0, 88, 0, 0, 30, 0, 86, 0, 84, 21, 37, 0, 0, 93, 0, 75, 68, 69, 70, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 123, 124, 124, 128, 152, 125, 0, 0, 0, 0, 9, 0, 7, 82, 0, 148, 0, 0, 0, 112, 0, 0, 47, 0, 35, 21, 0, 0, 0, 21, 0, 21, 97, 0, 95, 72, 0, 81, 83, 39, 22, 74, 92, 0, 90, 0, 64, 65, 61, 62, 60, 63, 66, 52, 53, 59, 54, 56, 57, 55, 58, 0, 117, 142, 131, 132, 133, 0, 127, 13, 119, 121, 5, 146, 147, 0, 152, 163, 0, 162, 152, 116, 0, 44, 48, 0, 0, 25, 0, 94, 29, 28, 89, 34, 0, 43, 0, 87, 85, 73, 93, 76, 152, 0, 0, 0, 0, 159, 0, 157, 151, 150, 152, 161, 149, 24, 21, 47, 21, 0, 21, 0, 98, 96, 91, 118, 0, 120, 122, 0, 0, 0, 82, 166, 0, 45, 49, 50, 0, 26, 77, 0, 0, 0, 154, 160, 152, 158, 152, 0, 46, 21, 99, 0, 0, 0, 143, 165, 0, 164, 167, 27, 0, 152, 155, 0, 168, 152, 144, 145, 112, 169, 156, 0, 170, 0, 0, 0 }; static const short yydefgoto[] = { 340, 8, 9, 10, 48, 32, 11, 86, 13, 72, 73, 74, 128, 135, 247, 248, 249, 105, 82, 83, 76, 138, 139, 136, 208, 209, 129, 198, 199, 14, 25, 15, 21, 22, 16, 29, 30, 17, 242, 34, 92, 18, 19, 43, 93, 94, 95, 229, 106, 107, 108, 231, 109, 110, 111, 112, 113, 114, 115, 308, 309, 273, 274, 243, 244, 278, 299, 324, 325 }; static const short yypact[] = { 29, 0, 19, 21, 33, 36, 44, 46,-32768,-32768,-32768, 30, 73, 32,-32768,-32768,-32768,-32768,-32768,-32768, 40, -32768, 34, -23, 35, 49, 51, 53, 56,-32768, 57, -2, 60,-32768, 63,-32768, 517,-32768,-32768, 120, 0, 32, 11, 66, 21,-32768, 83, 86, 88, 366, 44, 120, 86, 366, 46, 120, 123, 125,-32768, 95, 120, 97,-32768, 100, 517,-32768,-32768, 120, 120, 104, 120, 120, 106,-32768, 142, 39,-32768,-32768, 120, 120, 120, 546,-32768, 50,-32768, 110, 73, 143, 114, 145, 86, 128,-32768, 129, 130,-32768, 366,-32768, 167, 134, 32, 481,-32768, 416, 366, 257,-32768,-32768,-32768,-32768,-32768, -32768,-32768,-32768,-32768, 14,-32768, 583,-32768,-32768,-32768, 515, 158,-32768, 517, 530, 366, 120,-32768,-32768, 147, 176, 296, 179, 120,-32768, 140, 273, 141, 151, 517, -32768, 120, 180, 120, 120,-32768,-32768,-32768,-32768, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120,-32768, 51, 51,-32768, 15,-32768, 11, 146, 152, 153,-32768, 157, 73, 28, 169,-32768, 120, 156, 196, 46, 197, 185, 120, 120,-32768, 517, 181, 172, 120, 517, 120, 517, 605, 195, 201,-32768, 120,-32768, 120,-32768, 546,-32768, 546, 199, 204, 174, 148, 148, 148, 148, 148, 148, 148, 225, 225, 225, -32768,-32768,-32768,-32768,-32768, 207,-32768,-32768,-32768,-32768, -32768, 245,-32768, 404,-32768,-32768,-32768,-32768, 546, 430, 366,-32768, 246, 253, 366,-32768, 250, 239, 218, 220, 561, 259, 120,-32768, 546,-32768,-32768,-32768, 120,-32768, 120, 546,-32768,-32768, 120,-32768, 366, 221, 226, 227, 315,-32768, 217, 230,-32768,-32768, 380,-32768,-32768,-32768, 517, 120, 517, 120, 517, 646, 627,-32768,-32768,-32768, 261,-32768,-32768, 120, 256, 430, 42,-32768, 258, 229, -32768,-32768, 242,-32768,-32768, 120, 270, 233, 238, 546, 366,-32768, 366, 120,-32768, 517, 546, 269, 319, 261, -32768,-32768, 247,-32768, 297,-32768, 299, 15,-32768, 295, 120, 366,-32768,-32768, 46,-32768,-32768, 298,-32768, 344, 346,-32768 }; static const short yypgoto[] = {-32768, -32768,-32768,-32768,-32768, -34, -38, 27,-32768, -114, -3, -50,-32768,-32768,-32768, 80,-32768, -39, 52, -31,-32768, 160,-32768, -61, 99,-32768,-32768, 122,-32768,-32768, 321, -32768, 345,-32768,-32768, 334,-32768,-32768, -1,-32768,-32768, -32768,-32768, -22, 216,-32768, 301,-32768, -52, -167,-32768, 61,-32768,-32768,-32768,-32768,-32768,-32768, -158, 68,-32768, 96,-32768, 59,-32768,-32768,-32768, 67,-32768 }; #define YYLAST 711 static const short yytable[] = { 81, 119, 230, 85, 46, 75, 33, 133, 91, 37, 189, 232, 117, 99, 130, 20, 121, 182, 118, 246, 51, 125, 41, 42, 87, 183, 88, 12, 131, 132, 228, 132, 137, 75, 23, 1, 89, 24, 1, 102, 38, 52, 2, 184, 172, 2, 185, 3, 26, 90, 3, 27, 180, 120, 4, 5, 91, 4, 142, 28, 174, 31, 176, -142, 132, 6, 192, 7, 6, 179, 7, 52, 35, 272, 191, -11, 252, 36, 44, 40, 256, 143, 258, 37, 210, 144, 313, 145, 132, 146, 204, 39, 143, 75, 45, 197, 144, 42, 145, 47, 146, 88, 50, 205, 53, 207, 132, 49, 54, 75, 96, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 250, 177, 98, 272, 147, 148, 149, 100, 257, 58, 77, 91, 122, 124, 61, 123, 239, 126, 226, 227, 127, 62, 132, 251, 134, 140, 141, 66, 255, 165, 132, 52, 166, 75, 167, 333, 262, 75, 137, 75, 70, 300, 71, 302, 232, 304, 169, 1, 37, 171, 170, 188, 78, 79, 2, 175, 173, 194, 193, 3, 196, 200, 80, 275, 202, 234, 4, 279, 203, 206, 270, 235, 236, 237, 228, 271, 326, 6, 240, 7, 157, 158, 159, 160, 161, 162, 163, 164, 286, 290, 238, 241, 245, 254, 287, 250, 197, 266, 253, 298, 207, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 260, 132, 261, 303, 264, 265, 268, 316, 75, 267, 75, 323, 75, 310, 276, 271, 277, 321, 280, 322, 281, 282, 283, 181, 295, 317, 285, 291, 323, 292, 293, 296, 315, 132, 307, 311, 318, 314, 337, 201, 319, 320, 327, 75, 160, 161, 162, 163, 164, 330, 132, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 294, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 195, 328, 335, 331, 332, 341, 339, 342, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 301, 263, 289, 97, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 101, 77, 288, 116, 84, 61, 233, 329, 334, 102, 168, 312, 62, 338, 297, 77, 0, 336, 66, 61, 0, 0, 0, 102, 0, 0, 62, 0, 0, 1, 0, 103, 66, 71, 0, 104, 2, 0, 269, 0, 0, 3, 0, 78, 79, 103, 0, 71, 4, 104, 178, 77, 0, 80, 0, 61, 0, 78, 79, 6, 0, 7, 62, 0, 101, 77, 0, 80, 66, 61, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 0, 70, 66, 71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 78, 79, 70, 0, 71, 0, 0, -142, 0, 0, 80, -142, -142, -142, 78, 79, 0, -142, 0, 0, -142, 0, 0, 0, 80, -142, 0, 0, -142, 0, 0, 0, -142, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -142, 0, -142, 0, 36, 55, 0, -142, 0, -142, 0, -142, 56, -142, 57, 58, 59, 60, 0, 187, 61, 0, 0, 0, 0, 0, 0, 62, 63, 0, 64, 65, 0, 66, 0, 0, 0, 0, 0, 67, 68, 69, 0, 0, 0, 0, 70, 190, 71, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 284, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 186, 0, 0, 0, 0, 0, 0, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 259, 0, 0, 0, 0, 0, 0, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 306, 0, 0, 0, 0, 0, 0, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 305, 0, 0, 0, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164 }; static const short yycheck[] = { 39, 53, 169, 41, 26, 36, 7, 68, 42, 12, 124, 169, 51, 47, 64, 15, 55, 3, 52, 186, 22, 60, 45, 46, 13, 11, 15, 0, 67, 68, 15, 70, 71, 64, 15, 6, 25, 16, 6, 24, 13, 43, 13, 29, 96, 13, 32, 18, 15, 38, 18, 15, 104, 54, 25, 26, 90, 25, 19, 15, 98, 15, 100, 21, 103, 36, 127, 38, 36, 103, 38, 43, 42, 240, 126, 47, 190, 4, 43, 45, 194, 42, 196, 86, 145, 46, 44, 48, 127, 50, 140, 51, 42, 124, 45, 134, 46, 46, 48, 46, 50, 15, 45, 142, 44, 144, 145, 51, 45, 140, 44, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 187, 100, 45, 296, 78, 79, 80, 45, 195, 15, 16, 171, 15, 44, 20, 16, 181, 46, 166, 167, 46, 27, 187, 188, 46, 45, 10, 33, 193, 45, 195, 43, 15, 190, 15, 328, 201, 194, 203, 196, 46, 281, 48, 283, 328, 285, 44, 6, 177, 45, 47, 19, 58, 59, 13, 47, 15, 7, 37, 18, 7, 47, 68, 241, 49, 45, 25, 245, 43, 15, 234, 45, 45, 42, 15, 240, 316, 36, 48, 38, 58, 59, 60, 61, 62, 63, 64, 65, 253, 267, 47, 21, 21, 47, 259, 282, 261, 49, 43, 277, 265, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 47, 282, 43, 284, 47, 43, 3, 7, 281, 44, 283, 314, 285, 294, 10, 296, 5, 311, 10, 313, 23, 45, 44, 8, 49, 306, 9, 48, 331, 45, 45, 43, 45, 314, 15, 21, 8, 21, 332, 8, 49, 45, 15, 316, 61, 62, 63, 64, 65, 44, 331, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 8, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 43, 21, 46, 45, 44, 0, 47, 0, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 282, 203, 265, 44, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 15, 16, 261, 50, 40, 20, 171, 320, 328, 24, 90, 296, 27, 335, 15, 16, -1, 331, 33, 20, -1, -1, -1, 24, -1, -1, 27, -1, -1, 6, -1, 46, 33, 48, -1, 50, 13, -1, 15, -1, -1, 18, -1, 58, 59, 46, -1, 48, 25, 50, 15, 16, -1, 68, -1, 20, -1, 58, 59, 36, -1, 38, 27, -1, 15, 16, -1, 68, 33, 20, -1, -1, -1, -1, -1, -1, 27, -1, -1, -1, -1, 46, 33, 48, -1, -1, -1, -1, -1, -1, -1, -1, -1, 58, 59, 46, -1, 48, -1, -1, 0, -1, -1, 68, 4, 5, 6, 58, 59, -1, 10, -1, -1, 13, -1, -1, -1, 68, 18, -1, -1, 21, -1, -1, -1, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 36, -1, 38, -1, 4, 5, -1, 43, -1, 45, -1, 47, 12, 49, 14, 15, 16, 17, -1, 21, 20, -1, -1, -1, -1, -1, -1, 27, 28, -1, 30, 31, -1, 33, -1, -1, -1, -1, -1, 39, 40, 41, -1, -1, -1, -1, 46, 34, 48, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 35, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 44, -1, -1, -1, -1, -1, -1, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 44, -1, -1, -1, -1, -1, -1, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 44, -1, -1, -1, -1, -1, -1, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 47, -1, -1, -1, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65 }; /* -*-C-*- Note some compilers choke on comments on `#line' lines. */ #line 3 "/usr/local/share/bison.simple" /* Skeleton output parser for bison, Copyright (C) 1984, 1989, 1990 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* As a special exception, when this file is copied by Bison into a Bison output file, you may use that output file without restriction. This special exception was added by the Free Software Foundation in version 1.24 of Bison. */ #ifndef alloca #ifdef __GNUC__ #define alloca __builtin_alloca #else /* not GNU C. */ #if (!defined (__STDC__) && defined (sparc)) || defined (__sparc__) || defined (__sparc) || defined (__sgi) #include <alloca.h> #else /* not sparc */ #if defined (MSDOS) && !defined (__TURBOC__) #include <malloc.h> #else /* not MSDOS, or __TURBOC__ */ #if defined(_AIX) #include <malloc.h> #pragma alloca #else /* not MSDOS, __TURBOC__, or _AIX */ #ifdef __hpux #ifdef __cplusplus extern "C" { void *alloca (unsigned int); }; #else /* not __cplusplus */ void *alloca (); #endif /* not __cplusplus */ #endif /* __hpux */ #endif /* not _AIX */ #endif /* not MSDOS, or __TURBOC__ */ #endif /* not sparc. */ #endif /* not GNU C. */ #endif /* alloca not defined. */ /* This is the parser code that is written into each bison parser when the %semantic_parser declaration is not specified in the grammar. It was written by Richard Stallman by simplifying the hairy parser used when %semantic_parser is specified. */ /* Note: there must be only one dollar sign in this file. It is replaced by the list of actions, each action as one case of the switch. */ #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY -2 #define YYEOF 0 #define YYACCEPT return(0) #define YYABORT return(1) #define YYERROR goto yyerrlab1 /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. */ #define YYFAIL goto yyerrlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(token, value) \ do \ if (yychar == YYEMPTY && yylen == 1) \ { yychar = (token), yylval = (value); \ yychar1 = YYTRANSLATE (yychar); \ YYPOPSTACK; \ goto yybackup; \ } \ else \ { yyerror ("syntax error: cannot back up"); YYERROR; } \ while (0) #define YYTERROR 1 #define YYERRCODE 256 #ifndef YYPURE #define YYLEX yylex() #endif #ifdef YYPURE #ifdef YYLSP_NEEDED #ifdef YYLEX_PARAM #define YYLEX yylex(&yylval, &yylloc, YYLEX_PARAM) #else #define YYLEX yylex(&yylval, &yylloc) #endif #else /* not YYLSP_NEEDED */ #ifdef YYLEX_PARAM #define YYLEX yylex(&yylval, YYLEX_PARAM) #else #define YYLEX yylex(&yylval) #endif #endif /* not YYLSP_NEEDED */ #endif /* If nonreentrant, generate the variables here */ #ifndef YYPURE int yychar; /* the lookahead symbol */ YYSTYPE yylval; /* the semantic value of the */ /* lookahead symbol */ #ifdef YYLSP_NEEDED YYLTYPE yylloc; /* location data for the lookahead */ /* symbol */ #endif int yynerrs; /* number of parse errors so far */ #endif /* not YYPURE */ #if YYDEBUG != 0 int yydebug; /* nonzero means print parse trace */ /* Since this is uninitialized, it does not stop multiple parsers from coexisting. */ #endif /* YYINITDEPTH indicates the initial size of the parser's stacks */ #ifndef YYINITDEPTH #define YYINITDEPTH 200 #endif /* YYMAXDEPTH is the maximum size the stacks can grow to (effective only if the built-in stack extension method is used). */ #if YYMAXDEPTH == 0 #undef YYMAXDEPTH #endif #ifndef YYMAXDEPTH #define YYMAXDEPTH 10000 #endif /* Prevent warning if -Wstrict-prototypes. */ #ifdef __GNUC__ int yyparse (void); #endif #if __GNUC__ > 1 /* GNU C and GNU C++ define this. */ #define __yy_memcpy(FROM,TO,COUNT) __builtin_memcpy(TO,FROM,COUNT) #else /* not GNU C or C++ */ #ifndef __cplusplus /* This is the most reliable way to avoid incompatibilities in available built-in functions on various systems. */ static void __yy_memcpy (from, to, count) char *from; char *to; int count; { register char *f = from; register char *t = to; register int i = count; while (i-- > 0) *t++ = *f++; } #else /* __cplusplus */ /* This is the most reliable way to avoid incompatibilities in available built-in functions on various systems. */ static void __yy_memcpy (char *from, char *to, int count) { register char *f = from; register char *t = to; register int i = count; while (i-- > 0) *t++ = *f++; } #endif #endif #line 192 "/usr/local/share/bison.simple" /* The user can define YYPARSE_PARAM as the name of an argument to be passed into yyparse. The argument should have type void *. It should actually point to an object. Grammar actions can access the variable by casting it to the proper pointer type. */ #ifdef YYPARSE_PARAM #define YYPARSE_PARAM_DECL void *YYPARSE_PARAM; #else #define YYPARSE_PARAM #define YYPARSE_PARAM_DECL #endif int yyparse(YYPARSE_PARAM) YYPARSE_PARAM_DECL { register int yystate; register int yyn; register short *yyssp; register YYSTYPE *yyvsp; int yyerrstatus; /* number of tokens to shift before error messages enabled */ int yychar1 = 0; /* lookahead token as an internal (translated) token number */ short yyssa[YYINITDEPTH]; /* the state stack */ YYSTYPE yyvsa[YYINITDEPTH]; /* the semantic value stack */ short *yyss = yyssa; /* refer to the stacks thru separate pointers */ YYSTYPE *yyvs = yyvsa; /* to allow yyoverflow to reallocate them elsewhere */ #ifdef YYLSP_NEEDED YYLTYPE yylsa[YYINITDEPTH]; /* the location stack */ YYLTYPE *yyls = yylsa; YYLTYPE *yylsp; #define YYPOPSTACK (yyvsp--, yyssp--, yylsp--) #else #define YYPOPSTACK (yyvsp--, yyssp--) #endif int yystacksize = YYINITDEPTH; #ifdef YYPURE int yychar; YYSTYPE yylval; int yynerrs; #ifdef YYLSP_NEEDED YYLTYPE yylloc; #endif #endif YYSTYPE yyval; /* the variable used to return */ /* semantic values from the action */ /* routines */ int yylen; #if YYDEBUG != 0 if (yydebug) fprintf(stderr, "Starting parse\n"); #endif yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss - 1; yyvsp = yyvs; #ifdef YYLSP_NEEDED yylsp = yyls; #endif /* Push a new state, which is found in yystate . */ /* In all cases, when you get here, the value and location stacks have just been pushed. so pushing a state here evens the stacks. */ yynewstate: *++yyssp = yystate; if (yyssp >= yyss + yystacksize - 1) { /* Give user a chance to reallocate the stack */ /* Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; short *yyss1 = yyss; #ifdef YYLSP_NEEDED YYLTYPE *yyls1 = yyls; #endif /* Get the current used size of the three stacks, in elements. */ int size = yyssp - yyss + 1; #ifdef yyoverflow /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. */ #ifdef YYLSP_NEEDED /* This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow("parser stack overflow", &yyss1, size * sizeof (*yyssp), &yyvs1, size * sizeof (*yyvsp), &yyls1, size * sizeof (*yylsp), &yystacksize); #else yyoverflow("parser stack overflow", &yyss1, size * sizeof (*yyssp), &yyvs1, size * sizeof (*yyvsp), &yystacksize); #endif yyss = yyss1; yyvs = yyvs1; #ifdef YYLSP_NEEDED yyls = yyls1; #endif #else /* no yyoverflow */ /* Extend the stack our own way. */ if (yystacksize >= YYMAXDEPTH) { yyerror("parser stack overflow"); return 2; } yystacksize *= 2; if (yystacksize > YYMAXDEPTH) yystacksize = YYMAXDEPTH; yyss = (short *) alloca (yystacksize * sizeof (*yyssp)); __yy_memcpy ((char *)yyss1, (char *)yyss, size * sizeof (*yyssp)); yyvs = (YYSTYPE *) alloca (yystacksize * sizeof (*yyvsp)); __yy_memcpy ((char *)yyvs1, (char *)yyvs, size * sizeof (*yyvsp)); #ifdef YYLSP_NEEDED yyls = (YYLTYPE *) alloca (yystacksize * sizeof (*yylsp)); __yy_memcpy ((char *)yyls1, (char *)yyls, size * sizeof (*yylsp)); #endif #endif /* no yyoverflow */ yyssp = yyss + size - 1; yyvsp = yyvs + size - 1; #ifdef YYLSP_NEEDED yylsp = yyls + size - 1; #endif #if YYDEBUG != 0 if (yydebug) fprintf(stderr, "Stack size increased to %d\n", yystacksize); #endif if (yyssp >= yyss + yystacksize - 1) YYABORT; } #if YYDEBUG != 0 if (yydebug) fprintf(stderr, "Entering state %d\n", yystate); #endif goto yybackup; yybackup: /* Do appropriate processing given the current state. */ /* Read a lookahead token if we need one and don't already have one. */ /* yyresume: */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yyn == YYFLAG) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* yychar is either YYEMPTY or YYEOF or a valid token in external form. */ if (yychar == YYEMPTY) { #if YYDEBUG != 0 if (yydebug) fprintf(stderr, "Reading a token: "); #endif yychar = YYLEX; } /* Convert token to internal form (in yychar1) for indexing tables with */ if (yychar <= 0) /* This means end of input. */ { yychar1 = 0; yychar = YYEOF; /* Don't call YYLEX any more */ #if YYDEBUG != 0 if (yydebug) fprintf(stderr, "Now at end of input.\n"); #endif } else { yychar1 = YYTRANSLATE(yychar); #if YYDEBUG != 0 if (yydebug) { fprintf (stderr, "Next token is %d (%s", yychar, yytname[yychar1]); /* Give the individual parser a way to print the precise meaning of a token, for further debugging info. */ #ifdef YYPRINT YYPRINT (stderr, yychar, yylval); #endif fprintf (stderr, ")\n"); } #endif } yyn += yychar1; if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != yychar1) goto yydefault; yyn = yytable[yyn]; /* yyn is what to do for this token type in this state. Negative => reduce, -yyn is rule number. Positive => shift, yyn is new state. New state is final state => don't bother to shift, just return success. 0, or most negative number => error. */ if (yyn < 0) { if (yyn == YYFLAG) goto yyerrlab; yyn = -yyn; goto yyreduce; } else if (yyn == 0) goto yyerrlab; if (yyn == YYFINAL) YYACCEPT; /* Shift the lookahead token. */ #if YYDEBUG != 0 if (yydebug) fprintf(stderr, "Shifting token %d (%s), ", yychar, yytname[yychar1]); #endif /* Discard the token being shifted unless it is eof. */ if (yychar != YYEOF) yychar = YYEMPTY; *++yyvsp = yylval; #ifdef YYLSP_NEEDED *++yylsp = yylloc; #endif /* count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; yystate = yyn; goto yynewstate; /* Do the default action for the current state. */ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; /* Do a reduction. yyn is the number of a rule to reduce with. */ yyreduce: yylen = yyr2[yyn]; if (yylen > 0) yyval = yyvsp[1-yylen]; /* implement default value of the action */ #if YYDEBUG != 0 if (yydebug) { int i; fprintf (stderr, "Reducing via rule %d (line %d), ", yyn, yyrline[yyn]); /* Print the symbols being reduced, and their result. */ for (i = yyprhs[yyn]; yyrhs[i] > 0; i++) fprintf (stderr, "%s ", yytname[yyrhs[i]]); fprintf (stderr, " -> %s\n", yytname[yyr1[yyn]]); } #endif switch (yyn) { case 1: #line 224 "parser.y" { yyvsp[0].n_node->attrib(ctx_program); yyvsp[0].n_node->translate(ctx_program); ; break;} case 4: #line 231 "parser.y" { yyval.n_node = new program_node(NULL, NULL, NULL, NULL, yyvsp[-1].n_block, yyvsp[0].tok); ; break;} case 5: #line 233 "parser.y" { yyval.n_node = new program_node(yyvsp[-5].tok, yyvsp[-4].tok, yyvsp[-3].n_imp, yyvsp[-2].tok, yyvsp[-1].n_block, yyvsp[0].tok); ; break;} case 6: #line 237 "parser.y" { yyval.n_node = new module_node(NULL, NULL, NULL, NULL, yyvsp[0].n_decl); ; break;} case 7: #line 239 "parser.y" { yyval.n_node = new module_node(yyvsp[-4].tok, yyvsp[-3].tok, yyvsp[-2].n_imp, yyvsp[-1].tok, yyvsp[0].n_decl); ; break;} case 8: #line 244 "parser.y" { yyval.n_imp = NULL; ; break;} case 9: #line 245 "parser.y" { yyval.n_imp = new import_list_node(yyvsp[-2].tok, yyvsp[-1].toks, yyvsp[0].tok); ; break;} case 10: #line 247 "parser.y" { yyval.toks = new token_list(yyvsp[-2].tok, yyvsp[0].toks); ; break;} case 11: #line 248 "parser.y" { yyval.toks = new token_list(yyvsp[0].tok); ; break;} case 12: #line 251 "parser.y" { yyval.n_block = new block_node(yyvsp[-1].n_decl, yyvsp[0].n_comp); ; break;} case 13: #line 255 "parser.y" { yyval.n_decl = NULL; ; break;} case 14: #line 256 "parser.y" { yyvsp[-1].n_decl->next = yyvsp[0].n_decl; yyval.n_decl = yyvsp[-1].n_decl; ; break;} case 21: #line 288 "parser.y" { yyval.n_stmt = new empty_node(curr_token->prev_relevant()); ; break;} case 22: #line 289 "parser.y" { yyval.n_stmt = new assign_node(yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 23: #line 290 "parser.y" { yyval.n_stmt = new goto_node(yyvsp[-1].tok, yyvsp[0].tok); ; break;} case 24: #line 291 "parser.y" { yyval.n_stmt = new switch_node(yyvsp[-4].tok, yyvsp[-3].n_expr, yyvsp[-2].tok, yyvsp[-1].n_case, yyvsp[0].tok); ; break;} case 25: #line 292 "parser.y" { yyval.n_stmt = new if_node(yyvsp[-3].tok, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_stmt); ; break;} case 26: #line 294 "parser.y" { yyval.n_stmt = new if_node(yyvsp[-5].tok, yyvsp[-4].n_expr, yyvsp[-3].tok, yyvsp[-2].n_stmt, yyvsp[-1].tok, yyvsp[0].n_stmt); ; break;} case 27: #line 296 "parser.y" { yyval.n_stmt = new for_node(yyvsp[-7].tok, yyvsp[-6].tok, yyvsp[-5].tok, yyvsp[-4].n_expr, yyvsp[-3].tok, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_stmt); ; break;} case 28: #line 297 "parser.y" { yyval.n_stmt = new while_node(yyvsp[-3].tok, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_stmt); ; break;} case 29: #line 298 "parser.y" { yyval.n_stmt = new repeat_node(yyvsp[-3].tok, yyvsp[-2].n_stmt, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 30: #line 299 "parser.y" { yyval.n_stmt = new write_node(yyvsp[-1].tok, yyvsp[0].n_wrls); ; break;} case 31: #line 300 "parser.y" { yyval.n_stmt = new read_node(yyvsp[-1].tok, yyvsp[0].n_grp); ; break;} case 32: #line 301 "parser.y" { yyval.n_stmt = new pcall_node(yyvsp[0].n_expr); ; break;} case 33: #line 302 "parser.y" { yyval.n_stmt = new return_node(yyvsp[0].tok); ; break;} case 34: #line 303 "parser.y" { yyval.n_stmt = new with_node(yyvsp[-3].tok, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_stmt); ; break;} case 35: #line 304 "parser.y" { yyval.n_stmt = new label_node(yyvsp[-2].tok, yyvsp[-1].tok, yyvsp[0].n_stmt); ; break;} case 36: #line 305 "parser.y" { yyval.n_stmt = yyvsp[0].n_comp; ; break;} case 37: #line 307 "parser.y" { yyval.n_comp = new compound_node(yyvsp[-2].tok, yyvsp[-1].n_stmt, yyvsp[0].tok); ; break;} case 39: #line 309 "parser.y" { yyvsp[-2].n_stmt->next = yyvsp[0].n_stmt; yyval.n_stmt = yyvsp[-2].n_stmt; ; break;} case 40: #line 310 "parser.y" { yyval.n_grp = NULL; ; break;} case 41: #line 310 "parser.y" { yyval.n_grp = yyvsp[0].n_grp; ; break;} case 42: #line 312 "parser.y" { yyval.n_wrls = NULL; ; break;} case 43: #line 313 "parser.y" { yyval.n_wrls = new write_list_node(yyvsp[-2].tok, yyvsp[-1].n_wrtp, yyvsp[0].tok); ; break;} case 45: #line 317 "parser.y" { if (yyvsp[-2].n_case != NULL) { case_node** cpp; for(cpp = &yyvsp[-2].n_case->next; *cpp != NULL; cpp = &(*cpp)->next); *cpp = new case_node(NULL, yyvsp[-1].tok, yyvsp[0].n_stmt); yyval.n_case = yyvsp[-2].n_case; } else { yyval.n_case = new case_node(NULL, yyvsp[-1].tok, yyvsp[0].n_stmt); } ; break;} case 46: #line 328 "parser.y" { if (yyvsp[-3].n_case != NULL) { case_node** cpp; for(cpp = &yyvsp[-3].n_case->next; *cpp != NULL; cpp = &(*cpp)->next); *cpp = new case_node(NULL, yyvsp[-2].tok, yyvsp[-1].n_stmt); yyval.n_case = yyvsp[-3].n_case; } else { yyval.n_case = new case_node(NULL, yyvsp[-2].tok, yyvsp[-1].n_stmt); } ; break;} case 47: #line 339 "parser.y" { yyval.n_case = NULL; ; break;} case 49: #line 341 "parser.y" { yyvsp[-2].n_case->next = yyvsp[0].n_case; yyval.n_case = yyvsp[-2].n_case; ; break;} case 50: #line 343 "parser.y" { yyval.n_case = new case_node(yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_stmt); ; break;} case 52: #line 368 "parser.y" { yyval.n_expr = new op_node(tn_add, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 53: #line 369 "parser.y" { yyval.n_expr = new op_node(tn_sub, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 54: #line 370 "parser.y" { yyval.n_expr = new op_node(tn_mod, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 55: #line 371 "parser.y" { yyval.n_expr = new op_node(tn_mul, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 56: #line 372 "parser.y" { yyval.n_expr = new op_node(tn_div, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 57: #line 373 "parser.y" { yyval.n_expr = new op_node(tn_divr, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 58: #line 375 "parser.y" { yyval.n_expr = new op_node(tn_and, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 59: #line 376 "parser.y" { yyval.n_expr = new op_node(tn_or, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 60: #line 378 "parser.y" { yyval.n_expr = new op_node(tn_gt, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 61: #line 379 "parser.y" { yyval.n_expr = new op_node(tn_lt, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 62: #line 380 "parser.y" { yyval.n_expr = new op_node(tn_le, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 63: #line 381 "parser.y" { yyval.n_expr = new op_node(tn_ge, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 64: #line 382 "parser.y" { yyval.n_expr = new op_node(tn_eq, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 65: #line 383 "parser.y" { yyval.n_expr = new op_node(tn_ne, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 66: #line 384 "parser.y" { yyval.n_expr = new op_node(tn_in, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 68: #line 387 "parser.y" { yyval.n_expr = new op_node(tn_plus, NULL, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 69: #line 390 "parser.y" { yyval.n_expr = new op_node(tn_minus, NULL, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 70: #line 392 "parser.y" { yyval.n_expr = new op_node(tn_not, NULL, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 72: #line 395 "parser.y" { yyval.n_expr = new expr_group_node(yyvsp[-2].tok, yyvsp[-1].n_expr, yyvsp[0].tok); ; break;} case 73: #line 396 "parser.y" { yyval.n_expr = new fcall_node(yyvsp[-3].n_expr, yyvsp[-2].tok, yyvsp[-1].n_expr, yyvsp[0].tok); ; break;} case 74: #line 397 "parser.y" { yyval.n_expr = new access_expr_node(yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].tok); ; break;} case 75: #line 398 "parser.y" { yyval.n_expr = new deref_expr_node(yyvsp[-1].n_expr, yyvsp[0].tok); ; break;} case 76: #line 399 "parser.y" { yyval.n_expr = new idx_expr_node(yyvsp[-3].n_expr, yyvsp[-2].tok, yyvsp[-1].n_expr, yyvsp[0].tok); ; break;} case 77: #line 400 "parser.y" { yyval.n_expr = new loophole_node(yyvsp[-5].tok, yyvsp[-4].tok, yyvsp[-3].n_tpd, yyvsp[-2].tok, yyvsp[-1].n_expr, yyvsp[0].tok); ; break;} case 78: #line 402 "parser.y" { yyval.n_expr = new integer_node(yyvsp[0].tok); ; break;} case 79: #line 403 "parser.y" { yyval.n_expr = new real_node(yyvsp[0].tok); ; break;} case 80: #line 404 "parser.y" { yyval.n_expr = new string_node(yyvsp[0].tok); ; break;} case 81: #line 405 "parser.y" { yyval.n_expr = new set_node(yyvsp[-2].tok, yyvsp[-1].n_item, yyvsp[0].tok); ; break;} case 82: #line 406 "parser.y" { yyval.n_expr = new atom_expr_node(yyvsp[0].tok); ; break;} case 83: #line 408 "parser.y" { yyval.n_item = NULL; ; break;} case 85: #line 410 "parser.y" { yyvsp[-2].n_item->next = yyvsp[0].n_item; yyval.n_item = yyvsp[-2].n_item; ; break;} case 86: #line 412 "parser.y" { yyval.n_item = new set_elem_node(yyvsp[0].n_expr); ; break;} case 87: #line 413 "parser.y" { yyval.n_item = new set_range_node(yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 89: #line 415 "parser.y" { yyvsp[-2].n_expr->next = yyvsp[0].n_expr; yyval.n_expr = yyvsp[-2].n_expr; ; break;} case 91: #line 418 "parser.y" { yyvsp[-2].n_expr->next = yyvsp[0].n_expr; yyval.n_expr = yyvsp[-2].n_expr; ; break;} case 93: #line 420 "parser.y" { yyval.n_expr = new skipped_node(curr_token->prev_relevant()); ; break;} case 94: #line 423 "parser.y" { yyval.n_grp = new expr_group_node(yyvsp[-2].tok, yyvsp[-1].n_expr, yyvsp[0].tok); ; break;} case 96: #line 426 "parser.y" { yyvsp[-2].n_wrtp->next = yyvsp[0].n_wrtp; yyval.n_wrtp = yyvsp[-2].n_wrtp; ; break;} case 97: #line 428 "parser.y" { yyval.n_wrtp = new write_param_node(yyvsp[0].n_expr); ; break;} case 98: #line 429 "parser.y" { yyval.n_wrtp = new write_param_node(yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 99: #line 430 "parser.y" { yyval.n_wrtp = new write_param_node(yyvsp[-4].n_expr, yyvsp[-3].tok, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 100: #line 473 "parser.y" { yyval.n_decl = new label_decl_part_node(yyvsp[-2].tok, yyvsp[-1].toks, yyvsp[0].tok); ; break;} case 101: #line 475 "parser.y" { yyval.toks = new token_list(yyvsp[0].tok); ; break;} case 102: #line 476 "parser.y" { yyval.toks = new token_list(yyvsp[-2].tok, yyvsp[0].toks); ; break;} case 103: #line 479 "parser.y" { yyval.n_decl = new const_def_part_node(yyvsp[-1].tok, yyvsp[0].n_cdef); ; break;} case 104: #line 481 "parser.y" { yyval.n_cdef = NULL; ; break;} case 105: #line 482 "parser.y" { yyvsp[-2].n_cdef->next = yyvsp[0].n_cdef; yyval.n_cdef = yyvsp[-2].n_cdef; ; break;} case 106: #line 484 "parser.y" { yyval.n_cdef = new const_def_node(yyvsp[-2].tok, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 107: #line 487 "parser.y" { yyval.n_decl = new type_def_part_node(yyvsp[-1].tok, yyvsp[0].n_tdef); ; break;} case 108: #line 489 "parser.y" { yyval.n_tdef = NULL; ; break;} case 109: #line 490 "parser.y" { yyvsp[-2].n_tdef->next = yyvsp[0].n_tdef; yyval.n_tdef = yyvsp[-2].n_tdef; ; break;} case 110: #line 492 "parser.y" { yyval.n_tdef = new type_def_node(yyvsp[-2].tok, yyvsp[-1].tok, yyvsp[0].n_tpd); ; break;} case 111: #line 495 "parser.y" { yyval.n_decl = new var_decl_part_node(yyvsp[-1].tok, yyvsp[0].n_vdcl); ; break;} case 112: #line 497 "parser.y" { yyval.n_vdcl = NULL; ; break;} case 114: #line 499 "parser.y" { yyvsp[-2].n_vdcl->next = yyvsp[0].n_vdcl; yyval.n_vdcl = yyvsp[-2].n_vdcl; ; break;} case 115: #line 501 "parser.y" { yyval.n_vdcl = new var_decl_node(yyvsp[-2].toks, yyvsp[-1].tok, yyvsp[0].n_tpd); ; break;} case 116: #line 503 "parser.y" { yyval.n_vdcl = (var_decl_node*)new var_origin_decl_node(yyvsp[-4].tok, yyvsp[-3].tok, yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_tpd); ; break;} case 117: #line 507 "parser.y" { yyval.n_decl = new proc_decl_node(yyvsp[-2].tok, yyvsp[-1].tok, yyvsp[0].n_plist); ; break;} case 118: #line 509 "parser.y" { yyval.n_decl = new proc_decl_node(yyvsp[-4].tok, yyvsp[-3].tok, yyvsp[-2].n_plist, yyvsp[-1].tok, yyvsp[0].n_tpd); ; break;} case 119: #line 514 "parser.y" { yyval.n_decl = new proc_fwd_decl_node(yyvsp[-5].tok, yyvsp[-4].tok, yyvsp[-3].n_plist, NULL, NULL, yyvsp[-2].tok, yyvsp[-1].tok, yyvsp[0].tok); ; break;} case 120: #line 516 "parser.y" { yyval.n_decl = new proc_fwd_decl_node(yyvsp[-7].tok, yyvsp[-6].tok, yyvsp[-5].n_plist, yyvsp[-4].tok, yyvsp[-3].n_tpd, yyvsp[-2].tok, yyvsp[-1].tok, yyvsp[0].tok); ; break;} case 121: #line 520 "parser.y" { yyval.n_decl = new proc_def_node(yyvsp[-5].tok, yyvsp[-4].tok, yyvsp[-3].n_plist, NULL, NULL, yyvsp[-2].tok, yyvsp[-1].n_block, yyvsp[0].tok); ; break;} case 122: #line 522 "parser.y" { yyval.n_decl = new proc_def_node(yyvsp[-7].tok, yyvsp[-6].tok, yyvsp[-5].n_plist, yyvsp[-4].tok, yyvsp[-3].n_tpd, yyvsp[-2].tok, yyvsp[-1].n_block, yyvsp[0].tok); ; break;} case 123: #line 524 "parser.y" { yyval.n_decl = new proc_def_node(yyvsp[-4].tok, yyvsp[-3].tok, NULL, NULL, NULL, yyvsp[-2].tok, yyvsp[-1].n_block, yyvsp[0].tok); ; break;} case 124: #line 526 "parser.y" { yyval.n_plist = NULL; ; break;} case 125: #line 527 "parser.y" { yyval.n_plist = new param_list_node(yyvsp[-2].tok, yyvsp[-1].n_decl, yyvsp[0].tok); ; break;} case 127: #line 530 "parser.y" { yyvsp[-2].n_decl->next = yyvsp[0].n_decl; yyval.n_decl = yyvsp[-2].n_decl; ; break;} case 128: #line 532 "parser.y" { yyval.n_decl = new var_decl_part_node(yyvsp[-1].tok, yyvsp[0].n_vdcl); ; break;} case 129: #line 533 "parser.y" { yyval.n_decl = yyvsp[0].n_vdcl; ; break;} case 131: #line 535 "parser.y" { yyval.n_vdcl = new var_decl_node(yyvsp[-2].toks, yyvsp[-1].tok, yyvsp[0].n_tpd); ; break;} case 142: #line 546 "parser.y" { yyval.n_tpd = new simple_tpd_node(yyvsp[0].tok); ; break;} case 143: #line 549 "parser.y" { yyval.n_tpd = new array_tpd_node(yyvsp[-6].tok, yyvsp[-5].tok, yyvsp[-4].tok, yyvsp[-3].n_idx, yyvsp[-2].tok, yyvsp[-1].tok, yyvsp[0].n_tpd); ; break;} case 144: #line 552 "parser.y" { yyval.n_tpd = new array_tpd_node(yyvsp[-6].tok, yyvsp[-5].tok, yyvsp[-4].tok, yyvsp[-3].n_idx, yyvsp[-2].tok, yyvsp[-1].tok, yyvsp[0].n_tpd); ; break;} case 145: #line 554 "parser.y" { yyval.n_tpd = new array_tpd_node(yyvsp[-6].tok, yyvsp[-5].tok, yyvsp[-4].tok, yyvsp[-3].n_idx, yyvsp[-2].tok, yyvsp[-1].tok, yyvsp[0].n_tpd); ; break;} case 146: #line 556 "parser.y" { yyval.n_tpd = new enum_tpd_node(yyvsp[-2].tok, yyvsp[-1].toks, yyvsp[0].tok); ; break;} case 147: #line 559 "parser.y" { yyval.n_tpd = new range_tpd_node(yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 148: #line 561 "parser.y" { yyval.n_tpd = new ptr_tpd_node(yyvsp[-1].tok, yyvsp[0].n_tpd); ; break;} case 149: #line 563 "parser.y" { yyval.n_tpd = new set_tpd_node(yyvsp[-3].tok, yyvsp[-2].tok, yyvsp[-1].tok, yyvsp[0].n_tpd); ; break;} case 150: #line 566 "parser.y" { yyval.n_tpd = new record_tpd_node(yyvsp[-3].tok, yyvsp[-2].tok, yyvsp[-1].n_fldls, yyvsp[0].tok); ; break;} case 151: #line 568 "parser.y" { yyval.n_tpd = new file_tpd_node(yyvsp[-3].tok, yyvsp[-2].tok, yyvsp[-1].tok, yyvsp[0].n_tpd); ; break;} case 152: #line 570 "parser.y" { yyval.tok = NULL; ; break;} case 155: #line 573 "parser.y" { yyvsp[-2].n_idx->next = yyvsp[0].n_idx; yyval.n_idx = yyvsp[-2].n_idx; ; break;} case 156: #line 576 "parser.y" { yyval.n_idx = new conformant_index_node(yyvsp[-4].tok, yyvsp[-3].tok, yyvsp[-2].tok, yyvsp[-1].tok, yyvsp[0].n_tpd); ; break;} case 158: #line 579 "parser.y" { yyvsp[-2].n_idx->next = yyvsp[0].n_idx; yyval.n_idx = yyvsp[-2].n_idx; ; break;} case 159: #line 581 "parser.y" { yyval.n_idx = new type_index_node(yyvsp[0].n_tpd); ; break;} case 160: #line 582 "parser.y" { yyval.n_idx = new range_index_node(yyvsp[-2].n_expr, yyvsp[-1].tok, yyvsp[0].n_expr); ; break;} case 161: #line 587 "parser.y" { yyval.n_fldls = new field_list_node(yyvsp[-1].n_vdcl, yyvsp[0].n_varp); ; break;} case 162: #line 589 "parser.y" { yyval.n_fldls = new field_list_node(yyvsp[0].n_vdcl); ; break;} case 164: #line 594 "parser.y" { yyval.n_varp = new variant_part_node(yyvsp[-3].tok, yyvsp[-2].n_sel, yyvsp[-1].tok, yyvsp[0].n_vari); ; break;} case 165: #line 598 "parser.y" { yyval.n_sel = new selector_node(yyvsp[-2].tok, yyvsp[-1].tok, yyvsp[0].n_tpd); ; break;} case 166: #line 599 "parser.y" { yyval.n_sel = new selector_node(NULL, NULL, yyvsp[0].n_tpd); ; break;} case 168: #line 603 "parser.y" { yyval.n_vari = yyvsp[-1].n_vari; ; break;} case 169: #line 604 "parser.y" { yyvsp[-2].n_vari->next = yyvsp[0].n_vari; yyval.n_vari = yyvsp[-2].n_vari; ; break;} case 170: #line 607 "parser.y" { yyval.n_vari = new variant_node(yyvsp[-4].n_expr, yyvsp[-3].tok, yyvsp[-2].tok, yyvsp[-1].n_fldls, yyvsp[0].tok); ; break;} } /* the action file gets copied in in place of this dollarsign */ #line 487 "/usr/local/share/bison.simple" yyvsp -= yylen; yyssp -= yylen; #ifdef YYLSP_NEEDED yylsp -= yylen; #endif #if YYDEBUG != 0 if (yydebug) { short *ssp1 = yyss - 1; fprintf (stderr, "state stack now"); while (ssp1 != yyssp) fprintf (stderr, " %d", *++ssp1); fprintf (stderr, "\n"); } #endif *++yyvsp = yyval; #ifdef YYLSP_NEEDED yylsp++; if (yylen == 0) { yylsp->first_line = yylloc.first_line; yylsp->first_column = yylloc.first_column; yylsp->last_line = (yylsp-1)->last_line; yylsp->last_column = (yylsp-1)->last_column; yylsp->text = 0; } else { yylsp->last_line = (yylsp+yylen-1)->last_line; yylsp->last_column = (yylsp+yylen-1)->last_column; } #endif /* Now "shift" the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTBASE] + *yyssp; if (yystate >= 0 && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTBASE]; goto yynewstate; yyerrlab: /* here on detecting error */ if (! yyerrstatus) /* If not already recovering from an error, report this error. */ { ++yynerrs; #ifdef YYERROR_VERBOSE yyn = yypact[yystate]; if (yyn > YYFLAG && yyn < YYLAST) { int size = 0; char *msg; int x, count; count = 0; /* Start X at -yyn if nec to avoid negative indexes in yycheck. */ for (x = (yyn < 0 ? -yyn : 0); x < (sizeof(yytname) / sizeof(char *)); x++) if (yycheck[x + yyn] == x) size += strlen(yytname[x]) + 15, count++; msg = (char *) malloc(size + 15); if (msg != 0) { strcpy(msg, "parse error"); if (count < 5) { count = 0; for (x = (yyn < 0 ? -yyn : 0); x < (sizeof(yytname) / sizeof(char *)); x++) if (yycheck[x + yyn] == x) { strcat(msg, count == 0 ? ", expecting `" : " or `"); strcat(msg, yytname[x]); strcat(msg, "'"); count++; } } yyerror(msg); free(msg); } else yyerror ("parse error; also virtual memory exceeded"); } else #endif /* YYERROR_VERBOSE */ yyerror("parse error"); } goto yyerrlab1; yyerrlab1: /* here on error raised explicitly by an action */ if (yyerrstatus == 3) { /* if just tried and failed to reuse lookahead token after an error, discard it. */ /* return failure if at end of input */ if (yychar == YYEOF) YYABORT; #if YYDEBUG != 0 if (yydebug) fprintf(stderr, "Discarding token %d (%s).\n", yychar, yytname[yychar1]); #endif yychar = YYEMPTY; } /* Else will try to reuse lookahead token after shifting the error token. */ yyerrstatus = 3; /* Each real token shifted decrements this */ goto yyerrhandle; yyerrdefault: /* current state does not do anything special for the error token. */ #if 0 /* This is wrong; only states that explicitly want error tokens should shift them. */ yyn = yydefact[yystate]; /* If its default is to accept any token, ok. Otherwise pop it.*/ if (yyn) goto yydefault; #endif yyerrpop: /* pop the current state because it cannot handle the error token */ if (yyssp == yyss) YYABORT; yyvsp--; yystate = *--yyssp; #ifdef YYLSP_NEEDED yylsp--; #endif #if YYDEBUG != 0 if (yydebug) { short *ssp1 = yyss - 1; fprintf (stderr, "Error: state stack now"); while (ssp1 != yyssp) fprintf (stderr, " %d", *++ssp1); fprintf (stderr, "\n"); } #endif yyerrhandle: yyn = yypact[yystate]; if (yyn == YYFLAG) goto yyerrdefault; yyn += YYTERROR; if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != YYTERROR) goto yyerrdefault; yyn = yytable[yyn]; if (yyn < 0) { if (yyn == YYFLAG) goto yyerrpop; yyn = -yyn; goto yyreduce; } else if (yyn == 0) goto yyerrpop; if (yyn == YYFINAL) YYACCEPT; #if YYDEBUG != 0 if (yydebug) fprintf(stderr, "Shifting error token, "); #endif *++yyvsp = yylval; #ifdef YYLSP_NEEDED *++yylsp = yylloc; #endif yystate = yyn; goto yynewstate; } #line 611 "parser.y" int zzlex() { curr_token = curr_token ? curr_token->next_relevant() : token::first_relevant(); zzlval.tok = curr_token; return zzcnv_table[curr_token->tag]; }
[ [ [ 1, 1878 ] ] ]
e9baf8b66907e3711bffac85a916f0d74d2b288f
b799c972367cd014a1ffed4288a9deb72f590bec
/project/NetServices/drv/usb/UsbHostMgr.cpp
c25652717e114483c9cc2014b9c7240127ad9a8d
[]
no_license
intervigilium/csm213a-embedded
647087de8f831e3c69e05d847d09f5fa12b468e6
ae4622be1eef8eb6e4d1677a9b2904921be19a9e
refs/heads/master
2021-01-13T02:22:42.397072
2011-12-11T22:50:37
2011-12-11T22:50:37
2,832,079
2
1
null
null
null
null
UTF-8
C++
false
false
11,690
cpp
/* Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com) 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 "UsbHostMgr.h" #include "usb_mem.h" #include "string.h" //For memcpy, memmove, memset #include "netCfg.h" #if NET_USB //#define __DEBUG #include "dbg/dbg.h" // bits of the USB/OTG clock control register #define HOST_CLK_EN (1<<0) #define DEV_CLK_EN (1<<1) #define PORTSEL_CLK_EN (1<<3) #define AHB_CLK_EN (1<<4) // bits of the USB/OTG clock status register #define HOST_CLK_ON (1<<0) #define DEV_CLK_ON (1<<1) #define PORTSEL_CLK_ON (1<<3) #define AHB_CLK_ON (1<<4) // we need host clock, OTG/portsel clock and AHB clock #define CLOCK_MASK (HOST_CLK_EN | PORTSEL_CLK_EN | AHB_CLK_EN) static UsbHostMgr* pMgr = NULL; extern "C" void sUsbIrqhandler(void) __irq { DBG("\n+Int\n"); if(pMgr) pMgr->UsbIrqhandler(); DBG("\n-Int\n"); return; } UsbHostMgr::UsbHostMgr() : m_lpDevices() { /*if(!pMgr)*/ //Assume singleton pMgr = this; usb_mem_init(); memset(m_lpDevices, NULL, sizeof(UsbDevice*) * USB_HOSTMGR_MAX_DEVS); m_pHcca = (HCCA*) usb_get_hcca(); memset((void*)m_pHcca, 0, 0x100); DBG("Host manager at %p\n", this); } UsbHostMgr::~UsbHostMgr() { if(pMgr == this) pMgr = NULL; } UsbErr UsbHostMgr::init() //Initialize host { NVIC_DisableIRQ(USB_IRQn); /* Disable the USB interrupt source */ LPC_SC->PCONP &= ~(1UL<<31); //Cut power wait(1); // turn on power for USB LPC_SC->PCONP |= (1UL<<31); // Enable USB host clock, port selection and AHB clock LPC_USB->USBClkCtrl |= CLOCK_MASK; // Wait for clocks to become available while ((LPC_USB->USBClkSt & CLOCK_MASK) != CLOCK_MASK) ; // it seems the bits[0:1] mean the following // 0: U1=device, U2=host // 1: U1=host, U2=host // 2: reserved // 3: U1=host, U2=device // NB: this register is only available if OTG clock (aka "port select") is enabled!! // since we don't care about port 2, set just bit 0 to 1 (U1=host) LPC_USB->OTGStCtrl |= 1; // now that we've configured the ports, we can turn off the portsel clock LPC_USB->USBClkCtrl &= ~PORTSEL_CLK_EN; // power pins are not connected on mbed, so we can skip them /* P1[18] = USB_UP_LED, 01 */ /* P1[19] = /USB_PPWR, 10 */ /* P1[22] = USB_PWRD, 10 */ /* P1[27] = /USB_OVRCR, 10 */ /*LPC_PINCON->PINSEL3 &= ~((3<<4) | (3<<6) | (3<<12) | (3<<22)); LPC_PINCON->PINSEL3 |= ((1<<4)|(2<<6) | (2<<12) | (2<<22)); // 0x00802080 */ // configure USB D+/D- pins /* P0[29] = USB_D+, 01 */ /* P0[30] = USB_D-, 01 */ LPC_PINCON->PINSEL1 &= ~((3<<26) | (3<<28)); LPC_PINCON->PINSEL1 |= ((1<<26)|(1<<28)); // 0x14000000 DBG("Initializing Host Stack\n"); wait_ms(100); /* Wait 50 ms before apply reset */ LPC_USB->HcControl = 0; /* HARDWARE RESET */ LPC_USB->HcControlHeadED = 0; /* Initialize Control list head to Zero */ LPC_USB->HcBulkHeadED = 0; /* Initialize Bulk list head to Zero */ /* SOFTWARE RESET */ LPC_USB->HcCommandStatus = OR_CMD_STATUS_HCR; LPC_USB->HcFmInterval = DEFAULT_FMINTERVAL; /* Write Fm Interval and Largest Data Packet Counter */ /* Put HC in operational state */ LPC_USB->HcControl = (LPC_USB->HcControl & (~OR_CONTROL_HCFS)) | OR_CONTROL_HC_OPER; LPC_USB->HcRhStatus = OR_RH_STATUS_LPSC; /* Set Global Power */ LPC_USB->HcHCCA = (uint32_t)(m_pHcca); LPC_USB->HcInterruptStatus |= LPC_USB->HcInterruptStatus; /* Clear Interrrupt Status */ LPC_USB->HcInterruptEnable = OR_INTR_ENABLE_MIE | OR_INTR_ENABLE_WDH | OR_INTR_ENABLE_RHSC; NVIC_SetPriority(USB_IRQn, 0); /* highest priority */ /* Enable the USB Interrupt */ NVIC_SetVector(USB_IRQn, (uint32_t)(sUsbIrqhandler)); LPC_USB->HcRhPortStatus1 = OR_RH_PORT_CSC; LPC_USB->HcRhPortStatus1 = OR_RH_PORT_PRSC; /* Check for any connected devices */ if (LPC_USB->HcRhPortStatus1 & OR_RH_PORT_CCS) //Root device connected { //Device connected wait(1); DBG("Device connected (%08x)\n", LPC_USB->HcRhPortStatus1); onUsbDeviceConnected(0, 1); //Hub 0 (root hub), Port 1 (count starts at 1) } DBG("Enabling IRQ\n"); NVIC_EnableIRQ(USB_IRQn); DBG("End of host stack initialization\n"); return USBERR_OK; } void UsbHostMgr::poll() //Enumerate connected devices, etc { /* Check for any connected devices */ if (LPC_USB->HcRhPortStatus1 & OR_RH_PORT_CCS) //Root device connected { //Device connected wait(1); DBG("Device connected (%08x)\n", LPC_USB->HcRhPortStatus1); onUsbDeviceConnected(0, 1); //Hub 0 (root hub), Port 1 (count starts at 1) } for(int i = 0; i < devicesCount(); i++) { if( (m_lpDevices[i]->m_connected) && !(m_lpDevices[i]->m_enumerated) ) { m_lpDevices[i]->enumerate(); return; } } } int UsbHostMgr::devicesCount() { int i; for(i = 0; i < USB_HOSTMGR_MAX_DEVS; i++) { if (m_lpDevices[i] == NULL) break; } return i; } UsbDevice* UsbHostMgr::getDevice(int item) { UsbDevice* pDev = m_lpDevices[item]; if(!pDev) return NULL; pDev->m_refs++; return pDev; } void UsbHostMgr::releaseDevice(UsbDevice* pDev) { pDev->m_refs--; if(pDev->m_refs > 0) return; //If refs count = 0, delete //Find & remove from list int i; for(i = 0; i < USB_HOSTMGR_MAX_DEVS; i++) { if (m_lpDevices[i] == pDev) break; } if(i!=USB_HOSTMGR_MAX_DEVS) memmove(&m_lpDevices[i], &m_lpDevices[i+1], sizeof(UsbDevice*) * (USB_HOSTMGR_MAX_DEVS - (i + 1))); //Safer than memcpy because of overlapping mem m_lpDevices[USB_HOSTMGR_MAX_DEVS - 1] = NULL; delete pDev; } void UsbHostMgr::UsbIrqhandler() { uint32_t int_status; uint32_t ie_status; int_status = LPC_USB->HcInterruptStatus; /* Read Interrupt Status */ ie_status = LPC_USB->HcInterruptEnable; /* Read Interrupt enable status */ if (!(int_status & ie_status)) { return; } else { int_status = int_status & ie_status; if (int_status & OR_INTR_STATUS_RHSC) /* Root hub status change interrupt */ { DBG("LPC_USB->HcRhPortStatus1 = %08x\n", LPC_USB->HcRhPortStatus1); if (LPC_USB->HcRhPortStatus1 & OR_RH_PORT_CSC) { if (LPC_USB->HcRhStatus & OR_RH_STATUS_DRWE) { /* * When DRWE is on, Connect Status Change * means a remote wakeup event. */ //HOST_RhscIntr = 1;// JUST SOMETHING FOR A BREAKPOINT } else { /* * When DRWE is off, Connect Status Change * is NOT a remote wakeup event */ if (LPC_USB->HcRhPortStatus1 & OR_RH_PORT_CCS) //Root device connected { //Device connected DBG("Device connected (%08x)\n", LPC_USB->HcRhPortStatus1); onUsbDeviceConnected(0, 1); //Hub 0 (root hub), Port 1 (count starts at 1) } else //Root device disconnected { //Device disconnected DBG("Device disconnected\n"); onUsbDeviceDisconnected(0, 1); } //TODO: HUBS } LPC_USB->HcRhPortStatus1 = OR_RH_PORT_CSC; } if (LPC_USB->HcRhPortStatus1 & OR_RH_PORT_PRSC) { LPC_USB->HcRhPortStatus1 = OR_RH_PORT_PRSC; } } if (int_status & OR_INTR_STATUS_WDH) /* Writeback Done Head interrupt */ { //UsbEndpoint::sOnCompletion((LPC_USB->HccaDoneHead) & 0xFE); if(m_pHcca->DoneHead) { UsbEndpoint::sOnCompletion(m_pHcca->DoneHead); m_pHcca->DoneHead = 0; LPC_USB->HcInterruptStatus = OR_INTR_STATUS_WDH; if(m_pHcca->DoneHead) DBG("??????????????????????????????\n\n\n"); } else { //Probably an error int_status = LPC_USB->HcInterruptStatus; DBG("HcInterruptStatus = %08x\n", int_status); if (int_status & OR_INTR_STATUS_UE) //Unrecoverable error, disconnect devices and resume { onUsbDeviceDisconnected(0, 1); LPC_USB->HcInterruptStatus = OR_INTR_STATUS_UE; LPC_USB->HcCommandStatus = 0x01; //Host Controller Reset } } } LPC_USB->HcInterruptStatus = int_status; /* Clear interrupt status register */ } return; } void UsbHostMgr::onUsbDeviceConnected(int hub, int port) { int item = devicesCount(); if( item == USB_HOSTMGR_MAX_DEVS ) return; //List full... //Find a free address (not optimized, but not really important) int i; int addr = 1; for(i = 0; i < item; i++) { addr = MAX( addr, m_lpDevices[i]->m_addr + 1 ); } m_lpDevices[item] = new UsbDevice( this, hub, port, addr ); m_lpDevices[item]->m_connected = true; } void UsbHostMgr::onUsbDeviceDisconnected(int hub, int port) { for(int i = 0; i < devicesCount(); i++) { if( (m_lpDevices[i]->m_hub == hub) && (m_lpDevices[i]->m_port == port) ) { m_lpDevices[i]->m_connected = false; if(!m_lpDevices[i]->m_enumerated) { delete m_lpDevices[i]; m_lpDevices[i] = NULL; } return; } } } void UsbHostMgr::resetPort(int hub, int port) { DBG("Resetting hub %d, port %d\n", hub, port); if(hub == 0) //Root hub { wait_ms(100); /* USB 2.0 spec says at least 50ms delay before port reset */ LPC_USB->HcRhPortStatus1 = OR_RH_PORT_PRS; // Initiate port reset DBG("Before loop\n"); while (LPC_USB->HcRhPortStatus1 & OR_RH_PORT_PRS) ; LPC_USB->HcRhPortStatus1 = OR_RH_PORT_PRSC; // ...and clear port reset signal DBG("After loop\n"); wait_ms(200); /* Wait for 100 MS after port reset */ } else { //TODO: Hubs } DBG("Port reset OK\n"); } #endif
[ [ [ 1, 367 ] ] ]
40d0394c406321af89f9f52b4024c735840976ad
f057c62b9392fa28f2b941c7db65b0983d4fd317
/uEpgUI/uEpgUI/uEpgUIDlg.cpp
1ea5e31cee2e02f7b7741c9076a7f0a74b4b2f26
[]
no_license
r2d23cpo/uepg
710c5f29a086cfa39bb01b84dae0bd22121f03fa
c10f841f85fa8ed88e52d1664d197f4f9f47cdd0
refs/heads/master
2021-01-10T04:52:01.886770
2008-10-02T21:19:03
2008-10-02T21:19:03
48,803,326
0
0
null
null
null
null
UTF-8
C++
false
false
9,732
cpp
// uEpgUIDlg.cpp : implementation file // #include "stdafx.h" #include "uEpgUI.h" #include "uEpgUIDlg.h" #include "EpgControl.h" #include "moduleAPI.h" #ifdef _DEBUG #define new DEBUG_NEW #endif CuEpgUIDlg::CuEpgUIDlg(CWnd* pParent /*=NULL*/) : CDialog(CuEpgUIDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); _pChl = 0; } void CuEpgUIDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_CHANNEL_LIST, _channelList); DDX_Control(pDX, IDC_SAT_LIST, _satList); DDX_Control(pDX, IDC_TAG_LIST, _tagList); DDX_Control(pDX, IDC_COMBO_CHANNEL_SORT, _channelSortCombo); DDX_Control(pDX, IDC_EDIT_CHANNEL_SEARCH, _channelSearchEdit); DDX_Control(pDX, IDC_COMBO_CHANNEL_TYPES, _channelTypesCombo); } BEGIN_MESSAGE_MAP(CuEpgUIDlg, CDialog) ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_CBN_SELCHANGE(IDC_COMBO_CHANNEL_SORT, &CuEpgUIDlg::OnCbnSelchangeComboChannelSort) ON_EN_CHANGE(IDC_EDIT_CHANNEL_SEARCH, &CuEpgUIDlg::OnEnChangeEditChannelSearch) ON_WM_TIMER() ON_LBN_SELCHANGE(IDC_SAT_LIST, &CuEpgUIDlg::OnLbnSelchangeSatList) ON_CBN_EDITCHANGE(IDC_COMBO_CHANNEL_TYPES, &CuEpgUIDlg::OnCbnEditchangeComboChannelTypes) ON_CBN_SELCHANGE(IDC_COMBO_CHANNEL_TYPES, &CuEpgUIDlg::OnCbnSelchangeComboChannelTypes) END_MESSAGE_MAP() // CuEpgUIDlg message handlers void CuEpgUIDlg::UpdateChannelTypesCombo() { int types[] = {CHTYPE_TV, CHTYPE_RADIO, CHTYPE_DATA}; wchar_t* typesNames[] = {L"TV", L"Radio", L"Data"}; _channelTypesCombo.ResetContent(); CString selectedStr; int selectedCount=0; for (int x=0; x<sizeof(types)/sizeof(int); x++) { int n=0; if (_channelTypes & (1<<types[x])) { if (selectedCount) selectedStr += L", "; selectedStr += typesNames[x]; selectedCount++; } } if (!selectedCount) selectedStr = L"<Nothing selected>"; _channelTypesCombo.InsertString(0, selectedStr); for (int x=0; x<sizeof(types)/sizeof(int); x++) { int n=0; if (_channelTypes & (1<<types[x])) { if (selectedCount) selectedStr += L", "; selectedStr += typesNames[x]; selectedCount++; CString comboStr; comboStr.Format(L"Hide %s", typesNames[x]); n=_channelTypesCombo.InsertString(-1, comboStr); } else { CString comboStr; comboStr.Format(L"Show %s", typesNames[x]); n=_channelTypesCombo.InsertString(-1, comboStr); } _channelTypesCombo.SetItemData(n, (1<<types[x])); } _channelTypesCombo.SetCurSel(0); } BOOL CuEpgUIDlg::OnInitDialog() { CDialog::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon _channelSortCombo.SetItemData( _channelSortCombo.AddString(L"Sort by Name"), (int)ChannelSortName); _channelSortCombo.SetItemData( _channelSortCombo.AddString(L"Sort by SID"), (int)ChannelSortSID); _channelSortCombo.SetCurSel(0); _channelTypes = (1<<CHTYPE_TV)|(1<<CHTYPE_RADIO)|(1<<CHTYPE_DATA); UpdateChannelTypesCombo(); CWnd* pStatic = GetDlgItem(IDC_STATIC); pStatic->ShowWindow(SW_HIDE); CRect pStaticRect; pStatic->GetWindowRect(pStaticRect); ScreenToClient(pStaticRect); //_epgControl.Create(this, CRect(CPoint(150, 20), CSize(750, 480))); _epgControl.Create(this, pStaticRect); UpdateChlDataFromFile("c:\\code\\epg.bin"); ASSERT(_epgDatabase.Open("c:\\code\\epg.db")==0); UpdateEpgGrid(); return TRUE; // return TRUE unless you set the focus to a control } void CuEpgUIDlg::UpdateEpgGrid() { } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CuEpgUIDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CuEpgUIDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CuEpgUIDlg::UpdateChlDataFromFile(const char* filename) { TCHL* pChl = new TCHL; FILE* file; fopen_s(&file, filename, "rb"); if (file) { fread(pChl, sizeof(TCHL), 1, file); UpdateChlData(pChl); } delete pChl; } bool TChlChannel_CompareName(TChlChannel* first, TChlChannel* second) { return (strcmp(first->ChName, second->ChName)<0); } bool TChlChannel_CompareSID(TChlChannel* first, TChlChannel* second) { return (first->wSID<second->wSID); } const char *strnistr(const char* str, const char* strSearch) { size_t n = strlen(strSearch); while (*str) { const char* s1 = str; const char* s2 = strSearch; while (tolower(*s1++) == tolower(*s2++)) { if (!*s2) return str; else if (!*s1) break; } str++; } return 0; } void CuEpgUIDlg::BuildChannelInfoList() { TChlChannel* pChannels = _pChl->Channels; CString searchStrTemp; char searchStr[32]; int searchSats[256]; bool doSearchName = false; bool doSearchSat = false; _channelSearchEdit.GetWindowText(searchStrTemp); searchStrTemp.MakeLower(); if (searchStrTemp.GetLength()) { doSearchName = true; size_t n; wcstombs_s(&n, searchStr, sizeof(searchStr), searchStrTemp, searchStrTemp.GetLength()); } int * pSearchSat = searchSats; for (int s=0; s<_satList.GetCount(); s++) { if (_satList.GetSel(s)) { TChlSat* pSatellite = (TChlSat*)_satList.GetItemData(s); if (pSatellite) { *pSearchSat++ = pSatellite->wPos; doSearchSat = true; } else { doSearchSat = false; break; } } } *pSearchSat = 0; _channelInfoList.clear(); for (int c=0; c<MAX_CHANNELS; c++) { TChlChannel* pChannel = &pChannels[c]; if (pChannel->wSatPos) { if (doSearchName) { if (!strnistr(pChannel->ChName, searchStr)) continue; } if (doSearchSat) { int* pSat =0; for (pSat=searchSats; *pSat!=pChannel->wSatPos && *pSat; pSat++); if (!*pSat) continue; } if (_channelTypes & (1<<pChannel->ChType)) _channelInfoList.push_back(pChannel); } } } void CuEpgUIDlg::UpdateChannelList() { switch(_channelSortCombo.GetItemData(_channelSortCombo.GetCurSel())) { case ChannelSortName: _channelInfoList.sort(TChlChannel_CompareName); break; case ChannelSortSID: _channelInfoList.sort(TChlChannel_CompareSID); break; } CString str; _channelList.SetRedraw(false); _channelList.ResetContent(); str.Format(L"<All Channels (%d)>", _channelInfoList.size()); int first = _channelList.InsertString(0, str); ChannelInfoList::iterator i; for (i=_channelInfoList.begin(); i!=_channelInfoList.end(); i++) { CString chStr; TChlChannel* pChannel = *i; chStr.Format(L"[%04d] %S", pChannel->wSID, pChannel->ChName); int n = _channelList.InsertString(-1, chStr); _channelList.SetItemData(n, (DWORD_PTR)pChannel); } _channelList.SetSel(first, TRUE); _channelList.SetRedraw(true); } void CuEpgUIDlg::UpdateSatList() { int count = 0; _satList.SetRedraw(false); _satList.ResetContent(); for (int x=0; x<MAX_SATELLITES; x++) { TChlSat* pSatellite = &_pChl->Satellites[x]; if (pSatellite->wPos) { CString satStr; satStr.Format(L"[%04d] %S", pSatellite->wPos, pSatellite->SatName); int n = _satList.InsertString(-1, satStr); _satList.SetItemData(n, (DWORD_PTR)pSatellite); count++; } } CString str; str.Format(L"<All Satellites (%d)>", count); int n = _satList.InsertString(0, str); _satList.SetItemData(n, NULL); _satList.SetSel(n, TRUE); _satList.SetRedraw(true); } void CuEpgUIDlg::UpdateChlData(TCHL* pChl) { if (!_pChl) _pChl = new TCHL; memcpy(_pChl, pChl, sizeof(TCHL)); UpdateSatList(); BuildChannelInfoList(); UpdateChannelList(); } void CuEpgUIDlg::OnCbnSelchangeComboChannelSort() { UpdateChannelList(); } void CuEpgUIDlg::OnEnChangeEditChannelSearch() { KillTimer(TimerEventChannelSearchEdit); SetTimer(TimerEventChannelSearchEdit, 500, NULL); } void CuEpgUIDlg::OnTimer(UINT_PTR nIDEvent) { CDialog::OnTimer(nIDEvent); switch (nIDEvent) { case TimerEventChannelSearchEdit: BuildChannelInfoList(); UpdateChannelList(); break; } KillTimer(nIDEvent); } void CuEpgUIDlg::OnLbnSelchangeSatList() { BuildChannelInfoList(); UpdateChannelList(); } void CuEpgUIDlg::OnCbnEditchangeComboChannelTypes() { // TODO: Add your control notification handler code here } void CuEpgUIDlg::OnCbnSelchangeComboChannelTypes() { _channelTypes ^= _channelTypesCombo.GetItemData(_channelTypesCombo.GetCurSel()); UpdateChannelTypesCombo(); BuildChannelInfoList(); UpdateChannelList(); } void CuEpgUIDlg::FindEventsCallback(void* param, const int eventid, const int starttime, const int duration, const char* eventname, const char* shortdescr, const char* extendeddescr) { }
[ "Jonathan.Fillion@f94d0768-90c5-11dd-aee7-853fd145579a" ]
[ [ [ 1, 437 ] ] ]
81afc9a5ad8470aa630fb77b3b07f5be8be791e3
dba70d101eb0e52373a825372e4413ed7600d84d
/RendererComplement/source/DefaultPipeline.cpp
243f61e40ddaa2902fa8ff171b6e32abc389e797
[]
no_license
nustxujun/simplerenderer
2aa269199f3bab5dc56069caa8162258e71f0f96
466a43a1e4f6e36e7d03722d0d5355395872ad86
refs/heads/master
2021-03-12T22:38:06.759909
2010-10-02T03:30:26
2010-10-02T03:30:26
32,198,944
0
0
null
null
null
null
GB18030
C++
false
false
20,762
cpp
#include "DefaultPipeline.h" #include "RendererHeader.h" #include <sstream> namespace RCP { DefaultPipeline::DefaultPipeline(): mVertexShader(NULL) { } DefaultPipeline::~DefaultPipeline() {} void DefaultPipeline::initImpl() { mPlane[0]= Vector4(1,0,0,1); mPlane[1]= Vector4(-1,0,0,1); mPlane[2]= Vector4(0,1,0,1); mPlane[3]= Vector4(0,-1,0,1); mPlane[4]= Vector4(0,0,1,1); mPlane[5]= Vector4(0,0,-1,1); const RendererParameters& rp = getRendererParameters(); mRasterizer.initialize(rp.backBufferWidth, rp.backBufferHeight, rp.backBufferPixelFormat); } void DefaultPipeline::execute(const RenderData& renderData) { const RenderParameter& rp = renderData.renderParameter; //设置自定义渲染状态 setOtherState(rp.propertys); if (rp.vertexBuffer->getVertexCount() > mVertexList.size()) mVertexList.resize(rp.vertexBuffer->getVertexCount());//這裡就直接初始化了,下面就不再push_back了 vertexProcessing(renderData,mVertexList); primitiveAssembly(renderData,mVertexList); mRasterizer.flush(*rp.frameBuffer,rp.renderState); } void DefaultPipeline::vertexProcessing(const RenderData& elem, VertexList& verVec) { const VertexBuffer* vb = elem.renderParameter.vertexBuffer; unsigned int vertexSize = vb->getVertexDeclaration().getSizeInBytes(); //這裡取的是elem的vertexCount,注意,和VertexBuffer裏不一樣 size_t dataSize = vb->getVertexCount() * vertexSize; //各个数据在一個頂點中的偏移大小 const VertexDeclaration& verDecl = vb->getVertexDeclaration(); unsigned int posDataOffset = verDecl.getElementOffsetInBytes(VES_POSITION); unsigned int diffuseDataOffset = verDecl.getElementOffsetInBytes(VES_DIFFUSE); unsigned int specularDataOffset = verDecl.getElementOffsetInBytes(VES_SPECULAR); unsigned int normalDataOffset = verDecl.getElementOffsetInBytes(VES_NORMAL); unsigned int tangentDataOffset = verDecl.getElementOffsetInBytes(VES_TANGENT); unsigned int binormalDataOffset = verDecl.getElementOffsetInBytes(VES_BINORMAL); unsigned int texCroodDataOffset[8]; for (unsigned char i = 0; i < 8; ++i) { texCroodDataOffset[i] = verDecl.getElementOffsetInBytes(VES_TEXTURE_COORDINATES,i); } //尋不到Position信息就傻了 if(posDataOffset == -1) THROW_EXCEPTION("未找到顶点位置信息,因为没有多流,因此顶点处理失败"); //獲取4個權重的偏移 unsigned int weightDataOffet[4] ; for (int i = 0; i < 4; ++i ) weightDataOffet[i]= verDecl.getElementOffsetInBytes(VES_BLEND_WEIGHTS,i); //原始数据 const unsigned char* data = vb->getData() ; //const unsigned char* end = vb->getData() + dataSize; Matrix4X4 transMat; float weight[4] = {1,0,0,0}; Colour diffuse,specular,ambient, diffuseBlend,specularBlend, ambientBlend; float power; bool enable = false; Vector3 posVec; Vector4 normVec4; Vector3 H,L,V,lightPos,normVec3; const unsigned char *vertexData; for (size_t i = 0; i < vb->getVertexCount(); ++i) { vertexData = data + i * vertexSize; //定位頂點position mDataCollector.getData(posVec,vertexData + posDataOffset); verVec[i].pos = posVec; //点 verVec[i].pos.w= 1.0f; //----------------------------------------------------- //這裡注意!!!! //暫時默認為4個weight的混合 //----------------------------------------------------- //獲取4個權重 for (int j = 0; j < 4; ++j) { if (weightDataOffet[j] == -1)//儅該權重不存在 { //計算權重 weight[j] = 1; for (int k = 0; k < j ; ++k ) weight[j] = weight[j] - weight[k]; break; } mDataCollector.getData(weight[j],vertexData + weightDataOffet[j]); } //获取颜色(材质ye处理) diffuse = elem.renderParameter.material.diffuse; specular = elem.renderParameter.material.specular; power = elem.renderParameter.material.power; ambient = elem.renderParameter.material.ambient; if (diffuseDataOffset != -1 && elem.renderParameter.material.isDiffuseVertexColorEnable()) { if (verDecl.getElementSizeInBytes(VES_DIFFUSE) == 4) { int c; mDataCollector.getData(c,vertexData + diffuseDataOffset); diffuse = Colour().getFromARGB(c) * diffuse ; } else if (verDecl.getElementSizeInBytes(VES_DIFFUSE) == 16) { Vector4 c; mDataCollector.getData(c,vertexData + diffuseDataOffset); diffuse = diffuse * Colour(c.x,c.y,c.z,c.w); } } if (specularDataOffset != -1 && elem.renderParameter.material.isSpecularVertexColorEnable()) { if (verDecl.getElementSizeInBytes(VES_SPECULAR) == 4) { int c; mDataCollector.getData(c,vertexData + specularDataOffset); specular = specular + Colour().getFromARGB(c); } else if (verDecl.getElementSizeInBytes(VES_SPECULAR) == 16) { Vector4 c; mDataCollector.getData(c,vertexData + specularDataOffset); diffuse = diffuse * Colour(c.x,c.y,c.z,c.w); } } //法线 if (normalDataOffset != -1) { mDataCollector.getData(verVec[i].norm,vertexData + normalDataOffset); } //纹理坐标 for (unsigned char k = 0; k < 8; ++k ) { if (texCroodDataOffset[k] != -1 && elem.renderParameter.sampler[k].texture != NULL) { mDataCollector.getData(verVec[i].texCrood[k],vertexData + texCroodDataOffset[k]); //取样时才计算寻址 //elem.sampler[k].assignUV(verVec[i].texCrood[k].x,verVec[i].texCrood[k].y); } } //切线 if (tangentDataOffset != -1) { mDataCollector.getData(verVec[i].tan,vertexData + tangentDataOffset); } //次法线 if (binormalDataOffset != -1) { mDataCollector.getData(verVec[i].bino,vertexData + binormalDataOffset); } //以上为数据采集 if (mVertexShader != NULL) { mVertexShader->execute(verVec[i]); continue; } //以下为数据计算 //計算混合 transMat = elem.renderParameter.matrices[TS_WORLD] * weight[0] + elem.renderParameter.matrices[TS_WORLD2] * weight[1] + elem.renderParameter.matrices[TS_WORLD3] * weight[2] + elem.renderParameter.matrices[TS_WORLD4] * weight[3]; //矩阵变换 verVec[i].pos = elem.renderParameter.matrices[TS_VIEW] *( transMat * verVec[i].pos );//* elem.matrices[TS_PROJECTION] ; //记录下变换前的坐标 进行光照计算 posVec.x = verVec[i].pos.x; posVec.y = verVec[i].pos.y; posVec.z = verVec[i].pos.z; //继续变换 verVec[i].pos = elem.renderParameter.matrices[TS_PROJECTION] * verVec[i].pos; //光照计算 diffuseBlend.getFromABGR(0); specularBlend.getFromABGR(0); ambientBlend.getFromABGR(0); enable = false; for (unsigned int index = 0; index < 8; ++index) { if (!elem.renderParameter.light[index].isEnable()) continue; enable = true; //注意这里灯的坐标和法向量都进行了变换。 //因为此时要的到顶点指向摄像机的向量需要摄像机坐标,而这里没有提供逆矩阵 //于是将法向量和灯变换到摄像机坐标系。 //当然法向量的话 还有一个世界坐标系的变换。 lightPos = elem.renderParameter.matrices[TS_VIEW] *(elem.renderParameter.light[index].position); L = lightPos - posVec; L.normalise(); V = - posVec; V.normalise(); H = L + V; H.normalise(); //注意这里有个隐藏操作是normVec4.w设为了0,不是1 normVec4 = verVec[i].norm; //normal的话只需要旋转方向 normVec4 = elem.renderParameter.matrices[TS_VIEW] * (transMat * normVec4); normVec3.x = normVec4.x; normVec3.y = normVec4.y; normVec3.z = normVec4.z; diffuseBlend += elem.renderParameter.light[index].diffuse * std::max<float>(0,normVec3.dotProduct(L)); specularBlend += elem.renderParameter.light[index].specular * pow(std::max<float>(0,H.dotProduct(normVec3)),power); ambientBlend += elem.renderParameter.light[index].ambient; } //如果使用了灯光。 if (enable) { float a; a = diffuse.a; diffuse = diffuse * diffuseBlend; diffuse.a = a; a = ambient.a; ambient = ambient * ambientBlend; ambient.a = a; a = specular.a; specular = specular * specularBlend; specular.a = a; //diffuse.clip(); //ambient.clip(); //specular.clip(); } //temp verVec[i].color[0] = diffuse + ambient; verVec[i].specular = specular; } } void DefaultPipeline::primitiveAssembly(const RenderData& elem,const VertexList& verVec) { const IndexBuffer* ib = elem.renderParameter.indexBuffer; const VertexBuffer* vb = elem.renderParameter.vertexBuffer; unsigned int skipVertexCount = 0; size_t realVertexCount = 0; unsigned int type = 0; //得到实际需要绘制的顶点数 if (ib != NULL) realVertexCount = ib->getIndexCount(); else realVertexCount = vb->getVertexCount(); //图元需要的顶点数 unsigned int vertexNumInGeom ; switch (elem.ptType) { case PT_POINTLIST: vertexNumInGeom = 1; type = Primitive::PT_POINT; skipVertexCount = elem.beginPrimitiveOffset; break; case PT_LINELIST: vertexNumInGeom = 2; type = Primitive::PT_LINE; skipVertexCount = elem.beginPrimitiveOffset; break; case PT_LINESTRIP: vertexNumInGeom = 2; type = Primitive::PT_LINE; skipVertexCount = elem.beginPrimitiveOffset * 2; break; case PT_TRIANGLELIST: case PT_TRIANGLEFAN: type = Primitive::PT_TRIANGLE; vertexNumInGeom = 3; skipVertexCount = elem.beginPrimitiveOffset ; break; case PT_TRIANGLESTRIP: type = Primitive::PT_TRIANGLE; vertexNumInGeom = 3; skipVertexCount = elem.beginPrimitiveOffset * 3; break; default: assert(0); break; } //保证剩余顶点数足够形成图元 if (realVertexCount - skipVertexCount < vertexNumInGeom*elem.primitiveCount ) THROW_EXCEPTION("顶点数量不足以绘制指定数量图元"); Primitive prim ; Primitive priResult[5]; for (unsigned int i = 0; i < elem.primitiveCount; ++i) { prim.type = type; prim.vp = &elem.renderParameter.viewport; for (short j = 0; j < 8; ++j) { prim.sampler[j] = elem.renderParameter.sampler[j]; } //输入顶点 for (unsigned int j = 0; j < vertexNumInGeom; ++j) { if (ib != NULL) { prim.vertex[j] = verVec[(*ib)[skipVertexCount + i*vertexNumInGeom + j]]; } else { prim.vertex[j] = verVec[skipVertexCount + i*vertexNumInGeom + j]; } } //返回true则说明通过,false则剔除 if (prim.type == Primitive::PT_ERROR || !culling(prim,elem.renderParameter.renderState.cullMode) ) continue; //同时把齐次归一,视口映射给做了,因为在顶点级可以少做几个顶点 clipping(prim,priResult); //产生的clip新结果插入 for ( int k = 0; k < 5; ++k) { rasterize(priResult[k]); priResult[k].type = Primitive::PT_ERROR; } } } bool DefaultPipeline::culling(const Primitive& prim,CullMode cm) { if (prim.type != Primitive::PT_TRIANGLE || cm == CM_DISABLE) return true; const Vector4& pos0 = prim.vertex[0].pos; const Vector4& pos1 = prim.vertex[1].pos; const Vector4& pos2 = prim.vertex[2].pos; //暂时默认逆时针剔除 float result = (float)(pos0.w * (pos1.x * pos2.y - pos2.x * pos1.y) + pos1.w * (pos2.x * pos0.y - pos0.x * pos2.y) + pos2.w * (pos0.x * pos1.y - pos1.x * pos0.y)) ; if (result > 0) return cm == CM_CCW ; else return cm != CM_CCW; } void DefaultPipeline::clipping(const Primitive& prim,Primitive prims[5]) { switch (prim.type) { case Primitive::PT_POINT: { clippingPoint(prim,prims[0]); break; } case Primitive::PT_LINE: { clippingLine(prim,prims[0]); break; } case Primitive::PT_TRIANGLE: { clippingTriangle(prim,prims); break; } default: assert(0); } } void DefaultPipeline::rasterize(Primitive& prim) { if (prim.type == Primitive::PT_ERROR) return; unsigned int num = 0; switch(prim.type) { case Primitive::PT_POINT: num = 1; break; case Primitive::PT_LINE: num = 2; break; case Primitive::PT_TRIANGLE: num = 3; break; default: assert(0); } mRasterizer.pushPrimitive(prim); } void DefaultPipeline::homogeneousDivide(Vertex& vert) { assert ( fabs(vert.pos.w) > 0.01f ); float invw = 1.0f/vert.pos.w; vert.pos *= invw; vert.pos.w = invw; //vert.color *= invw; vert.specular *= invw; for (unsigned int i = 0; i < 8; ++i) { if(vert.texCrood.isUsed(i)) vert.texCrood[i] *= invw; if(vert.color.isUsed(i)) vert.color[i] *= invw; } } void DefaultPipeline::viewportMapping(Vector4& pos,const Viewport* vp) { vp->mapping(pos); } void DefaultPipeline::generateNewVertex(Vertex& newVertex,const Vertex& vert1, const Vertex& vert2, float dist1, float dist2) { float scale = (0 - dist1) / (dist2 - dist1); lerp(newVertex.specular,scale,vert1.specular,vert2.specular); lerp(newVertex.norm,scale,vert1.norm,vert2.norm); lerp(newVertex.tan,scale,vert1.tan,vert2.tan); lerp(newVertex.bino,scale,vert1.bino,vert2.bino); lerp(newVertex.pos,scale,vert1.pos,vert2.pos); for (unsigned int i = 0 ; i < 8; ++i) { if (vert1.texCrood.isUsed(i) || vert2.texCrood.isUsed(i)) lerp(newVertex.texCrood[i],scale,vert1.texCrood[i],vert2.texCrood[i]); if (vert1.color.isUsed(i) || vert2.color.isUsed(i)) lerp(newVertex.color[i],scale,vert1.color[i],vert2.color[i]); } } bool DefaultPipeline::checkPointInScreen(const Vector4& point) { if ( fabs(point.x ) > point.w || fabs(point.y ) > point.w || fabs(point.z ) > point.w ) return false; return true; } void DefaultPipeline::clippingPoint(const Primitive& prim,Primitive& resultPrim) { const Vector4& pos = prim.vertex[0].pos; //被裁减 if ( !checkPointInScreen(pos) ) return; resultPrim = prim; homogeneousDivide(resultPrim.vertex[0]); viewportMapping(resultPrim.vertex[0].pos,prim.vp); } void DefaultPipeline::clippingLine(const Primitive& prim,Primitive& resultPrim) { assert(prim.type == Primitive::PT_LINE); Vertex vertices[2][2]; //使用的顶点下标 int beforeClip = 0; int afterClip = 1; float d1,d2; for (int i =0; i < 2; ++i) { vertices[beforeClip][i] = prim.vertex[i]; } int numPlane = 6; for(int plane = 0; plane < numPlane; ++plane) { d1 = vertices[beforeClip][0].pos.dotProduct(mPlane[plane]); d2 = vertices[beforeClip][1].pos.dotProduct(mPlane[plane]); if (d1 >= 0.0f) { vertices[afterClip][0] = vertices[beforeClip][0]; if (d2 < 0.0f) { //lerp generateNewVertex( vertices[afterClip][1], vertices[beforeClip][0], vertices[beforeClip][1], d1,d2); } else { vertices[afterClip][1] = vertices[beforeClip][1]; } } else { if (d2 >= 0.0f) { vertices[afterClip][1] = vertices[beforeClip][1]; //lerp generateNewVertex( vertices[afterClip][0], vertices[beforeClip][0], vertices[beforeClip][1], d1,d2); } else { return; //都被裁剪 } } //交换组 (++beforeClip) &= 1; (++afterClip) &= 1; }//plane //齐次坐标归一(透视除法) & 视口映射 for ( int i =0; i < 2; ++i) { homogeneousDivide(vertices[afterClip][i]); viewportMapping(vertices[afterClip][i].pos,prim.vp); } //生成新primitive resultPrim = prim; resultPrim.vertex[0] = vertices[afterClip][0]; resultPrim.vertex[1] = vertices[afterClip][1]; } void DefaultPipeline::clippingTriangle(const Primitive& prim,Primitive prims[5]) { assert(prim.type == Primitive::PT_TRIANGLE); //2组顶点,一组裁剪前一组裁剪后,交替使用 //三角形最多被3个面裁剪,生成6个顶点,特殊情况是,再多包含一个两个面的交点 也就是7个点 Vertex vertices[2][7]; //2组顶点的数量 int numVertices[2]; //使用的顶点下标 int beforeClip = 0; int afterClip = 1; float d1,d2; if (checkPointInScreen(prim.vertex[0].pos) && checkPointInScreen(prim.vertex[1].pos) && checkPointInScreen(prim.vertex[2].pos)) { for (int i =0; i < 3; ++i) vertices[afterClip][i] = prim.vertex[i]; numVertices[afterClip] = 3; //用了goto,真是抱歉,不想看到长长的if {} else {} goto result; } for (int i =0; i < 3; ++i) { vertices[beforeClip][i] = prim.vertex[i]; } numVertices[beforeClip] = 3; int numPlane = 6; beforeClip = 1; afterClip = 0; for(int plane = 0; plane < numPlane; ++plane) { //交換組 (++beforeClip) &= 1; (++afterClip) &= 1; //全部被裁剪 if (numVertices[beforeClip] == 0) return; numVertices[afterClip]= 0; //先把第一个顶点的dist算出来,后面每向后移一位就把之前的d2给d1以减少计算 d1 = vertices[beforeClip][0].pos.dotProduct(mPlane[plane]); for (int i = 0,j= 1;i < numVertices[beforeClip]; ++i,j = (i+1) % numVertices[beforeClip]) { d2 = vertices[beforeClip][j].pos.dotProduct(mPlane[plane]); if (d1 >= 0.0f) { vertices[afterClip][numVertices[afterClip]] = vertices[beforeClip][i]; ++numVertices[afterClip]; if (d2 < 0.0f) { //lerp generateNewVertex( vertices[afterClip][numVertices[afterClip]], vertices[beforeClip][i], vertices[beforeClip][j], d1,d2); ++numVertices[afterClip]; } else { //没有被裁剪,下轮推入verteices[afterClip] } } else { if (d2 >= 0.0f) { //lerp generateNewVertex( vertices[afterClip][numVertices[afterClip]], vertices[beforeClip][i], vertices[beforeClip][j], d1,d2); ++numVertices[afterClip]; } else { //都被裁剪 } } d1 = d2; }//verteices }//plane //如果所有点都在屏幕内直接跳转到这里 result: assert(numVertices[afterClip] < 8); if (numVertices[afterClip] < 3) return; //齐次坐标归一(透视除法) & 视口映射 for ( int i =0; i < numVertices[afterClip]; ++i) { homogeneousDivide(vertices[afterClip][i]); viewportMapping(vertices[afterClip][i].pos,prim.vp); } //生成新primitive int num = numVertices[afterClip] - 1; for (int i = 1,j = 0; i < num; ++i,++j ) { prims[j] = prim; prims[j].vertex[0] = vertices[afterClip][0]; prims[j].vertex[1] = vertices[afterClip][i]; prims[j].vertex[2] = vertices[afterClip][ (i + 1)% numVertices[afterClip] ]; } } void DefaultPipeline::setVertexShader(VertexShader* vs) { mVertexShader = vs; } void DefaultPipeline::setPixelShader(PixelShader* ps) { mRasterizer.setPixelShader(ps); } void DefaultPipeline::setOtherState(const std::map<std::string,Any>& p) { VertexShader* vs = NULL; PixelShader* ps = NULL; std::map<std::string,Any>::const_iterator i,endi = p.end(); i = p.find("VertexShader"); if (i != endi) { vs = any_cast<VertexShader*>(i->second); setVertexShader(vs); } i = p.find("PixelShader"); if (i != endi) { ps = any_cast<PixelShader*>(i->second); setPixelShader(ps); } std::string mhead ="Matrix"; std::string vhead ="Vector"; std::string param; for (unsigned int index = 0; index < 16; ++index) { std::ostringstream convert; convert << (int)index; //matrix param = mhead + convert.str(); i = p.find(param); if (i != endi) { if (vs != NULL) vs->matrix4X4[index] = any_cast< Matrix4X4>(i->second); if(ps != NULL) ps->matrix4X4[index] = any_cast<Matrix4X4>(i->second); } //vector param = vhead + convert.str(); i = p.find(param); if (i != endi) { if (vs != NULL) vs->vector4[index] = any_cast<Vector4>(i->second); if(ps != NULL) ps->vector4[index] = any_cast<Vector4>(i->second); } } } }
[ "[email protected]@c2606ca0-2ebb-fda8-717c-293879e69bc3" ]
[ [ [ 1, 764 ] ] ]
656fb1ef4a08cc74fb9730b0cbf6315657ea3def
c2a70374051ef8f96105d65c84023d97c90f4806
/bin/src/loadBmp/common/plpicdec.cpp
1c6f6be393741f30d8e4c728330ddb71cd89e091
[]
no_license
haselab-net/SpringheadOne
dcf6f10cb1144b17790a782f519ae25cbe522bb2
004335b64ec7bea748ae65a85463c0e85b98edbd
refs/heads/master
2023-08-04T20:27:17.158435
2006-04-15T16:49:35
2006-04-15T16:49:35
407,701,182
1
0
null
null
null
null
UTF-8
C++
false
false
13,510
cpp
/* /-------------------------------------------------------------------- | | $Id: plpicdec.cpp,v 1.13 2003/08/03 12:54:10 uzadow Exp $ | Generic Picture Decoder Class | | Abstract base class to construct PLBmps from picture data in | memory or in a file. Classes derived from this class implement | concrete decoders for specific file formats. The data is | returned in 8- or 32-bit DIBs with a valid alpha channel. | | Copyright (c) 1996-2002 Ulrich von Zadow | \-------------------------------------------------------------------- */ #include "plstdpch.h" #include "plpicdec.h" #include "plfilesrc.h" #ifdef _WINDOWS #include "plressrc.h" #endif #include "plmemsrc.h" //#include "plurlsrc.h" #include "plexcept.h" #include "planybmp.h" #include <stdio.h> // Set default Trace configuration here. The defined levels are // explained in picdec.h. int PLPicDecoder::m_TraceLevel = 0; char * PLPicDecoder::m_pszTraceFName = NULL; PLPicDecoder::PLPicDecoder () : m_pDataSrc (0) // Creates a decoder { } PLPicDecoder::~PLPicDecoder () { if (m_pszTraceFName) delete [] m_pszTraceFName; m_pszTraceFName = NULL; } void PLPicDecoder::MakeBmpFromFile ( const char * pszFName, PLBmp * pBmp, int BPPWanted, PLIProgressNotification * pProgNot ) // Decodes a picture in a file by creating a file data source and // calling MakeBmp with this data source. { try { OpenFile (pszFName, pProgNot); MakeBmp (pBmp, BPPWanted); Close(); } catch (PLTextException) { // Clean up on error if (m_pDataSrc) Close(); throw; } } #ifdef _WINDOWS void PLPicDecoder::MakeBmpFromFileW ( const wchar_t * pszwFName, PLBmp * pBmp, int BPPWanted, PLIProgressNotification * pProgNot ) // Decodes a picture in a file by creating a file data source and // calling MakeBmp with this data source. { try { OpenFileW (pszwFName, pProgNot); MakeBmp (pBmp, BPPWanted); Close(); } catch (PLTextException) { // Clean up on error if (m_pDataSrc) Close(); throw; } } #endif #if 0 void PLPicDecoder::MakeBmpFromURL ( const char * pszURL, PLBmp * pBmp, int BPPWanted, PLIProgressNotification * pProgNot ) { int err; char sz[256]; sprintf (sz, "--- Decoding URL %s. ---\n", pszURL); Trace (1, sz); PLURLSource * pSrc; try { pSrc = new PLURLSource (); m_pDataSrc = pSrc; err = pSrc->Open (pszURL); if (err) { sprintf (sz, "Reading URL %s failed, reason: %s", pszURL, pSrc->GetCurlErrStr()); raiseError (err, sz); } Open (pSrc); m_pDataSrc = pSrc; MakeBmp (pBmp, BPPWanted); Close (); } catch (PLTextException e) { // Clean up on error int MCode = pSrc->GetCurlErrCode(); delete pSrc; if (e.GetCode() == PL_ERRURL_SOURCE) { throw PLTextException(e.GetCode(), MCode, (const char*)e); } else { throw; } } } #endif #ifdef _WINDOWS void PLPicDecoder::MakeBmpFromResource ( HINSTANCE hInstResource, int ResourceID, PLBmp * pBmp, int BPPWanted, const char * ResType, HMODULE hResModule ) // Decodes a picture in a resource by creating a resource data // source and calling MakeBmp with this data source. { int err; char sz[256]; sprintf (sz, "--- Decoding resource ID %i. ---\n", ResourceID); Trace (1, sz); PLResourceSource * pResSrc; try { pResSrc = new PLResourceSource (); m_pDataSrc = pResSrc; err = pResSrc->Open (hInstResource, ResourceID, ResType); if (err) { sprintf (sz, "Opening resource %i failed", ResourceID); raiseError (err, sz); } Open (pResSrc); m_pDataSrc = pResSrc; MakeBmp (pBmp, BPPWanted); Close (); } catch (PLTextException) { // Clean up on error delete pResSrc; throw; } } #endif void PLPicDecoder::MakeBmpFromMemory ( unsigned char * ucMemSrc, int MemSrcSize, PLBmp * pBmp, int BPPWanted, PLIProgressNotification * pProgNot ) // Decodes a picture from memory directly resembling the image file by // creating a memory data source and calling MakeBmp with this data source. { PLMemSource * pMemSrc = NULL; int err; char sz[256]; sprintf (sz, "--- Decoding from memory at %p. ---\n", ucMemSrc); Trace (1, sz); try { PLMemSource * pMemSrc = new PLMemSource (); err = pMemSrc->Open (ucMemSrc, MemSrcSize); if (err) { sprintf (sz, "Reading from memory at %p failed", ucMemSrc); raiseError (err, sz); } Open (pMemSrc); m_pDataSrc = pMemSrc; MakeBmp (pBmp, BPPWanted); Close (); } catch (PLTextException) { // Clean up on error delete pMemSrc; throw; } } void PLPicDecoder::MakeBmp ( PLBmp * pBmp, int BPPWanted ) // Decodes a picture by getting the encoded data from m_pDataSrc. // Stores the results in pBmp. { PLBmp * pTempBmp; if (BPPWanted == 0 || BPPWanted == GetBitsPerPixel()) pTempBmp = pBmp; else if (BPPWanted > GetBitsPerPixel()) pTempBmp = new PLAnyBmp; else throw (PLTextException (PL_ERRFORMAT_NOT_SUPPORTED, "Image bit depth doesn't match request.")); pTempBmp->Create (*this); GetImage (*pTempBmp); if (BPPWanted > GetBitsPerPixel()) { pBmp->CreateCopy(*pTempBmp, BPPWanted); delete pTempBmp; } } void PLPicDecoder::SetTraceConfig ( int Level, char * pszFName ) { // Level has to be between 0 and 3. PLASSERT (Level < 4); m_TraceLevel = Level; if (m_pszTraceFName) delete [] m_pszTraceFName; if (pszFName) { m_pszTraceFName = new char[strlen (pszFName)+1]; strcpy (m_pszTraceFName, pszFName); // Delete any old Trace file with the same name. remove (m_pszTraceFName); } else m_pszTraceFName = NULL; } #ifdef _WINDOWS void PLPicDecoder::OpenFileW ( const wchar_t * pszwFName, PLIProgressNotification * pProgNot ) { int err; char sz[1024]; char sz2[900]; // First calculate how much room the result will take up int neededSize = ::WideCharToMultiByte(CP_ACP, 0, pszwFName, -1, NULL, 0, NULL, NULL); if (neededSize < 900){ // Prevent overflow of our buffer ::WideCharToMultiByte(CP_ACP, 0, pszwFName, -1, sz2, 900, NULL, NULL); } else{ strcpy(sz2,"{{Filename too long}}"); } sprintf (sz, "--- Decoding file %s. ---\n", sz2); Trace (1, sz); PLFileSource * pFileSrc = 0; try { pFileSrc = new PLFileSource (pProgNot); err = pFileSrc->OpenW (pszwFName); if (err) { sprintf (sz, "Opening %s failed", sz2); raiseError (err, sz); } Open (pFileSrc); m_pDataSrc = pFileSrc; } catch (PLTextException) { if (pFileSrc != 0) pFileSrc->Close(); delete pFileSrc; throw; } } #endif void PLPicDecoder::OpenFile ( const char * pszFName, PLIProgressNotification * pProgNot ) { int err; char sz[1024]; sprintf (sz, "--- Decoding file %s. ---\n", pszFName); Trace (1, sz); PLFileSource * pFileSrc = 0; try { pFileSrc = new PLFileSource (pProgNot); err = pFileSrc->Open (pszFName); if (err) { sprintf (sz, "Opening %s failed", pszFName); raiseError (err, sz); } Open (pFileSrc); m_pDataSrc = pFileSrc; } catch (PLTextException) { if (pFileSrc != 0) pFileSrc->Close(); delete pFileSrc; throw; } } void PLPicDecoder::SetDataSrc (PLDataSource * pDataSrc) { PLASSERT (m_pDataSrc == 0); m_pDataSrc = pDataSrc; } void PLPicDecoder::Close () { if (m_pDataSrc) { m_pDataSrc->Close (); delete m_pDataSrc; m_pDataSrc = 0; } } void PLPicDecoder::raiseError ( int Code, char * pszErr ) // This function is needed by callbacks outside of any object, // so it's public and static. It should not be called from // outside of the library. { char sz[256]; sprintf (sz, "Decoder error: %s\n", pszErr); Trace (0, sz); throw (PLTextException (Code, sz)); } void PLPicDecoder::Trace ( int TraceLevel, const char * pszMessage ) // Outputs debugging data to a file or to the MSVC debug console. { if (TraceLevel <= m_TraceLevel) { if (m_pszTraceFName) { // The file is closed after every call so no data is lost // if the program crashes. FILE * pFile = fopen (m_pszTraceFName, "a+t"); if (pFile != (FILE *)0) { fprintf (pFile, pszMessage); fclose (pFile); } else { // No permission? File locked? Filename nonsense? PLTRACE ("Error opening Trace file!\n"); } } else PLTRACE (pszMessage); } } PLBYTE * PLPicDecoder::unpackPictRow ( PLBYTE * pLineBuf, PLDataSource * pDataSrc, int Width, int rowBytes, int SrcBytes ) { PLBYTE * pRawLine = pLineBuf; if (rowBytes < 8) { // Ah-ha! The bits aren't actually packed. This will be easy. pRawLine = pDataSrc->ReadNBytes (rowBytes); } else { PLBYTE * pSrcLine = pDataSrc->ReadNBytes(SrcBytes); PLBYTE * pCurPixel = pRawLine; // Unpack RLE. The data is packed bytewise. for (int j = 0; j < SrcBytes; ) { PLBYTE FlagCounter = pSrcLine[j]; if (FlagCounter & 0x80) { if (FlagCounter == 0x80) // Special case: repeat value of 0. // Apple sais ignore. j++; else { // Packed data. int len = ((FlagCounter ^ 255) & 255) + 2; memset (pCurPixel, *(pSrcLine+j+1), len); pCurPixel += len; j += 2; } } else { // Unpacked data int len = (FlagCounter & 255) + 1; memcpy (pCurPixel, pSrcLine+j+1, len); pCurPixel += len; j += len + 1; } } } return pRawLine; } /* /-------------------------------------------------------------------- | | $Log: /Project/Springhead/bin/src/loadBmp/common/plpicdec.cpp $ * * 1 04/07/12 13:34 Hase | Revision 1.13 2003/08/03 12:54:10 uzadow | Fixed broken linux build. | | Revision 1.12 2003/08/03 12:48:50 uzadow | Added unicode support; fixed some header includes. | | Revision 1.11 2003/08/03 12:03:20 uzadow | Added unicode support; fixed some header includes. | | Revision 1.10 2003/02/24 22:10:27 uzadow | Linux version of MakeBmpFromURL() tests | | Revision 1.9 2003/02/15 21:26:58 uzadow | Added win32 version of url data source. | | Revision 1.8 2002/08/05 19:06:30 uzadow | no message | | Revision 1.7 2002/08/04 21:20:41 uzadow | no message | | Revision 1.6 2002/08/04 20:08:01 uzadow | Added PLBmpInfo class, ability to extract metainformation from images without loading the whole image and proper greyscale support. | | Revision 1.5 2002/03/03 16:29:55 uzadow | Re-added BPPWanted. | | Revision 1.4 2001/10/21 17:12:40 uzadow | Added PSD decoder beta, removed BPPWanted from all decoders, added PLFilterPixel. | | Revision 1.3 2001/10/16 17:12:26 uzadow | Added support for resolution information (Luca Piergentili) | | Revision 1.2 2001/10/06 22:37:08 uzadow | Linux compatibility. | | Revision 1.1 2001/09/16 19:03:22 uzadow | Added global name prefix PL, changed most filenames. | | Revision 1.13 2001/09/15 21:02:44 uzadow | Cleaned up stdpch.h and config.h to make them internal headers. | | Revision 1.12 2001/02/04 14:31:52 uzadow | Member initialization list cleanup (Erik Hoffmann). | | Revision 1.11 2001/02/04 14:07:24 uzadow | Changed max. filename length. | | Revision 1.10 2001/01/21 14:28:21 uzadow | Changed array cleanup from delete to delete[]. | | Revision 1.9 2000/12/18 22:42:52 uzadow | Replaced RGBAPIXEL with PLPixel32. | | Revision 1.8 2000/03/30 21:24:15 Ulrich von Zadow | Added MakeBmpFromMemory() function by Markus Ewald | | Revision 1.7 2000/01/16 20:43:14 anonymous | Removed MFC dependencies | | Revision 1.6 2000/01/11 21:40:30 Ulrich von Zadow | Added instance handle parameter to LoadFromResource() | | Revision 1.5 2000/01/08 15:51:30 Ulrich von Zadow | Misc. modifications to png encoder. | | Revision 1.4 1999/11/08 22:12:51 Ulrich von Zadow | Andreas Koepf: Added resource type as parameter to | MakeBmpFromResource | | Revision 1.3 1999/10/03 18:50:51 Ulrich von Zadow | Added automatic logging of changes. | | \-------------------------------------------------------------------- */
[ "jumius@05cee5c3-a2e9-0310-9523-9dfc2f93dbe1" ]
[ [ [ 1, 573 ] ] ]
5daea38f06312b5f6277b65eccc5b92aee1d55ed
011359e589f99ae5fe8271962d447165e9ff7768
/src/burn/konami/d_ajax.cpp
7544781682ceff868704dbc91af05ceacb286c5d
[]
no_license
PS3emulators/fba-next-slim
4c753375fd68863c53830bb367c61737393f9777
d082dea48c378bddd5e2a686fe8c19beb06db8e1
refs/heads/master
2021-01-17T23:05:29.479865
2011-12-01T18:16:02
2011-12-01T18:16:02
2,899,840
1
0
null
null
null
null
UTF-8
C++
false
false
28,482
cpp
// FB Alpha Ajax driver module // Based on MAME driver by Manuel Abadia #include "tiles_generic.h" #include "konami_intf.h" #include "konamiic.h" #include "burn_ym2151.h" #include "k007232.h" #include "m6809_intf.h" static unsigned char *AllMem; static unsigned char *MemEnd; static unsigned char *AllRam; static unsigned char *RamEnd; static unsigned char *DrvKonROM; static unsigned char *DrvM6809ROM; static unsigned char *DrvZ80ROM; static unsigned char *DrvGfxROM0; static unsigned char *DrvGfxROM1; static unsigned char *DrvGfxROM2; static unsigned char *DrvGfxROMExp0; static unsigned char *DrvGfxROMExp1; static unsigned char *DrvSndROM0; static unsigned char *DrvSndROM1; static unsigned char *DrvShareRAM; static unsigned char *DrvKonRAM; static unsigned char *DrvPalRAM; static unsigned char *DrvZ80RAM; static unsigned int *DrvPalette; static unsigned char DrvRecalc; static unsigned char *soundlatch; static unsigned char *nDrvBankRom; static unsigned char DrvInputs[3]; static unsigned char DrvJoy1[8]; static unsigned char DrvJoy2[8]; static unsigned char DrvJoy3[8]; static unsigned char DrvDips[3]; static unsigned char DrvReset; static int firq_enable; static int ajax_priority; static struct BurnInputInfo AjaxInputList[] = { {"P1 Coin", BIT_DIGITAL, DrvJoy1 + 0, "p1 coin" }, {"P1 Start", BIT_DIGITAL, DrvJoy1 + 3, "p1 start" }, {"P1 Up", BIT_DIGITAL, DrvJoy2 + 2, "p1 up" }, {"P1 Down", BIT_DIGITAL, DrvJoy2 + 3, "p1 down" }, {"P1 Left", BIT_DIGITAL, DrvJoy2 + 0, "p1 left" }, {"P1 Right", BIT_DIGITAL, DrvJoy2 + 1, "p1 right" }, {"P1 Button 1", BIT_DIGITAL, DrvJoy2 + 4, "p1 fire 1" }, {"P1 Button 2", BIT_DIGITAL, DrvJoy2 + 5, "p1 fire 2" }, {"P1 Button 3", BIT_DIGITAL, DrvJoy2 + 6, "p1 fire 3" }, {"P2 Coin", BIT_DIGITAL, DrvJoy1 + 1, "p2 coin" }, {"P2 Start", BIT_DIGITAL, DrvJoy1 + 4, "p2 start" }, {"P2 Up", BIT_DIGITAL, DrvJoy3 + 2, "p2 up" }, {"P2 Down", BIT_DIGITAL, DrvJoy3 + 3, "p2 down" }, {"P2 Left", BIT_DIGITAL, DrvJoy3 + 0, "p2 left" }, {"P2 Right", BIT_DIGITAL, DrvJoy3 + 1, "p2 right" }, {"P2 Button 1", BIT_DIGITAL, DrvJoy3 + 4, "p2 fire 1" }, {"P2 Button 2", BIT_DIGITAL, DrvJoy3 + 5, "p2 fire 2" }, {"P2 Button 3", BIT_DIGITAL, DrvJoy3 + 6, "p2 fire 3" }, {"Reset", BIT_DIGITAL, &DrvReset, "reset"}, {"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" }, {"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip" }, {"Dip C", BIT_DIPSWITCH, DrvDips + 2, "dip" }, }; STDINPUTINFO(Ajax) static struct BurnDIPInfo AjaxDIPList[]= { {0x13, 0xff, 0xff, 0xff, NULL }, {0x14, 0xff, 0xff, 0x52, NULL }, {0x15, 0xff, 0xff, 0xff, NULL }, {0 , 0xfe, 0 , 16, "Coin A" }, {0x13, 0x01, 0x0f, 0x02, "4 Coins 1 Credits" }, {0x13, 0x01, 0x0f, 0x05, "3 Coins 1 Credits" }, {0x13, 0x01, 0x0f, 0x08, "2 Coins 1 Credits" }, {0x13, 0x01, 0x0f, 0x04, "3 Coins 2 Credits" }, {0x13, 0x01, 0x0f, 0x01, "4 Coins 3 Credits" }, {0x13, 0x01, 0x0f, 0x0f, "1 Coin 1 Credits" }, {0x13, 0x01, 0x0f, 0x03, "3 Coins 4 Credits" }, {0x13, 0x01, 0x0f, 0x07, "2 Coins 3 Credits" }, {0x13, 0x01, 0x0f, 0x0e, "1 Coin 2 Credits" }, {0x13, 0x01, 0x0f, 0x06, "2 Coins 5 Credits" }, {0x13, 0x01, 0x0f, 0x0d, "1 Coin 3 Credits" }, {0x13, 0x01, 0x0f, 0x0c, "1 Coin 4 Credits" }, {0x13, 0x01, 0x0f, 0x0b, "1 Coin 5 Credits" }, {0x13, 0x01, 0x0f, 0x0a, "1 Coin 6 Credits" }, {0x13, 0x01, 0x0f, 0x09, "1 Coin 7 Credits" }, {0x13, 0x01, 0x0f, 0x00, "Free Play" }, {0 , 0xfe, 0 , 15, "Coin B" }, {0x13, 0x01, 0xf0, 0x20, "4 Coins 1 Credits" }, {0x13, 0x01, 0xf0, 0x50, "3 Coins 1 Credits" }, {0x13, 0x01, 0xf0, 0x80, "2 Coins 1 Credits" }, {0x13, 0x01, 0xf0, 0x40, "3 Coins 2 Credits" }, {0x13, 0x01, 0xf0, 0x10, "4 Coins 3 Credits" }, {0x13, 0x01, 0xf0, 0xf0, "1 Coin 1 Credits" }, {0x13, 0x01, 0xf0, 0x30, "3 Coins 4 Credits" }, {0x13, 0x01, 0xf0, 0x70, "2 Coins 3 Credits" }, {0x13, 0x01, 0xf0, 0xe0, "1 Coin 2 Credits" }, {0x13, 0x01, 0xf0, 0x60, "2 Coins 5 Credits" }, {0x13, 0x01, 0xf0, 0xd0, "1 Coin 3 Credits" }, {0x13, 0x01, 0xf0, 0xc0, "1 Coin 4 Credits" }, {0x13, 0x01, 0xf0, 0xb0, "1 Coin 5 Credits" }, {0x13, 0x01, 0xf0, 0xa0, "1 Coin 6 Credits" }, {0x13, 0x01, 0xf0, 0x90, "1 Coin 7 Credits" }, {0 , 0xfe, 0 , 4, "Lives" }, {0x14, 0x01, 0x03, 0x03, "2" }, {0x14, 0x01, 0x03, 0x02, "3" }, {0x14, 0x01, 0x03, 0x01, "5" }, {0x14, 0x01, 0x03, 0x00, "7" }, // {0 , 0xfe, 0 , 2, "Cabinet" }, // {0x14, 0x01, 0x04, 0x00, "Upright" }, // {0x14, 0x01, 0x04, 0x04, "Cocktail" }, {0 , 0xfe, 0 , 4, "Bonus Life" }, {0x14, 0x01, 0x18, 0x18, "30000 150000" }, {0x14, 0x01, 0x18, 0x10, "50000 200000" }, {0x14, 0x01, 0x18, 0x08, "30000" }, {0x14, 0x01, 0x18, 0x00, "50000" }, {0 , 0xfe, 0 , 4, "Difficulty" }, {0x14, 0x01, 0x60, 0x60, "Easy" }, {0x14, 0x01, 0x60, 0x40, "Normal" }, {0x14, 0x01, 0x60, 0x20, "Difficult" }, {0x14, 0x01, 0x60, 0x00, "Very Difficult" }, {0 , 0xfe, 0 , 2, "Demo Sounds" }, {0x14, 0x01, 0x80, 0x80, "Off" }, {0x14, 0x01, 0x80, 0x00, "On" }, // {0 , 0xfe, 0 , 2, "Flip Screen" }, // {0x15, 0x01, 0x01, 0x01, "Off" }, // {0x15, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 2, "Upright Controls" }, {0x15, 0x01, 0x02, 0x02, "Single" }, {0x15, 0x01, 0x02, 0x00, "Dual" }, {0 , 0xfe, 0 , 2, "Service Mode" }, {0x15, 0x01, 0x04, 0x04, "Off" }, {0x15, 0x01, 0x04, 0x00, "On" }, {0 , 0xfe, 0 , 2, "Control in 3D Stages" }, {0x15, 0x01, 0x08, 0x08, "Normal" }, {0x15, 0x01, 0x08, 0x00, "Inverted" }, }; STDDIPINFO(Ajax) static void ajax_main_bankswitch(int data) { nDrvBankRom[0] = data; int nBank = 0x10000 + ((data & 0x80) << 9) + ((data & 7) << 13); ajax_priority = data & 0x08; konamiMapMemory(DrvKonROM + nBank, 0x6000, 0x7fff, KON_ROM); } void ajax_main_write(unsigned short address, unsigned char data) { if (address <= 0x1c0) { switch ((address & 0x01c0) >> 6) { case 0x0000: if (address == 0 && firq_enable) { M6809SetIRQ(1, M6809_IRQSTATUS_AUTO); } break; case 0x0001: ZetSetIRQLine(0, ZET_IRQSTATUS_ACK); break; case 0x0002: *soundlatch = data; break; case 0x0003: ajax_main_bankswitch(data); break; } } if ((address & 0xfff8) == 0x0800) { K051937Write(address & 7, data); return; } if ((address & 0xfc00) == 0x0c00) { K051960Write(address & 0x3ff, data); return; } } unsigned char ajax_main_read(unsigned short address) { if (address <= 0x01c0) { switch ((address & 0x1c0) >> 6) { case 0x0000: return konamiTotalCycles() & 0xff; // rand case 0x0004: return DrvInputs[2]; case 0x0006: switch (address & 3) { case 0: return DrvInputs[0]; case 1: return DrvInputs[1]; case 2: return DrvDips[0]; case 3: return DrvDips[1]; } return 0; case 0x0007: return DrvDips[2]; } } if ((address & 0xfff8) == 0x0800) { return K051937Read(address & 7); } if ((address & 0xfc00) == 0x0c00) { return K051960Read(address & 0x3ff); } return 0; } static void ajax_sub_bankswitch(unsigned char data) { nDrvBankRom[1] = data; K052109RMRDLine = data & 0x40; K051316WrapEnable(0, data & 0x20); firq_enable = data & 0x10; int nBank = ((data & 0x0f) << 13) + 0x10000; M6809MapMemory(DrvM6809ROM + nBank, 0x8000, 0x9fff, M6809_ROM); } void ajax_sub_write(unsigned short address, unsigned char data) { if ((address & 0xf800) == 0x0000) { K051316Write(0, address & 0x7ff, data); return; } if ((address & 0xfff0) == 0x0800) { K051316WriteCtrl(0, address & 0x0f, data); return; } if (address == 0x1800) { ajax_sub_bankswitch(data); return; } if ((address & 0xc000) == 0x4000) { K052109Write(address & 0x3fff, data); return; } } unsigned char ajax_sub_read(unsigned short address) { if ((address & 0xf800) == 0x0000) { return K051316Read(0, address & 0x7ff); } if ((address & 0xf800) == 0x1000) { return K051316ReadRom(0, address & 0x7ff); } if ((address & 0xc000) == 0x4000) { return K052109Read(address & 0x3fff); } return 0; } void __fastcall ajax_sound_write(unsigned short address, unsigned char data) { if ((address & 0xfff0) == 0xa000) { K007232WriteReg(0, address & 0x0f, data); return; } if ((address & 0xfff0) == 0xb000) { K007232WriteReg(1, address & 0x0f, data); return; } switch (address) { case 0x9000: k007232_set_bank(0, (data >> 1) & 1, (data >> 0) & 1 ); k007232_set_bank(1, (data >> 4) & 3, (data >> 2) & 3 ); return; case 0xb80c: K007232SetVolume(1, 0, (data & 0x0f) * 0x11/2, (data & 0x0f) * 0x11/2); return; case 0xc000: BurnYM2151SelectRegister(data); return; case 0xc001: BurnYM2151WriteRegister(data); return; } } unsigned char __fastcall ajax_sound_read(unsigned short address) { if ((address & 0xfff0) == 0xa000) { return K007232ReadReg(0, address & 0x0f); } if ((address & 0xfff0) == 0xb000) { return K007232ReadReg(1, address & 0x0f); } switch (address) { case 0xc000: case 0xc001: return BurnYM2151ReadStatus(); case 0xe000: ZetSetIRQLine(0, ZET_IRQSTATUS_NONE); return *soundlatch; } return 0; } static void K052109Callback(int layer, int bank, int *code, int *color, int *, int *) { int layer_colorbase[3] = { 64, 0, 32 }; *code |= ((*color & 0x0f) << 8) | (bank << 12); *code &= 0x3fff; *color = layer_colorbase[layer] + ((*color & 0xf0) >> 4); } static void K051960Callback(int *code, int *color,int *priority, int *) { *priority = 0; if ( *color & 0x10) *priority = 1; if (~*color & 0x40) *priority = 2; if ( *color & 0x20) *priority = 3; *color = 16 + (*color & 0x0f); *code &= 0x1fff; } static void K051316Callback(int *code,int *color,int *) { *code |= ((*color & 0x07) << 8); *code &= 0x7ff; *color = 6 + ((*color & 0x08) >> 3); } static void DrvK007232VolCallback0(int v) { K007232SetVolume(0, 0, (v >> 0x4) * 0x11, 0); K007232SetVolume(0, 1, 0, (v & 0x0f) * 0x11); } static void DrvK007232VolCallback1(int v) { K007232SetVolume(1, 0, (v & 0x0f) * 0x11/2, (v & 0x0f) * 0x11/2); } static int DrvDoReset() { DrvReset = 0; memset (AllRam, 0, RamEnd - AllRam); konamiOpen(0); konamiReset(); konamiClose(); M6809Open(0); M6809Reset(); M6809Close(); ZetOpen(0); ZetReset(); ZetClose(); BurnYM2151Reset(); KonamiICReset(); firq_enable = 0; ajax_priority = 0; return 0; } static int MemIndex() { unsigned char *Next; Next = AllMem; DrvKonROM = Next; Next += 0x030000; DrvM6809ROM = Next; Next += 0x030000; DrvZ80ROM = Next; Next += 0x010000; DrvGfxROM0 = Next; Next += 0x080000; DrvGfxROM1 = Next; Next += 0x100000; DrvGfxROM2 = Next; Next += 0x080000; DrvGfxROMExp0 = Next; Next += 0x100000; DrvGfxROMExp1 = Next; Next += 0x200000; DrvSndROM0 = Next; Next += 0x040000; DrvSndROM1 = Next; Next += 0x080000; DrvPalette = (unsigned int*)Next; Next += 0x800 * sizeof(int); AllRam = Next; DrvShareRAM = Next; Next += 0x002000; DrvKonRAM = Next; Next += 0x002000; DrvPalRAM = Next; Next += 0x001000 + 0x1000; DrvZ80RAM = Next; Next += 0x000800; soundlatch = Next; Next += 0x000001; nDrvBankRom = Next; Next += 0x000002; RamEnd = Next; MemEnd = Next; return 0; } static int DrvGfxDecode() { int Plane0[4] = { 0x018, 0x010, 0x008, 0x000 }; int Plane1[4] = { 0x000, 0x008, 0x010, 0x018 }; int XOffs0[16] = { 0x000, 0x001, 0x002, 0x003, 0x004, 0x005, 0x006, 0x007, 0x100, 0x101, 0x102, 0x103, 0x104, 0x105, 0x106, 0x107 }; int YOffs0[16] = { 0x000, 0x020, 0x040, 0x060, 0x080, 0x0a0, 0x0c0, 0x0e0, 0x200, 0x220, 0x240, 0x260, 0x280, 0x2a0, 0x2c0, 0x2e0 }; konami_rom_deinterleave_2(DrvGfxROM0, 0x080000); konami_rom_deinterleave_2(DrvGfxROM1, 0x100000); GfxDecode(0x04000, 4, 8, 8, Plane0, XOffs0, YOffs0, 0x100, DrvGfxROM0, DrvGfxROMExp0); GfxDecode(0x02000, 4, 16, 16, Plane1, XOffs0, YOffs0, 0x400, DrvGfxROM1, DrvGfxROMExp1); return 0; } static int DrvInit() { AllMem = NULL; MemIndex(); int nLen = MemEnd - (unsigned char *)0; if ((AllMem = (unsigned char *)malloc(nLen)) == NULL) return 1; memset(AllMem, 0, nLen); MemIndex(); { if (BurnLoadRom(DrvKonROM + 0x020000, 0, 1)) return 1; if (BurnLoadRom(DrvKonROM + 0x010000, 1, 1)) return 1; memcpy (DrvKonROM + 0x08000, DrvKonROM + 0x28000, 0x8000); if (BurnLoadRom(DrvM6809ROM + 0x20000, 2, 1)) return 1; memcpy (DrvM6809ROM + 0xa000, DrvM6809ROM + 0x22000, 0x6000); if (BurnLoadRom(DrvM6809ROM + 0x10000, 3, 1)) return 1; if (BurnLoadRom(DrvZ80ROM + 0x000000, 4, 1)) return 1; if (strcmp(BurnDrvGetTextA(DRV_NAME), "ajax") == 0) { if (BurnLoadRom(DrvGfxROM0 + 0x000000, 5, 2)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x000001, 6, 2)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x020000, 7, 2)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x020001, 8, 2)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x040000, 9, 2)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x040001, 10, 2)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x060000, 11, 2)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x060001, 12, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x000000, 13, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x000001, 14, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x020000, 15, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x020001, 16, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x040000, 17, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x040001, 18, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x060000, 19, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x060001, 20, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x080000, 21, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x080001, 22, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x0a0000, 23, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x0a0001, 24, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x0c0000, 25, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x0c0001, 26, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x0e0000, 27, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x0e0001, 28, 2)) return 1; if (BurnLoadRom(DrvGfxROM2 + 0x000000, 29, 1)) return 1; if (BurnLoadRom(DrvGfxROM2 + 0x040000, 30, 1)) return 1; if (BurnLoadRom(DrvSndROM0 + 0x000000, 31, 1)) return 1; if (BurnLoadRom(DrvSndROM0 + 0x010000, 32, 1)) return 1; if (BurnLoadRom(DrvSndROM0 + 0x020000, 33, 1)) return 1; if (BurnLoadRom(DrvSndROM0 + 0x030000, 34, 1)) return 1; if (BurnLoadRom(DrvSndROM1 + 0x000000, 35, 1)) return 1; if (BurnLoadRom(DrvSndROM1 + 0x010000, 36, 1)) return 1; if (BurnLoadRom(DrvSndROM1 + 0x020000, 37, 1)) return 1; if (BurnLoadRom(DrvSndROM1 + 0x030000, 38, 1)) return 1; if (BurnLoadRom(DrvSndROM1 + 0x040000, 39, 1)) return 1; if (BurnLoadRom(DrvSndROM1 + 0x050000, 40, 1)) return 1; if (BurnLoadRom(DrvSndROM1 + 0x060000, 41, 1)) return 1; if (BurnLoadRom(DrvSndROM1 + 0x070000, 42, 1)) return 1; } else { if (BurnLoadRom(DrvGfxROM0 + 0x000000, 5, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x040000, 6, 1)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x000000, 7, 1)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x080000, 8, 1)) return 1; if (BurnLoadRom(DrvGfxROM2 + 0x000000, 9, 1)) return 1; if (BurnLoadRom(DrvGfxROM2 + 0x040000, 10, 1)) return 1; if (BurnLoadRom(DrvSndROM0 + 0x000000, 11, 1)) return 1; if (BurnLoadRom(DrvSndROM1 + 0x000000, 12, 1)) return 1; } DrvGfxDecode(); } konamiInit(1); konamiOpen(0); konamiMapMemory(DrvPalRAM, 0x1000, 0x1fff, KON_RAM); konamiMapMemory(DrvShareRAM, 0x2000, 0x3fff, KON_RAM); konamiMapMemory(DrvKonRAM, 0x4000, 0x5fff, KON_RAM); konamiMapMemory(DrvKonROM + 0x10000, 0x6000, 0x7fff, KON_ROM); konamiMapMemory(DrvKonROM + 0x08000, 0x8000, 0xffff, KON_ROM); konamiSetWriteHandler(ajax_main_write); konamiSetReadHandler(ajax_main_read); konamiClose(); M6809Init(1); M6809Open(0); M6809MapMemory(DrvShareRAM, 0x2000, 0x3fff, M6809_RAM); M6809MapMemory(DrvM6809ROM + 0x10000, 0x8000, 0x9fff, M6809_ROM); M6809MapMemory(DrvM6809ROM + 0x0a000, 0xa000, 0xffff, M6809_ROM); M6809SetWriteByteHandler(ajax_sub_write); M6809SetReadByteHandler(ajax_sub_read); M6809Close(); ZetInit(1); ZetOpen(0); ZetMapArea(0x0000, 0x7fff, 0, DrvZ80ROM); ZetMapArea(0x0000, 0x7fff, 2, DrvZ80ROM); ZetMapArea(0x8000, 0x87ff, 0, DrvZ80RAM); ZetMapArea(0x8000, 0x87ff, 1, DrvZ80RAM); ZetMapArea(0x8000, 0x87ff, 2, DrvZ80RAM); ZetSetWriteHandler(ajax_sound_write); ZetSetReadHandler(ajax_sound_read); ZetMemEnd(); ZetClose(); BurnYM2151Init(3579545, 25.0); K007232Init(0, 3579545, DrvSndROM0, 0x40000); K007232SetPortWriteHandler(0, DrvK007232VolCallback0); K007232Init(1, 3579545, DrvSndROM1, 0x80000); K007232SetPortWriteHandler(1, DrvK007232VolCallback1); K052109Init(DrvGfxROM0, 0x7ffff); K052109SetCallback(K052109Callback); K052109AdjustScroll(8, 0); K051960Init(DrvGfxROM1, 0xfffff); K051960SetCallback(K051960Callback); K051960SetSpriteOffset(8, 0); K051316Init(0, DrvGfxROM2, DrvGfxROM2, 0x7ffff, K051316Callback, 7, 0); K051316SetOffset(0, -112, -16); GenericTilesInit(); DrvDoReset(); return 0; } static int DrvExit() { GenericTilesExit(); KonamiICExit(); M6809Exit(); konamiExit(); ZetExit(); K007232Exit(); BurnYM2151Exit(); free (AllMem); AllMem = NULL; return 0; } static int DrvDraw() { if (DrvRecalc) { KonamiRecalcPal(DrvPalRAM, DrvPalette, 0x1000); } K052109UpdateScroll(); BurnTransferClear(); if (nBurnLayer & 1) K052109RenderLayer(2, 0, DrvGfxROMExp0); if (ajax_priority) { if (nBurnLayer & 2) K051316_zoom_draw(0, 4); if (nBurnLayer & 4) K052109RenderLayer(1, 0, DrvGfxROMExp0); } else { if (nBurnLayer & 4) K052109RenderLayer(1, 0, DrvGfxROMExp0); if (nBurnLayer & 2) K051316_zoom_draw(0, 4); } // needs work... if (nSpriteEnable & 1) K051960SpritesRender(DrvGfxROMExp1, 3); if (nSpriteEnable & 2) K051960SpritesRender(DrvGfxROMExp1, 2); if (nSpriteEnable & 4) K051960SpritesRender(DrvGfxROMExp1, 1); if (nSpriteEnable & 8) K051960SpritesRender(DrvGfxROMExp1, 0); if (nBurnLayer & 8) K052109RenderLayer(0, 0, DrvGfxROMExp0); BurnTransferCopy(DrvPalette); return 0; } static int DrvFrame() { if (DrvReset) { DrvDoReset(); } { memset (DrvInputs, 0xff, 3); for (int i = 0; i < 8; i++) { DrvInputs[0] ^= (DrvJoy1[i] & 1) << i; DrvInputs[1] ^= (DrvJoy2[i] & 1) << i; DrvInputs[2] ^= (DrvJoy3[i] & 1) << i; } if ((DrvInputs[1] & 0x0c) == 0) DrvInputs[1] |= 0x0c; if ((DrvInputs[1] & 0x03) == 0) DrvInputs[1] |= 0x03; if ((DrvInputs[0] & 0x0c) == 0) DrvInputs[0] |= 0x0c; if ((DrvInputs[0] & 0x03) == 0) DrvInputs[0] |= 0x03; } int nSoundBufferPos = 0; int nInterleave = 100; int nCyclesTotal[3] = { (((3000000 / 60) * 133) / 100) /* 33% overclock */, 3000000 / 60, 3579545 / 60 }; int nCyclesDone[3] = { 0, 0, 0 }; ZetOpen(0); M6809Open(0); konamiOpen(0); for (int i = 0; i < nInterleave; i++) { int nSegment = (nCyclesTotal[0] / nInterleave) * (i + 1); nCyclesDone[0] += konamiRun(nSegment - nCyclesDone[0]); nCyclesDone[1] += M6809Run(nSegment - nCyclesDone[1]); nSegment = (nCyclesTotal[2] / nInterleave) * (i + 1); nCyclesDone[2] += ZetRun(nSegment - nCyclesDone[2]); if (pBurnSoundOut) { int nSegmentLength = nBurnSoundLen - nSoundBufferPos; short* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1); BurnYM2151Render(pSoundBuf, nSegmentLength); K007232Update(0, pSoundBuf, nSegmentLength); K007232Update(1, pSoundBuf, nSegmentLength); nSoundBufferPos += nSegmentLength; } } if (K051960_irq_enabled) konamiSetIrqLine(KONAMI_IRQ_LINE, KONAMI_HOLD_LINE); if (pBurnSoundOut) { int nSegmentLength = nBurnSoundLen - nSoundBufferPos; if (nSegmentLength) { short* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1); BurnYM2151Render(pSoundBuf, nSegmentLength); K007232Update(0, pSoundBuf, nSegmentLength); K007232Update(1, pSoundBuf, nSegmentLength); } } konamiClose(); M6809Close(); ZetClose(); if (pBurnDraw) { DrvDraw(); } return 0; } static int DrvScan(int nAction,int *pnMin) { struct BurnArea ba; if (pnMin) { *pnMin = 0x029705; } if (nAction & ACB_VOLATILE) { memset(&ba, 0, sizeof(ba)); ba.Data = AllRam; ba.nLen = RamEnd - AllRam; ba.szName = "All Ram"; BurnAcb(&ba); konamiCpuScan(nAction, pnMin); M6809Scan(nAction); ZetScan(nAction); BurnYM2151Scan(nAction); K007232Scan(nAction, pnMin); KonamiICScan(nAction); } if (nAction & ACB_WRITE) { konamiOpen(0); ajax_main_bankswitch(nDrvBankRom[0]); konamiClose(); M6809Open(0); ajax_sub_bankswitch(nDrvBankRom[1]); M6809Close(); } return 0; } // Ajax static struct BurnRomInfo ajaxRomDesc[] = { { "770_m01.n11", 0x10000, 0x4a64e53a, 1 | BRF_PRG | BRF_ESS }, // 0 Konami Custom Code { "770_l02.n12", 0x10000, 0xad7d592b, 1 | BRF_PRG | BRF_ESS }, // 1 { "770_l05.i16", 0x08000, 0xed64fbb2, 2 | BRF_PRG | BRF_ESS }, // 2 M6809 Code { "770_f04.g16", 0x10000, 0xe0e4ec9c, 2 | BRF_PRG | BRF_ESS }, // 3 { "770_h03.f16", 0x08000, 0x2ffd2afc, 3 | BRF_PRG | BRF_ESS }, // 4 Z80 Code { "770c13-a.f3", 0x10000, 0x4ef6fff2, 4 | BRF_GRA }, // 5 K052109 Tiles { "770c13-c.f4", 0x10000, 0x97ffbab6, 4 | BRF_GRA }, // 6 { "770c13-b.e3", 0x10000, 0x86fdd706, 4 | BRF_GRA }, // 7 { "770c13-d.e4", 0x10000, 0x7d7acb2d, 4 | BRF_GRA }, // 8 { "770c12-a.f5", 0x10000, 0x6c0ade68, 4 | BRF_GRA }, // 9 { "770c12-c.f6", 0x10000, 0x61fc39cc, 4 | BRF_GRA }, // 10 { "770c12-b.e5", 0x10000, 0x5f221cc6, 4 | BRF_GRA }, // 11 { "770c12-d.e6", 0x10000, 0xf1edb2f4, 4 | BRF_GRA }, // 12 { "770c09-a.f8", 0x10000, 0x76690fb8, 5 | BRF_GRA }, // 13 K051960 Tiles { "770c09-e.f9", 0x10000, 0x17b482c9, 5 | BRF_GRA }, // 14 { "770c09-b.e8", 0x10000, 0xcd1709d1, 5 | BRF_GRA }, // 15 { "770c09-f.e9", 0x10000, 0xcba4b47e, 5 | BRF_GRA }, // 16 { "770c09-c.d8", 0x10000, 0xbfd080b8, 5 | BRF_GRA }, // 17 { "770c09-g.d9", 0x10000, 0x77d58ea0, 5 | BRF_GRA }, // 18 { "770c09-d.c8", 0x10000, 0x6f955600, 5 | BRF_GRA }, // 19 { "770c09-h.c9", 0x10000, 0x494a9090, 5 | BRF_GRA }, // 20 { "770c08-a.f10", 0x10000, 0xefd29a56, 5 | BRF_GRA }, // 21 { "770c08-e.f11", 0x10000, 0x6d43afde, 5 | BRF_GRA }, // 22 { "770c08-b.e10", 0x10000, 0xf3374014, 5 | BRF_GRA }, // 23 { "770c08-f.e11", 0x10000, 0xf5ba59aa, 5 | BRF_GRA }, // 24 { "770c08-c.d10", 0x10000, 0x28e7088f, 5 | BRF_GRA }, // 25 { "770c08-g.d11", 0x10000, 0x17da8f6d, 5 | BRF_GRA }, // 26 { "770c08-d.c10", 0x10000, 0x91591777, 5 | BRF_GRA }, // 27 { "770c08-h.c11", 0x10000, 0xd97d4b15, 5 | BRF_GRA }, // 28 { "770c06", 0x40000, 0xd0c592ee, 6 | BRF_GRA }, // 29 K051960 Tiles { "770c07", 0x40000, 0x0b399fb1, 6 | BRF_GRA }, // 30 { "770c10-a.a7", 0x10000, 0xe45ec094, 7 | BRF_SND }, // 31 K007232 #0 Samples { "770c10-b.a6", 0x10000, 0x349db7d3, 7 | BRF_SND }, // 32 { "770c10-c.a5", 0x10000, 0x71cb1f05, 7 | BRF_SND }, // 33 { "770c10-d.a4", 0x10000, 0xe8ab1844, 7 | BRF_SND }, // 34 { "770c11-a.c6", 0x10000, 0x8cccd9e0, 8 | BRF_SND }, // 35 K007232 #1 Samples { "770c11-b.c5", 0x10000, 0x0af2fedd, 8 | BRF_SND }, // 36 { "770c11-c.c4", 0x10000, 0x7471f24a, 8 | BRF_SND }, // 37 { "770c11-d.c3", 0x10000, 0xa58be323, 8 | BRF_SND }, // 38 { "770c11-e.b7", 0x10000, 0xdd553541, 8 | BRF_SND }, // 39 { "770c11-f.b6", 0x10000, 0x3f78bd0f, 8 | BRF_SND }, // 40 { "770c11-g.b5", 0x10000, 0x078c51b2, 8 | BRF_SND }, // 41 { "770c11-h.b4", 0x10000, 0x7300c2e1, 8 | BRF_SND }, // 42 { "63s241.j11", 0x00200, 0x9bdd719f, 9 | BRF_OPT }, // 43 Timing Prom (unused) }; STD_ROM_PICK(ajax) STD_ROM_FN(ajax) struct BurnDriver BurnDrvAjax = { "ajax", NULL, NULL, "1987", "Ajax\0", NULL, "Konami", "GX770", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_ORIENTATION_VERTICAL | BDF_ORIENTATION_FLIPPED, 2, HARDWARE_PREFIX_KONAMI, NULL, ajaxRomInfo, ajaxRomName, AjaxInputInfo, AjaxDIPInfo, DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 224, 288, 3, 4 }; // Typhoon static struct BurnRomInfo typhoonRomDesc[] = { { "770_k01.n11", 0x10000, 0x5ba74a22, 1 | BRF_PRG | BRF_ESS }, // 0 Konami Custom Code { "770_k02.n12", 0x10000, 0x3bcf782a, 1 | BRF_PRG | BRF_ESS }, // 1 { "770_k05.i16", 0x08000, 0x0f1bebbb, 2 | BRF_PRG | BRF_ESS }, // 2 M6809 Code { "770_f04.g16", 0x10000, 0xe0e4ec9c, 2 | BRF_PRG | BRF_ESS }, // 3 { "770_h03.f16", 0x08000, 0x2ffd2afc, 3 | BRF_PRG | BRF_ESS }, // 4 Z80 Code { "770c13", 0x40000, 0xb859ca4e, 4 | BRF_GRA }, // 5 K052109 Tiles { "770c12", 0x40000, 0x50d14b72, 4 | BRF_GRA }, // 6 { "770c09", 0x80000, 0x1ab4a7ff, 5 | BRF_GRA }, // 7 K051960 Tiles { "770c08", 0x80000, 0xa8e80586, 5 | BRF_GRA }, // 8 { "770c06", 0x40000, 0xd0c592ee, 6 | BRF_GRA }, // 9 K051960 Tiles { "770c07", 0x40000, 0x0b399fb1, 6 | BRF_GRA }, // 10 { "770c10", 0x40000, 0x7fac825f, 7 | BRF_SND }, // 11 K007232 #0 Samples { "770c11", 0x80000, 0x299a615a, 8 | BRF_SND }, // 12 K007232 #1 Samples { "63s241.j11", 0x00200, 0x9bdd719f, 9 | BRF_OPT }, // 13 Timing Prom (unused) }; STD_ROM_PICK(typhoon) STD_ROM_FN(typhoon) struct BurnDriver BurnDrvTyphoon = { "typhoon", "ajax", NULL, "1987", "Typhoon\0", NULL, "Konami", "GX770", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE | BDF_ORIENTATION_VERTICAL | BDF_ORIENTATION_FLIPPED, 2, HARDWARE_PREFIX_KONAMI, NULL, typhoonRomInfo, typhoonRomName, AjaxInputInfo, AjaxDIPInfo, DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 224, 288, 3, 4 }; // Ajax (Japan) static struct BurnRomInfo ajaxjRomDesc[] = { { "770_l01.n11", 0x10000, 0x7cea5274, 1 | BRF_PRG | BRF_ESS }, // 0 Konami Custom Code { "770_l02.n12", 0x10000, 0xad7d592b, 1 | BRF_PRG | BRF_ESS }, // 1 { "770_l05.i16", 0x08000, 0xed64fbb2, 2 | BRF_PRG | BRF_ESS }, // 2 M6809 code { "770_f04.g16", 0x10000, 0xe0e4ec9c, 2 | BRF_PRG | BRF_ESS }, // 3 { "770_f03.f16", 0x08000, 0x3fe914fd, 3 | BRF_PRG | BRF_ESS }, // 4 Z80 Code { "770c13", 0x40000, 0xb859ca4e, 4 | BRF_GRA }, // 5 K052109 Tiles { "770c12", 0x40000, 0x50d14b72, 4 | BRF_GRA }, // 6 { "770c09", 0x80000, 0x1ab4a7ff, 5 | BRF_GRA }, // 7 K051960 Tiles { "770c08", 0x80000, 0xa8e80586, 5 | BRF_GRA }, // 8 { "770c06", 0x40000, 0xd0c592ee, 6 | BRF_GRA }, // 9 K051960 Tiles { "770c07", 0x40000, 0x0b399fb1, 6 | BRF_GRA }, // 10 { "770c10", 0x40000, 0x7fac825f, 7 | BRF_SND }, // 11 K007232 #0 Samples { "770c11", 0x80000, 0x299a615a, 8 | BRF_SND }, // 12 K007232 #1 Samples { "63s241.j11", 0x00200, 0x9bdd719f, 9 | BRF_OPT }, // 13 Timing Prom (unused) }; STD_ROM_PICK(ajaxj) STD_ROM_FN(ajaxj) struct BurnDriver BurnDrvAjaxj = { "ajaxj", "ajax", NULL, "1987", "Ajax (Japan)\0", NULL, "Konami", "GX770", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE | BDF_ORIENTATION_VERTICAL | BDF_ORIENTATION_FLIPPED, 2, HARDWARE_PREFIX_KONAMI, NULL, ajaxjRomInfo, ajaxjRomName, AjaxInputInfo, AjaxDIPInfo, DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 224, 288, 3, 4 };
[ [ [ 1, 936 ] ] ]
f8a6b69208f75d0778adf74a14acc1b97c07eda5
011359e589f99ae5fe8271962d447165e9ff7768
/src/burn/misc/post90s/d_1945kiii.cpp
531a77595fc330cb11ac2b4adfe2d595531defd4
[]
no_license
PS3emulators/fba-next-slim
4c753375fd68863c53830bb367c61737393f9777
d082dea48c378bddd5e2a686fe8c19beb06db8e1
refs/heads/master
2021-01-17T23:05:29.479865
2011-12-01T18:16:02
2011-12-01T18:16:02
2,899,840
1
0
null
null
null
null
UTF-8
C++
false
false
22,375
cpp
/* 1945K-III Oriental, 2000 port to Finalburn Alpha by OopsWare. 2007 */ #include "burnint.h" #include "msm6295.h" static unsigned char *Mem = NULL, *MemEnd = NULL; static unsigned char *RamStart, *RamEnd; static unsigned char *Rom68K; static unsigned char *RomBg; static unsigned char *RomSpr; static unsigned char *Ram68K; static unsigned short *RamPal; static unsigned short *RamSpr0; static unsigned short *RamSpr1; static unsigned short *RamBg; static unsigned short *RamCurPal; static unsigned char bRecalcPalette = 0; static unsigned char DrvReset = 0; static unsigned short scrollx, scrolly; static unsigned char m6295bank[2]; static unsigned char DrvButton[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static unsigned char DrvJoy1[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static unsigned char DrvJoy2[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static unsigned char DrvInput[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static inline unsigned int CalcCol(unsigned short nColour) { int r, g, b; r = (nColour & 0x001F) << 3; // Red r |= r >> 5; g = (nColour & 0x03E0) >> 2; // Green g |= g >> 5; b = (nColour & 0x7C00) >> 7; // Blue b |= b >> 5; return BurnHighCol(r, g, b, 0); } static struct BurnInputInfo _1945kiiiInputList[] = { {"P1 Coin", BIT_DIGITAL, DrvButton + 0, "p1 coin"}, {"P1 Start", BIT_DIGITAL, DrvButton + 2, "p1 start"}, {"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up"}, {"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down"}, {"P1 Left", BIT_DIGITAL, DrvJoy1 + 2, "p1 left"}, {"P1 Right", BIT_DIGITAL, DrvJoy1 + 3, "p1 right"}, {"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1"}, {"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2"}, {"P1 Button 3", BIT_DIGITAL, DrvJoy1 + 6, "p1 fire 3"}, {"P1 Button 4", BIT_DIGITAL, DrvJoy1 + 7, "p1 fire 4"}, {"P2 Start", BIT_DIGITAL, DrvButton + 3, "p2 start"}, {"P2 Up", BIT_DIGITAL, DrvJoy2 + 0, "p2 up"}, {"P2 Down", BIT_DIGITAL, DrvJoy2 + 1, "p2 down"}, {"P2 Left", BIT_DIGITAL, DrvJoy2 + 2, "p2 left"}, {"P2 Right", BIT_DIGITAL, DrvJoy2 + 3, "p2 right"}, {"P2 Button 1", BIT_DIGITAL, DrvJoy2 + 4, "p2 fire 1"}, {"P2 Button 2", BIT_DIGITAL, DrvJoy2 + 5, "p2 fire 2"}, {"P2 Button 3", BIT_DIGITAL, DrvJoy2 + 6, "p2 fire 3"}, {"P2 Button 4", BIT_DIGITAL, DrvJoy2 + 7, "p2 fire 4"}, {"Reset", BIT_DIGITAL, &DrvReset, "reset"}, {"Dip A", BIT_DIPSWITCH, DrvInput + 4, "dip"}, {"Dip B", BIT_DIPSWITCH, DrvInput + 5, "dip"}, }; STDINPUTINFO(_1945kiii) static struct BurnDIPInfo _1945kiiiDIPList[] = { // Defaults {0x14, 0xFF, 0xFF, 0x10, NULL}, {0x15, 0xFF, 0xFF, 0x00, NULL}, // DIP 1 {0, 0xFE, 0, 8, "Coin 1"}, {0x14, 0x01, 0x07, 0x00, "1 coin 1 credit"}, {0x14, 0x01, 0x07, 0x01, "2 coins 1 credit"}, {0x14, 0x01, 0x07, 0x02, "3 coins 1 credit"}, {0x14, 0x01, 0x07, 0x03, "1 coin 2 credits"}, {0x14, 0x01, 0x07, 0x04, "Free Play"}, {0x14, 0x01, 0x07, 0x05, "5 coins 1 credit"}, {0x14, 0x01, 0x07, 0x06, "4 coins 1 credit"}, {0x14, 0x01, 0x07, 0x07, "1 coin 3 credits"}, {0, 0xFE, 0, 4, "Difficulty"}, {0x14, 0x01, 0x18, 0x00, "Hardest"}, {0x14, 0x01, 0x18, 0x08, "Hard"}, {0x14, 0x01, 0x18, 0x10, "Normal"}, {0x14, 0x01, 0x18, 0x18, "Easy"}, {0, 0xFE, 0, 4, "Lives"}, {0x14, 0x01, 0x60, 0x00, "3"}, {0x14, 0x01, 0x60, 0x20, "2"}, {0x14, 0x01, 0x60, 0x40, "4"}, {0x14, 0x01, 0x60, 0x60, "5"}, {0, 0xFE, 0, 2, "Service"}, {0x14, 0x01, 0x80, 0x00, "Off"}, {0x14, 0x01, 0x80, 0x80, "On"}, // DIP 2 {0, 0xFE, 0, 2, "Demo sound"}, {0x15, 0x01, 0x01, 0x00, "Off"}, {0x15, 0x01, 0x01, 0x01, "On"}, {0, 0xFE, 0, 2, "Allow Continue"}, {0x15, 0x01, 0x02, 0x00, "Yes"}, {0x15, 0x01, 0x02, 0x02, "No"}, }; STDDIPINFO(_1945kiii) static struct BurnRomInfo _1945kiiiRomDesc[] = { { "prg-1.u51", 0x080000, 0x6b345f27, BRF_ESS | BRF_PRG }, // 68000 code { "prg-2.u52", 0x080000, 0xce09b98c, BRF_ESS | BRF_PRG }, { "m16m-1.u62", 0x200000, 0x0b9a6474, BRF_GRA }, // layer 0 { "m16m-2.u63", 0x200000, 0x368a8c2e, BRF_GRA }, { "m16m-3.u61", 0x200000, 0x32fc80dd, BRF_GRA }, // layer 1 { "snd-1.su7", 0x080000, 0xbbb7f0ff, BRF_SND }, // sound 1 { "snd-2.su4", 0x080000, 0x47e3952e, BRF_SND }, // sound 2 }; STD_ROM_PICK(_1945kiii) STD_ROM_FN(_1945kiii) static void sndSetBank(unsigned char bank0, unsigned char bank1) { if (bank0 != m6295bank[0]) { m6295bank[0] = bank0; for (int nChannel = 0; nChannel < 4; nChannel++) { MSM6295SampleInfo[0][nChannel] = MSM6295ROM + 0x000000 + 0x040000 * bank0 + (nChannel << 8); MSM6295SampleData[0][nChannel] = MSM6295ROM + 0x000000 + 0x040000 * bank0 + (nChannel << 16); } } if (bank1 != m6295bank[1]) { m6295bank[1] = bank1; for (int nChannel = 0; nChannel < 4; nChannel++) { MSM6295SampleInfo[1][nChannel] = MSM6295ROM + 0x080000 + 0x040000 * bank1 + (nChannel << 8); MSM6295SampleData[1][nChannel] = MSM6295ROM + 0x080000 + 0x040000 * bank1 + (nChannel << 16); } } } /* unsigned char __fastcall k1945iiiReadByte(unsigned int sekAddress) { switch (sekAddress) { default: bprintf(PRINT_NORMAL, _T("Attempt to read byte value of location %x\n"), sekAddress); } return 0; } */ unsigned short __fastcall k1945iiiReadWord(unsigned int sekAddress) { switch (sekAddress) { case 0x400000: return ~( DrvInput[0] + (DrvInput[1]<<8) ); case 0x440000: return ~DrvInput[2]; case 0x480000: return ~( DrvInput[4] + (DrvInput[5]<<8) ); case 0x4C0000: return MSM6295ReadStatus(0); case 0x500000: return MSM6295ReadStatus(1); //default: // bprintf(PRINT_NORMAL, _T("Attempt to read word value of location %x\n"), sekAddress); } return 0; } void __fastcall k1945iiiWriteByte(unsigned int sekAddress, unsigned char byteValue) { switch (sekAddress) { case 0x4C0000: MSM6295Command(0, byteValue); break; case 0x500000: MSM6295Command(1, byteValue); break; // default: // bprintf(PRINT_NORMAL, _T("Attempt to write byte value %x to location %x\n"), byteValue, sekAddress); } } void __fastcall k1945iiiWriteWord(unsigned int sekAddress, unsigned short wordValue) { switch (sekAddress) { case 0x340000: scrollx = wordValue; break; case 0x380000: scrolly = wordValue; break; case 0x3C0000: //bprintf(PRINT_NORMAL, _T("soundbanks write %d %d\n"), (wordValue & 2) >> 1, (wordValue & 4) >> 2); sndSetBank((wordValue & 2) >> 1, (wordValue & 4) >> 2); break; //default: // bprintf(PRINT_NORMAL, _T("Attempt to write word value %x to location %x\n"), wordValue, sekAddress); } } /* void __fastcall k1945iiiWriteBytePalette(unsigned int sekAddress, unsigned char byteValue) { bprintf(PRINT_NORMAL, _T("Palette to write byte value %x to location %x\n"), byteValue, sekAddress); } */ void __fastcall k1945iiiWriteWordPalette(unsigned int sekAddress, unsigned short wordValue) { sekAddress -= 0x200000; sekAddress >>= 1; RamPal[sekAddress] = swapWord(wordValue); RamCurPal[sekAddress] = (CalcCol((wordValue) )); } static int MemIndex() { unsigned char *Next; Next = Mem; Rom68K = Next; Next += 0x0100000; // 68000 ROM RomBg = Next; Next += 0x0200000; RomSpr = Next; Next += 0x0400000; MSM6295ROM = Next; Next += 0x0100000; RamStart = Next; Ram68K = Next; Next += 0x020000; RamPal = (unsigned short *) Next; Next += 0x001000; RamSpr0 = (unsigned short *) Next; Next += 0x001000; RamSpr1 = (unsigned short *) Next; Next += 0x001000; RamBg = (unsigned short *) Next; Next += 0x001000; RamEnd = Next; RamCurPal = (unsigned short *) Next; Next += 0x001000; MemEnd = Next; return 0; } static int DrvDoReset() { SekOpen(0); SekSetIRQLine(0, SEK_IRQSTATUS_NONE); SekReset(); SekClose(); MSM6295Reset(0); MSM6295Reset(1); m6295bank[0] = 1; m6295bank[1] = 1; sndSetBank(0, 0); return 0; } static int DrvInit() { int nRet; Mem = NULL; MemIndex(); int nLen = MemEnd - (unsigned char *)0; if ((Mem = (unsigned char *)malloc(nLen)) == NULL) return 1; memset(Mem, 0, nLen); // blank all memory MemIndex(); nRet = BurnLoadRom(Rom68K + 0x000000, 0, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(Rom68K + 0x000001, 1, 2); if (nRet != 0) return 1; BurnLoadRom(RomSpr + 0, 2, 2); BurnLoadRom(RomSpr + 1, 3, 2); // decode sprites unsigned char * tmp = RomSpr; for (int i=0; i<(0x400000/4); i++) { unsigned char c = tmp[2]; tmp[2] = tmp[1]; tmp[1] = c; tmp += 4; } BurnLoadRom(RomBg, 4, 1); BurnLoadRom(MSM6295ROM + 0x00000, 5, 1); BurnLoadRom(MSM6295ROM + 0x80000, 6, 1); { SekInit(0, 0x68000); // Allocate 68000 SekOpen(0); // Map 68000 memory: SekMapMemory(Rom68K, 0x000000, 0x0FFFFF, SM_ROM); // CPU 0 ROM SekMapMemory(Ram68K, 0x100000, 0x10FFFF, SM_RAM); // CPU 0 RAM SekMapMemory((unsigned char *)RamPal, 0x200000, 0x200FFF, SM_ROM); // palette SekMapMemory((unsigned char *)RamSpr0, 0x240000, 0x240FFF, SM_RAM); // sprites 0 SekMapMemory((unsigned char *)RamSpr1, 0x280000, 0x280FFF, SM_RAM); // sprites 1 SekMapMemory((unsigned char *)RamBg, 0x2C0000, 0x2C0FFF, SM_RAM); // back ground SekMapMemory(Ram68K+0x10000,0x8C0000, 0x8CFFFF, SM_RAM); // not used? SekMapHandler(1, 0x200000, 0x200FFF, SM_WRITE); SekSetReadWordHandler(0, k1945iiiReadWord); // SekSetReadByteHandler(0, k1945iiiReadByte); SekSetWriteWordHandler(0, k1945iiiWriteWord); SekSetWriteByteHandler(0, k1945iiiWriteByte); // SekSetWriteByteHandler(1, k1945iiiWriteBytePalette); SekSetWriteWordHandler(1, k1945iiiWriteWordPalette); SekClose(); } MSM6295Init(0, 7500, 80, 1); MSM6295Init(1, 7500, 80, 1); DrvDoReset(); return 0; } static int DrvExit() { SekExit(); MSM6295Exit(0); MSM6295Exit(1); free(Mem); Mem = NULL; return 0; } static void DrawBackground() { int offs, mx, my, x, y; unsigned short *pal = RamCurPal; mx = -1; my = 0; for (offs = 0; offs < 64*32; offs++) { mx++; if (mx == 32) { mx = 0; my++; } x = mx * 16 - scrollx; if (x <= -192) x += 512; y = my * 16 - scrolly; //if (y <= (224-512)) y += 512; if ( x<=-16 || x>=320 || y<=-16 || y>= 224 ) continue; unsigned short swappedRamBg = swapWord(RamBg[offs]); unsigned char *d = RomBg + ( swappedRamBg & 0x1fff ) * 256; unsigned short * p = (unsigned short *) pBurnDraw + y * 320 + x; #if defined (_XBOX) unsigned short d0,d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15; #endif if ( x >=0 && x <= (320-16) && y >= 0 && y <= (224-16)) { for (int k=0;k<16;k++) { #if defined (_XBOX) d0 = (pal[ d[ 0] ]); d1 = (pal[ d[ 1] ]); d2 = (pal[ d[ 2] ]); d3 = (pal[ d[ 3] ]); d4 = (pal[ d[ 4] ]); d5 = (pal[ d[ 5] ]); d6 = (pal[ d[ 6] ]); d7 = (pal[ d[ 7] ]); d8 = (pal[ d[ 8] ]); d9 = (pal[ d[ 9] ]); d10 = (pal[ d[ 10] ]); d11 = (pal[ d[ 11] ]); d12 = (pal[ d[ 12] ]); d13 = (pal[ d[ 13] ]); d14 = (pal[ d[ 14] ]); d15 = (pal[ d[ 15] ]); p[ 0] = d0; p[ 1] = d1; p[ 2] = d2; p[ 3] = d3; p[ 4] = d4; p[ 5] = d5; p[ 6] = d6; p[ 7] = d7; p[ 8] = d8; p[ 9] = d9; p[10] = d10; p[11] = d11; p[12] = d12; p[13] = d13; p[14] = d14; p[15] = d15; #else p[ 0] = (pal[ d[ 0] ]); p[ 1] = (pal[ d[ 1] ]); p[ 2] = (pal[ d[ 2] ]); p[ 3] = (pal[ d[ 3] ]); p[ 4] = (pal[ d[ 4] ]); p[ 5] = (pal[ d[ 5] ]); p[ 6] = (pal[ d[ 6] ]); p[ 7] = (pal[ d[ 7] ]); p[ 8] = (pal[ d[ 8] ]); p[ 9] = (pal[ d[ 9] ]); p[10] = (pal[ d[10] ]); p[11] = (pal[ d[11] ]); p[12] = (pal[ d[12] ]); p[13] = (pal[ d[13] ]); p[14] = (pal[ d[14] ]); p[15] = (pal[ d[15] ]); #endif d += 16; p += 320; } } else { for (int k=0;k<16;k++) { if ( (y+k)>=0 && (y+k)<224 ) { #if defined (_XBOX) d0 = (pal[ d[ 0] ]); d1 = (pal[ d[ 1] ]); d2 = (pal[ d[ 2] ]); d3 = (pal[ d[ 3] ]); d4 = (pal[ d[ 4] ]); d5 = (pal[ d[ 5] ]); d6 = (pal[ d[ 6] ]); d7 = (pal[ d[ 7] ]); d8 = (pal[ d[ 8] ]); d9 = (pal[ d[ 9] ]); d10 = (pal[ d[ 10] ]); d11 = (pal[ d[ 11] ]); d12 = (pal[ d[ 12] ]); d13 = (pal[ d[ 13] ]); d14 = (pal[ d[ 14] ]); d15 = (pal[ d[ 15] ]); if ((x + 0) >= 0 && (x + 0)<320) p[ 0] = d0; if ((x + 1) >= 0 && (x + 1)<320) p[ 1] = d1; if ((x + 2) >= 0 && (x + 2)<320) p[ 2] = d2; if ((x + 3) >= 0 && (x + 3)<320) p[ 3] = d3; if ((x + 4) >= 0 && (x + 4)<320) p[ 4] = d4; if ((x + 5) >= 0 && (x + 5)<320) p[ 5] = d5; if ((x + 6) >= 0 && (x + 6)<320) p[ 6] = d6; if ((x + 7) >= 0 && (x + 7)<320) p[ 7] = d7; if ((x + 8) >= 0 && (x + 8)<320) p[ 8] = d8; if ((x + 9) >= 0 && (x + 9)<320) p[ 9] = d9; if ((x + 10) >= 0 && (x + 10)<320) p[10] = d10; if ((x + 11) >= 0 && (x + 11)<320) p[11] = d11; if ((x + 12) >= 0 && (x + 12)<320) p[12] = d12; if ((x + 13) >= 0 && (x + 13)<320) p[13] = d13; if ((x + 14) >= 0 && (x + 14)<320) p[14] = d14; if ((x + 15) >= 0 && (x + 15)<320) p[15] = d15; #else if ((x + 0) >= 0 && (x + 0)<320) p[ 0] = pal[ d[ 0] ]; if ((x + 1) >= 0 && (x + 1)<320) p[ 1] = pal[ d[ 1] ]; if ((x + 2) >= 0 && (x + 2)<320) p[ 2] = pal[ d[ 2] ]; if ((x + 3) >= 0 && (x + 3)<320) p[ 3] = pal[ d[ 3] ]; if ((x + 4) >= 0 && (x + 4)<320) p[ 4] = pal[ d[ 4] ]; if ((x + 5) >= 0 && (x + 5)<320) p[ 5] = pal[ d[ 5] ]; if ((x + 6) >= 0 && (x + 6)<320) p[ 6] = pal[ d[ 6] ]; if ((x + 7) >= 0 && (x + 7)<320) p[ 7] = pal[ d[ 7] ]; if ((x + 8) >= 0 && (x + 8)<320) p[ 8] = pal[ d[ 8] ]; if ((x + 9) >= 0 && (x + 9)<320) p[ 9] = pal[ d[ 9] ]; if ((x + 10) >= 0 && (x + 10)<320) p[10] = pal[ d[10] ]; if ((x + 11) >= 0 && (x + 11)<320) p[11] = pal[ d[11] ]; if ((x + 12) >= 0 && (x + 12)<320) p[12] = pal[ d[12] ]; if ((x + 13) >= 0 && (x + 13)<320) p[13] = pal[ d[13] ]; if ((x + 14) >= 0 && (x + 14)<320) p[14] = pal[ d[14] ]; if ((x + 15) >= 0 && (x + 15)<320) p[15] = pal[ d[15] ]; #endif } d += 16; p += 320; } } } } static void drawgfx(unsigned int code, int sx,int sy) { unsigned short * p = (unsigned short *) pBurnDraw; unsigned char * d = RomSpr + code * 256; unsigned short * pal = RamCurPal + 0x100; if (sx >= (320+16)) sx -= 512; if (sy >= (224+16)) sy -= 256; p += sy * 320 + sx; #if defined (_XBOX) unsigned short d0,d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15; #endif if (sx >= 0 && sx <= (320-16) && sy > 0 && sy <= (224-16) ) { for (int k=0;k<16;k++) { #if defined (_XBOX) d0 = (pal[ d[ 0] ]); d1 = (pal[ d[ 1] ]); d2 = (pal[ d[ 2] ]); d3 = (pal[ d[ 3] ]); d4 = (pal[ d[ 4] ]); d5 = (pal[ d[ 5] ]); d6 = (pal[ d[ 6] ]); d7 = (pal[ d[ 7] ]); d8 = (pal[ d[ 8] ]); d9 = (pal[ d[ 9] ]); d10 = (pal[ d[ 10] ]); d11 = (pal[ d[ 11] ]); d12 = (pal[ d[ 12] ]); d13 = (pal[ d[ 13] ]); d14 = (pal[ d[ 14] ]); d15 = (pal[ d[ 15] ]); if( d[ 0] ) p[ 0] = d0; if( d[ 1] ) p[ 1] = d1; if( d[ 2] ) p[ 2] = d2; if( d[ 3] ) p[ 3] = d3; if( d[ 4] ) p[ 4] = d4; if( d[ 5] ) p[ 5] = d5; if( d[ 6] ) p[ 6] = d6; if( d[ 7] ) p[ 7] = d7; if( d[ 8] ) p[ 8] = d8; if( d[ 9] ) p[ 9] = d9; if( d[10] ) p[10] = d10; if( d[11] ) p[11] = d11; if( d[12] ) p[12] = d12; if( d[13] ) p[13] = d13; if( d[14] ) p[14] = d14; if( d[15] ) p[15] = d15; #else if( d[ 0] ) p[ 0] = pal[ d[ 0] ]; if( d[ 1] ) p[ 1] = pal[ d[ 1] ]; if( d[ 2] ) p[ 2] = pal[ d[ 2] ]; if( d[ 3] ) p[ 3] = pal[ d[ 3] ]; if( d[ 4] ) p[ 4] = pal[ d[ 4] ]; if( d[ 5] ) p[ 5] = pal[ d[ 5] ]; if( d[ 6] ) p[ 6] = pal[ d[ 6] ]; if( d[ 7] ) p[ 7] = pal[ d[ 7] ]; if( d[ 8] ) p[ 8] = pal[ d[ 8] ]; if( d[ 9] ) p[ 9] = pal[ d[ 9] ]; if( d[10] ) p[10] = pal[ d[10] ]; if( d[11] ) p[11] = pal[ d[11] ]; if( d[12] ) p[12] = pal[ d[12] ]; if( d[13] ) p[13] = pal[ d[13] ]; if( d[14] ) p[14] = pal[ d[14] ]; if( d[15] ) p[15] = pal[ d[15] ]; #endif d += 16; p += 320; } } else if (sx >= -16 && sx < 320 && sy >= -16 && sy < 224 ) { for (int k=0;k<16;k++) { if ( (sy+k)>=0 && (sy+k)<224 ) { #if defined (_XBOX) // we dont swap here since the stored value in dX is written back to p[X] d0 = (pal[ d[ 0] ]); d1 = (pal[ d[ 1] ]); d2 = (pal[ d[ 2] ]); d3 = (pal[ d[ 3] ]); d4 = (pal[ d[ 4] ]); d5 = (pal[ d[ 5] ]); d6 = (pal[ d[ 6] ]); d7 = (pal[ d[ 7] ]); d8 = (pal[ d[ 8] ]); d9 = (pal[ d[ 9] ]); d10 = (pal[ d[ 10] ]); d11 = (pal[ d[ 11] ]); d12 = (pal[ d[ 12] ]); d13 = (pal[ d[ 13] ]); d14 = (pal[ d[ 14] ]); d15 = (pal[ d[ 15] ]); if( d[ 0] && (sx+ 0)>=0 && (sx+ 0)<320 ) p[ 0] = d0; if( d[ 1] && (sx+ 1)>=0 && (sx+ 1)<320 ) p[ 1] = d1; if( d[ 2] && (sx+ 2)>=0 && (sx+ 2)<320 ) p[ 2] = d2; if( d[ 3] && (sx+ 3)>=0 && (sx+ 3)<320 ) p[ 3] = d3; if( d[ 4] && (sx+ 4)>=0 && (sx+ 4)<320 ) p[ 4] = d4; if( d[ 5] && (sx+ 5)>=0 && (sx+ 5)<320 ) p[ 5] = d5; if( d[ 6] && (sx+ 6)>=0 && (sx+ 6)<320 ) p[ 6] = d6; if( d[ 7] && (sx+ 7)>=0 && (sx+ 7)<320 ) p[ 7] = d7; if( d[ 8] && (sx+ 8)>=0 && (sx+ 8)<320 ) p[ 8] = d8; if( d[ 9] && (sx+ 9)>=0 && (sx+ 9)<320 ) p[ 9] = d9; if( d[10] && (sx+10)>=0 && (sx+10)<320 ) p[10] = d10; if( d[11] && (sx+11)>=0 && (sx+11)<320 ) p[11] = d11; if( d[12] && (sx+12)>=0 && (sx+12)<320 ) p[12] = d12; if( d[13] && (sx+13)>=0 && (sx+13)<320 ) p[13] = d13; if( d[14] && (sx+14)>=0 && (sx+14)<320 ) p[14] = d14; if( d[15] && (sx+15)>=0 && (sx+15)<320 ) p[15] = d15; #else if( d[ 0] && (sx+ 0)>=0 && (sx+ 0)<320 ) p[ 0] = pal[ d[ 0] ]; if( d[ 1] && (sx+ 1)>=0 && (sx+ 1)<320 ) p[ 1] = pal[ d[ 1] ]; if( d[ 2] && (sx+ 2)>=0 && (sx+ 2)<320 ) p[ 2] = pal[ d[ 2] ]; if( d[ 3] && (sx+ 3)>=0 && (sx+ 3)<320 ) p[ 3] = pal[ d[ 3] ]; if( d[ 4] && (sx+ 4)>=0 && (sx+ 4)<320 ) p[ 4] = pal[ d[ 4] ]; if( d[ 5] && (sx+ 5)>=0 && (sx+ 5)<320 ) p[ 5] = pal[ d[ 5] ]; if( d[ 6] && (sx+ 6)>=0 && (sx+ 6)<320 ) p[ 6] = pal[ d[ 6] ]; if( d[ 7] && (sx+ 7)>=0 && (sx+ 7)<320 ) p[ 7] = pal[ d[ 7] ]; if( d[ 8] && (sx+ 8)>=0 && (sx+ 8)<320 ) p[ 8] = pal[ d[ 8] ]; if( d[ 9] && (sx+ 9)>=0 && (sx+ 9)<320 ) p[ 9] = pal[ d[ 9] ]; if( d[10] && (sx+10)>=0 && (sx+10)<320 ) p[10] = pal[ d[10] ]; if( d[11] && (sx+11)>=0 && (sx+11)<320 ) p[11] = pal[ d[11] ]; if( d[12] && (sx+12)>=0 && (sx+12)<320 ) p[12] = pal[ d[12] ]; if( d[13] && (sx+13)>=0 && (sx+13)<320 ) p[13] = pal[ d[13] ]; if( d[14] && (sx+14)>=0 && (sx+14)<320 ) p[14] = pal[ d[14] ]; if( d[15] && (sx+15)>=0 && (sx+15)<320 ) p[15] = pal[ d[15] ]; #endif } d += 16; p += 320; } } } static void DrawSprites() { unsigned short *source = RamSpr0; unsigned short *source2 =RamSpr1; unsigned short *finish = source + 0x1000/2; while( source < finish ) { int xpos, ypos; int tileno; xpos = (swapWord(source[0]) & 0xff00) >> 8; ypos = (swapWord(source[0]) & 0x00ff) >> 0; tileno = (swapWord(source2[0]) & 0x7ffe) >> 1; xpos |= (swapWord(source2[0]) & 0x0001) << 8; if (tileno) drawgfx(tileno, xpos, ypos); source++;source2++; } } static void DrvDraw() { DrawBackground(); DrawSprites(); } static int DrvFrame() { if (DrvReset) DrvDoReset(); if (bRecalcPalette) { for (int i=0;i<(0x1000/2); i++) RamCurPal[i] = CalcCol( RamPal[i] ); bRecalcPalette = 0; } DrvInput[0] = 0x00; // Joy1 DrvInput[1] = 0x00; // Joy2 DrvInput[2] = 0x00; // Buttons for (int i = 0; i < 8; i++) { DrvInput[0] |= (DrvJoy1[i] & 1) << i; DrvInput[1] |= (DrvJoy2[i] & 1) << i; DrvInput[2] |= (DrvButton[i] & 1) << i; } SekNewFrame(); SekOpen(0); #if 0 int nCyclesDone = 0; int nCyclesNext = 0; for(int i=0; i<10; i++) { nCyclesNext += (16000000 / 60 / 10); nCyclesDone += SekRun( nCyclesNext - nCyclesDone ); } #else SekRun(16000000 / 60); #endif SekSetIRQLine(4, SEK_IRQSTATUS_AUTO); SekClose(); if (pBurnDraw) DrvDraw(); if (pBurnSoundOut) { memset(pBurnSoundOut, 0, nBurnSoundLen * 4); MSM6295Render(0, pBurnSoundOut, nBurnSoundLen); MSM6295Render(1, pBurnSoundOut, nBurnSoundLen); } return 0; } static int DrvScan(int nAction,int *pnMin) { if (pnMin) *pnMin = 0x029671; struct BurnArea ba; if (nAction & ACB_MEMORY_RAM) { // Scan all memory, devices & variables memset(&ba, 0, sizeof(ba)); ba.Data = RamStart; ba.nLen = RamEnd-RamStart; ba.szName = "All Ram"; BurnAcb(&ba); if (nAction & ACB_WRITE) bRecalcPalette = 1; } if (nAction & ACB_DRIVER_DATA) { SekScan(nAction); // Scan 68000 state SCAN_VAR(DrvInput); SCAN_VAR(scrollx); SCAN_VAR(scrolly); SCAN_VAR(m6295bank); MSM6295Scan(0, nAction); MSM6295Scan(1, nAction); if (nAction & ACB_WRITE) { } } return 0; } struct BurnDriver BurnDrv1945kiii = { "1945kiii", NULL, NULL, "2000", "1945k III\0", NULL, "Oriental", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_ORIENTATION_VERTICAL | BDF_16BIT_ONLY, 2, HARDWARE_MISC_MISC, NULL, _1945kiiiRomInfo, _1945kiiiRomName, _1945kiiiInputInfo, _1945kiiiDIPInfo, DrvInit, DrvExit, DrvFrame, NULL, DrvScan, &bRecalcPalette, 224, 320, 3, 4 };
[ [ [ 1, 797 ] ] ]
da4a42b4e1c59fa066238f779f6be4e750f73e92
5eb582292aeef7c56b13bc05accf71592d15931f
/include/raknet/RSACrypt.h
476f7b764b64ba968e87cf0f16683e406b0e0ab2
[]
no_license
goebish/WiiBlob
9316a56f2a60a506ecbd856ab7c521f906b961a1
bef78fc2fdbe2d52749ed3bc965632dd699c2fea
refs/heads/master
2020-05-26T12:19:40.164479
2010-09-05T18:09:07
2010-09-05T18:09:07
188,229,195
0
0
null
null
null
null
UTF-8
C++
false
false
23,854
h
/* -*- mode: c++; c-file-style: raknet; tab-always-indent: nil; -*- */ /* Performant RSA en/decryption with 256-bit to 16384-bit modulus catid([email protected]) 7/30/2004 Fixed VS6 compat 7/26/2004 Now internally generates private keys simpleModExp() is faster for encryption than MontyModExp CRT-MontyModExp is faster for decryption than CRT-SimpleModExp 7/25/2004 Implemented Montgomery modular exponentation Implemented CRT modular exponentation optimization 7/21/2004 Did some pre-lim coding Best performance on my 1.8 GHz P4 (mobile): 1024-bit generate key : 30 seconds 1024-bit set private key : 100 ms (pre-compute this step) 1024-bit encryption : 200 usec 1024-bit decryption : 400 ms TODO There's a bug in MonModExp() that restricts us to k-1 bits Tabs: 4 spaces Dist: public */ #ifndef RSACRYPT_H #define RSACRYPT_H #define RSASUPPORTGENPRIME // Can't go under 256 or you'll need to disable the USEASSEMBLY macro in bigtypes.h // That's because the assembly assumes at least 128-bit data to work on // #define RSA_BIT_SIZE big::u512 #define RSA_BIT_SIZE big::u256 #include "BigTypes.h" #include "Rand.h" //Giblet - added missing include for randomMT() namespace big { using namespace cat; // r = x^y Mod n (fast for small y) BIGONETYPE void simpleModExp( T &x0, T &y0, T &n0, T &r0 ) { BIGDOUBLESIZE( T, x ); BIGDOUBLESIZE( T, y ); BIGDOUBLESIZE( T, n ); BIGDOUBLESIZE( T, r ); usetlow( x, x0 ); usetlow( y, y0 ); usetlow( n, n0 ); usetw( r, 1 ); umodulo( x, n, x ); u32 squares = 0; for ( u32 ii = 0; ii < BIGWORDCOUNT( T ); ++ii ) { word y_i = y[ ii ]; u32 ctr = WORDBITS; while ( y_i ) { if ( y_i & 1 ) { if ( squares ) do { usquare( x ); umodulo( x, n, x ); } while ( --squares ); umultiply( r, x, r ); umodulo( r, n, r ); } y_i >>= 1; ++squares; --ctr; } squares += ctr; } takelow( r0, r ); } // computes Rn = 2^k (mod n), n < 2^k BIGONETYPE void rModn( T &n, T &Rn ) { BIGDOUBLESIZE( T, dR ); BIGDOUBLESIZE( T, dn ); BIGDOUBLESIZE( T, dRn ); T one; // dR = 2^k usetw( one, 1 ); sethigh( dR, one ); // Rn = 2^k (mod n) usetlow( dn, n ); umodulo( dR, dn, dRn ); takelow( Rn, dRn ); } // computes c = GCD(a, b) BIGONETYPE void GCD( T &a0, T &b0, T &c ) { T a; umodulo( a0, b0, c ); if ( isZero( c ) ) { set ( c, b0 ) ; return ; } umodulo( b0, c, a ); if ( isZero( a ) ) return ; #pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant while ( true ) { umodulo( c, a, c ); if ( isZero( c ) ) { set ( c, a ) ; return ; } umodulo( a, c, a ); if ( isZero( a ) ) return ; } } // directly computes x = c - a * b (mod n) > 0, c < n BIGONETYPE void SubMulMod( T &a, T &b, T &c, T &n, T &x ) { BIGDOUBLESIZE( T, da ); BIGDOUBLESIZE( T, dn ); T y; // y = a b (mod n) usetlow( da, a ); umultiply( da, b ); usetlow( dn, n ); umodulo( da, dn, da ); takelow( y, da ); // x = (c - y) (mod n) > 0 set ( x, c ) ; if ( ugreater( c, y ) ) { subtract( x, y ); } else { subtract( x, y ); add ( x, n ) ; } } /* directly compute a' s.t. a' a - b' b = 1 b = b0 = n0 rp = a' a = 2^k a > b > 0 GCD(a, b) = 1 (b odd) Trying to keep everything positive */ BIGONETYPE void computeRinverse( T &n0, T &rp ) { T x0, x1, x2, a, b, q; //x[0] = 1 usetw( x0, 1 ); // a = 2^k (mod b0) rModn( n0, a ); // {q, b} = b0 / a udivide( n0, a, q, b ); // if b = 0, return x[0] if ( isZero( b ) ) { set ( rp, x0 ) ; return ; } // x[1] = -q (mod b0) = b0 - q, q <= b0 set ( x1, n0 ) ; subtract( x1, q ); // {q, a} = a / b udivide( a, b, q, a ); // if a = 0, return x[1] if ( isZero( a ) ) { set ( rp, x1 ) ; return ; } #pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant while ( true ) { // x[2] = x[0] - x[1] * q (mod b0) SubMulMod( q, x1, x0, n0, x2 ); // {q, b} = b / a udivide( b, a, q, b ); // if b = 0, return x[2] if ( isZero( b ) ) { set ( rp, x2 ) ; return ; } // x[0] = x[1] - x[2] * q (mod b0) SubMulMod( q, x2, x1, n0, x0 ); // {q, a} = a / b udivide( a, b, q, a ); // if a = 0, return x[0] if ( isZero( a ) ) { set ( rp, x0 ) ; return ; } // x[1] = x[2] - x[0] * q (mod b0) SubMulMod( q, x0, x2, n0, x1 ); // {q, b} = b / a udivide( b, a, q, b ); // if b = 0, return x[1] if ( isZero( b ) ) { set ( rp, x1 ) ; return ; } // x[2] = x[0] - x[1] * q (mod b0) SubMulMod( q, x1, x0, n0, x2 ); // {q, a} = a / b udivide( a, b, q, a ); // if a = 0, return x[2] if ( isZero( a ) ) { set ( rp, x2 ) ; return ; } // x[0] = x[1] - x[2] * q (mod b0) SubMulMod( q, x2, x1, n0, x0 ); // {q, b} = b / a udivide( b, a, q, b ); // if b = 0, return x[0] if ( isZero( b ) ) { set ( rp, x0 ) ; return ; } // x[1] = x[2] - x[0] * q (mod b0) SubMulMod( q, x0, x2, n0, x1 ); // {q, a} = a / b udivide( a, b, q, a ); // if a = 0, return x[1] if ( isZero( a ) ) { set ( rp, x1 ) ; return ; } } } /* BIGONETYPE void computeRinverse2(T &_n0, T &_rp) { //T x0, x1, x2, a, b, q; BIGDOUBLESIZE(T, x0); BIGDOUBLESIZE(T, x1); BIGDOUBLESIZE(T, x2); BIGDOUBLESIZE(T, a); BIGDOUBLESIZE(T, b); BIGDOUBLESIZE(T, q); BIGDOUBLESIZE(T, n0); BIGDOUBLESIZE(T, rp); usetlow(n0, _n0); usetlow(rp, _rp); std::string old; //x[0] = 1 usetw(x0, 1); T _a; // a = 2^k (mod b0) rModn(_n0, _a); RECORD("TEST") << "a=" << toString(a, false) << " = 2^k (mod " << toString(n0, false) << ")"; usetlow(a, _a); // {q, b} = b0 / a udivide(n0, a, q, b); RECORD("TEST") << "{q=" << toString(q, false) << ", b=" << toString(b, false) << "} = n0=" << toString(n0, false) << " / a=" << toString(a, false); // if b = 0, return x[0] if (isZero(b)) { RECORD("TEST") << "b == 0, Returning x[0]"; set(rp, x0); takelow(_rp, rp); return; } // x[1] = -q (mod b0) negate(q); smodulo(q, n0, x1); if (BIGHIGHBIT(x1)) add(x1, n0); // q > 0 RECORD("TEST") << "x1=" << toString(x1, false) << " = q=" << toString(q, false) << " (mod n0=" << toString(n0, false) << ")"; // {q, a} = a / b old = toString(a, false); udivide(a, b, q, a); RECORD("TEST") << "{q=" << toString(q, false) << ", a=" << toString(a, false) << "} = a=" << old << " / b=" << toString(b); // if a = 0, return x[1] if (isZero(a)) { RECORD("TEST") << "a == 0, Returning x[1]"; set(rp, x1); takelow(_rp, rp); return; } RECORD("TEST") << "Entering loop..."; while (true) { // x[2] = x[0] - x[1] * q (mod b0) SubMulMod(q, x1, x0, n0, x2); RECORD("TEST") << "x[0] = " << toString(x0, false); RECORD("TEST") << "x[1] = " << toString(x1, false); RECORD("TEST") << "x[2] = " << toString(x2, false); // {q, b} = b / a old = toString(b); udivide(b, a, q, b); RECORD("TEST") << "{q=" << toString(q, false) << ", b=" << toString(b) << "} = b=" << old << " / a=" << toString(a, false); // if b = 0, return x[2] if (isZero(b)) { RECORD("TEST") << "b == 0, Returning x[2]"; set(rp, x2); takelow(_rp, rp); return; } // x[0] = x[1] - x[2] * q (mod b0) SubMulMod(q, x2, x1, n0, x0); RECORD("TEST") << "x[0] = " << toString(x0, false); RECORD("TEST") << "x[1] = " << toString(x1, false); RECORD("TEST") << "x[2] = " << toString(x2, false); // {q, a} = a / b old = toString(a, false); udivide(a, b, q, a); RECORD("TEST") << "{q=" << toString(q, false) << ", a=" << toString(a, false) << "} = a=" << old << " / b=" << toString(b); // if a = 0, return x[0] if (isZero(a)) { RECORD("TEST") << "a == 0, Returning x[0]"; set(rp, x0); takelow(_rp, rp); return; } // x[1] = x[2] - x[0] * q (mod b0) SubMulMod(q, x0, x2, n0, x1); RECORD("TEST") << "x[0] = " << toString(x0, false); RECORD("TEST") << "x[1] = " << toString(x1, false); RECORD("TEST") << "x[2] = " << toString(x2, false); // {q, b} = b / a old = toString(b); udivide(b, a, q, b); RECORD("TEST") << "{q=" << toString(q, false) << ", b=" << toString(b) << "} = b=" << old << " / a=" << toString(a, false); // if b = 0, return x[1] if (isZero(b)) { RECORD("TEST") << "b == 0, Returning x[1]"; set(rp, x1); takelow(_rp, rp); return; } // x[2] = x[0] - x[1] * q (mod b0) SubMulMod(q, x1, x0, n0, x2); RECORD("TEST") << "x[0] = " << toString(x0, false); RECORD("TEST") << "x[1] = " << toString(x1, false); RECORD("TEST") << "x[2] = " << toString(x2, false); // {q, a} = a / b old = toString(a, false); udivide(a, b, q, a); RECORD("TEST") << "{q=" << toString(q, false) << ", a=" << toString(a, false) << "} = a=" << old << " / b=" << toString(b); // if a = 0, return x[2] if (isZero(a)) { RECORD("TEST") << "a == 0, Returning x[2]"; set(rp, x2); takelow(_rp, rp); return; } // x[0] = x[1] - x[2] * q (mod b0) SubMulMod(q, x2, x1, n0, x0); RECORD("TEST") << "x[0] = " << toString(x0, false); RECORD("TEST") << "x[1] = " << toString(x1, false); RECORD("TEST") << "x[2] = " << toString(x2, false); // {q, b} = b / a old = toString(b); udivide(b, a, q, b); RECORD("TEST") << "{q=" << toString(q, false) << ", b=" << toString(b) << "} = b=" << old << " / a=" << toString(a, false); // if b = 0, return x[0] if (isZero(b)) { RECORD("TEST") << "b == 0, Returning x[0]"; set(rp, x0); takelow(_rp, rp); return; } // x[1] = x[2] - x[0] * q (mod b0) SubMulMod(q, x0, x2, n0, x1); RECORD("TEST") << "x[0] = " << toString(x0, false); RECORD("TEST") << "x[1] = " << toString(x1, false); RECORD("TEST") << "x[2] = " << toString(x2, false); // {q, a} = a / b old = toString(a, false); udivide(a, b, q, a); RECORD("TEST") << "{q=" << toString(q, false) << ", a=" << toString(a, false) << "} = a=" << old << " / b=" << toString(b); // if a = 0, return x[1] if (isZero(a)) { RECORD("TEST") << "a == 0, Returning x[1]"; set(rp, x1); takelow(_rp, rp); return; } } } */ // directly compute a^-1 s.t. a^-1 a (mod b) = 1, a < b, GCD(a, b) BIGONETYPE void computeModularInverse( T &a0, T &b0, T &ap ) { T x0, x1, x2; T a, b, q; // x[2] = 1 usetw( x2, 1 ); // {q, b} = b0 / a0 udivide( b0, a0, q, b ); // x[0] = -q (mod b0) = b0 - q, q <= b0 set ( x0, b0 ) ; subtract( x0, q ); set ( a, a0 ) ; #pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant while ( true ) { // {q, a} = a / b udivide( a, b, q, a ); // if a = 0, return x[0] if ( isZero( a ) ) { set ( ap, x0 ) ; return ; } // x[1] = x[2] - x[0] * q (mod b0) SubMulMod( x0, q, x2, b0, x1 ); // {q, b} = b / a udivide( b, a, q, b ); // if b = 0, return x[1] if ( isZero( b ) ) { set ( ap, x1 ) ; return ; } // x[2] = x[0] - x[1] * q (mod b0) SubMulMod( x1, q, x0, b0, x2 ); // {q, a} = a / b udivide( a, b, q, a ); // if a = 0, return x[2] if ( isZero( a ) ) { set ( ap, x2 ) ; return ; } // x[0] = x[1] - x[2] * q (mod b0) SubMulMod( x2, q, x1, b0, x0 ); // {q, b} = b / a udivide( b, a, q, b ); // if b = 0, return x[0] if ( isZero( b ) ) { set ( ap, x0 ) ; return ; } // x[1] = x[2] - x[0] * q (mod b0) SubMulMod( x0, q, x2, b0, x1 ); // {q, a} = a / b udivide( a, b, q, a ); // if a = 0, return x[1] if ( isZero( a ) ) { set ( ap, x1 ) ; return ; } // x[2] = x[0] - x[1] * q (mod b0) SubMulMod( x1, q, x0, b0, x2 ); // {q, b} = b / a udivide( b, a, q, b ); // if b = 0, return x[2] if ( isZero( b ) ) { set ( ap, x2 ) ; return ; } // x[0] = x[1] - x[2] * q (mod b0) SubMulMod( x2, q, x1, b0, x0 ); } } // indirectly computes n' s.t. 1 = r' r - n' n = GCD(r, n) BIGONETYPE void computeNRinverse( T &n0, T &np ) { BIGDOUBLESIZE( T, r ); BIGDOUBLESIZE( T, n ); // r' = (1 + n' n) / r computeRinverse( n0, np ); // n' = (r' r - 1) / n sethigh( r, np ); // special case of r = 2^k decrement( r ); usetlow( n, n0 ); udivide( r, n, n, r ); takelow( np, n ); } /* // indirectly computes n' s.t. 1 = r' r - n' n = GCD(r, n) BIGONETYPE void computeNRinverse2(T &n0, T &np) { BIGDOUBLESIZE(T, r); BIGDOUBLESIZE(T, n); // r' = (1 + n' n) / r computeRinverse2(n0, np); // n' = (r' r - 1) / n sethigh(r, np); // special case of r = 2^k decrement(r); usetlow(n, n0); udivide(r, n, n, r); takelow(np, n); } */ // Montgomery product u = a * b (mod n) BIGONETYPE void MonPro( T &ap, T &bp, T &n, T &np, T &u_out ) { BIGDOUBLESIZE( T, t ); BIGDOUBLESIZE( T, u ); T m; // t = a' b' umultiply( ap, bp, t ); // m = (low half of t)*np (mod r) takelow( m, t ); umultiply( m, np ); // u = (t + m*n), u_out = u / r = high half of u umultiply( m, n, u ); add ( u, t ) ; takehigh( u_out, u ); // if u >= n, return u - n, else u if ( ugreaterOrEqual( u_out, n ) ) subtract( u_out, n ); } // indirectly calculates x = M^e (mod n) BIGONETYPE void MonModExp( T &x, T &M, T &e, T &n, T &np, T &xp0 ) { // x' = xp0 set ( x, xp0 ) ; // find M' = M r (mod n) BIGDOUBLESIZE( T, dM ); BIGDOUBLESIZE( T, dn ); T Mp; sethigh( dM, M ); // dM = M r usetlow( dn, n ); umodulo( dM, dn, dM ); // dM = dM (mod n) takelow( Mp, dM ); // M' = M r (mod n) /* i may be wrong, but it seems to me that the squaring results in a constant until we hit the first set bit this could save a lot of time, but it needs to be proven */ s32 ii, bc; word e_i; // for i = k - 1 down to 0 do for ( ii = BIGWORDCOUNT( T ) - 1; ii >= 0; --ii ) { e_i = e[ ii ]; bc = WORDBITS; while ( bc-- ) { // if e_i = 1, x = MonPro(M', x') if ( e_i & WORDHIGHBIT ) goto start_squaring; e_i <<= 1; } } for ( ; ii >= 0; --ii ) { e_i = e[ ii ]; bc = WORDBITS; while ( bc-- ) { // x' = MonPro(x', x') MonPro( x, x, n, np, x ); // if e_i = 1, x = MonPro(M', x') if ( e_i & WORDHIGHBIT ) { start_squaring: MonPro( Mp, x, n, np, x ); } e_i <<= 1; } } // x = MonPro(x', 1) T one; usetw( one, 1 ); MonPro( x, one, n, np, x ); } // indirectly calculates x = C ^ d (mod n) using the Chinese Remainder Thm #pragma warning( disable : 4100 ) // warning C4100: <variable name> : unreferenced formal parameter BIGTWOTYPES void CRTModExp( Bigger &x, Bigger &C, Bigger &d, T &p, T &q, T &pInverse, T &pnp, T &pxp, T &qnp, T &qxp ) { // d1 = d mod (p - 1) Bigger dd1; T d1; usetlow( dd1, p ); decrement( dd1 ); umodulo( d, dd1, dd1 ); takelow( d1, dd1 ); // M1 = C1^d1 (mod p) Bigger dp, dC1; T M1, C1; usetlow( dp, p ); umodulo( C, dp, dC1 ); takelow( C1, dC1 ); simpleModExp( C1, d1, p, M1 ); //MonModExp(M1, C1, d1, p, pnp, pxp); // d2 = d mod (q - 1) Bigger dd2; T d2; usetlow( dd2, q ); decrement( dd2 ); umodulo( d, dd2, dd2 ); takelow( d2, dd2 ); // M2 = C2^d2 (mod q) Bigger dq, dC2; T M2, C2; usetlow( dq, q ); umodulo( C, dq, dC2 ); takelow( C2, dC2 ); simpleModExp( C2, d2, q, M2 ); //MonModExp(M2, C2, d2, q, qnp, qxp); // x = M1 + p * ((M2 - M1)(p^-1 mod q) mod q) if ( ugreater( M2, M1 ) ) { subtract( M2, M1 ); } else { subtract( M2, M1 ); add ( M2, q ) ; } // x = M1 + p * (( M2 )(p^-1 mod q) mod q) umultiply( M2, pInverse, x ); // x = M1 + p * (( x ) mod q) umodulo( x, dq, x ); // x = M1 + p * ( x ) umultiply( x, dp ); // x = M1 + ( x ) Bigger dM1; usetlow( dM1, M1 ); // x = ( dM1 ) + ( x ) add ( x, dM1 ) ; } // generates a suitable public exponent s.t. 4 < e << phi, GCD(e, phi) = 1 BIGONETYPE void computePublicExponent( T &phi, T &e ) { T r, one, two; usetw( one, 1 ); usetw( two, 2 ); usetw( e, 65537 - 2 ); if ( ugreater( e, phi ) ) usetw( e, 5 - 2 ); do { add ( e, two ) ; GCD( phi, e, r ); } while ( !equal( r, one ) ); } // directly computes private exponent BIGONETYPE void computePrivateExponent( T &e, T &phi, T &d ) { // d = e^-1 (mod phi), 1 < e << phi computeModularInverse( e, phi, d ); } #ifdef RSASUPPORTGENPRIME static const u16 PRIME_TABLE[ 256 ] = { 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621 }; /* modified Rabin-Miller primality test (added small primes) When picking a value for insurance, note that the probability of failure of the test to detect a composite number is at most 4^(-insurance), so: insurance max. probability of failure 3 1.56% 4 0.39% 5 0.098% <-- default 6 0.024% ... */ BIGONETYPE bool RabinMillerPrimalityTest( T &n, u32 insurance ) { // check divisibility by small primes <= 1621 (speeds up computation) T temp; for ( u32 ii = 0; ii < 256; ++ii ) { usetw( temp, PRIME_TABLE[ ii++ ] ); umodulo( n, temp, temp ); if ( isZero( temp ) ) return false; } // n1 = n - 1 T n1; set ( n1, n ) ; decrement( n1 ); // write r 2^s = n - 1, r is odd T r; u32 s = 0; set ( r, n1 ) ; while ( !( r[ 0 ] & 1 ) ) { ushiftRight1( r ); ++s; } // one = 1 T one; usetw( one, 1 ); // cache n -> dn BIGDOUBLESIZE( T, dy ); BIGDOUBLESIZE( T, dn ); usetlow( dn, n ); while ( insurance-- ) { // choose random integer a s.t. 1 < a < n - 1 T a; int index; for ( index = 0; index < sizeof( a ) / sizeof( a[ 0 ] ); index++ ) a[ index ] = randomMT(); umodulo( a, n1, a ); // compute y = a ^ r (mod n) T y; simpleModExp( a, r, n, y ); if ( !equal( y, one ) && !equal( y, n1 ) ) { u32 j = s; while ( ( j-- > 1 ) && !equal( y, n1 ) ) { umultiply( y, y, dy ); umodulo( dy, dn, dy ); takelow( y, dy ); if ( equal( y, one ) ) return false; } if ( !equal( y, n1 ) ) return false; } } return true; } // generates a strong pseudo-prime BIGONETYPE void generateStrongPseudoPrime( T &n ) { do { int index; for ( index = 0; index < sizeof( n ) / sizeof( n[ 0 ] ); index++ ) n[ index ] = randomMT(); n[ BIGWORDCOUNT( T ) - 1 ] |= WORDHIGHBIT; //n[BIGWORDCOUNT(T) - 1] &= ~WORDHIGHBIT; n[BIGWORDCOUNT(T) - 1] |= WORDHIGHBIT >> 1; n[ 0 ] |= 1; } while ( !RabinMillerPrimalityTest( n, 5 ) ); } #endif // RSASUPPORTGENPRIME //////// RSACrypt class //////// BIGONETYPE class RSACrypt { // public key T e, n; T np, xp; // private key bool factorsAvailable; T d, phi; BIGHALFSIZE( T, p ); BIGHALFSIZE( T, pnp ); BIGHALFSIZE( T, pxp ); BIGHALFSIZE( T, q ); BIGHALFSIZE( T, qnp ); BIGHALFSIZE( T, qxp ); BIGHALFSIZE( T, pInverse ); public: RSACrypt() { reset(); } ~RSACrypt() { reset(); } public: void reset() { zero( d ); zero( p ); zero( q ); zero( pInverse ); factorsAvailable = false; } #ifdef RSASUPPORTGENPRIME void generateKeys() { BIGHALFSIZE( T, p0 ); BIGHALFSIZE( T, q0 ); generateStrongPseudoPrime( p0 ); generateStrongPseudoPrime( q0 ); setPrivateKey( p0, q0 ); } #endif // RSASUPPORTGENPRIME BIGSMALLTYPE void setPrivateKey( Smaller &c_p, Smaller &c_q ) { factorsAvailable = true; // re-order factors s.t. q > p if ( ugreater( c_p, c_q ) ) { set ( q, c_p ) ; set ( p, c_q ) ; } else { set ( p, c_p ) ; set ( q, c_q ) ; } // phi = (p - 1)(q - 1) BIGHALFSIZE( T, p1 ); BIGHALFSIZE( T, q1 ); set ( p1, p ) ; decrement( p1 ); set ( q1, q ) ; decrement( q1 ); umultiply( p1, q1, phi ); // compute e computePublicExponent( phi, e ); // compute d computePrivateExponent( e, phi, d ); // compute p^-1 mod q computeModularInverse( p, q, pInverse ); // compute n = pq umultiply( p, q, n ); // find n' computeNRinverse( n, np ); // x' = 1*r (mod n) rModn( n, xp ); // find pn' computeNRinverse( p, pnp ); // computeNRinverse2(p, pnp); // px' = 1*r (mod p) rModn( p, pxp ); // find qn' computeNRinverse( q, qnp ); // qx' = 1*r (mod q) rModn( q, qxp ); } void setPublicKey( u32 c_e, T &c_n ) { reset(); // in case we knew a private key usetw( e, c_e ); set ( n, c_n ) ; // find n' computeNRinverse( n, np ); // x' = 1*r (mod n) rModn( n, xp ); } public: void getPublicKey( u32 &c_e, T &c_n ) { c_e = e[ 0 ]; set ( c_n, n ) ; } BIGSMALLTYPE void getPrivateKey( Smaller &c_p, Smaller &c_q ) { set ( c_p, p ) ; set ( c_q, q ) ; } public: void encrypt( T &M, T &x ) { if ( factorsAvailable ) CRTModExp( x, M, e, p, q, pInverse, pnp, pxp, qnp, qxp ); else simpleModExp( M, e, n, x ); } void decrypt( T &C, T &x ) { if ( factorsAvailable ) CRTModExp( x, C, d, p, q, pInverse, pnp, pxp, qnp, qxp ); } }; } #endif // RSACRYPT_H
[ [ [ 1, 1238 ] ] ]
a6b01e5f54f48f7ce86ec8ea175fe47c3c12f5b9
b6bad03a59ec436b60c30fc793bdcf687a21cf31
/som2416/wince5/sdmemmain.cpp
27145aab6657abaa896a001dee7fa031b314875e
[]
no_license
blackfa1con/openembed
9697f99b12df16b1c5135e962890e8a3935be877
3029d7d8c181449723bb16d0a73ee87f63860864
refs/heads/master
2021-01-10T14:14:39.694809
2010-12-16T03:20:27
2010-12-16T03:20:27
52,422,065
0
0
null
null
null
null
UTF-8
C++
false
false
39,880
cpp
// // Copyright (c) Microsoft Corporation. All rights reserved. // // // Use of this sample source code is subject to the terms of the Microsoft // license agreement under which you licensed this sample source code. If // you did not accept the terms of the license agreement, you are not // authorized to use this sample source code. For the terms of the license, // please see the license agreement between you and Microsoft or, if applicable, // see the LICENSE.RTF on your install media or the root of your tools installation. // THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES. // // Copyright (c) 2002 BSQUARE Corporation. All rights reserved. // DO NOT REMOVE --- BEGIN EXTERNALLY DEVELOPED SOURCE CODE ID 40973--- DO NOT REMOVE // Driver entry points for SD Memory Card client driver #include "SDMemory.h" #include <ceddk.h> // initialize debug zones SD_DEBUG_INSTANTIATE_ZONES( TEXT("SDMemory"), // module name ZONE_ENABLE_INIT | ZONE_ENABLE_ERROR | ZONE_ENABLE_WARN, // initial settings TEXT("Disk I/O"), TEXT("Card I/O"), TEXT("Bus Requests"), TEXT("Power"), TEXT(""), TEXT(""), TEXT(""), TEXT(""), TEXT(""), TEXT(""), TEXT("")); DWORD SetDiskInfo( PSD_MEMCARD_INFO, PDISK_INFO ); DWORD GetDiskInfo( PSD_MEMCARD_INFO, PDISK_INFO ); DWORD GetStorageID( PSD_MEMCARD_INFO, PSTORAGE_IDENTIFICATION, DWORD, DWORD* ); BOOL GetDeviceInfo(PSD_MEMCARD_INFO pMemCard, PSTORAGEDEVICEINFO pStorageInfo); #define DEFAULT_MEMORY_TAGS 4 /////////////////////////////////////////////////////////////////////////////// // DllEntry - the main dll entry point // Input: hInstance - the instance that is attaching // Reason - the reason for attaching // pReserved - not much // Output: // Return: always returns TRUE // Notes: this is only used to initialize the zones /////////////////////////////////////////////////////////////////////////////// extern "C" BOOL WINAPI DllEntry(HINSTANCE hInstance, ULONG Reason, LPVOID pReserved) { BOOL fRet = TRUE; if ( Reason == DLL_PROCESS_ATTACH ) { if (!SDInitializeCardLib()) { fRet = FALSE; } } else if ( Reason == DLL_PROCESS_DETACH ) { SDDeinitializeCardLib(); } return fRet; } /////////////////////////////////////////////////////////////////////////////// // SMC_Close - the close entry point for the memory driver // Input: hOpenContext - the context returned from SMC_Open // Output: // Return: always returns TRUE // Notes: /////////////////////////////////////////////////////////////////////////////// extern "C" BOOL WINAPI SMC_Close(DWORD hOpenContext) { DEBUGMSG(SDCARD_ZONE_FUNC, (TEXT("SDMemory: +-SMC_Close\n"))); return TRUE; } /////////////////////////////////////////////////////////////////////////////// // CleanUpDevice - cleanup the device instance // Input: pDevice - device instance // Output: // Return: // Notes: /////////////////////////////////////////////////////////////////////////////// VOID CleanUpDevice(PSD_MEMCARD_INFO pDevice) { DeinitializePowerManagement(pDevice); // acquire removal lock AcquireRemovalLock(pDevice); if (NULL != pDevice->pRegPath) { // free the reg path SDFreeMemory(pDevice->pRegPath); } if (NULL != pDevice->hBufferList) { // delete the buffer memory list SDDeleteMemList(pDevice->hBufferList); } ReleaseRemovalLock(pDevice); DeleteCriticalSection(&pDevice->RemovalLock); DeleteCriticalSection(&pDevice->CriticalSection); // free the sterile I/O request if (NULL != pDevice->pSterileIoRequest) { LocalFree(pDevice->pSterileIoRequest); pDevice->pSterileIoRequest = NULL; } // free the device memory SDFreeMemory(pDevice); } /////////////////////////////////////////////////////////////////////////////// // SMC_Deinit - the deinit entry point for the memory driver // Input: hDeviceContext - the context returned from SMC_Init // Output: // Return: always returns TRUE // Notes: /////////////////////////////////////////////////////////////////////////////// extern "C" BOOL WINAPI SMC_Deinit(DWORD hDeviceContext) { PSD_MEMCARD_INFO pDevice; DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: +SMC_Deinit\n"))); pDevice = (PSD_MEMCARD_INFO)hDeviceContext; // now it is safe to clean up CleanUpDevice(pDevice); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: -SMC_Deinit\n"))); return TRUE; } /////////////////////////////////////////////////////////////////////////////// // SlotEventCallBack - slot event callback for fast-path events // Input: hDevice - device handle // pContext - device specific context that was registered // SlotEventType - slot event type // pData - Slot event data (can be NULL) // DataLength - length of slot event data (can be 0) // Output: // Return: // Notes: // // If this callback is registered the client driver can be notified of // slot events (such as device removal) using a fast path mechanism. This // is useful if a driver must be notified of device removal // before its XXX_Deinit is called. // // This callback can be called at a high thread priority and should only // set flags or set events. This callback must not perform any // bus requests or call any apis that can perform bus requests. /////////////////////////////////////////////////////////////////////////////// VOID SlotEventCallBack(SD_DEVICE_HANDLE hDevice, PVOID pContext, SD_SLOT_EVENT_TYPE SlotEventType, PVOID pData, DWORD DataLength) { PSD_MEMCARD_INFO pDevice; DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: +SlotEventCallBack - %d \n"),SlotEventType)); switch (SlotEventType) { case SDCardEjected : pDevice = (PSD_MEMCARD_INFO)pContext; // mark that the card is being ejected pDevice->CardEjected = TRUE; // acquire the removal lock to block this callback // in case an ioctl is in progress AcquireRemovalLock(pDevice); ReleaseRemovalLock(pDevice); break; } DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: -SlotEventCallBack \n"))); } /////////////////////////////////////////////////////////////////////////////// // SMC_Init - the init entry point for the memory driver // Input: dwContext - the context for this init // Output: // Return: non-zero context // Notes: /////////////////////////////////////////////////////////////////////////////// extern "C" DWORD WINAPI SMC_Init(DWORD dwContext) { SD_DEVICE_HANDLE hClientHandle; // client handle PSD_MEMCARD_INFO pDevice; // this instance of the device SDCARD_CLIENT_REGISTRATION_INFO ClientInfo; // client into ULONG BufferSize; // size of buffer HKEY hSubKey; // registry key SD_API_STATUS Status; // intermediate status DWORD data; // registry data DWORD dataLength; // registry data length DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: +SMC_Init\r\n"))); pDevice = (PSD_MEMCARD_INFO)SDAllocateMemoryWithTag( sizeof(SD_MEMCARD_INFO), SD_MEMORY_TAG); if (pDevice == NULL) { DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("SDMemory: Failed to allocate device info\r\n"))); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: -SMC_Init\r\n"))); return 0; } // initialize sterile I/O request to NULL pDevice->pSterileIoRequest = NULL; InitializeCriticalSection(&pDevice->CriticalSection); InitializeCriticalSection(&pDevice->RemovalLock); // get the device handle from the bus driver hClientHandle = SDGetDeviceHandle(dwContext, &pDevice->pRegPath); // store device handle in local context pDevice->hDevice = hClientHandle; if (NULL == hClientHandle) { DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("SDMemory: Failed to get client handle\r\n"))); CleanUpDevice(pDevice); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: -SMC_Init\r\n"))); return 0; } // allocate sterile I/O request pDevice->pSterileIoRequest = (PSG_REQ)LocalAlloc( LPTR, (sizeof(SG_REQ) + ((MAX_SG_BUF - 1) * sizeof(SG_BUF))) ); if (NULL == pDevice->pSterileIoRequest) { DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("SDMemory: Failed to allocate sterile I/O request\r\n"))); CleanUpDevice(pDevice); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: -SMC_Init\r\n"))); return 0; } // register our debug zones SDRegisterDebugZones(hClientHandle, pDevice->pRegPath); memset(&ClientInfo, 0, sizeof(ClientInfo)); // set client options and register as a client device _tcscpy(ClientInfo.ClientName, TEXT("Memory Card")); // set the callback ClientInfo.pSlotEventCallBack = SlotEventCallBack; Status = SDRegisterClient(hClientHandle, pDevice, &ClientInfo); if (!SD_API_SUCCESS(Status)) { DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("SDMemory: Failed to register client : 0x%08X\r\n"), Status)); CleanUpDevice(pDevice); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: -SMC_Init\r\n"))); return 0; } #ifdef _FOR_MOVI_NAND_ /*************************************************************************/ /****** Date : 07.05.28 ******/ /****** Developer : HS.JANG ******/ /****** Description : There is no way to distinguish between HSMMC ******/ /****** and moviNAND. So, We assume A HSMMC card is ******/ /****** a moviNAND. Default value is false; ******/ /*************************************************************************/ pDevice->IsHSMMC = FALSE; /*************************************************************************/ #endif // configure card and retrieve disk size/format information if( SDMemCardConfig( pDevice ) != ERROR_SUCCESS ) { CleanUpDevice(pDevice); DEBUGMSG( SDCARD_ZONE_ERROR, (TEXT("SDMemory: Error initializing MemCard structure and card\r\n"))); return 0; } // aet a default block transfer size pDevice->BlockTransferSize = DEFAULT_BLOCK_TRANSFER_SIZE; // read configuration from registry // open the reg path if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, pDevice->pRegPath, 0, KEY_ALL_ACCESS, &hSubKey) == ERROR_SUCCESS ) { // read "BlockTransferSize" dataLength = sizeof(pDevice->BlockTransferSize); RegQueryValueEx( hSubKey, BLOCK_TRANSFER_SIZE_KEY, NULL, NULL, (PUCHAR)&(pDevice->BlockTransferSize), &dataLength); if (pDevice->BlockTransferSize != DEFAULT_BLOCK_TRANSFER_SIZE) { DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: Initialize: Using block transfer size of %d blocks\r\n"), pDevice->BlockTransferSize)); } // read "SingleBlockWrites" // default to using mulitple block writes pDevice->SingleBlockWrites = FALSE; dataLength = sizeof(DWORD); data = 0; if (RegQueryValueEx( hSubKey, SINGLE_BLOCK_WRITES_KEY, NULL, NULL, (PUCHAR)&data, &dataLength) == ERROR_SUCCESS ) { // key is present pDevice->SingleBlockWrites = TRUE; DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: Initialize: Using single block write commands only\r\n"))); } // read "DisablePowerManagement" // on by default unless key is present pDevice->EnablePowerManagement = TRUE; dataLength = sizeof(DWORD); data = 0; if (RegQueryValueEx( hSubKey, DISABLE_POWER_MANAGEMENT, NULL, NULL, (PUCHAR)&data, &dataLength) == ERROR_SUCCESS ) { // key is present DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: Initialize: Disabled power management\r\n"))); pDevice->EnablePowerManagement = FALSE; } // read "IdleTimeout" pDevice->IdleTimeout = DEFAULT_IDLE_TIMEOUT; dataLength = sizeof(pDevice->IdleTimeout); if (RegQueryValueEx( hSubKey, IDLE_TIMEOUT, NULL, NULL, (PUCHAR)&pDevice->IdleTimeout, &dataLength) == ERROR_SUCCESS ) { // key is present DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: Initialize: Using idle timeout of %u milliseconds\r\n"), pDevice->IdleTimeout)); } // read "IdlePowerState" // default power state for idle // if the power state is greater than D2, we do idle checking pDevice->PowerStateForIdle = D2; dataLength = sizeof(DWORD); data = 0; if (RegQueryValueEx( hSubKey, IDLE_POWER_STATE, NULL, NULL, (PUCHAR)&data, &dataLength) == ERROR_SUCCESS ) { if (data <= (ULONG)D4) { pDevice->PowerStateForIdle = (CEDEVICE_POWER_STATE)data; } } DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: Idle Timeout: %d Idle Power State: %d\r\n"), pDevice->IdleTimeout, pDevice->PowerStateForIdle)); RegCloseKey(hSubKey); } // allocate our buffer list; we need 2 buffers: 1 for read and 1 for write data BufferSize = (ULONG)(pDevice->BlockTransferSize * SD_BLOCK_SIZE); // create the data buffer memory list pDevice->hBufferList = SDCreateMemoryList(SD_MEMORY_TAG, 2, BufferSize); if (pDevice->hBufferList == NULL) { DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("SDMemory: Initialize: Failed to allocate buffer list\r\n"))); CleanUpDevice(pDevice); return 0; } #ifdef _LOCKUP_FIX_ pDevice->fPreDeinitCalled = FALSE; #endif InitializePowerManagement(pDevice); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: -SMC_Init\r\n"))); return (DWORD)pDevice; } /////////////////////////////////////////////////////////////////////////////// // SMC_IOControl - the I/O control entry point for the memory driver // Input: Handle - the context returned from SMC_Open // IoctlCode - the ioctl code // pInBuf - the input buffer from the user // InBufSize - the length of the input buffer // pOutBuf - the output buffer from the user // InBufSize - the length of the output buffer // pBytesReturned - the size of the transfer // Output: // Return: TRUE if ioctl was handled // Notes: /////////////////////////////////////////////////////////////////////////////// extern "C" BOOL WINAPI SMC_IOControl( DWORD Handle, DWORD IoctlCode, PBYTE pInBuf, DWORD InBufSize, PBYTE pOutBuf, DWORD OutBufSize, PDWORD pBytesReturned ) { DWORD Status = ERROR_SUCCESS; // win32 status PSD_MEMCARD_INFO pHandle = (PSD_MEMCARD_INFO)Handle; // memcard info PSG_REQ pSG; // scatter gather buffer SD_API_STATUS sdStatus; // SD API status DWORD SafeBytesReturned = 0; // safe copy of pBytesReturned DEBUGMSG(SDCARD_ZONE_FUNC, (TEXT("SDMemory: +SMC_IOControl\r\n"))); if (OEM_CERTIFY_TRUST != PSLGetCallerTrust()) { SetLastError(ERROR_ACCESS_DENIED); return FALSE; } // any of these IOCTLs can access the device instance or card handle so we // must protect it from being freed from XXX_Deinit; Windows CE does not // synchronize the callback from Deinit AcquireRemovalLock(pHandle); #ifdef _LOCKUP_FIX_ if (pHandle->fPreDeinitCalled) { Status = ERROR_INVALID_HANDLE; goto ErrorStatusReturn; } #endif sdStatus = RequestPrologue(pHandle, IoctlCode); if (!SD_API_SUCCESS(sdStatus)) { ReleaseRemovalLock(pHandle); SetLastError(SDAPIStatusToErrorCode(sdStatus)); return FALSE; } DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("SMC_IOControl: Recevied IOCTL %d ="), IoctlCode)); switch(IoctlCode) { case IOCTL_DISK_READ: DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("IOCTL_DISK_READ\r\n"))); break; case DISK_IOCTL_READ: DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("DISK_IOCTL_READ\r\n"))); break; case IOCTL_DISK_WRITE: DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("IOCTL_DISK_WRITE\r\n"))); break; case DISK_IOCTL_WRITE: DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("DISK_IOCTL_WRITE\r\n"))); break; case IOCTL_DISK_GETINFO: DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("IOCTL_DISK_GETINFO\r\n"))); break; case DISK_IOCTL_GETINFO: DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("DISK_IOCTL_GETINFO\r\n"))); break; case IOCTL_DISK_SETINFO: DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("IOCTL_DISK_SETINFO\r\n"))); break; case DISK_IOCTL_INITIALIZED: DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("DISK_IOCTL_INITIALIZED\r\n"))); break; case IOCTL_DISK_INITIALIZED: DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("IOCTL_DISK_INITIALIZED\r\n"))); break; case IOCTL_DISK_GETNAME: DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("IOCTL_DISK_GETNAME\r\n"))); break; case DISK_IOCTL_GETNAME: DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("DISK_IOCTL_GETNAME\r\n"))); break; case IOCTL_DISK_GET_STORAGEID: DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("IOCTL_DISK_GET_STORAGEID\r\n"))); break; case IOCTL_DISK_FORMAT_MEDIA: case DISK_IOCTL_FORMAT_MEDIA: DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("IOCTL_DISK_FORMAT_MEDIA\r\n"))); break; case IOCTL_DISK_DEVICE_INFO: DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("IOCTL_DISK_DEVICE_INFO\r\n"))); break; case IOCTL_DISK_DELETE_SECTORS: DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("IOCTL_DISK_DELETE_SECTORS\r\n"))); break; default: DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("**UNKNOWN**\r\n"))); break; } // validate parameters switch(IoctlCode) { case IOCTL_DISK_READ: case DISK_IOCTL_READ: case IOCTL_DISK_WRITE: case DISK_IOCTL_WRITE: if (pInBuf == NULL || InBufSize < sizeof(SG_REQ) || InBufSize > (sizeof(SG_REQ) + ((MAX_SG_BUF - 1) * sizeof(SG_BUF)))) { Status = ERROR_INVALID_PARAMETER; } break; case DISK_IOCTL_GETINFO: case IOCTL_DISK_SETINFO: if (NULL == pInBuf || InBufSize != sizeof(DISK_INFO)) { Status = ERROR_INVALID_PARAMETER; } break; case IOCTL_DISK_DELETE_SECTORS: if (pInBuf == NULL || InBufSize != sizeof(DELETE_SECTOR_INFO)) { Status = ERROR_INVALID_PARAMETER; } break; case IOCTL_DISK_GETINFO: if (pOutBuf == NULL || OutBufSize != sizeof(DISK_INFO)) { Status = ERROR_INVALID_PARAMETER; } break; case IOCTL_DISK_GET_STORAGEID: // the identification data is stored after the struct, so the out // buffer must be at least the size of the struct. if (pOutBuf == NULL || OutBufSize < sizeof(STORAGE_IDENTIFICATION)) { Status = ERROR_INVALID_PARAMETER; } break; case IOCTL_DISK_FORMAT_MEDIA: case DISK_IOCTL_FORMAT_MEDIA: break; case IOCTL_DISK_DEVICE_INFO: if (NULL == pInBuf || (InBufSize != sizeof(STORAGEDEVICEINFO))) { Status = ERROR_INVALID_PARAMETER; } break; case IOCTL_POWER_CAPABILITIES: if (!pOutBuf || OutBufSize < sizeof(POWER_CAPABILITIES) || !pBytesReturned) { Status = ERROR_INVALID_PARAMETER; } break; case IOCTL_POWER_SET: if (!pOutBuf || OutBufSize < sizeof(CEDEVICE_POWER_STATE) || !pBytesReturned) { Status = ERROR_INVALID_PARAMETER; } break; default: Status = ERROR_INVALID_PARAMETER; } if (Status != ERROR_SUCCESS) { goto ErrorStatusReturn; } // execute the IOCTL switch(IoctlCode) { case IOCTL_DISK_READ: case DISK_IOCTL_READ: pSG = (PSG_REQ)pInBuf; if (0 == CeSafeCopyMemory((LPVOID)pHandle->pSterileIoRequest, (LPVOID)pSG, InBufSize)) { Status = ERROR_INVALID_PARAMETER; break; } Status = SDMemRead(pHandle, pHandle->pSterileIoRequest); __try { pSG->sr_status = Status; if (pBytesReturned && (ERROR_SUCCESS == Status)) { *pBytesReturned = (pHandle->pSterileIoRequest->sr_num_sec * SD_BLOCK_SIZE); } } __except(EXCEPTION_EXECUTE_HANDLER) { Status = ERROR_INVALID_PARAMETER; } break; case IOCTL_DISK_WRITE: case DISK_IOCTL_WRITE: pSG = (PSG_REQ)pInBuf; if (0 == CeSafeCopyMemory((LPVOID)pHandle->pSterileIoRequest, (LPVOID)pSG, InBufSize)) { Status = ERROR_INVALID_PARAMETER; break; } Status = SDMemWrite(pHandle, pHandle->pSterileIoRequest); __try { pSG->sr_status = Status; if (pBytesReturned && (ERROR_SUCCESS == Status)) { *pBytesReturned = (pHandle->pSterileIoRequest->sr_num_sec * SD_BLOCK_SIZE); } } __except(EXCEPTION_EXECUTE_HANDLER) { Status = ERROR_INVALID_PARAMETER; } break; case IOCTL_DISK_GETINFO: { DISK_INFO SafeDiskInfo = {0}; SafeBytesReturned = sizeof(DISK_INFO); Status = GetDiskInfo(pHandle, &SafeDiskInfo); if (0 == CeSafeCopyMemory((LPVOID)pOutBuf, (LPVOID)&SafeDiskInfo, sizeof(DISK_INFO))) { Status = ERROR_INVALID_PARAMETER; break; } if (pBytesReturned) { if (0 == CeSafeCopyMemory((LPVOID)pBytesReturned, (LPVOID)&SafeBytesReturned, sizeof(DWORD))) { Status = ERROR_INVALID_PARAMETER; break; } } } break; case DISK_IOCTL_GETINFO: { DISK_INFO SafeDiskInfo = {0}; SafeBytesReturned = sizeof(DISK_INFO); Status = GetDiskInfo(pHandle, &SafeDiskInfo); if (0 == CeSafeCopyMemory((LPVOID)pInBuf, (LPVOID)&SafeDiskInfo, sizeof(DISK_INFO))) { Status = ERROR_INVALID_PARAMETER; break; } if (pBytesReturned) { if (0 == CeSafeCopyMemory((LPVOID)pBytesReturned, (LPVOID)&SafeBytesReturned, sizeof(DWORD))) { Status = ERROR_INVALID_PARAMETER; break; } } } break; case IOCTL_DISK_SETINFO: { DISK_INFO SafeDiskInfo = {0}; if (0 == CeSafeCopyMemory((LPVOID)&SafeDiskInfo, (LPVOID)pInBuf, sizeof(DISK_INFO))) { Status = ERROR_INVALID_PARAMETER; break; } Status = SetDiskInfo(pHandle, &SafeDiskInfo); } break; case IOCTL_DISK_FORMAT_MEDIA: case DISK_IOCTL_FORMAT_MEDIA: Status = ERROR_SUCCESS; break; case IOCTL_DISK_GET_STORAGEID: { __try { Status = GetStorageID( pHandle, (PSTORAGE_IDENTIFICATION)pOutBuf, OutBufSize, pBytesReturned); } __except(EXCEPTION_EXECUTE_HANDLER) { Status = ERROR_INVALID_PARAMETER; } } break; case IOCTL_DISK_DEVICE_INFO: { STORAGEDEVICEINFO SafeStorageDeviceInfo = {0}; SafeBytesReturned = sizeof(STORAGEDEVICEINFO); if (!GetDeviceInfo(pHandle, &SafeStorageDeviceInfo)) { Status = ERROR_GEN_FAILURE; break; } if (0 == CeSafeCopyMemory((LPVOID)pInBuf, (LPVOID)&SafeStorageDeviceInfo, sizeof(STORAGEDEVICEINFO))) { Status = ERROR_INVALID_PARAMETER; break; } Status = ERROR_SUCCESS; if (pBytesReturned) { if (0 == CeSafeCopyMemory((LPVOID)pBytesReturned, (LPVOID)&SafeBytesReturned, sizeof(DWORD))) { Status = ERROR_INVALID_PARAMETER; } } } break; case IOCTL_DISK_DELETE_SECTORS: { DELETE_SECTOR_INFO SafeDeleteSectorInfo = {0}; if (0 != CeSafeCopyMemory((LPVOID)&SafeDeleteSectorInfo, (LPVOID)pInBuf, sizeof(DELETE_SECTOR_INFO))) { Status = ERROR_INVALID_PARAMETER; break; } Status = SDMemErase(pHandle, &SafeDeleteSectorInfo); } break; case IOCTL_POWER_CAPABILITIES: { POWER_CAPABILITIES SafePowerCapabilities = {0}; SafeBytesReturned = sizeof(POWER_CAPABILITIES); // support D0 + PowerStateForIdle (D2, by default) SafePowerCapabilities.DeviceDx = DX_MASK(D0) | DX_MASK(pHandle->PowerStateForIdle); SafePowerCapabilities.Power[D0] = PwrDeviceUnspecified; SafePowerCapabilities.Power[D1] = PwrDeviceUnspecified; SafePowerCapabilities.Power[D2] = PwrDeviceUnspecified; SafePowerCapabilities.Power[D3] = PwrDeviceUnspecified; SafePowerCapabilities.Power[D4] = PwrDeviceUnspecified; SafePowerCapabilities.Latency[D0] = 0; SafePowerCapabilities.Latency[D1] = 0; SafePowerCapabilities.Latency[D2] = 0; SafePowerCapabilities.Latency[D3] = 0; SafePowerCapabilities.Latency[D4] = 0; // no device wake SafePowerCapabilities.WakeFromDx = 0; // no inrush SafePowerCapabilities.InrushDx = 0; if (0 == CeSafeCopyMemory((LPVOID)pOutBuf, (LPVOID)&SafePowerCapabilities, sizeof(POWER_CAPABILITIES))) { Status = ERROR_INVALID_PARAMETER; break; } Status = ERROR_SUCCESS; if (pBytesReturned) { if (0 == CeSafeCopyMemory((LPVOID)pBytesReturned, (LPVOID)&SafeBytesReturned, sizeof(DWORD))) { Status = ERROR_INVALID_PARAMETER; } } } break; case IOCTL_POWER_SET: { // pOutBuf is a pointer to CEDEVICE_POWER_STATE; this is the device // state incd .. which to put the device; if the driver does not support // the requested power state, then we return the adjusted power // state CEDEVICE_POWER_STATE SafeCeDevicePowerState; SafeBytesReturned = sizeof(CEDEVICE_POWER_STATE); if (0 == CeSafeCopyMemory((LPVOID)&SafeCeDevicePowerState, (LPVOID)pOutBuf, sizeof(CEDEVICE_POWER_STATE))) { Status = ERROR_INVALID_PARAMETER; break; } Status = ERROR_SUCCESS; HandleIoctlPowerSet(pHandle, &SafeCeDevicePowerState); // return the adjusted power state if (0 == CeSafeCopyMemory((LPVOID)pOutBuf, (LPVOID)&SafeCeDevicePowerState, sizeof(CEDEVICE_POWER_STATE))) { Status = ERROR_INVALID_PARAMETER; break; } if (pBytesReturned) { if (0 == CeSafeCopyMemory((LPVOID)pBytesReturned, (LPVOID)&SafeBytesReturned, sizeof(DWORD))) { Status = ERROR_INVALID_PARAMETER; } } } break; default: Status = ERROR_INVALID_PARAMETER; break; } RequestEnd(pHandle); ErrorStatusReturn: ReleaseRemovalLock(pHandle); DEBUGMSG(SDCARD_ZONE_FUNC, (TEXT("SDMemory: -SMC_IOControl returning %d\n"),Status == ERROR_SUCCESS)); if (Status != ERROR_SUCCESS) { SetLastError(Status); } return (ERROR_SUCCESS == Status); } /////////////////////////////////////////////////////////////////////////////// // SMC_Open - the open entry point for the memory driver // Input: hDeviceContext - the device context from SMC_Init // AccessCode - the desired access // ShareMode - the desired share mode // Output: // Return: open context to device instance // Notes: /////////////////////////////////////////////////////////////////////////////// extern "C" DWORD WINAPI SMC_Open( DWORD hDeviceContext, DWORD AccessCode, DWORD ShareMode ) { DEBUGMSG(SDCARD_ZONE_FUNC, (TEXT("SDMemory: +-SMC_Open\n"))); return hDeviceContext; } /////////////////////////////////////////////////////////////////////////////// // SMC_PowerDown - the power down entry point for the bus driver // Input: hDeviceContext - the device context from SMC_Init // Output: // Return: // Notes: preforms no actions /////////////////////////////////////////////////////////////////////////////// extern "C" VOID WINAPI SMC_PowerDown(DWORD hDeviceContext) { // no prints allowed return; } /////////////////////////////////////////////////////////////////////////////// // SMC_PowerUp - the power up entry point for the CE file system wrapper // Input: hDeviceContext - the device context from SMC_Init // Output: // Return: // Notes: preforms no actions /////////////////////////////////////////////////////////////////////////////// extern "C" VOID WINAPI SMC_PowerUp(DWORD hDeviceContext) { // no prints allowed return; } /////////////////////////////////////////////////////////////////////////////// // SMC_Read - the read entry point for the memory driver // Input: hOpenContext - the context from SMC_Open // pBuffer - the user's buffer // Count - the size of the transfer // Output: // Return: zero // Notes: always returns zero (failure) /////////////////////////////////////////////////////////////////////////////// extern "C" DWORD WINAPI SMC_Read(DWORD hOpenContext, LPVOID pBuffer, DWORD Count) { DEBUGMSG(SDCARD_ZONE_FUNC, (TEXT("SDMemory: +-SMC_Read\n"))); return 0; } /////////////////////////////////////////////////////////////////////////////// // SMC_Seek - the seek entry point for the memory driver // Input: hOpenContext - the context from SMC_Open // Amount - the amount to seek // Type - the type of seek // Output: // Return: zero // Notes: always returns zero (failure) /////////////////////////////////////////////////////////////////////////////// extern "C" DWORD WINAPI SMC_Seek(DWORD hOpenContext, long Amount, DWORD Type) { DEBUGMSG(SDCARD_ZONE_FUNC, (TEXT("SDMemory: +-SMC_Seek\n"))); return 0; } /////////////////////////////////////////////////////////////////////////////// // SMC_Write - the write entry point for the memory driver // Input: hOpenContext - the context from SMC_Open // pBuffer - the user's buffer // Count - the size of the transfer // Output: // Return: zero // Notes: always returns zero (failure) /////////////////////////////////////////////////////////////////////////////// extern "C" DWORD WINAPI SMC_Write(DWORD hOpenContext, LPCVOID pBuffer, DWORD Count) { DEBUGMSG(SDCARD_ZONE_FUNC, (TEXT("SDMemory: +-SMC_Write\n"))); return 0; } /////////////////////////////////////////////////////////////////////////////// // GetDiskInfo - return disk info in response to DISK_IOCTL_GETINFO // Input: pMemCard - SD memory card structure // Output: pInfo - PDISK_INFO structure containing disk parameters // Return: win32 status // Notes: /////////////////////////////////////////////////////////////////////////////// DWORD GetDiskInfo( PSD_MEMCARD_INFO pMemCard, PDISK_INFO pInfo ) { *pInfo = pMemCard->DiskInfo; return ERROR_SUCCESS; } /////////////////////////////////////////////////////////////////////////////// // SetDiskInfo - store disk info in response to DISK_IOCTL_SETINFO // Input: pMemCard - SD memory card structure // pInfo - PDISK_INFO structure containing disk parameters // Output: // Return: win32 status // Notes /////////////////////////////////////////////////////////////////////////////// DWORD SetDiskInfo( PSD_MEMCARD_INFO pMemCard, PDISK_INFO pInfo ) { pMemCard->DiskInfo = *pInfo; return ERROR_SUCCESS; } /////////////////////////////////////////////////////////////////////////////// // GetStorageID - Returns storage ID based on manufactured ID + serial # // Input: pMemCard - SD memory card structure // cBytes - Size of psid buffer // Output: psid - Storage ID structure // pcBytes - Size of data written to psid // Return: win32 status // Notes: The Storage ID gets to written to space allocated after the actual // PSTORAGE_IDENTIFICATION structure. /////////////////////////////////////////////////////////////////////////////// DWORD GetStorageID( PSD_MEMCARD_INFO pMemCard, PSTORAGE_IDENTIFICATION psid, DWORD cBytes, DWORD *pcBytes ) { PCHAR pDstOffset; // destination offset for ID DEBUGMSG( SDCARD_ZONE_FUNC, (TEXT("SDMemory: +GetStorageID\r\n"))); // check enough space exists in buffer if( cBytes < (sizeof(*psid)+SD_SIZEOF_STORAGE_ID) ) { DEBUGMSG( SDCARD_ZONE_ERROR, (TEXT("SDMemory: GetStorageID Insufficient buffer space\r\nSDMemory: -GetStorageID\r\n"))); psid->dwSize = (sizeof(*psid)+SD_SIZEOF_STORAGE_ID); return ERROR_INSUFFICIENT_BUFFER; } // point to location after end of PSTORAGE_IDENTIFICATION pDstOffset = (PCHAR)(psid+1); // form manufacturer ID as string in the structure psid->dwManufactureIDOffset = pDstOffset - (PCHAR)psid; pDstOffset += sprintf( pDstOffset, "%02X\0", pMemCard->CIDRegister.ManufacturerID ); // form serial number as string in the structure psid->dwSerialNumOffset = pDstOffset - (PCHAR)psid; sprintf( pDstOffset, "%08X\0", pMemCard->CIDRegister.ProductSerialNumber ); // set structure fields psid->dwSize = sizeof(*psid) + SD_SIZEOF_STORAGE_ID; psid->dwFlags = 0; *pcBytes = psid->dwSize; DEBUGMSG( SDCARD_ZONE_FUNC, (TEXT("SDMemory: -GetStorageID\r\n"))); return ERROR_SUCCESS; } /////////////////////////////////////////////////////////////////////////////// // GetDeviceInfo - get the device profile and information // Input: pMemCard - the memory card instance // pStorageInfo - storage info structure to fill in // Output: // Return: returns TRUE if device information was retreived // Notes /////////////////////////////////////////////////////////////////////////////// BOOL GetDeviceInfo(PSD_MEMCARD_INFO pMemCard, PSTORAGEDEVICEINFO pStorageInfo) { HKEY hDriverKey; // driver key DWORD ValType; // registry key value type DWORD status; // win32 status DWORD dwSize; // size of key // get the FolderName key if it exists if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, pMemCard->pRegPath, 0, KEY_ALL_ACCESS, &hDriverKey) != ERROR_SUCCESS) { DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("SDemory: GetDeviceInfo - Failed to open reg path %s \r\n"), pMemCard->pRegPath)); return FALSE; } if (hDriverKey) { dwSize = sizeof(pStorageInfo->szProfile); status = RegQueryValueEx( hDriverKey, TEXT("Profile"), NULL, &ValType, (LPBYTE)pStorageInfo->szProfile, &dwSize); if ((status != ERROR_SUCCESS) || (dwSize > sizeof(pStorageInfo->szProfile))){ DEBUGMSG(SDCARD_ZONE_ERROR | SDCARD_ZONE_INIT, (TEXT("SDemory: GetDeviceInfo - RegQueryValueEx(Profile) returned %d\r\n"), status)); wcscpy( pStorageInfo->szProfile, L"Default"); } else { DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: GetDeviceInfo - Profile = %s, length = %d\r\n"), pStorageInfo->szProfile, dwSize)); } RegCloseKey(hDriverKey); } pStorageInfo->dwDeviceClass = STORAGE_DEVICE_CLASS_BLOCK; pStorageInfo->dwDeviceType = STORAGE_DEVICE_TYPE_UNKNOWN; pStorageInfo->dwDeviceType |= STORAGE_DEVICE_TYPE_REMOVABLE_DRIVE; if (pMemCard->WriteProtected) { pStorageInfo->dwDeviceFlags = STORAGE_DEVICE_FLAG_READONLY; } else { pStorageInfo->dwDeviceFlags = STORAGE_DEVICE_FLAG_READWRITE; } return TRUE; } #ifdef _LOCKUP_FIX_ /////////////////////////////////////////////////////////////////////////////// // SMC_PreDeinit - the deinit entry point for the memory driver // Input: hDeviceContext - the context returned from SMC_Init // Output: // Return: always returns TRUE // Notes: /////////////////////////////////////////////////////////////////////////////// extern "C" BOOL WINAPI SMC_PreDeinit(DWORD hDeviceContext) { PSD_MEMCARD_INFO pDevice; DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: +SMC_PreDeinit\n"))); pDevice = (PSD_MEMCARD_INFO)hDeviceContext; AcquireRemovalLock(pDevice); pDevice->fPreDeinitCalled = TRUE; ReleaseRemovalLock(pDevice); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SDMemory: -SMC_PreDeinit\n"))); return TRUE; } #endif // DO NOT REMOVE --- END EXTERNALLY DEVELOPED SOURCE CODE ID --- DO NOT REMOVE
[ [ [ 1, 1074 ] ] ]
53a7488bb75e44c32f0ac4b4e42f6e0a85cddbeb
d6a28d9d845a20463704afe8ebe644a241dc1a46
/source/Irrlicht/COpenGLDriver.h
3b37868552b202751c41a439298c4a37e91e662c
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive", "Zlib" ]
permissive
marky0720/irrlicht-android
6932058563bf4150cd7090d1dc09466132df5448
86512d871eeb55dfaae2d2bf327299348cc5202c
refs/heads/master
2021-04-30T08:19:25.297407
2010-10-08T08:27:33
2010-10-08T08:27:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,402
h
// Copyright (C) 2002-2009 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in Irrlicht.h #ifndef __C_VIDEO_OPEN_GL_H_INCLUDED__ #define __C_VIDEO_OPEN_GL_H_INCLUDED__ #include "IrrCompileConfig.h" #include "SIrrCreationParameters.h" namespace irr { class CIrrDeviceWin32; class CIrrDeviceLinux; class CIrrDeviceSDL; class CIrrDeviceMacOSX; } #ifdef _IRR_COMPILE_WITH_OPENGL_ #include "CNullDriver.h" #include "IMaterialRendererServices.h" // also includes the OpenGL stuff #include "COpenGLExtensionHandler.h" namespace irr { namespace video { class COpenGLTexture; class COpenGLDriver : public CNullDriver, public IMaterialRendererServices, public COpenGLExtensionHandler { public: #ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_ COpenGLDriver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, CIrrDeviceWin32* device); //! inits the windows specific parts of the open gl driver bool initDriver(SIrrlichtCreationParameters params, CIrrDeviceWin32* device); bool changeRenderContext(const SExposedVideoData& videoData, CIrrDeviceWin32* device); #endif #ifdef _IRR_COMPILE_WITH_X11_DEVICE_ COpenGLDriver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, CIrrDeviceLinux* device); //! inits the GLX specific parts of the open gl driver bool initDriver(SIrrlichtCreationParameters params, CIrrDeviceLinux* device); bool changeRenderContext(const SExposedVideoData& videoData, CIrrDeviceLinux* device); #endif #ifdef _IRR_COMPILE_WITH_SDL_DEVICE_ COpenGLDriver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, CIrrDeviceSDL* device); #endif #ifdef _IRR_COMPILE_WITH_OSX_DEVICE_ COpenGLDriver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, CIrrDeviceMacOSX *device); #endif //! generic version which overloads the unimplemented versions bool changeRenderContext(const SExposedVideoData& videoData, void* device) {return false;} //! destructor virtual ~COpenGLDriver(); //! clears the zbuffer virtual bool beginScene(bool backBuffer=true, bool zBuffer=true, SColor color=SColor(255,0,0,0), const SExposedVideoData& videoData=SExposedVideoData(), core::rect<s32>* sourceRect=0); //! presents the rendered scene on the screen, returns false if failed virtual bool endScene(); //! sets transformation virtual void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat); struct SHWBufferLink_opengl : public SHWBufferLink { SHWBufferLink_opengl(const scene::IMeshBuffer *_MeshBuffer): SHWBufferLink(_MeshBuffer), vbo_verticesID(0),vbo_indicesID(0){} GLuint vbo_verticesID; //tmp GLuint vbo_indicesID; //tmp GLuint vbo_verticesSize; //tmp GLuint vbo_indicesSize; //tmp }; //! updates hardware buffer if needed virtual bool updateHardwareBuffer(SHWBufferLink *HWBuffer); //! Create hardware buffer from mesh virtual SHWBufferLink *createHardwareBuffer(const scene::IMeshBuffer* mb); //! Delete hardware buffer (only some drivers can) virtual void deleteHardwareBuffer(SHWBufferLink *HWBuffer); //! Draw hardware buffer virtual void drawHardwareBuffer(SHWBufferLink *HWBuffer); //! Create occlusion query. /** Use node for identification and mesh for occlusion test. */ virtual void createOcclusionQuery(scene::ISceneNode* node, const scene::IMesh* mesh=0); //! Remove occlusion query. virtual void removeOcclusionQuery(scene::ISceneNode* node); //! Run occlusion query. Draws mesh stored in query. /** If the mesh shall not be rendered visible, use overrideMaterial to disable the color and depth buffer. */ virtual void runOcclusionQuery(scene::ISceneNode* node, bool visible=false); //! Update occlusion query. Retrieves results from GPU. /** If the query shall not block, set the flag to false. Update might not occur in this case, though */ virtual void updateOcclusionQuery(scene::ISceneNode* node, bool block=true); //! Return query result. /** Return value is the number of visible pixels/fragments. The value is a safe approximation, i.e. can be larger then the actual value of pixels. */ virtual u32 getOcclusionQueryResult(scene::ISceneNode* node) const; //! draws a vertex primitive list virtual void drawVertexPrimitiveList(const void* vertices, u32 vertexCount, const void* indexList, u32 primitiveCount, E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType); //! draws a vertex primitive list in 2d virtual void draw2DVertexPrimitiveList(const void* vertices, u32 vertexCount, const void* indexList, u32 primitiveCount, E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType); //! queries the features of the driver, returns true if feature is available virtual bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const { return FeatureEnabled[feature] && COpenGLExtensionHandler::queryFeature(feature); } //! Sets a material. All 3d drawing functions draw geometry now //! using this material. //! \param material: Material to be used from now on. virtual void setMaterial(const SMaterial& material); //! draws a set of 2d images, using a color and the alpha channel of the //! texture if desired. void draw2DImageBatch(const video::ITexture* texture, const core::array<core::position2d<s32> >& positions, const core::array<core::rect<s32> >& sourceRects, const core::rect<s32>* clipRect, SColor color, bool useAlphaChannelOfTexture); //! draws an 2d image, using a color (if color is other then Color(255,255,255,255)) and the alpha channel of the texture if wanted. virtual void draw2DImage(const video::ITexture* texture, const core::position2d<s32>& destPos, const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect = 0, SColor color=SColor(255,255,255,255), bool useAlphaChannelOfTexture=false); //! draws a set of 2d images, using a color and the alpha /** channel of the texture if desired. The images are drawn beginning at pos and concatenated in one line. All drawings are clipped against clipRect (if != 0). The subtextures are defined by the array of sourceRects and are chosen by the indices given. \param texture: Texture to be drawn. \param pos: Upper left 2d destination position where the image will be drawn. \param sourceRects: Source rectangles of the image. \param indices: List of indices which choose the actual rectangle used each time. \param clipRect: Pointer to rectangle on the screen where the image is clipped to. This pointer can be 0. Then the image is not clipped. \param color: Color with which the image is colored. Note that the alpha component is used: If alpha is other than 255, the image will be transparent. \param useAlphaChannelOfTexture: If true, the alpha channel of the texture is used to draw the image. */ virtual void draw2DImage(const video::ITexture* texture, const core::position2d<s32>& pos, const core::array<core::rect<s32> >& sourceRects, const core::array<s32>& indices, const core::rect<s32>* clipRect=0, SColor color=SColor(255,255,255,255), bool useAlphaChannelOfTexture=false); //! Draws a part of the texture into the rectangle. virtual void draw2DImage(const video::ITexture* texture, const core::rect<s32>& destRect, const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect = 0, const video::SColor* const colors=0, bool useAlphaChannelOfTexture=false); //! draw an 2d rectangle virtual void draw2DRectangle(SColor color, const core::rect<s32>& pos, const core::rect<s32>* clip = 0); //!Draws an 2d rectangle with a gradient. virtual void draw2DRectangle(const core::rect<s32>& pos, SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown, const core::rect<s32>* clip = 0); //! Draws a 2d line. virtual void draw2DLine(const core::position2d<s32>& start, const core::position2d<s32>& end, SColor color=SColor(255,255,255,255)); //! Draws a single pixel virtual void drawPixel(u32 x, u32 y, const SColor & color); //! Draws a 3d line. virtual void draw3DLine(const core::vector3df& start, const core::vector3df& end, SColor color = SColor(255,255,255,255)); //! \return Returns the name of the video driver. Example: In case of the Direct3D8 //! driver, it would return "Direct3D8.1". virtual const wchar_t* getName() const; //! deletes all dynamic lights there are virtual void deleteAllDynamicLights(); //! adds a dynamic light, returning an index to the light //! \param light: the light data to use to create the light //! \return An index to the light, or -1 if an error occurs virtual s32 addDynamicLight(const SLight& light); //! Turns a dynamic light on or off //! \param lightIndex: the index returned by addDynamicLight //! \param turnOn: true to turn the light on, false to turn it off virtual void turnLightOn(s32 lightIndex, bool turnOn); //! returns the maximal amount of dynamic lights the device can handle virtual u32 getMaximalDynamicLightAmount() const; //! Sets the dynamic ambient light color. The default color is //! (0,0,0,0) which means it is dark. //! \param color: New color of the ambient light. virtual void setAmbientLight(const SColorf& color); //! Draws a shadow volume into the stencil buffer. To draw a stencil shadow, do //! this: First, draw all geometry. Then use this method, to draw the shadow //! volume. Then, use IVideoDriver::drawStencilShadow() to visualize the shadow. virtual void drawStencilShadowVolume(const core::vector3df* triangles, s32 count, bool zfail); //! Fills the stencil shadow with color. After the shadow volume has been drawn //! into the stencil buffer using IVideoDriver::drawStencilShadowVolume(), use this //! to draw the color of the shadow. virtual void drawStencilShadow(bool clearStencilBuffer=false, video::SColor leftUpEdge = video::SColor(0,0,0,0), video::SColor rightUpEdge = video::SColor(0,0,0,0), video::SColor leftDownEdge = video::SColor(0,0,0,0), video::SColor rightDownEdge = video::SColor(0,0,0,0)); //! sets a viewport virtual void setViewPort(const core::rect<s32>& area); //! Sets the fog mode. virtual void setFog(SColor color, E_FOG_TYPE fogType, f32 start, f32 end, f32 density, bool pixelFog, bool rangeFog); //! Only used by the internal engine. Used to notify the driver that //! the window was resized. virtual void OnResize(const core::dimension2d<u32>& size); //! Returns type of video driver virtual E_DRIVER_TYPE getDriverType() const; //! get color format of the current color buffer virtual ECOLOR_FORMAT getColorFormat() const; //! Returns the transformation set by setTransform virtual const core::matrix4& getTransform(E_TRANSFORMATION_STATE state) const; //! Can be called by an IMaterialRenderer to make its work easier. virtual void setBasicRenderStates(const SMaterial& material, const SMaterial& lastmaterial, bool resetAllRenderstates); //! Sets a vertex shader constant. virtual void setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount=1); //! Sets a pixel shader constant. virtual void setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount=1); //! Sets a constant for the vertex shader based on a name. virtual bool setVertexShaderConstant(const c8* name, const f32* floats, int count); //! Sets a constant for the pixel shader based on a name. virtual bool setPixelShaderConstant(const c8* name, const f32* floats, int count); //! sets the current Texture //! Returns whether setting was a success or not. bool setActiveTexture(u32 stage, const video::ITexture* texture); //! disables all textures beginning with the optional fromStage parameter. Otherwise all texture stages are disabled. //! Returns whether disabling was successful or not. bool disableTextures(u32 fromStage=0); //! Adds a new material renderer to the VideoDriver, using //! extGLGetObjectParameteriv(shaderHandle, GL_OBJECT_COMPILE_STATUS_ARB, &status) //! pixel and/or vertex shaders to render geometry. virtual s32 addShaderMaterial(const c8* vertexShaderProgram, const c8* pixelShaderProgram, IShaderConstantSetCallBack* callback, E_MATERIAL_TYPE baseMaterial, s32 userData); //! Adds a new material renderer to the VideoDriver, using GLSL to render geometry. virtual s32 addHighLevelShaderMaterial( const c8* vertexShaderProgram, const c8* vertexShaderEntryPointName, E_VERTEX_SHADER_TYPE vsCompileTarget, const c8* pixelShaderProgram, const c8* pixelShaderEntryPointName, E_PIXEL_SHADER_TYPE psCompileTarget, const c8* geometryShaderProgram, const c8* geometryShaderEntryPointName = "main", E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, u32 verticesOut = 0, IShaderConstantSetCallBack* callback = 0, E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, s32 userData = 0); //! Returns a pointer to the IVideoDriver interface. (Implementation for //! IMaterialRendererServices) virtual IVideoDriver* getVideoDriver(); //! Returns the maximum amount of primitives (mostly vertices) which //! the device is able to render with one drawIndexedTriangleList //! call. virtual u32 getMaximalPrimitiveCount() const; virtual ITexture* addRenderTargetTexture(const core::dimension2d<u32>& size, const io::path& name, const ECOLOR_FORMAT format = ECF_UNKNOWN); //! set or reset render target virtual bool setRenderTarget(video::E_RENDER_TARGET target, bool clearTarget, bool clearZBuffer, SColor color); //! set or reset render target texture virtual bool setRenderTarget(video::ITexture* texture, bool clearBackBuffer, bool clearZBuffer, SColor color); //! Sets multiple render targets virtual bool setRenderTarget(const core::array<video::IRenderTarget>& texture, bool clearBackBuffer=true, bool clearZBuffer=true, SColor color=SColor(0,0,0,0)); //! Clears the ZBuffer. virtual void clearZBuffer(); //! Returns an image created from the last rendered frame. virtual IImage* createScreenShot(); //! checks if an OpenGL error has happend and prints it //! for performance reasons only available in debug mode bool testGLError(); //! Set/unset a clipping plane. //! There are at least 6 clipping planes available for the user to set at will. //! \param index: The plane index. Must be between 0 and MaxUserClipPlanes. //! \param plane: The plane itself. //! \param enable: If true, enable the clipping plane else disable it. virtual bool setClipPlane(u32 index, const core::plane3df& plane, bool enable=false); //! Enable/disable a clipping plane. //! There are at least 6 clipping planes available for the user to set at will. //! \param index: The plane index. Must be between 0 and MaxUserClipPlanes. //! \param enable: If true, enable the clipping plane else disable it. virtual void enableClipPlane(u32 index, bool enable); //! Enable the 2d override material virtual void enableMaterial2D(bool enable=true); //! Returns the graphics card vendor name. virtual core::stringc getVendorInfo() {return VendorName;} //! Returns the maximum texture size supported. virtual core::dimension2du getMaxTextureSize() const; ITexture* createDepthTexture(ITexture* texture, bool shared=true); void removeDepthTexture(ITexture* texture); //! Convert E_PRIMITIVE_TYPE to OpenGL equivalent GLenum primitiveTypeToGL(scene::E_PRIMITIVE_TYPE type) const; private: //! clears the zbuffer and color buffer void clearBuffers(bool backBuffer, bool zBuffer, bool stencilBuffer, SColor color); bool updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); bool updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); void uploadClipPlane(u32 index); //! inits the parts of the open gl driver used on all platforms bool genericDriverInit(const core::dimension2d<u32>& screenSize, bool stencilBuffer); //! returns a device dependent texture from a software surface (IImage) virtual video::ITexture* createDeviceDependentTexture(IImage* surface, const io::path& name, void* mipmapData); //! creates a transposed matrix in supplied GLfloat array to pass to OpenGL inline void createGLMatrix(GLfloat gl_matrix[16], const core::matrix4& m); inline void createGLTextureMatrix(GLfloat gl_matrix[16], const core::matrix4& m); //! Set GL pipeline to desired texture wrap modes of the material void setWrapMode(const SMaterial& material); //! get native wrap mode value GLint getTextureWrapMode(const u8 clamp); //! sets the needed renderstates void setRenderStates3DMode(); //! sets the needed renderstates void setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel); // returns the current size of the screen or rendertarget virtual const core::dimension2d<u32>& getCurrentRenderTargetSize() const; void createMaterialRenderers(); //! Assign a hardware light to the specified requested light, if any //! free hardware lights exist. //! \param[in] lightIndex: the index of the requesting light void assignHardwareLight(u32 lightIndex); //! helper function for render setup. void createColorBuffer(const void* vertices, u32 vertexCount, E_VERTEX_TYPE vType); //! helper function doing the actual rendering. void renderArray(const void* indexList, u32 primitiveCount, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType); core::stringw Name; core::matrix4 Matrices[ETS_COUNT]; core::array<u8> ColorBuffer; //! enumeration for rendering modes such as 2d and 3d for minizing the switching of renderStates. enum E_RENDER_MODE { ERM_NONE = 0, // no render state has been set yet. ERM_2D, // 2d drawing rendermode ERM_3D // 3d rendering mode }; E_RENDER_MODE CurrentRenderMode; //! bool to make all renderstates reset if set to true. bool ResetRenderStates; bool Transformation3DChanged; u8 AntiAlias; SMaterial Material, LastMaterial; COpenGLTexture* RenderTargetTexture; const ITexture* CurrentTexture[MATERIAL_MAX_TEXTURES]; core::array<ITexture*> DepthTextures; struct SUserClipPlane { SUserClipPlane() : Enabled(false) {} core::plane3df Plane; bool Enabled; }; core::array<SUserClipPlane> UserClipPlanes; core::dimension2d<u32> CurrentRendertargetSize; core::stringc VendorName; core::matrix4 TextureFlipMatrix; //! Color buffer format ECOLOR_FORMAT ColorFormat; //! Render target type for render operations E_RENDER_TARGET CurrentTarget; bool Doublebuffer; bool Stereo; //! All the lights that have been requested; a hardware limited //! number of them will be used at once. struct RequestedLight { RequestedLight(SLight const & lightData) : LightData(lightData), HardwareLightIndex(-1), DesireToBeOn(true) { } SLight LightData; s32 HardwareLightIndex; // GL_LIGHT0 - GL_LIGHT7 bool DesireToBeOn; }; core::array<RequestedLight> RequestedLights; #ifdef _IRR_WINDOWS_API_ HDC HDc; // Private GDI Device Context HWND Window; #ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_ CIrrDeviceWin32 *Device; #endif #endif #ifdef _IRR_COMPILE_WITH_X11_DEVICE_ GLXDrawable Drawable; Display* X11Display; CIrrDeviceLinux *Device; #endif #ifdef _IRR_COMPILE_WITH_OSX_DEVICE_ CIrrDeviceMacOSX *Device; #endif #ifdef _IRR_COMPILE_WITH_SDL_DEVICE_ CIrrDeviceSDL *Device; #endif E_DEVICE_TYPE DeviceType; }; } // end namespace video } // end namespace irr #endif // _IRR_COMPILE_WITH_OPENGL_ #endif
[ "hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475", "bitplane@dfc29bdd-3216-0410-991c-e03cc46cb475", "engineer_apple@dfc29bdd-3216-0410-991c-e03cc46cb475", "lukeph@dfc29bdd-3216-0410-991c-e03cc46cb475", "Rogerborg@dfc29bdd-3216-0410-991c-e03cc46cb475", "monstrobishi@dfc29bdd-3216-0410-991c-e03cc46cb475" ]
[ [ [ 1, 1 ], [ 9, 9 ], [ 12, 19 ], [ 24, 25 ], [ 28, 28 ], [ 34, 34 ], [ 40, 53 ], [ 60, 62 ], [ 67, 70 ], [ 72, 74 ], [ 84, 87 ], [ 102, 125 ], [ 127, 127 ], [ 131, 135 ], [ 137, 140 ], [ 147, 155 ], [ 157, 157 ], [ 177, 177 ], [ 186, 186 ], [ 188, 188 ], [ 214, 214 ], [ 230, 230 ], [ 255, 255 ], [ 263, 263 ], [ 265, 267 ], [ 269, 269 ], [ 272, 272 ], [ 293, 293 ], [ 295, 298 ], [ 302, 317 ], [ 326, 326 ], [ 329, 329 ], [ 331, 336 ], [ 339, 342 ], [ 353, 368 ], [ 370, 376 ], [ 378, 380 ], [ 383, 390 ], [ 394, 394 ], [ 397, 398 ], [ 400, 405 ], [ 422, 428 ], [ 433, 433 ], [ 442, 443 ], [ 445, 445 ], [ 449, 457 ], [ 461, 461 ], [ 465, 473 ], [ 482, 482 ], [ 490, 492 ], [ 495, 497 ], [ 500, 505 ] ], [ [ 2, 8 ], [ 22, 23 ], [ 26, 27 ], [ 29, 33 ], [ 35, 39 ], [ 54, 59 ], [ 63, 66 ], [ 71, 71 ], [ 75, 77 ], [ 126, 126 ], [ 130, 130 ], [ 136, 136 ], [ 141, 146 ], [ 156, 156 ], [ 158, 176 ], [ 178, 185 ], [ 187, 187 ], [ 189, 203 ], [ 207, 213 ], [ 215, 218 ], [ 228, 229 ], [ 231, 254 ], [ 256, 259 ], [ 261, 262 ], [ 264, 264 ], [ 268, 268 ], [ 270, 271 ], [ 273, 288 ], [ 290, 292 ], [ 294, 294 ], [ 299, 301 ], [ 318, 325 ], [ 327, 327 ], [ 330, 330 ], [ 337, 338 ], [ 343, 352 ], [ 381, 382 ], [ 391, 391 ], [ 393, 393 ], [ 395, 396 ], [ 399, 399 ], [ 406, 412 ], [ 414, 416 ], [ 429, 432 ], [ 434, 441 ], [ 444, 444 ], [ 446, 448 ], [ 458, 458 ], [ 460, 460 ], [ 463, 464 ], [ 487, 489 ], [ 493, 494 ], [ 498, 499 ], [ 506, 515 ] ], [ [ 10, 11 ], [ 20, 21 ] ], [ [ 78, 83 ], [ 88, 101 ], [ 128, 129 ], [ 369, 369 ], [ 377, 377 ], [ 421, 421 ], [ 462, 462 ] ], [ [ 204, 206 ], [ 219, 227 ], [ 260, 260 ], [ 328, 328 ], [ 392, 392 ], [ 413, 413 ], [ 417, 420 ], [ 459, 459 ], [ 474, 481 ], [ 483, 486 ] ], [ [ 289, 289 ] ] ]
2e50ed062cf12315ff5b0b863b8a5ffd053d6172
d7320c9c1f155e2499afa066d159bfa6aa94b432
/ghost/bnet.cpp
cf57a49aad34990cb13781b9e6e50b7c79e30188
[]
no_license
HOST-PYLOS/ghostnordicleague
c44c804cb1b912584db3dc4bb811f29f3761a458
9cb262d8005dda0150b75d34b95961d664b1b100
refs/heads/master
2016-09-05T10:06:54.279724
2011-02-23T08:02:50
2011-02-23T08:02:50
32,241,503
0
1
null
null
null
null
UTF-8
C++
false
false
112,872
cpp
/* Copyright [2008] [Trevor Hogan] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. CODE PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/ */ #include "ghost.h" #include "util.h" #include "config.h" #include "language.h" #include "socket.h" #include "commandpacket.h" #include "ghostdb.h" #include "bncsutilinterface.h" #include "bnlsclient.h" #include "bnetprotocol.h" #include "bnet.h" #include "map.h" #include "packed.h" #include "savegame.h" #include "replay.h" #include "gameprotocol.h" #include "game_base.h" #include <boost/filesystem.hpp> #include <boost/regex.hpp> using namespace boost :: filesystem; // CUSTOM INCLUDE #include <stdio.h> #include <stdlib.h> #include <time.h> //#include "dirent.h" #include <time.h> // // CBNET // CBNET :: CBNET( CGHost *nGHost, string nServer, string nServerAlias, string nBNLSServer, uint16_t nBNLSPort, uint32_t nBNLSWardenCookie, string nCDKeyROC, string nCDKeyTFT, string nCountryAbbrev, string nCountry, string nUserName, string nUserPassword, string nFirstChannel, string nRootAdmin, char nCommandTrigger, bool nHoldFriends, bool nHoldClan, bool nPublicCommands, unsigned char nWar3Version, BYTEARRAY nEXEVersion, BYTEARRAY nEXEVersionHash, string nPasswordHashType, string nPVPGNRealmName, uint32_t nMaxMessageLength, uint32_t nHostCounterID ) { // todotodo: append path seperator to Warcraft3Path if needed m_GHost = nGHost; m_Socket = new CTCPClient( ); m_Protocol = new CBNETProtocol( ); m_BNLSClient = NULL; m_BNCSUtil = new CBNCSUtilInterface( nUserName, nUserPassword ); m_CallableAdminList = m_GHost->m_DB->ThreadedAdminList( nServer ); m_CallableBanList = m_GHost->m_DB->ThreadedBanList( nServer ); m_Exiting = false; m_Server = nServer; string LowerServer = m_Server; transform( LowerServer.begin( ), LowerServer.end( ), LowerServer.begin( ), (int(*)(int))tolower ); if( !nServerAlias.empty( ) ) m_ServerAlias = nServerAlias; else if( LowerServer == "useast.battle.net" ) m_ServerAlias = "USEast"; else if( LowerServer == "uswest.battle.net" ) m_ServerAlias = "USWest"; else if( LowerServer == "asia.battle.net" ) m_ServerAlias = "Asia"; else if( LowerServer == "europe.battle.net" ) m_ServerAlias = "Europe"; else m_ServerAlias = m_Server; m_BNLSServer = nBNLSServer; m_BNLSPort = nBNLSPort; m_BNLSWardenCookie = nBNLSWardenCookie; m_CDKeyROC = nCDKeyROC; m_CDKeyTFT = nCDKeyTFT; // remove dashes from CD keys and convert to uppercase m_CDKeyROC.erase( remove( m_CDKeyROC.begin( ), m_CDKeyROC.end( ), '-' ), m_CDKeyROC.end( ) ); m_CDKeyTFT.erase( remove( m_CDKeyTFT.begin( ), m_CDKeyTFT.end( ), '-' ), m_CDKeyTFT.end( ) ); transform( m_CDKeyROC.begin( ), m_CDKeyROC.end( ), m_CDKeyROC.begin( ), (int(*)(int))toupper ); transform( m_CDKeyTFT.begin( ), m_CDKeyTFT.end( ), m_CDKeyTFT.begin( ), (int(*)(int))toupper ); if( m_CDKeyROC.size( ) != 26 ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] warning - your ROC CD key is not 26 characters long and is probably invalid" ); if( m_CDKeyTFT.size( ) != 26 ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] warning - your TFT CD key is not 26 characters long and is probably invalid" ); m_CountryAbbrev = nCountryAbbrev; m_Country = nCountry; m_UserName = nUserName; m_UserPassword = nUserPassword; m_FirstChannel = nFirstChannel; m_RootAdmin = nRootAdmin; transform( m_RootAdmin.begin( ), m_RootAdmin.end( ), m_RootAdmin.begin( ), (int(*)(int))tolower ); m_CommandTrigger = nCommandTrigger; m_War3Version = nWar3Version; m_EXEVersion = nEXEVersion; m_EXEVersionHash = nEXEVersionHash; m_PasswordHashType = nPasswordHashType; m_PVPGNRealmName = nPVPGNRealmName; m_MaxMessageLength = nMaxMessageLength; m_HostCounterID = nHostCounterID; m_NextConnectTime = GetTime( ); m_LastNullTime = 0; m_LastOutPacketTicks = 0; m_LastOutPacketSize = 0; m_LastAdminRefreshTime = GetTime( ); m_LastBanRefreshTime = GetTime( ); m_WaitingToConnect = true; m_LoggedIn = false; m_InChat = false; m_HoldFriends = nHoldFriends; m_HoldClan = nHoldClan; m_PublicCommands = nPublicCommands; } CBNET :: ~CBNET( ) { delete m_Socket; delete m_Protocol; delete m_BNLSClient; while( !m_Packets.empty( ) ) { delete m_Packets.front( ); m_Packets.pop( ); } delete m_BNCSUtil; for( vector<CIncomingFriendList *> :: iterator i = m_Friends.begin( ); i != m_Friends.end( ); i++ ) delete *i; for( vector<CIncomingClanList *> :: iterator i = m_Clans.begin( ); i != m_Clans.end( ); i++ ) delete *i; for( vector<PairedAdminCount> :: iterator i = m_PairedAdminCounts.begin( ); i != m_PairedAdminCounts.end( ); i++ ) m_GHost->m_Callables.push_back( i->second ); for( vector<PairedAdminAdd> :: iterator i = m_PairedAdminAdds.begin( ); i != m_PairedAdminAdds.end( ); i++ ) m_GHost->m_Callables.push_back( i->second ); for( vector<PairedAdminRemove> :: iterator i = m_PairedAdminRemoves.begin( ); i != m_PairedAdminRemoves.end( ); i++ ) m_GHost->m_Callables.push_back( i->second ); for( vector<PairedBanCount> :: iterator i = m_PairedBanCounts.begin( ); i != m_PairedBanCounts.end( ); i++ ) m_GHost->m_Callables.push_back( i->second ); for( vector<PairedBanAdd> :: iterator i = m_PairedBanAdds.begin( ); i != m_PairedBanAdds.end( ); i++ ) m_GHost->m_Callables.push_back( i->second ); for( vector<PairedRegisterPlayerAdd> :: iterator i = m_PairedRegisterPlayerAdds.begin( ); i != m_PairedRegisterPlayerAdds.end( ); i++ ) m_GHost->m_Callables.push_back( i->second ); for( vector<PairedBanRemove> :: iterator i = m_PairedBanRemoves.begin( ); i != m_PairedBanRemoves.end( ); i++ ) m_GHost->m_Callables.push_back( i->second ); for( vector<PairedGPSCheck> :: iterator i = m_PairedGPSChecks.begin( ); i != m_PairedGPSChecks.end( ); i++ ) m_GHost->m_Callables.push_back( i->second ); for( vector<PairedDPSCheck> :: iterator i = m_PairedDPSChecks.begin( ); i != m_PairedDPSChecks.end( ); i++ ) m_GHost->m_Callables.push_back( i->second ); if( m_CallableAdminList ) m_GHost->m_Callables.push_back( m_CallableAdminList ); if( m_CallableBanList ) m_GHost->m_Callables.push_back( m_CallableBanList ); for( vector<CDBBan *> :: iterator i = m_Bans.begin( ); i != m_Bans.end( ); i++ ) delete *i; } BYTEARRAY CBNET :: GetUniqueName( ) { return m_Protocol->GetUniqueName( ); } unsigned int CBNET :: SetFD( void *fd, void *send_fd, int *nfds ) { unsigned int NumFDs = 0; if( !m_Socket->HasError( ) && m_Socket->GetConnected( ) ) { m_Socket->SetFD( (fd_set *)fd, (fd_set *)send_fd, nfds ); NumFDs++; if( m_BNLSClient ) NumFDs += m_BNLSClient->SetFD( fd, send_fd, nfds ); } return NumFDs; } bool CBNET :: Update( void *fd, void *send_fd ) { // // update callables // for( vector<PairedAdminCount> :: iterator i = m_PairedAdminCounts.begin( ); i != m_PairedAdminCounts.end( ); ) { if( i->second->GetReady( ) ) { uint32_t Count = i->second->GetResult( ); if( Count == 0 ) QueueChatCommand( m_GHost->m_Language->ThereAreNoAdmins( m_Server ), i->first, !i->first.empty( ) ); else if( Count == 1 ) QueueChatCommand( m_GHost->m_Language->ThereIsAdmin( m_Server ), i->first, !i->first.empty( ) ); else QueueChatCommand( m_GHost->m_Language->ThereAreAdmins( m_Server, UTIL_ToString( Count ) ), i->first, !i->first.empty( ) ); m_GHost->m_DB->RecoverCallable( i->second ); delete i->second; i = m_PairedAdminCounts.erase( i ); } else i++; } for( vector<PairedAdminAdd> :: iterator i = m_PairedAdminAdds.begin( ); i != m_PairedAdminAdds.end( ); ) { if( i->second->GetReady( ) ) { if( i->second->GetResult( ) ) { AddAdmin( i->second->GetUser( ) ); QueueChatCommand( m_GHost->m_Language->AddedUserToAdminDatabase( m_Server, i->second->GetUser( ) ), i->first, !i->first.empty( ) ); } else QueueChatCommand( m_GHost->m_Language->ErrorAddingUserToAdminDatabase( m_Server, i->second->GetUser( ) ), i->first, !i->first.empty( ) ); m_GHost->m_DB->RecoverCallable( i->second ); delete i->second; i = m_PairedAdminAdds.erase( i ); } else i++; } for( vector<PairedAdminRemove> :: iterator i = m_PairedAdminRemoves.begin( ); i != m_PairedAdminRemoves.end( ); ) { if( i->second->GetReady( ) ) { if( i->second->GetResult( ) ) { RemoveAdmin( i->second->GetUser( ) ); QueueChatCommand( m_GHost->m_Language->DeletedUserFromAdminDatabase( m_Server, i->second->GetUser( ) ), i->first, !i->first.empty( ) ); } else QueueChatCommand( m_GHost->m_Language->ErrorDeletingUserFromAdminDatabase( m_Server, i->second->GetUser( ) ), i->first, !i->first.empty( ) ); m_GHost->m_DB->RecoverCallable( i->second ); delete i->second; i = m_PairedAdminRemoves.erase( i ); } else i++; } for( vector<PairedBanCount> :: iterator i = m_PairedBanCounts.begin( ); i != m_PairedBanCounts.end( ); ) { if( i->second->GetReady( ) ) { uint32_t Count = i->second->GetResult( ); if( Count == 0 ) QueueChatCommand( m_GHost->m_Language->ThereAreNoBannedUsers( m_Server ), i->first, !i->first.empty( ) ); else if( Count == 1 ) QueueChatCommand( m_GHost->m_Language->ThereIsBannedUser( m_Server ), i->first, !i->first.empty( ) ); else QueueChatCommand( m_GHost->m_Language->ThereAreBannedUsers( m_Server, UTIL_ToString( Count ) ), i->first, !i->first.empty( ) ); m_GHost->m_DB->RecoverCallable( i->second ); delete i->second; i = m_PairedBanCounts.erase( i ); } else i++; } for( vector<PairedBanAdd> :: iterator i = m_PairedBanAdds.begin( ); i != m_PairedBanAdds.end( ); ) { if( i->second->GetReady( ) ) { if( i->second->GetResult( ) ) { AddBan( i->second->GetUser( ), i->second->GetIP( ), i->second->GetGameName( ), i->second->GetAdmin( ), i->second->GetReason( ), i->second->GetIPBan() ); if (i->second->GetIPBan() == 0) QueueChatCommand( m_GHost->m_Language->BannedUser( i->second->GetServer( ), i->second->GetUser( ) ), i->first, !i->first.empty( ) ); else QueueChatCommand( m_GHost->m_Language->IPBannedUser( i->second->GetServer( ), i->second->GetUser( ), i->second->GetIP( ) ), i->first, !i->first.empty( ) ); } else QueueChatCommand( m_GHost->m_Language->ErrorBanningUser( i->second->GetServer( ), i->second->GetUser( ), i->second->GetIPBan() ), i->first, !i->first.empty( ) ); m_GHost->m_DB->RecoverCallable( i->second ); delete i->second; i = m_PairedBanAdds.erase( i ); } else i++; } for( vector<PairedRegisterPlayerAdd> :: iterator i = m_PairedRegisterPlayerAdds.begin( ); i != m_PairedRegisterPlayerAdds.end( ); ) { if( i->second->GetReady( ) ) { if( i->second->GetResult( ) > 1) { QueueChatCommand( "Your account [ " + i->second->GetUser() + " ] has been registered with e-mail [ " + i->second->GetMail() + " ] a mail with further instructions will be sent to you shortly!" , i->first, true ); } else if (i->second->GetResult( ) == 1) QueueChatCommand( "Your account [ " + i->second->GetUser() + " ] is already registered!", i->first, true); else { QueueChatCommand( "Something went terribly wrong..", i->first, true); CONSOLE_Print("[REGISTER] Error registering " + i->second->GetUser() + " with mail " + i->second->GetMail()); } m_GHost->m_DB->RecoverCallable( i->second ); delete i->second; i = m_PairedRegisterPlayerAdds.erase( i ); } else i++; } for( vector<PairedBanRemove> :: iterator i = m_PairedBanRemoves.begin( ); i != m_PairedBanRemoves.end( ); ) { if( i->second->GetReady( ) ) { if( i->second->GetResult( ) ) { RemoveBan( i->second->GetUser( ) ); QueueChatCommand( m_GHost->m_Language->UnbannedUser( i->second->GetUser( ) ), i->first, !i->first.empty( ) ); } else QueueChatCommand( m_GHost->m_Language->ErrorUnbanningUser( i->second->GetUser( ) ), i->first, !i->first.empty( ) ); m_GHost->m_DB->RecoverCallable( i->second ); delete i->second; i = m_PairedBanRemoves.erase( i ); } else i++; } for( vector<PairedGPSCheck> :: iterator i = m_PairedGPSChecks.begin( ); i != m_PairedGPSChecks.end( ); ) { if( i->second->GetReady( ) ) { CDBGamePlayerSummary *GamePlayerSummary = i->second->GetResult( ); if( GamePlayerSummary ) QueueChatCommand( m_GHost->m_Language->HasPlayedGamesWithThisBot( i->second->GetName( ), GamePlayerSummary->GetFirstGameDateTime( ), GamePlayerSummary->GetLastGameDateTime( ), UTIL_ToString( GamePlayerSummary->GetTotalGames( ) ), UTIL_ToString( (float)GamePlayerSummary->GetAvgLoadingTime( ) / 1000, 2 ), UTIL_ToString( GamePlayerSummary->GetAvgLeftPercent( ) ) ), i->first, !i->first.empty( ) ); else QueueChatCommand( m_GHost->m_Language->HasntPlayedGamesWithThisBot( i->second->GetName( ) ), i->first, !i->first.empty( ) ); m_GHost->m_DB->RecoverCallable( i->second ); delete i->second; i = m_PairedGPSChecks.erase( i ); } else i++; } for( vector<PairedDPSCheck> :: iterator i = m_PairedDPSChecks.begin( ); i != m_PairedDPSChecks.end( ); ) { if( i->second->GetReady( ) ) { CDBDotAPlayerSummary *DotAPlayerSummary = i->second->GetResult( ); if( DotAPlayerSummary ) { string Summary = m_GHost->m_Language->HasPlayedDotAGamesWithThisBot( i->second->GetName( ), UTIL_ToString( DotAPlayerSummary->GetTotalGames( ) ), UTIL_ToString( DotAPlayerSummary->GetTotalWins( ) ), UTIL_ToString( DotAPlayerSummary->GetTotalLosses( ) ), UTIL_ToString( DotAPlayerSummary->GetTotalKills( ) ), UTIL_ToString( DotAPlayerSummary->GetTotalDeaths( ) ), UTIL_ToString( DotAPlayerSummary->GetTotalCreepKills( ) ), UTIL_ToString( DotAPlayerSummary->GetTotalCreepDenies( ) ), UTIL_ToString( DotAPlayerSummary->GetTotalAssists( ) ), UTIL_ToString( DotAPlayerSummary->GetTotalNeutralKills( ) ), UTIL_ToString( DotAPlayerSummary->GetTotalTowerKills( ) ), UTIL_ToString( DotAPlayerSummary->GetTotalRaxKills( ) ), UTIL_ToString( DotAPlayerSummary->GetTotalCourierKills( ) ), UTIL_ToString( DotAPlayerSummary->GetAvgKills( ), 2 ), UTIL_ToString( DotAPlayerSummary->GetAvgDeaths( ), 2 ), UTIL_ToString( DotAPlayerSummary->GetAvgCreepKills( ), 2 ), UTIL_ToString( DotAPlayerSummary->GetAvgCreepDenies( ), 2 ), UTIL_ToString( DotAPlayerSummary->GetAvgAssists( ), 2 ), UTIL_ToString( DotAPlayerSummary->GetAvgNeutralKills( ), 2 ), UTIL_ToString( DotAPlayerSummary->GetAvgTowerKills( ), 2 ), UTIL_ToString( DotAPlayerSummary->GetAvgRaxKills( ), 2 ), UTIL_ToString( DotAPlayerSummary->GetAvgCourierKills( ), 2 ) ); uint32_t rank = DotAPlayerSummary->GetRank( ); if (rank > 0) Summary += " Rank: #" + UTIL_ToString(rank) + " with " + UTIL_ToString(DotAPlayerSummary->GetScore(), 2) + " points."; else Summary += " Rank: Unranked"; uint32_t streak = DotAPlayerSummary->GetStreak(); if (streak > 1) Summary += " Win streak: " + UTIL_ToString(streak); QueueChatCommand( Summary, i->first, !i->first.empty( ) ); } else QueueChatCommand( m_GHost->m_Language->HasntPlayedDotAGamesWithThisBot( i->second->GetName( ) ), i->first, !i->first.empty( ) ); m_GHost->m_DB->RecoverCallable( i->second ); delete i->second; i = m_PairedDPSChecks.erase( i ); } else i++; } // refresh the admin list every 5 minutes if( !m_CallableAdminList && GetTime( ) >= m_LastAdminRefreshTime + 300 ) m_CallableAdminList = m_GHost->m_DB->ThreadedAdminList( m_Server ); if( m_CallableAdminList && m_CallableAdminList->GetReady( ) ) { // CONSOLE_Print( "[BNET: " + m_ServerAlias + "] refreshed admin list (" + UTIL_ToString( m_Admins.size( ) ) + " -> " + UTIL_ToString( m_CallableAdminList->GetResult( ).size( ) ) + " admins)" ); m_Admins = m_CallableAdminList->GetResult( ); m_GHost->m_DB->RecoverCallable( m_CallableAdminList ); delete m_CallableAdminList; m_CallableAdminList = NULL; m_LastAdminRefreshTime = GetTime( ); } // refresh the ban list every 60 minutes // NordicLeague: changed to every 5 minutes to make temporary bans more accurate if( !m_CallableBanList && GetTime( ) >= m_LastBanRefreshTime + 360 ) m_CallableBanList = m_GHost->m_DB->ThreadedBanList( m_Server ); if( m_CallableBanList && m_CallableBanList->GetReady( ) ) { if (m_GHost->m_Debug) CONSOLE_Print( "[DEBUG][BNET: " + m_ServerAlias + "] refreshed ban list (" + UTIL_ToString( m_Bans.size( ) ) + " -> " + UTIL_ToString( m_CallableBanList->GetResult( ).size( ) ) + " bans)" ); for( vector<CDBBan *> :: iterator i = m_Bans.begin( ); i != m_Bans.end( ); i++ ) delete *i; m_Bans = m_CallableBanList->GetResult( ); m_GHost->m_DB->RecoverCallable( m_CallableBanList ); delete m_CallableBanList; m_CallableBanList = NULL; m_LastBanRefreshTime = GetTime( ); } // we return at the end of each if statement so we don't have to deal with errors related to the order of the if statements // that means it might take a few ms longer to complete a task involving multiple steps (in this case, reconnecting) due to blocking or sleeping // but it's not a big deal at all, maybe 100ms in the worst possible case (based on a 50ms blocking time) if( m_Socket->HasError( ) ) { // the socket has an error CONSOLE_Print( "[BNET: " + m_ServerAlias + "] disconnected from battle.net due to socket error" ); CONSOLE_Print( "[BNET: " + m_ServerAlias + "] waiting 90 seconds to reconnect" ); m_GHost->EventBNETDisconnected( this ); delete m_BNLSClient; m_BNLSClient = NULL; m_BNCSUtil->Reset( m_UserName, m_UserPassword ); m_Socket->Reset( ); m_NextConnectTime = GetTime( ) + 90; m_LoggedIn = false; m_InChat = false; m_WaitingToConnect = true; return m_Exiting; } if( !m_Socket->GetConnecting( ) && !m_Socket->GetConnected( ) && !m_WaitingToConnect ) { // the socket was disconnected CONSOLE_Print( "[BNET: " + m_ServerAlias + "] disconnected from battle.net due to socket not connected" ); CONSOLE_Print( "[BNET: " + m_ServerAlias + "] waiting 90 seconds to reconnect" ); m_GHost->EventBNETDisconnected( this ); delete m_BNLSClient; m_BNLSClient = NULL; m_BNCSUtil->Reset( m_UserName, m_UserPassword ); m_Socket->Reset( ); m_NextConnectTime = GetTime( ) + 90; m_LoggedIn = false; m_InChat = false; m_WaitingToConnect = true; return m_Exiting; } if( m_Socket->GetConnected( ) ) { // the socket is connected and everything appears to be working properly m_Socket->DoRecv( (fd_set *)fd ); ExtractPackets( ); ProcessPackets( ); // update the BNLS client if( m_BNLSClient ) { if( m_BNLSClient->Update( fd, send_fd ) ) { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] deleting BNLS client" ); delete m_BNLSClient; m_BNLSClient = NULL; } else { BYTEARRAY WardenResponse = m_BNLSClient->GetWardenResponse( ); if( !WardenResponse.empty( ) ) m_Socket->PutBytes( m_Protocol->SEND_SID_WARDEN( WardenResponse ) ); } } // check if at least one packet is waiting to be sent and if we've waited long enough to prevent flooding // this formula has changed many times but currently we wait 1 second if the last packet was "small", 3.5 seconds if it was "medium", and 4 seconds if it was "big" uint32_t WaitTicks = 0; if( m_LastOutPacketSize < 10 ) WaitTicks = 1000; else if( m_LastOutPacketSize < 100 ) WaitTicks = 2000; else WaitTicks = 3000; if( !m_OutPackets.empty( ) && GetTicks( ) >= m_LastOutPacketTicks + WaitTicks ) { if( m_OutPackets.size( ) > 7 ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] packet queue warning - there are " + UTIL_ToString( m_OutPackets.size( ) ) + " packets waiting to be sent" ); m_Socket->PutBytes( m_OutPackets.front( ) ); m_LastOutPacketSize = m_OutPackets.front( ).size( ); m_OutPackets.pop( ); m_LastOutPacketTicks = GetTicks( ); } // send a null packet every 60 seconds to detect disconnects if( GetTime( ) >= m_LastNullTime + 60 && GetTicks( ) >= m_LastOutPacketTicks + 60000 ) { m_Socket->PutBytes( m_Protocol->SEND_SID_NULL( ) ); m_LastNullTime = GetTime( ); } m_Socket->DoSend( (fd_set *)send_fd ); return m_Exiting; } if( m_Socket->GetConnecting( ) ) { // we are currently attempting to connect to battle.net if( m_Socket->CheckConnect( ) ) { // the connection attempt completed CONSOLE_Print( "[BNET: " + m_ServerAlias + "] connected" ); m_GHost->EventBNETConnected( this ); m_Socket->PutBytes( m_Protocol->SEND_PROTOCOL_INITIALIZE_SELECTOR( ) ); m_Socket->PutBytes( m_Protocol->SEND_SID_AUTH_INFO( m_War3Version, m_CountryAbbrev, m_Country ) ); m_Socket->DoSend( (fd_set *)send_fd ); m_LastNullTime = GetTime( ); m_LastOutPacketTicks = GetTicks( ); while( !m_OutPackets.empty( ) ) m_OutPackets.pop( ); return m_Exiting; } else if( GetTime( ) >= m_NextConnectTime + 15 ) { // the connection attempt timed out (15 seconds) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] connect timed out" ); CONSOLE_Print( "[BNET: " + m_ServerAlias + "] waiting 90 seconds to reconnect" ); m_GHost->EventBNETConnectTimedOut( this ); m_Socket->Reset( ); m_NextConnectTime = GetTime( ) + 90; m_WaitingToConnect = true; return m_Exiting; } } if( !m_Socket->GetConnecting( ) && !m_Socket->GetConnected( ) && GetTime( ) >= m_NextConnectTime ) { // attempt to connect to battle.net CONSOLE_Print( "[BNET: " + m_ServerAlias + "] connecting to server [" + m_Server + "] on port 6112" ); m_GHost->EventBNETConnecting( this ); if( !m_GHost->m_BindAddress.empty( ) ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] attempting to bind to address [" + m_GHost->m_BindAddress + "]" ); if( m_ServerIP.empty( ) ) { m_Socket->Connect( m_GHost->m_BindAddress, m_Server, 6112 ); if( !m_Socket->HasError( ) ) { m_ServerIP = m_Socket->GetIPString( ); CONSOLE_Print( "[BNET: " + m_ServerAlias + "] resolved and cached server IP address " + m_ServerIP ); } } else { // use cached server IP address since resolving takes time and is blocking CONSOLE_Print( "[BNET: " + m_ServerAlias + "] using cached server IP address " + m_ServerIP ); m_Socket->Connect( m_GHost->m_BindAddress, m_ServerIP, 6112 ); } m_WaitingToConnect = false; return m_Exiting; } return m_Exiting; } void CBNET :: ExtractPackets( ) { // extract as many packets as possible from the socket's receive buffer and put them in the m_Packets queue string *RecvBuffer = m_Socket->GetBytes( ); BYTEARRAY Bytes = UTIL_CreateByteArray( (unsigned char *)RecvBuffer->c_str( ), RecvBuffer->size( ) ); // a packet is at least 4 bytes so loop as long as the buffer contains 4 bytes while( Bytes.size( ) >= 4 ) { // byte 0 is always 255 if( Bytes[0] == BNET_HEADER_CONSTANT ) { // bytes 2 and 3 contain the length of the packet uint16_t Length = UTIL_ByteArrayToUInt16( Bytes, false, 2 ); if( Length >= 4 ) { if( Bytes.size( ) >= Length ) { m_Packets.push( new CCommandPacket( BNET_HEADER_CONSTANT, Bytes[1], BYTEARRAY( Bytes.begin( ), Bytes.begin( ) + Length ) ) ); *RecvBuffer = RecvBuffer->substr( Length ); Bytes = BYTEARRAY( Bytes.begin( ) + Length, Bytes.end( ) ); } else return; } else { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] error - received invalid packet from battle.net (bad length), disconnecting" ); m_Socket->Disconnect( ); return; } } else { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] error - received invalid packet from battle.net (bad header constant), disconnecting" ); m_Socket->Disconnect( ); return; } } } void CBNET :: ProcessPackets( ) { CIncomingGameHost *GameHost = NULL; CIncomingChatEvent *ChatEvent = NULL; BYTEARRAY WardenData; vector<CIncomingFriendList *> Friends; vector<CIncomingClanList *> Clans; // process all the received packets in the m_Packets queue // this normally means sending some kind of response while( !m_Packets.empty( ) ) { CCommandPacket *Packet = m_Packets.front( ); m_Packets.pop( ); if( Packet->GetPacketType( ) == BNET_HEADER_CONSTANT ) { switch( Packet->GetID( ) ) { case CBNETProtocol :: SID_NULL: // warning: we do not respond to NULL packets with a NULL packet of our own // this is because PVPGN servers are programmed to respond to NULL packets so it will create a vicious cycle of useless traffic // official battle.net servers do not respond to NULL packets m_Protocol->RECEIVE_SID_NULL( Packet->GetData( ) ); break; case CBNETProtocol :: SID_GETADVLISTEX: GameHost = m_Protocol->RECEIVE_SID_GETADVLISTEX( Packet->GetData( ) ); if( GameHost ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] joining game [" + GameHost->GetGameName( ) + "]" ); delete GameHost; GameHost = NULL; break; case CBNETProtocol :: SID_ENTERCHAT: if( m_Protocol->RECEIVE_SID_ENTERCHAT( Packet->GetData( ) ) ) { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] joining channel [" + m_FirstChannel + "]" ); m_InChat = true; m_Socket->PutBytes( m_Protocol->SEND_SID_JOINCHANNEL( m_FirstChannel ) ); } break; case CBNETProtocol :: SID_CHATEVENT: ChatEvent = m_Protocol->RECEIVE_SID_CHATEVENT( Packet->GetData( ) ); if( ChatEvent ) ProcessChatEvent( ChatEvent ); delete ChatEvent; ChatEvent = NULL; break; case CBNETProtocol :: SID_CHECKAD: m_Protocol->RECEIVE_SID_CHECKAD( Packet->GetData( ) ); break; case CBNETProtocol :: SID_STARTADVEX3: if( m_Protocol->RECEIVE_SID_STARTADVEX3( Packet->GetData( ) ) ) { m_InChat = false; m_GHost->EventBNETGameRefreshed( this ); } else { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] startadvex3 failed" ); m_GHost->EventBNETGameRefreshFailed( this ); } break; case CBNETProtocol :: SID_PING: m_Socket->PutBytes( m_Protocol->SEND_SID_PING( m_Protocol->RECEIVE_SID_PING( Packet->GetData( ) ) ) ); break; case CBNETProtocol :: SID_AUTH_INFO: if( m_Protocol->RECEIVE_SID_AUTH_INFO( Packet->GetData( ) ) ) { if( m_BNCSUtil->HELP_SID_AUTH_CHECK( m_GHost->m_Warcraft3Path, m_CDKeyROC, m_CDKeyTFT, m_Protocol->GetValueStringFormulaString( ), m_Protocol->GetIX86VerFileNameString( ), m_Protocol->GetClientToken( ), m_Protocol->GetServerToken( ) ) ) { // override the exe information generated by bncsutil if specified in the config file // apparently this is useful for pvpgn users if( m_EXEVersion.size( ) == 4 ) { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] using custom exe version bnet_custom_exeversion = " + UTIL_ToString( m_EXEVersion[0] ) + " " + UTIL_ToString( m_EXEVersion[1] ) + " " + UTIL_ToString( m_EXEVersion[2] ) + " " + UTIL_ToString( m_EXEVersion[3] ) ); m_BNCSUtil->SetEXEVersion( m_EXEVersion ); } if( m_EXEVersionHash.size( ) == 4 ) { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] using custom exe version hash bnet_custom_exeversionhash = " + UTIL_ToString( m_EXEVersionHash[0] ) + " " + UTIL_ToString( m_EXEVersionHash[1] ) + " " + UTIL_ToString( m_EXEVersionHash[2] ) + " " + UTIL_ToString( m_EXEVersionHash[3] ) ); m_BNCSUtil->SetEXEVersionHash( m_EXEVersionHash ); } m_Socket->PutBytes( m_Protocol->SEND_SID_AUTH_CHECK( m_Protocol->GetClientToken( ), m_BNCSUtil->GetEXEVersion( ), m_BNCSUtil->GetEXEVersionHash( ), m_BNCSUtil->GetKeyInfoROC( ), m_BNCSUtil->GetKeyInfoTFT( ), m_BNCSUtil->GetEXEInfo( ), "GHost" ) ); // the Warden seed is the first 4 bytes of the ROC key hash // initialize the Warden handler if( !m_BNLSServer.empty( ) ) { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] creating BNLS client" ); delete m_BNLSClient; m_BNLSClient = new CBNLSClient( m_BNLSServer, m_BNLSPort, m_BNLSWardenCookie ); m_BNLSClient->QueueWardenSeed( UTIL_ByteArrayToUInt32( m_BNCSUtil->GetKeyInfoROC( ), false, 16 ) ); } } else { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - bncsutil key hash failed (check your Warcraft 3 path and cd keys), disconnecting" ); m_Socket->Disconnect( ); delete Packet; return; } } break; case CBNETProtocol :: SID_AUTH_CHECK: if( m_Protocol->RECEIVE_SID_AUTH_CHECK( Packet->GetData( ) ) ) { // cd keys accepted CONSOLE_Print( "[BNET: " + m_ServerAlias + "] cd keys accepted" ); m_BNCSUtil->HELP_SID_AUTH_ACCOUNTLOGON( ); m_Socket->PutBytes( m_Protocol->SEND_SID_AUTH_ACCOUNTLOGON( m_BNCSUtil->GetClientKey( ), m_UserName ) ); } else { // cd keys not accepted switch( UTIL_ByteArrayToUInt32( m_Protocol->GetKeyState( ), false ) ) { case CBNETProtocol :: KR_ROC_KEY_IN_USE: CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - ROC CD key in use by user [" + m_Protocol->GetKeyStateDescription( ) + "], disconnecting" ); break; case CBNETProtocol :: KR_TFT_KEY_IN_USE: CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - TFT CD key in use by user [" + m_Protocol->GetKeyStateDescription( ) + "], disconnecting" ); break; case CBNETProtocol :: KR_OLD_GAME_VERSION: CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - game version is too old, disconnecting" ); break; case CBNETProtocol :: KR_INVALID_VERSION: CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - game version is invalid, disconnecting" ); break; default: CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - cd keys not accepted, disconnecting" ); break; } m_Socket->Disconnect( ); delete Packet; return; } break; case CBNETProtocol :: SID_AUTH_ACCOUNTLOGON: if( m_Protocol->RECEIVE_SID_AUTH_ACCOUNTLOGON( Packet->GetData( ) ) ) { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] username [" + m_UserName + "] accepted" ); if( m_PasswordHashType == "pvpgn" ) { // pvpgn logon CONSOLE_Print( "[BNET: " + m_ServerAlias + "] using pvpgn logon type (for pvpgn servers only)" ); m_BNCSUtil->HELP_PvPGNPasswordHash( m_UserPassword ); m_Socket->PutBytes( m_Protocol->SEND_SID_AUTH_ACCOUNTLOGONPROOF( m_BNCSUtil->GetPvPGNPasswordHash( ) ) ); } else { // battle.net logon CONSOLE_Print( "[BNET: " + m_ServerAlias + "] using battle.net logon type (for official battle.net servers only)" ); m_BNCSUtil->HELP_SID_AUTH_ACCOUNTLOGONPROOF( m_Protocol->GetSalt( ), m_Protocol->GetServerPublicKey( ) ); m_Socket->PutBytes( m_Protocol->SEND_SID_AUTH_ACCOUNTLOGONPROOF( m_BNCSUtil->GetM1( ) ) ); } } else { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - invalid username, disconnecting" ); m_Socket->Disconnect( ); delete Packet; return; } break; case CBNETProtocol :: SID_AUTH_ACCOUNTLOGONPROOF: if( m_Protocol->RECEIVE_SID_AUTH_ACCOUNTLOGONPROOF( Packet->GetData( ) ) ) { // logon successful CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon successful" ); m_LoggedIn = true; m_GHost->EventBNETLoggedIn( this ); m_Socket->PutBytes( m_Protocol->SEND_SID_NETGAMEPORT( m_GHost->m_HostPort ) ); m_Socket->PutBytes( m_Protocol->SEND_SID_ENTERCHAT( ) ); m_Socket->PutBytes( m_Protocol->SEND_SID_FRIENDSLIST( ) ); m_Socket->PutBytes( m_Protocol->SEND_SID_CLANMEMBERLIST( ) ); } else { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - invalid password, disconnecting" ); // try to figure out if the user might be using the wrong logon type since too many people are confused by this string Server = m_Server; transform( Server.begin( ), Server.end( ), Server.begin( ), (int(*)(int))tolower ); if( m_PasswordHashType == "pvpgn" && ( Server == "useast.battle.net" || Server == "uswest.battle.net" || Server == "asia.battle.net" || Server == "europe.battle.net" ) ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] it looks like you're trying to connect to a battle.net server using a pvpgn logon type, check your config file's \"battle.net custom data\" section" ); else if( m_PasswordHashType != "pvpgn" && ( Server != "useast.battle.net" && Server != "uswest.battle.net" && Server != "asia.battle.net" && Server != "europe.battle.net" ) ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] it looks like you're trying to connect to a pvpgn server using a battle.net logon type, check your config file's \"battle.net custom data\" section" ); m_Socket->Disconnect( ); delete Packet; return; } break; case CBNETProtocol :: SID_WARDEN: WardenData = m_Protocol->RECEIVE_SID_WARDEN( Packet->GetData( ) ); if( m_BNLSClient ) m_BNLSClient->QueueWardenRaw( WardenData ); else CONSOLE_Print( "[BNET: " + m_ServerAlias + "] warning - received warden packet but no BNLS server is available, you will be kicked from battle.net soon" ); break; case CBNETProtocol :: SID_FRIENDSLIST: Friends = m_Protocol->RECEIVE_SID_FRIENDSLIST( Packet->GetData( ) ); for( vector<CIncomingFriendList *> :: iterator i = m_Friends.begin( ); i != m_Friends.end( ); i++ ) delete *i; m_Friends = Friends; break; case CBNETProtocol :: SID_CLANMEMBERLIST: vector<CIncomingClanList *> Clans = m_Protocol->RECEIVE_SID_CLANMEMBERLIST( Packet->GetData( ) ); for( vector<CIncomingClanList *> :: iterator i = m_Clans.begin( ); i != m_Clans.end( ); i++ ) delete *i; m_Clans = Clans; break; } } delete Packet; } } void CBNET :: ProcessChatEvent( CIncomingChatEvent *chatEvent ) { CBNETProtocol :: IncomingChatEvent Event = chatEvent->GetChatEvent( ); bool Whisper = ( Event == CBNETProtocol :: EID_WHISPER ); string User = chatEvent->GetUser( ); string Message = chatEvent->GetMessage( ); if( Event == CBNETProtocol :: EID_WHISPER || Event == CBNETProtocol :: EID_TALK ) { if( Event == CBNETProtocol :: EID_WHISPER ) { CONSOLE_Print( "[WHISPER: " + m_ServerAlias + "] [" + User + "] " + Message ); m_GHost->EventBNETWhisper( this, User, Message ); } else { CONSOLE_Print( "[LOCAL: " + m_ServerAlias + "] [" + User + "] " + Message ); m_GHost->EventBNETChat( this, User, Message ); } // handle spoof checking for current game // this case covers whispers - we assume that anyone who sends a whisper to the bot with message "spoofcheck" should be considered spoof checked // note that this means you can whisper "spoofcheck" even in a public game to manually spoofcheck if the /whois fails if( Event == CBNETProtocol :: EID_WHISPER && m_GHost->m_CurrentGame ) { if( Message == "s" || Message == "sc" || Message == "spoof" || Message == "check" || Message == "spoofcheck" ) m_GHost->m_CurrentGame->AddToSpoofed( m_Server, User, true ); else if( Message.find( m_GHost->m_CurrentGame->GetGameName( ) ) != string :: npos ) { // look for messages like "entered a Warcraft III The Frozen Throne game called XYZ" // we don't look for the English part of the text anymore because we want this to work with multiple languages // it's a pretty safe bet that anyone whispering the bot with a message containing the game name is a valid spoofcheck if( m_PasswordHashType == "pvpgn" && User == m_PVPGNRealmName ) { // the equivalent pvpgn message is: [PvPGN Realm] Your friend abc has entered a Warcraft III Frozen Throne game named "xyz". vector<string> Tokens = UTIL_Tokenize( Message, ' ' ); if( Tokens.size( ) >= 3 ) m_GHost->m_CurrentGame->AddToSpoofed( m_Server, Tokens[2], false ); } else m_GHost->m_CurrentGame->AddToSpoofed( m_Server, User, false ); } } // handle bot commands if( !Message.empty( ) && Message[0] == m_CommandTrigger ) { // extract the command trigger, the command, and the payload // e.g. "!say hello world" -> command: "say", payload: "hello world" string Command; string Payload; string :: size_type PayloadStart = Message.find( " " ); if( PayloadStart != string :: npos ) { Command = Message.substr( 1, PayloadStart - 1 ); Payload = Message.substr( PayloadStart + 1 ); } else Command = Message.substr( 1 ); transform( Command.begin( ), Command.end( ), Command.begin( ), (int(*)(int))tolower ); if( IsAdmin( User ) || IsRootAdmin( User ) ) { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] admin [" + User + "] sent command [" + Message + "]" ); /***************** * ADMIN COMMANDS * ******************/ if ( Command == "disableff" ) { m_GHost->m_EnableFF = false; } if ( Command == "enableff" ) { m_GHost->m_EnableFF = true; } if ( Command == "debugon" ) { if( IsRootAdmin( User ) ) m_GHost->m_Debug = true; } if ( Command == "debugoff" ) { if( IsRootAdmin( User ) ) m_GHost->m_Debug = false; } if ( Command == "refreshbans" ) { if( IsRootAdmin( User ) ) { if (!m_CallableBanList) m_CallableBanList = m_GHost->m_DB->ThreadedBanList( m_Server ); } } // // !ADDADMIN // if( Command == "addadmin" && !Payload.empty( ) ) { if( IsRootAdmin( User ) ) { if( IsAdmin( Payload ) ) QueueChatCommand( m_GHost->m_Language->UserIsAlreadyAnAdmin( m_Server, Payload ), User, Whisper ); else m_PairedAdminAdds.push_back( PairedAdminAdd( Whisper ? User : string( ), m_GHost->m_DB->ThreadedAdminAdd( m_Server, Payload ) ) ); } else QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper ); } // // !ADDBAN // !BAN // !ipban // if( ( Command == "addban" || Command == "ban" || Command == "ipban" ) && !Payload.empty( ) ) { // extract the victim and the reason // e.g. "Varlock leaver after dying" -> victim: "Varlock", reason: "leaver after dying" bool IPBan = (Command == "ipban") ? true : false; string Victim; string Reason; stringstream SS; SS << Payload; SS >> Victim; if( !SS.eof( ) ) { getline( SS, Reason ); string :: size_type Start = Reason.find_first_not_of( " " ); if( Start != string :: npos ) Reason = Reason.substr( Start ); } if( IsBannedName( Victim ) ) { if (IPBan) { // We need to upgrade the regular ban to a ip-ban } QueueChatCommand( m_GHost->m_Language->UserIsAlreadyBanned( m_Server, Victim ), User, Whisper ); } else m_PairedBanAdds.push_back( PairedBanAdd( Whisper ? User : string( ), m_GHost->m_DB->ThreadedBanAdd( m_Server, Victim, string( ), string( ), User, Reason, 0, IPBan ? 1 : 0 ) ) ); } // // !TEMPBAN // !TBAN // if( ( Command == "tempban" || Command == "tban" ) && !Payload.empty( ) ) { // extract the victim and the reason // e.g. "Varlock leaver after dying" -> victim: "Varlock", reason: "leaver after dying" string Victim; string Reason; uint32_t Amount; uint32_t BanTime; string Suffix; stringstream SS; SS << Payload; SS >> Victim; if( SS.fail( ) || Victim.empty() ) CONSOLE_Print( "[TEMPBAN] bad input #1 to !TEMPBAN command" ); else { SS >> Amount; if( SS.fail( ) || Amount == 0 ) CONSOLE_Print( "[TEMPBAN] bad input #2 to !TEMPBAN command" ); else { SS >> Suffix; if (SS.fail() || Suffix.empty()) CONSOLE_Print( "[TEMPBAN] bad input #3 to autohost command" ); else { transform( Suffix.begin( ), Suffix.end( ), Suffix.begin( ), (int(*)(int))tolower ); // handle suffix // valid suffix is: hour, h, week, w, day, d, month, m bool ValidSuffix = false; if (Suffix == "minute" || Suffix == "minutes" || Suffix == "m") { BanTime = Amount * 3600; ValidSuffix = true; } else if (Suffix == "hour" || Suffix == "hours" || Suffix == "h") { BanTime = Amount * 3600; ValidSuffix = true; } else if (Suffix == "day" || Suffix == "days" || Suffix == "d") { BanTime = Amount * 86400; ValidSuffix = true; } else if (Suffix == "week" || Suffix == "weeks" || Suffix == "w") { BanTime = Amount * 604800; ValidSuffix = true; } else if (Suffix == "month" || Suffix == "months" || Suffix == "m") { BanTime = Amount * 2419200; ValidSuffix = true; } if (ValidSuffix) { if (!SS.eof()) { getline( SS, Reason ); string :: size_type Start = Reason.find_first_not_of( " " ); if( Start != string :: npos ) Reason = Reason.substr( Start ); } QueueChatCommand("Temporary ban: " + Victim + " for " + UTIL_ToString(Amount) + " " + Suffix + " with reason: " + Reason, User, Whisper); if( IsBannedName( Victim ) ) QueueChatCommand( m_GHost->m_Language->UserIsAlreadyBanned( m_Server, Victim ), User, Whisper ); else m_PairedBanAdds.push_back( PairedBanAdd( Whisper ? User : string( ), m_GHost->m_DB->ThreadedBanAdd( m_Server, Victim, string( ), string( ), User, Reason, BanTime, 0 ) ) ); } else { QueueChatCommand("Bad input, expected minute(s)/hour(s)/day(s)/week(s)/month(s), you said: " + Suffix, User, Whisper); } } } } } // // !ANNOUNCE // if( Command == "announce" && m_GHost->m_CurrentGame && !m_GHost->m_CurrentGame->GetCountDownStarted( ) ) { if( Payload.empty( ) || Payload == "off" ) { QueueChatCommand( m_GHost->m_Language->AnnounceMessageDisabled( ), User, Whisper ); m_GHost->m_CurrentGame->SetAnnounce( 0, string( ) ); } else { // extract the interval and the message // e.g. "30 hello everyone" -> interval: "30", message: "hello everyone" uint32_t Interval; string Message; stringstream SS; SS << Payload; SS >> Interval; if( SS.fail( ) || Interval == 0 ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #1 to announce command" ); else { if( SS.eof( ) ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] missing input #2 to announce command" ); else { getline( SS, Message ); string :: size_type Start = Message.find_first_not_of( " " ); if( Start != string :: npos ) Message = Message.substr( Start ); QueueChatCommand( m_GHost->m_Language->AnnounceMessageEnabled( ), User, Whisper ); m_GHost->m_CurrentGame->SetAnnounce( Interval, Message ); } } } } // // !AUTOHOST // if( Command == "autohost" ) { if( IsRootAdmin( User ) ) { if( Payload.empty( ) || Payload == "off" ) { QueueChatCommand( m_GHost->m_Language->AutoHostDisabled( ), User, Whisper ); m_GHost->m_AutoHostGameName.clear( ); m_GHost->m_AutoHostOwner.clear( ); m_GHost->m_AutoHostServer.clear( ); m_GHost->m_AutoHostMaximumGames = 0; m_GHost->m_AutoHostAutoStartPlayers = 0; m_GHost->m_LastAutoHostTime = GetTime( ); m_GHost->m_AutoHostMatchMaking = false; m_GHost->m_AutoHostMinimumScore = 0.0; m_GHost->m_AutoHostMaximumScore = 0.0; } else { // extract the maximum games, auto start players, and the game name // e.g. "5 10 BattleShips Pro" -> maximum games: "5", auto start players: "10", game name: "BattleShips Pro" uint32_t MaximumGames; uint32_t AutoStartPlayers; string GameName; stringstream SS; SS << Payload; SS >> MaximumGames; if( SS.fail( ) || MaximumGames == 0 ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #1 to autohost command" ); else { SS >> AutoStartPlayers; if( SS.fail( ) || AutoStartPlayers == 0 ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #2 to autohost command" ); else { if( SS.eof( ) ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] missing input #3 to autohost command" ); else { getline( SS, GameName ); string :: size_type Start = GameName.find_first_not_of( " " ); if( Start != string :: npos ) GameName = GameName.substr( Start ); QueueChatCommand( m_GHost->m_Language->AutoHostEnabled( ), User, Whisper ); delete m_GHost->m_AutoHostMap; m_GHost->m_AutoHostMap = new CMap( *m_GHost->m_Map ); m_GHost->m_AutoHostGameName = GameName; m_GHost->m_AutoHostOwner = User; m_GHost->m_AutoHostServer = m_Server; m_GHost->m_AutoHostMaximumGames = MaximumGames; m_GHost->m_AutoHostAutoStartPlayers = AutoStartPlayers; m_GHost->m_LastAutoHostTime = GetTime( ); m_GHost->m_AutoHostMatchMaking = false; m_GHost->m_AutoHostMinimumScore = 0.0; m_GHost->m_AutoHostMaximumScore = 0.0; } } } } } else QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper ); } // // !AUTOHOSTMM // if( Command == "autohostmm" ) { if( IsRootAdmin( User ) ) { if( Payload.empty( ) || Payload == "off" ) { QueueChatCommand( m_GHost->m_Language->AutoHostDisabled( ), User, Whisper ); m_GHost->m_AutoHostGameName.clear( ); m_GHost->m_AutoHostOwner.clear( ); m_GHost->m_AutoHostServer.clear( ); m_GHost->m_AutoHostMaximumGames = 0; m_GHost->m_AutoHostAutoStartPlayers = 0; m_GHost->m_LastAutoHostTime = GetTime( ); m_GHost->m_AutoHostMatchMaking = false; m_GHost->m_AutoHostMinimumScore = 0.0; m_GHost->m_AutoHostMaximumScore = 0.0; } else { // extract the maximum games, auto start players, minimum score, maximum score, and the game name // e.g. "5 10 800 1200 BattleShips Pro" -> maximum games: "5", auto start players: "10", minimum score: "800", maximum score: "1200", game name: "BattleShips Pro" uint32_t MaximumGames; uint32_t AutoStartPlayers; double MinimumScore; double MaximumScore; string GameName; stringstream SS; SS << Payload; SS >> MaximumGames; if( SS.fail( ) || MaximumGames == 0 ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #1 to autohostmm command" ); else { SS >> AutoStartPlayers; if( SS.fail( ) || AutoStartPlayers == 0 ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #2 to autohostmm command" ); else { SS >> MinimumScore; if( SS.fail( ) ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #3 to autohostmm command" ); else { SS >> MaximumScore; if( SS.fail( ) ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #4 to autohostmm command" ); else { if( SS.eof( ) ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] missing input #5 to autohostmm command" ); else { getline( SS, GameName ); string :: size_type Start = GameName.find_first_not_of( " " ); if( Start != string :: npos ) GameName = GameName.substr( Start ); QueueChatCommand( m_GHost->m_Language->AutoHostEnabled( ), User, Whisper ); delete m_GHost->m_AutoHostMap; m_GHost->m_AutoHostMap = new CMap( *m_GHost->m_Map ); m_GHost->m_AutoHostGameName = GameName; m_GHost->m_AutoHostOwner = User; m_GHost->m_AutoHostServer = m_Server; m_GHost->m_AutoHostMaximumGames = MaximumGames; m_GHost->m_AutoHostAutoStartPlayers = AutoStartPlayers; m_GHost->m_LastAutoHostTime = GetTime( ); m_GHost->m_AutoHostMatchMaking = true; m_GHost->m_AutoHostMinimumScore = MinimumScore; m_GHost->m_AutoHostMaximumScore = MaximumScore; } } } } } } } else QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper ); } // // !AUTOSTART // if( Command == "autostart" && m_GHost->m_CurrentGame && !m_GHost->m_CurrentGame->GetCountDownStarted( ) ) { if( Payload.empty( ) || Payload == "off" ) { QueueChatCommand( m_GHost->m_Language->AutoStartDisabled( ), User, Whisper ); m_GHost->m_CurrentGame->SetAutoStartPlayers( 0 ); } else { uint32_t AutoStartPlayers = UTIL_ToUInt32( Payload ); if( AutoStartPlayers != 0 ) { QueueChatCommand( m_GHost->m_Language->AutoStartEnabled( UTIL_ToString( AutoStartPlayers ) ), User, Whisper ); m_GHost->m_CurrentGame->SetAutoStartPlayers( AutoStartPlayers ); } } } // // !CHANNEL (change channel) // if( Command == "channel" && !Payload.empty( ) ) QueueChatCommand( "/join " + Payload ); // // !CHECKADMIN // if( Command == "checkadmin" && !Payload.empty( ) ) { if( IsRootAdmin( User ) ) { if( IsAdmin( Payload ) ) QueueChatCommand( m_GHost->m_Language->UserIsAnAdmin( m_Server, Payload ), User, Whisper ); else QueueChatCommand( m_GHost->m_Language->UserIsNotAnAdmin( m_Server, Payload ), User, Whisper ); } else QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper ); } // // !CHECKBAN // if( Command == "checkban" && !Payload.empty( ) ) { CDBBan *Ban = IsBannedName( Payload ); if( Ban ) { if (Ban->IsTemporary()) { if ( Ban->GetIPBan() ) QueueChatCommand( m_GHost->m_Language->UserWasIPBannedOnByBecauseTemp( m_Server, Payload, Ban->GetDate( ), Ban->GetAdmin( ), Ban->GetReason( ), Ban->GetIP(), Ban->GetExpires() ), User, Whisper ); else QueueChatCommand( m_GHost->m_Language->UserWasBannedOnByBecauseTemp( m_Server, Payload, Ban->GetDate( ), Ban->GetAdmin( ), Ban->GetReason( ), Ban->GetExpires() ), User, Whisper ); } else { if ( Ban->GetIPBan() ) QueueChatCommand( m_GHost->m_Language->UserWasIPBannedOnByBecause( m_Server, Payload, Ban->GetDate( ), Ban->GetAdmin( ), Ban->GetReason( ), Ban->GetIP() ), User, Whisper ); else QueueChatCommand( m_GHost->m_Language->UserWasBannedOnByBecause( m_Server, Payload, Ban->GetDate( ), Ban->GetAdmin( ), Ban->GetReason( ) ), User, Whisper ); } } else QueueChatCommand( m_GHost->m_Language->UserIsNotBanned( m_Server, Payload ), User, Whisper ); } // // !CLOSE (close slot) // if( Command == "close" && !Payload.empty( ) && m_GHost->m_CurrentGame ) { if( !m_GHost->m_CurrentGame->GetLocked( ) ) { // close as many slots as specified, e.g. "5 10" closes slots 5 and 10 stringstream SS; SS << Payload; while( !SS.eof( ) ) { uint32_t SID; SS >> SID; if( SS.fail( ) ) { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input to close command" ); break; } else m_GHost->m_CurrentGame->CloseSlot( (unsigned char)( SID - 1 ), true ); } } else QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper ); } // // !CLOSEALL // if( Command == "closeall" && m_GHost->m_CurrentGame ) { if( !m_GHost->m_CurrentGame->GetLocked( ) ) m_GHost->m_CurrentGame->CloseAllSlots( ); else QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper ); } // // !COOKIE // if( Command == "cookie" ) { if( !Payload.empty( ) ) { QueueChatCommand( Payload + " has been given a cookie.", User, Whisper ); CONSOLE_Print( "[BNET: " + m_Server + "] admin [" + User + "] gave [" + Payload + "] a cookie." ); QueueChatCommand( "/w " + Payload + " " + User + " gave you a cookie." ); } } // // !COUNTADMINS // if( Command == "countadmins" ) { if( IsRootAdmin( User ) ) m_PairedAdminCounts.push_back( PairedAdminCount( Whisper ? User : string( ), m_GHost->m_DB->ThreadedAdminCount( m_Server ) ) ); else QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper ); } // // !COUNTBANS // if( Command == "countbans" ) m_PairedBanCounts.push_back( PairedBanCount( Whisper ? User : string( ), m_GHost->m_DB->ThreadedBanCount( m_Server ) ) ); // // !DBSTATUS // if( Command == "dbstatus" ) QueueChatCommand( m_GHost->m_DB->GetStatus( ), User, Whisper ); // // !DELADMIN // if( Command == "deladmin" && !Payload.empty( ) ) { if( IsRootAdmin( User ) ) { if( !IsAdmin( Payload ) ) QueueChatCommand( m_GHost->m_Language->UserIsNotAnAdmin( m_Server, Payload ), User, Whisper ); else m_PairedAdminRemoves.push_back( PairedAdminRemove( Whisper ? User : string( ), m_GHost->m_DB->ThreadedAdminRemove( m_Server, Payload ) ) ); } else QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper ); } // // !DELBAN // !UNBAN // if( ( Command == "delban" || Command == "unban" ) && !Payload.empty( ) ) m_PairedBanRemoves.push_back( PairedBanRemove( Whisper ? User : string( ), m_GHost->m_DB->ThreadedBanRemove( Payload ) ) ); // // !DISABLE // if( Command == "disable" ) { if( IsRootAdmin( User ) ) { QueueChatCommand( m_GHost->m_Language->BotDisabled( ), User, Whisper ); m_GHost->m_Enabled = false; } else QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper ); } // // !DOWNLOADS // if( Command == "downloads" && !Payload.empty( ) ) { uint32_t Downloads = UTIL_ToUInt32( Payload ); if( Downloads == 0 ) { QueueChatCommand( m_GHost->m_Language->MapDownloadsDisabled( ), User, Whisper ); m_GHost->m_AllowDownloads = 0; } else if( Downloads == 1 ) { QueueChatCommand( m_GHost->m_Language->MapDownloadsEnabled( ), User, Whisper ); m_GHost->m_AllowDownloads = 1; } else if( Downloads == 2 ) { QueueChatCommand( m_GHost->m_Language->MapDownloadsConditional( ), User, Whisper ); m_GHost->m_AllowDownloads = 2; } } // // !ENABLE // if( Command == "enable" ) { if( IsRootAdmin( User ) ) { QueueChatCommand( m_GHost->m_Language->BotEnabled( ), User, Whisper ); m_GHost->m_Enabled = true; } else QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper ); } // // !END // if( Command == "end" && !Payload.empty( ) ) { // todotodo: what if a game ends just as you're typing this command and the numbering changes? uint32_t GameNumber = UTIL_ToUInt32( Payload ) - 1; if( GameNumber < m_GHost->m_Games.size( ) ) { QueueChatCommand( m_GHost->m_Language->EndingGame( m_GHost->m_Games[GameNumber]->GetDescription( ) ), User, Whisper ); CONSOLE_Print( "[GAME: " + m_GHost->m_Games[GameNumber]->GetGameName( ) + "] is over (admin ended game)" ); m_GHost->m_Games[GameNumber]->StopPlayers( "was disconnected (admin ended game)" ); } else QueueChatCommand( m_GHost->m_Language->GameNumberDoesntExist( Payload ), User, Whisper ); } // // !ENFORCESG // if( Command == "enforcesg" && !Payload.empty( ) ) { // only load files in the current directory just to be safe if( Payload.find( "/" ) != string :: npos || Payload.find( "\\" ) != string :: npos ) QueueChatCommand( m_GHost->m_Language->UnableToLoadReplaysOutside( ), User, Whisper ); else { string File = m_GHost->m_ReplayPath + Payload + ".w3g"; if( UTIL_FileExists( File ) ) { QueueChatCommand( m_GHost->m_Language->LoadingReplay( File ), User, Whisper ); CReplay *Replay = new CReplay( ); Replay->Load( File, false ); Replay->ParseReplay( false ); m_GHost->m_EnforcePlayers = Replay->GetPlayers( ); delete Replay; } else QueueChatCommand( m_GHost->m_Language->UnableToLoadReplayDoesntExist( File ), User, Whisper ); } } // // !EXIT // !QUIT // if( Command == "exit" || Command == "quit" ) { if( IsRootAdmin( User ) ) { if( Payload == "nice" ) m_GHost->m_ExitingNice = true; else if( Payload == "force" ) m_Exiting = true; else { if( m_GHost->m_CurrentGame || !m_GHost->m_Games.empty( ) ) QueueChatCommand( m_GHost->m_Language->AtLeastOneGameActiveUseForceToShutdown( ), User, Whisper ); else m_Exiting = true; } } else QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper ); } // // !GETCLAN // if( Command == "getclan" ) { SendGetClanList( ); QueueChatCommand( m_GHost->m_Language->UpdatingClanList( ), User, Whisper ); } // // !GETFRIENDS // if( Command == "getfriends" ) { SendGetFriendsList( ); QueueChatCommand( m_GHost->m_Language->UpdatingFriendsList( ), User, Whisper ); } // // !GETGAME // if( Command == "getgame" && !Payload.empty( ) ) { uint32_t GameNumber = UTIL_ToUInt32( Payload ) - 1; if( GameNumber < m_GHost->m_Games.size( ) ) QueueChatCommand( m_GHost->m_Language->GameNumberIs( Payload, m_GHost->m_Games[GameNumber]->GetDescription( ) ), User, Whisper ); else QueueChatCommand( m_GHost->m_Language->GameNumberDoesntExist( Payload ), User, Whisper ); } // // !GETGAMES // if( Command == "getgames" ) { if( m_GHost->m_CurrentGame ) QueueChatCommand( m_GHost->m_Language->GameIsInTheLobby( m_GHost->m_CurrentGame->GetDescription( ), UTIL_ToString( m_GHost->m_Games.size( ) ), UTIL_ToString( m_GHost->m_MaxGames ) ), User, Whisper ); else QueueChatCommand( m_GHost->m_Language->ThereIsNoGameInTheLobby( UTIL_ToString( m_GHost->m_Games.size( ) ), UTIL_ToString( m_GHost->m_MaxGames ) ), User, Whisper ); } // // !HOLD (hold a slot for someone) // if( Command == "hold" && !Payload.empty( ) && m_GHost->m_CurrentGame ) { // hold as many players as specified, e.g. "Varlock Kilranin" holds players "Varlock" and "Kilranin" stringstream SS; SS << Payload; while( !SS.eof( ) ) { string HoldName; SS >> HoldName; if( SS.fail( ) ) { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input to hold command" ); break; } else { QueueChatCommand( m_GHost->m_Language->AddedPlayerToTheHoldList( HoldName ), User, Whisper ); m_GHost->m_CurrentGame->AddToReserved( HoldName ); } } } // // !HOSTSG // if( Command == "hostsg" && !Payload.empty( ) ) m_GHost->CreateGame( m_GHost->m_Map, GAME_PRIVATE, true, Payload, User, User, m_Server, Whisper ); // // !LOADCFG (load config file using the old method) // if( Command == "loadcfg" ) { if( Payload.empty( ) ) QueueChatCommand( m_GHost->m_Language->CurrentlyLoadedMapCFGIs( m_GHost->m_Map->GetCFGFile( ) ), User, Whisper ); else { // only load files in the current directory just to be safe if( Payload.find( "/" ) != string :: npos || Payload.find( "\\" ) != string :: npos ) QueueChatCommand( m_GHost->m_Language->UnableToLoadConfigFilesOutside( ), User, Whisper ); else { string File = m_GHost->m_MapCFGPath + Payload + ".cfg"; if( UTIL_FileExists( File ) ) { // we have to be careful here because we didn't copy the map data when creating the game (there's only one global copy) // therefore if we change the map data while a game is in the lobby everything will get screwed up // the easiest solution is to simply reject the command if a game is in the lobby if( m_GHost->m_CurrentGame ) QueueChatCommand( m_GHost->m_Language->UnableToLoadConfigFileGameInLobby( ), User, Whisper ); else { QueueChatCommand( m_GHost->m_Language->LoadingConfigFile( File ), User, Whisper ); CConfig MapCFG; MapCFG.Read( File ); m_GHost->m_Map->Load( &MapCFG, File ); } } else QueueChatCommand( m_GHost->m_Language->UnableToLoadConfigFileDoesntExist( File ), User, Whisper ); } } } // // !LOAD (load config file) // if( Command == "load" ) { if( Payload.empty( ) ) QueueChatCommand( m_GHost->m_Language->CurrentlyLoadedMapCFGIs( m_GHost->m_Map->GetCFGFile( ) ), User, Whisper ); else { string FoundMapConfigs; try { path MapCFGPath( m_GHost->m_MapCFGPath ); boost :: regex Regex( Payload ); string Pattern = Payload; transform( Pattern.begin( ), Pattern.end( ), Pattern.begin( ), (int(*)(int))tolower ); if( !exists( MapCFGPath ) ) { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] error listing map configs - map config path doesn't exist" ); QueueChatCommand( m_GHost->m_Language->ErrorListingMapConfigs( ), User, Whisper ); } else { directory_iterator EndIterator; path LastMatch; uint32_t Matches = 0; for( directory_iterator i( MapCFGPath ); i != EndIterator; i++ ) { string FileName = i->filename( ); string Stem = i->path( ).stem( ); transform( FileName.begin( ), FileName.end( ), FileName.begin( ), (int(*)(int))tolower ); transform( Stem.begin( ), Stem.end( ), Stem.begin( ), (int(*)(int))tolower ); bool Matched = false; if( m_GHost->m_UseRegexes ) { if( boost :: regex_match( FileName, Regex ) ) Matched = true; } else if( FileName.find( Pattern ) != string :: npos ) Matched = true; if( !is_directory( i->status( ) ) && i->path( ).extension( ) == ".cfg" && Matched ) { LastMatch = i->path( ); Matches++; if( FoundMapConfigs.empty( ) ) FoundMapConfigs = i->filename( ); else FoundMapConfigs += ", " + i->filename( ); // if we aren't using regexes and the pattern matches the filename exactly, with or without extension, stop any further matching if( !m_GHost->m_UseRegexes && ( FileName == Pattern || Stem == Pattern ) ) { Matches = 1; break; } } } if( Matches == 0 ) QueueChatCommand( m_GHost->m_Language->NoMapConfigsFound( ), User, Whisper ); else if( Matches == 1 ) { string File = LastMatch.filename( ); QueueChatCommand( m_GHost->m_Language->LoadingConfigFile( m_GHost->m_MapCFGPath + File ), User, Whisper ); CConfig MapCFG; MapCFG.Read( LastMatch.string( ) ); m_GHost->m_Map->Load( &MapCFG, m_GHost->m_MapCFGPath + File ); } else QueueChatCommand( m_GHost->m_Language->FoundMapConfigs( FoundMapConfigs ), User, Whisper ); } } catch( const exception &ex ) { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] error listing map configs - caught exception [" + ex.what( ) + "]" ); QueueChatCommand( m_GHost->m_Language->ErrorListingMapConfigs( ), User, Whisper ); } } } // // !LOADSG // if( Command == "loadsg" && !Payload.empty( ) ) { // only load files in the current directory just to be safe if( Payload.find( "/" ) != string :: npos || Payload.find( "\\" ) != string :: npos ) QueueChatCommand( m_GHost->m_Language->UnableToLoadSaveGamesOutside( ), User, Whisper ); else { string File = m_GHost->m_SaveGamePath + Payload + ".w3z"; string FileNoPath = Payload + ".w3z"; if( UTIL_FileExists( File ) ) { if( m_GHost->m_CurrentGame ) QueueChatCommand( m_GHost->m_Language->UnableToLoadSaveGameGameInLobby( ), User, Whisper ); else { QueueChatCommand( m_GHost->m_Language->LoadingSaveGame( File ), User, Whisper ); m_GHost->m_SaveGame->Load( File, false ); m_GHost->m_SaveGame->ParseSaveGame( ); m_GHost->m_SaveGame->SetFileName( File ); m_GHost->m_SaveGame->SetFileNameNoPath( FileNoPath ); } } else QueueChatCommand( m_GHost->m_Language->UnableToLoadSaveGameDoesntExist( File ), User, Whisper ); } } // // !MAP (load map file) // if( Command == "map" ) { if( Payload.empty( ) ) QueueChatCommand( m_GHost->m_Language->CurrentlyLoadedMapCFGIs( m_GHost->m_Map->GetCFGFile( ) ), User, Whisper ); else { string FoundMaps; try { path MapPath( m_GHost->m_MapPath ); boost :: regex Regex( Payload ); string Pattern = Payload; transform( Pattern.begin( ), Pattern.end( ), Pattern.begin( ), (int(*)(int))tolower ); if( !exists( MapPath ) ) { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] error listing maps - map path doesn't exist" ); QueueChatCommand( m_GHost->m_Language->ErrorListingMaps( ), User, Whisper ); } else { directory_iterator EndIterator; path LastMatch; uint32_t Matches = 0; for( directory_iterator i( MapPath ); i != EndIterator; i++ ) { string FileName = i->filename( ); string Stem = i->path( ).stem( ); transform( FileName.begin( ), FileName.end( ), FileName.begin( ), (int(*)(int))tolower ); transform( Stem.begin( ), Stem.end( ), Stem.begin( ), (int(*)(int))tolower ); bool Matched = false; if( m_GHost->m_UseRegexes ) { if( boost :: regex_match( FileName, Regex ) ) Matched = true; } else if( FileName.find( Pattern ) != string :: npos ) Matched = true; if( !is_directory( i->status( ) ) && Matched ) { LastMatch = i->path( ); Matches++; if( FoundMaps.empty( ) ) FoundMaps = i->filename( ); else FoundMaps += ", " + i->filename( ); // if we aren't using regexes and the pattern matches the filename exactly, with or without extension, stop any further matching if( !m_GHost->m_UseRegexes && ( FileName == Pattern || Stem == Pattern ) ) { Matches = 1; break; } } } if( Matches == 0 ) QueueChatCommand( m_GHost->m_Language->NoMapsFound( ), User, Whisper ); else if( Matches == 1 ) { string File = LastMatch.filename( ); QueueChatCommand( m_GHost->m_Language->LoadingConfigFile( File ), User, Whisper ); // hackhack: create a config file in memory with the required information to load the map CConfig MapCFG; MapCFG.Set( "map_path", "Maps\\Download\\" + File ); MapCFG.Set( "map_localpath", File ); if (File.substr(0,4)=="DotA") { MapCFG.Set( "map_type", "dota" ); MapCFG.Set( "map_matchmakingcategory", "dota_elo" ); CONSOLE_Print("[MAP] set map_type = dota"); CONSOLE_Print("[MAP] set map_matchmakingcategory = dota_elo"); } m_GHost->m_Map->Load( &MapCFG, File ); } else QueueChatCommand( m_GHost->m_Language->FoundMaps( FoundMaps ), User, Whisper ); } } catch( const exception &ex ) { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] error listing maps - caught exception [" + ex.what( ) + "]" ); QueueChatCommand( m_GHost->m_Language->ErrorListingMaps( ), User, Whisper ); } } } // // !OPEN (open slot) // if( Command == "open" && !Payload.empty( ) && m_GHost->m_CurrentGame ) { if( !m_GHost->m_CurrentGame->GetLocked( ) ) { // open as many slots as specified, e.g. "5 10" opens slots 5 and 10 stringstream SS; SS << Payload; while( !SS.eof( ) ) { uint32_t SID; SS >> SID; if( SS.fail( ) ) { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input to open command" ); break; } else m_GHost->m_CurrentGame->OpenSlot( (unsigned char)( SID - 1 ), true ); } } else QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper ); } // // !OPENALL // if( Command == "openall" && m_GHost->m_CurrentGame ) { if( !m_GHost->m_CurrentGame->GetLocked( ) ) m_GHost->m_CurrentGame->OpenAllSlots( ); else QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper ); } // // !PRIV (host private game) // if( Command == "priv" && !Payload.empty( ) ) m_GHost->CreateGame( m_GHost->m_Map, GAME_PRIVATE, false, Payload, User, User, m_Server, Whisper ); // // !PRIVBY (host private game by other player) // if( Command == "privby" && !Payload.empty( ) ) { // extract the owner and the game name // e.g. "Varlock dota 6.54b arem ~~~" -> owner: "Varlock", game name: "dota 6.54b arem ~~~" string Owner; string GameName; string :: size_type GameNameStart = Payload.find( " " ); if( GameNameStart != string :: npos ) { Owner = Payload.substr( 0, GameNameStart ); GameName = Payload.substr( GameNameStart + 1 ); m_GHost->CreateGame( m_GHost->m_Map, GAME_PRIVATE, false, GameName, Owner, User, m_Server, Whisper ); } } // // !PRIVMM (host private matchmaking game) // if( Command == "privmm" && !Payload.empty( ) ) { m_GHost->CreateGame( m_GHost->m_Map, GAME_PRIVATE, false, Payload, User, User, m_Server, Whisper ); m_GHost->m_CurrentGame->SetMatchMaking( true ); m_GHost->m_CurrentGame->SetMinimumScore( 0 ); m_GHost->m_CurrentGame->SetMaximumScore( 10000 ); m_GHost->m_CurrentGame->SetAutoStartPlayers( 10 ); } // // !PRIVMMBY (host private matchmaking game by other player) // if( Command == "privmmby" && !Payload.empty( ) ) { // extract the owner and the game name // e.g. "Varlock dota 6.54b arem ~~~" -> owner: "Varlock", game name: "dota 6.54b arem ~~~" string Owner; string GameName; string :: size_type GameNameStart = Payload.find( " " ); if( GameNameStart != string :: npos ) { Owner = Payload.substr( 0, GameNameStart ); GameName = Payload.substr( GameNameStart + 1 ); m_GHost->CreateGame( m_GHost->m_Map, GAME_PRIVATE, false, GameName, Owner, User, m_Server, Whisper ); m_GHost->m_CurrentGame->SetMatchMaking( true ); m_GHost->m_CurrentGame->SetMinimumScore( 0 ); m_GHost->m_CurrentGame->SetMaximumScore( 10000 ); m_GHost->m_CurrentGame->SetAutoStartPlayers( 10 ); } } // // !AUTOBALANCE // if( Command == "autobalance") { // toggle autobalance if (m_GHost->m_EnforceBalance) { m_GHost->m_EnforceBalance = false; QueueChatCommand( "Autobalance: Off", User, Whisper ); } else { m_GHost->m_EnforceBalance = true; QueueChatCommand( "Autobalance: On", User, Whisper ); } CONSOLE_Print( "[BNET: " + m_ServerAlias + "] Autobalance set to [" + UTIL_ToString(m_GHost->m_EnforceBalance ? 1 : 0) + "]" ); } // // !reserveadmins // if( Command == "reserveadmins") { // toggle reserve admins if (m_GHost->m_AdminCanAlwaysJoin) { m_GHost->m_AdminCanAlwaysJoin = false; QueueChatCommand( "Reserve admins: Off", User, Whisper ); } else { m_GHost->m_AdminCanAlwaysJoin = true; QueueChatCommand( "Reserve admins: On", User, Whisper ); } CONSOLE_Print( "[BNET: " + m_ServerAlias + "] Reserve admins set to [" + UTIL_ToString(m_GHost->m_AdminCanAlwaysJoin ? 1 : 0) + "]" ); } // // !PUB (host public game) // if( Command == "pub" && !Payload.empty( ) ) m_GHost->CreateGame( m_GHost->m_Map, GAME_PUBLIC, false, Payload, User, User, m_Server, Whisper ); // // !PUBBY (host public game by other player) // if( Command == "pubby" && !Payload.empty( ) ) { // extract the owner and the game name // e.g. "Varlock dota 6.54b arem ~~~" -> owner: "Varlock", game name: "dota 6.54b arem ~~~" string Owner; string GameName; string :: size_type GameNameStart = Payload.find( " " ); if( GameNameStart != string :: npos ) { Owner = Payload.substr( 0, GameNameStart ); GameName = Payload.substr( GameNameStart + 1 ); m_GHost->CreateGame( m_GHost->m_Map, GAME_PUBLIC, false, GameName, Owner, User, m_Server, Whisper ); } } // // !RELOAD // if( Command == "reload" ) { if( IsRootAdmin( User ) ) { QueueChatCommand( m_GHost->m_Language->ReloadingConfigurationFiles( ), User, Whisper ); m_GHost->ReloadConfigs( ); } else QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper ); } // // !RELOADMAP // if( Command == "reloadmap" ) { if( IsRootAdmin( User ) ) { QueueChatCommand( "Reloading map and config... ", User, Whisper ); m_GHost->ReloadMap( ); } else QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper ); } // // !REQUEST // if( Command == "request" ) { if( !Payload.empty( ) ) { QueueChatCommand( "Your request for [" + Payload + "] has been submitted.", User, Whisper ); CONSOLE_RequestPrint( Payload,User ); CONSOLE_Print( "[BNET: " + m_Server + "] admin [" + User + "] requested [" + Payload + "]. It was added to request.log." ); } } // // !REPORT // if( Command == "report" ) { if( !Payload.empty( ) ) { QueueChatCommand( "Your report has been submitted. An administrator will view it soon.", User, Whisper ); CONSOLE_ReportPrint( Payload,User ); CONSOLE_Print( "[REPORT] admin [" + User + "] reported [" + Payload + "]. It was added to report.log." ); } } // // !SAY // if( Command == "say" && !Payload.empty( ) ) QueueChatCommand( Payload ); // // !SAYGAME // if( Command == "saygame" && !Payload.empty( ) ) { if( IsRootAdmin( User ) ) { // extract the game number and the message // e.g. "3 hello everyone" -> game number: "3", message: "hello everyone" uint32_t GameNumber; string Message; stringstream SS; SS << Payload; SS >> GameNumber; if( SS.fail( ) ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #1 to saygame command" ); else { if( SS.eof( ) ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] missing input #2 to saygame command" ); else { getline( SS, Message ); string :: size_type Start = Message.find_first_not_of( " " ); if( Start != string :: npos ) Message = Message.substr( Start ); if( GameNumber - 1 < m_GHost->m_Games.size( ) ) m_GHost->m_Games[GameNumber - 1]->SendAllChat( "ADMIN: " + Message ); else QueueChatCommand( m_GHost->m_Language->GameNumberDoesntExist( UTIL_ToString( GameNumber ) ), User, Whisper ); } } } else QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper ); } // // !SAYGAMES // if( Command == "saygames" && !Payload.empty( ) ) { if( IsRootAdmin( User ) ) { if( m_GHost->m_CurrentGame ) m_GHost->m_CurrentGame->SendAllChat( Payload ); for( vector<CBaseGame *> :: iterator i = m_GHost->m_Games.begin( ); i != m_GHost->m_Games.end( ); i++ ) (*i)->SendAllChat( "ADMIN: " + Payload ); } else QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper ); } // // SLAP COMMAND // if ( Command == "slap" && !Payload.empty( ) ) { string Victim; string Object; stringstream SS; SS << Payload; SS >> Victim; if( !SS.eof( ) ) { getline( SS, Object ); string :: size_type Start = Object.find_first_not_of( " " ); if( Start != string :: npos ) Object = Object.substr( Start ); } int RandomNumber = 5; srand((unsigned)time(0)); RandomNumber = (rand()%8); if ( Victim != User ) { if ( RandomNumber == 0 ) QueueChatCommand( User + " slaps " + Victim + " with a large trout." ); else if ( RandomNumber == 1 ) QueueChatCommand( User + " slaps " + Victim + " with a pink Macintosh." ); else if ( RandomNumber == 2 ) QueueChatCommand( User + " throws a Playstation 3 at " + Victim + "." ); else if ( RandomNumber == 3 ) QueueChatCommand( User + " drives a car over " + Victim + "." ); else if ( RandomNumber == 4 ) QueueChatCommand( User + " steals " + Victim + "'s cookies. mwahahah!" ); else if ( RandomNumber == 5 ) { QueueChatCommand( User + " washes " + Victim + "'s car. Oh, the irony!" ); } else if ( RandomNumber == 6 ) QueueChatCommand( User + " burns " + Victim + "'s house." ); else if ( RandomNumber == 7 ) QueueChatCommand( User + " finds " + Victim + "'s picture on uglypeople.com." ); } else { if ( RandomNumber == 0 ) QueueChatCommand( User + " slaps himself with a large trout." ); else if ( RandomNumber == 1 ) QueueChatCommand( User + " slaps himself with a pink Macintosh." ); else if ( RandomNumber == 2 ) QueueChatCommand( User + " throws a Playstation 3 at himself." ); else if ( RandomNumber == 3 ) QueueChatCommand( User + " drives a car over himself." ); else if ( RandomNumber == 4 ) QueueChatCommand( User + " steals his cookies. mwahahah!" ); else if ( RandomNumber == 5 ) { int Goatsex = rand(); string s; stringstream out; out << Goatsex; s = out.str(); QueueChatCommand( User + " searches yahoo.com for goatsex + " + User + ". " + s + " hits WEEE!" ); } else if ( RandomNumber == 6 ) QueueChatCommand( User + " burns his house." ); else if ( RandomNumber == 7 ) QueueChatCommand( User + " finds his picture on uglypeople.com." ); } } // // !SP // if( Command == "sp" && m_GHost->m_CurrentGame && !m_GHost->m_CurrentGame->GetCountDownStarted( ) ) { if( !m_GHost->m_CurrentGame->GetLocked( ) ) { m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->ShufflingPlayers( ) ); m_GHost->m_CurrentGame->ShuffleSlots( ); } else QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper ); } // // !START // if( Command == "start" && m_GHost->m_CurrentGame && !m_GHost->m_CurrentGame->GetCountDownStarted( ) && m_GHost->m_CurrentGame->GetNumHumanPlayers( ) > 0 ) { if( !m_GHost->m_CurrentGame->GetLocked( ) ) { // if the player sent "!start force" skip the checks and start the countdown // otherwise check that the game is ready to start if( Payload == "force" ) m_GHost->m_CurrentGame->StartCountDown( true ); else m_GHost->m_CurrentGame->StartCountDown( false ); } else QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper ); } // // !SWAP (swap slots) // if( Command == "swap" && !Payload.empty( ) && m_GHost->m_CurrentGame ) { if( !m_GHost->m_CurrentGame->GetLocked( ) ) { uint32_t SID1; uint32_t SID2; stringstream SS; SS << Payload; SS >> SID1; if( SS.fail( ) ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #1 to swap command" ); else { if( SS.eof( ) ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] missing input #2 to swap command" ); else { SS >> SID2; if( SS.fail( ) ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #2 to swap command" ); else m_GHost->m_CurrentGame->SwapSlots( (unsigned char)( SID1 - 1 ), (unsigned char)( SID2 - 1 ) ); } } } else QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper ); } // // !top10 // if( Command == "top10" ) { ifstream in; uint32_t Count = 0; string Line; Count = 0; Line = ""; in.open( "/home/ghost/ghost/league/top10.txt" ); if( !in.fail( ) ) { // don't print more than 1 line1 while( !in.eof( ) && Count < 2 ) { getline( in, Line ); if( !Line.empty( ) ) { QueueChatCommand( "Top10: " + Line, User, Whisper); //SendAllChat( Line ); } Count++; } in.close( ); } else { CONSOLE_Print( "[BNET: " + m_ServerAlias + "] Error opening league/top10.txt" ); } } // // !UNHOST // if( Command == "unhost" ) { if( m_GHost->m_CurrentGame ) { if( m_GHost->m_CurrentGame->GetCountDownStarted( ) ) QueueChatCommand( m_GHost->m_Language->UnableToUnhostGameCountdownStarted( m_GHost->m_CurrentGame->GetDescription( ) ), User, Whisper ); else { QueueChatCommand( m_GHost->m_Language->UnhostingGame( m_GHost->m_CurrentGame->GetDescription( ) ), User, Whisper ); m_GHost->m_CurrentGame->SetExiting( true ); } } else QueueChatCommand( m_GHost->m_Language->UnableToUnhostGameNoGameInLobby( ), User, Whisper ); } // // !WARDENSTATUS // if( Command == "wardenstatus" ) { if( m_BNLSClient ) QueueChatCommand( "WARDEN STATUS --- " + UTIL_ToString( m_BNLSClient->GetTotalWardenIn( ) ) + " requests received, " + UTIL_ToString( m_BNLSClient->GetTotalWardenOut( ) ) + " responses sent.", User, Whisper ); else QueueChatCommand( "WARDEN STATUS --- Not connected to BNLS server.", User, Whisper ); } if ( Command == "usenormalcountdown" && !Payload.empty( ) ) { if ( Payload == "on" ) { m_GHost->m_UseNormalCountDown = true; QueueChatCommand("Normal wc3 countdown enabled"); } else if ( Payload == "off" ) { m_GHost->m_UseNormalCountDown = false; QueueChatCommand("Normal wc3 countdown disabled"); } } // CUSTOM ADMIN COMMANDS /* // !CATS - list map categories if( Command == "cats" ) { string res, cats; DIR *pdir; struct dirent *pent; pdir = opendir( m_GHost->m_MapPath.c_str( ) ); if( !pdir ) QueueChatCommand( "Could not read map folder", User, Whisper ); else { while( pent = readdir( pdir ) ) { res = pent->d_name; if( res.find( "." ) == string :: npos ) cats += " " + res; } if( res == "" ) QueueChatCommand( "No map categories found", User, Whisper ); else QueueChatCommand( "Map categories:" + cats, User, Whisper ); } } // !DLOAD - dynamically load maps if( Command == "dload" ) { if( Payload.empty( ) ) QueueChatCommand( "You must at least specify a search term", User, Whisper ); else { string tmp, key, val, term, name = "tmp", type, res, dir, loc, mname[5]; int i = 0, index = 0, speed = 3, vis = 4, obs = 1, flags = 3, mapt = 9, extt = 1; string :: size_type pos; stringstream ss; ss << Payload; ss >> term; while( !ss.eof( ) ) { ss >> tmp; pos = tmp.find( "=" ); if( pos != string :: npos ) { key = tmp.substr( 0, pos ); val = tmp.substr( pos + 1 ); if( key == "name" ) name = val; else if( key == "speed" ) speed = atoi( val.c_str( ) ); else if( key == "vis" ) vis = atoi( val.c_str( ) ); else if( key == "obs" ) obs = atoi( val.c_str( ) ); else if( key == "flags" ) flags = atoi( val.c_str( ) ); else if( key == "type" ) type = val; } } DIR *pdir; pdir = opendir( m_GHost->m_MapPath.c_str( ) ); if( !pdir ) QueueChatCommand( "Could not read map folder", User, Whisper ); else { errno = 0; DIR *sdir; struct dirent *pent, *sent; transform( term.begin( ), term.end( ), term.begin( ), (int(*)(int))tolower ); while( ( pent = readdir( pdir ) ) && i < 5 ) { res = pent->d_name; transform( res.begin( ), res.end( ), res.begin( ), (int(*)(int))tolower ); if( res == "." || res == ".." || res == "static" ) continue; if( res.find( ".w3m" ) != string :: npos || res.find( ".w3x" ) != string :: npos ) { if( res.find( term ) != string :: npos ) { loc = ""; mapt = 1; extt = ( res.find( ".w3m" ) != string :: npos ) ? 1 : 2; mname[i] = pent->d_name; pos = mname[i].find( ".w3m" ); if( pos == string :: npos ) pos = mname[i].find( ".w3x" ); mname[i].replace( pos, 4, "" ); i++; } index++; } else if( res.find( "." ) == string :: npos ) { dir = m_GHost->m_MapPath + pent->d_name + "\\"; sdir = opendir( dir.c_str( ) ); if( sdir ) { errno = 0; while( ( sent = readdir( sdir ) ) && i < 5 ) { res = sent->d_name; transform( res.begin( ), res.end( ), res.begin( ), (int(*)(int))tolower ); if( res.find( ".w3m" ) != string :: npos || res.find( ".w3x" ) != string :: npos ) { if( res.find( term ) != string :: npos ) { loc = pent->d_name; loc += "\\"; mapt = ( loc == "melee" ) ? 9 : 1; extt = ( res.find( ".w3m" ) != string :: npos ) ? 1 : 2; mname[i] = sent->d_name; pos = mname[i].find( ".w3m" ); if( pos == string :: npos ) pos = mname[i].find( ".w3x" ); mname[i].replace( pos, 4, "" ); i++; } index++; } } } } } if( i == 0 ) QueueChatCommand( "No matches found for '" + term + "'" ); else if( i > 1 ) { string maps; maps = mname[0]; for( int I = 1; I < i; I++ ) maps += " - " + mname[I]; QueueChatCommand( UTIL_ToString( i ) + "+ matches: " + maps ); } else { string file = m_GHost->m_MapCFGPath + name + ".cfg"; ofstream tmpcfg; tmpcfg.open( file.c_str( ), ios :: trunc ); tmpcfg << "# automatically created map config" << endl << "# by DynMaps" << endl << "###########################" << endl << endl; tmpcfg << "map_path = Maps\\"; if( mapt == 1 ) tmpcfg << "Download\\"; else if( extt == 2 ) tmpcfg << "FrozenThrone\\"; tmpcfg << mname[0]; if( extt == 1 ) tmpcfg << ".w3m"; else tmpcfg << ".w3x"; tmpcfg << endl; tmpcfg << "map_speed = " << speed << endl; tmpcfg << "map_visibility = " << vis << endl; tmpcfg << "map_observers = " << obs << endl; tmpcfg << "map_flags = " << flags << endl; tmpcfg << "map_gametype = " << mapt << endl; tmpcfg << "map_type = " << type << endl; tmpcfg << "map_localpath = " << loc << mname[0]; if( extt == 1 ) tmpcfg << ".w3m"; else tmpcfg << ".w3x"; tmpcfg << endl; tmpcfg.close( ); //don't allow a map to be loaded if there is a game in the lobby if( m_GHost->m_CurrentGame ) QueueChatCommand( m_GHost->m_Language->UnableToLoadConfigFileGameInLobby( ), User, Whisper ); else { CConfig MapCFG; MapCFG.Read( file ); m_GHost->m_Map->Load( &MapCFG, file ); QueueChatCommand( "Map '" + mname[0] + "' [" + name + "] loaded" ); } } } } } // !RAND - random map if( Command == "rand" ) { if( Payload.find( "/" ) != string :: npos || Payload.find( "\\" ) != string :: npos || Payload == ".." ) QueueChatCommand( m_GHost->m_Language->UnableToLoadConfigFilesOutside( ) ); else { if( Payload == "melee" ) QueueChatCommand( "Melee maps can't be randomized yet", User, Whisper ); else { string path, file, res, dir = m_GHost->m_MapPath, AllFiles[1000]; int i = 0; DIR *pdir, *sdir; struct dirent *pent, *sent; if( !Payload.empty( ) ) { path = Payload + "\\"; dir += path; } pdir = opendir( dir.c_str( ) ); if( !pdir ) QueueChatCommand( "Invalid map category selected", User, Whisper ); else { errno = 0; while( ( pent = readdir( pdir ) ) && i < 1000 ) { res = pent->d_name; if( res.find( ".w3m" ) != string :: npos || res.find( ".w3x" ) != string :: npos ) { AllFiles[i] = pent->d_name; i++; } else if( res.find( "." ) == string :: npos ) { if( res == "melee" ) continue; dir = m_GHost->m_MapPath + pent->d_name + "\\"; sdir = opendir( dir.c_str( ) ); if( sdir ) { errno = 0; while( sent = readdir( sdir ) ) { res = sent->d_name; if( res.find( ".w3m" ) != string :: npos || res.find( ".w3x" ) != string :: npos ) { AllFiles[i] = pent->d_name; AllFiles[i] += "\\"; AllFiles[i] += sent->d_name; i++; } } } } } srand( time( NULL ) ); int I = rand( ) % ( i + 1 ); string :: size_type pos = AllFiles[I].find( "\\" ); if( pos != string :: npos ) { path += AllFiles[I].substr( 0, pos + 1 ); AllFiles[I].replace( 0, pos + 1, "" ); } string file = m_GHost->m_MapCFGPath + "tmp.cfg"; ofstream tmpcfg; tmpcfg.open( file.c_str( ), ios :: trunc ); tmpcfg << "# automatically created map config" << endl << "# by DynMaps" << endl << "###########################" << endl << endl; tmpcfg << "map_path = Maps\\Download\\" << AllFiles[I] << endl; tmpcfg << "map_speed = 3" << endl; tmpcfg << "map_visibility = 4" << endl; tmpcfg << "map_observers = 1" << endl; tmpcfg << "map_flags = 3" << endl; tmpcfg << "map_gametype = 1" << endl; tmpcfg << "map_type = " << endl; tmpcfg << "map_localpath = " << path << AllFiles[I] << endl; tmpcfg.close( ); pos = AllFiles[I].find( ".w3m" ); if( pos == string :: npos ) pos = AllFiles[I].find( ".w3x" ); AllFiles[I].replace( pos, 4, "" ); CConfig MapCFG; MapCFG.Read( file ); m_GHost->m_Map->Load( &MapCFG, file ); QueueChatCommand( "'" + AllFiles[I] + "' loaded out of " + UTIL_ToString( i ) + " maps" ); } } } } */ } else CONSOLE_Print( "[BNET: " + m_ServerAlias + "] non-admin [" + User + "] sent command [" + Message + "]" ); /********************* * NON ADMIN COMMANDS * *********************/ // don't respond to non admins if there are more than 3 messages already in the queue // this prevents malicious users from filling up the bot's chat queue and crippling the bot // in some cases the queue may be full of legitimate messages but we don't really care if the bot ignores one of these commands once in awhile // e.g. when several users join a game at the same time and cause multiple /whois messages to be queued at once if( IsAdmin( User ) || IsRootAdmin( User ) || ( m_PublicCommands && m_OutPackets.size( ) <= 3 ) ) { // // !STATS // if( Command == "stats" ) { string StatsUser = User; if( !Payload.empty( ) ) StatsUser = Payload; // check for potential abuse if( !StatsUser.empty( ) && StatsUser.size( ) < 16 && StatsUser[0] != '/' ) m_PairedGPSChecks.push_back( PairedGPSCheck( Whisper ? User : string( ), m_GHost->m_DB->ThreadedGamePlayerSummaryCheck( StatsUser ) ) ); } // // !STATSDOTA // if( Command == "statsdota" || Command == "sd" ) { string StatsUser = User; if( !Payload.empty( ) ) StatsUser = Payload; // check for potential abuse if( !StatsUser.empty( ) && StatsUser.size( ) < 16 && StatsUser[0] != '/' ) m_PairedDPSChecks.push_back( PairedDPSCheck( Whisper ? User : string( ), m_GHost->m_DB->ThreadedDotAPlayerSummaryCheck( StatsUser ) ) ); } // // !REGISTER // if( Command == "register" ) { string RegMail; string RegFile; string RegUser = User; if (!Whisper) { QueueChatCommand( "Usage: /w NordicOnlyBot2 !register [email protected]" , User, true); } else { if( !Payload.empty( ) ) RegMail = Payload; // check for potential abuse if (RegMail.empty()) QueueChatCommand( "No email adress specified! Usage: /w NordicOnlyBot2 !register [email protected]" , User, true ); else { boost::regex expression(m_GHost->m_RegisterEmailRegEx); if( boost :: regex_match( RegMail, expression ) ) m_PairedRegisterPlayerAdds.push_back( PairedRegisterPlayerAdd( User, m_GHost->m_DB->ThreadedRegisterPlayerAdd( User, RegMail, string() ) ) ); else QueueChatCommand( "Invalid email adress specified! Usage: /w NordicOnlyBot !register [email protected]" , User, true ); } } } // // !VERSION // if( Command == "version" ) { if( IsAdmin( User ) || IsRootAdmin( User ) ) QueueChatCommand( m_GHost->m_Language->VersionAdmin( m_GHost->m_Version ), User, Whisper ); else QueueChatCommand( m_GHost->m_Language->VersionNotAdmin( m_GHost->m_Version ), User, Whisper ); } } } } else if( Event == CBNETProtocol :: EID_CHANNEL ) { // keep track of current channel so we can rejoin it after hosting a game CONSOLE_Print( "[BNET: " + m_ServerAlias + "] joined channel [" + Message + "]" ); m_CurrentChannel = Message; } else if( Event == CBNETProtocol :: EID_INFO ) { CONSOLE_Print( "[INFO: " + m_ServerAlias + "] " + Message ); // extract the first word which we hope is the username // this is not necessarily true though since info messages also include channel MOTD's and such string UserName; string :: size_type Split = Message.find( " " ); if( Split != string :: npos ) UserName = Message.substr( 0, Split ); else UserName = Message.substr( 0 ); // handle spoof checking for current game // this case covers whois results which are used when hosting a public game (we send out a "/whois [player]" for each player) // at all times you can still /w the bot with "spoofcheck" to manually spoof check if( m_GHost->m_CurrentGame && m_GHost->m_CurrentGame->GetPlayerFromName( UserName, true ) ) { if( Message.find( "is away" ) != string :: npos ) m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofPossibleIsAway( UserName ) ); else if( Message.find( "is unavailable" ) != string :: npos ) m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofPossibleIsUnavailable( UserName ) ); else if( Message.find( "is refusing messages" ) != string :: npos ) m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofPossibleIsRefusingMessages( UserName ) ); else if( Message.find( "is using Warcraft III The Frozen Throne in the channel" ) != string :: npos ) m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofDetectedIsNotInGame( UserName ) ); else if( Message.find( "is using Warcraft III The Frozen Throne in channel" ) != string :: npos ) m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofDetectedIsNotInGame( UserName ) ); else if( Message.find( "is using Warcraft III The Frozen Throne in a private channel" ) != string :: npos ) m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofDetectedIsInPrivateChannel( UserName ) ); if( Message.find( "is using Warcraft III The Frozen Throne in game" ) != string :: npos || Message.find( "is using Warcraft III Frozen Throne and is currently in game" ) != string :: npos ) { // check both the current game name and the last game name against the /whois response // this is because when the game is rehosted, players who joined recently will be in the previous game according to battle.net // note: if the game is rehosted more than once it is possible (but unlikely) for a false positive because only two game names are checked if( Message.find( m_GHost->m_CurrentGame->GetGameName( ) ) != string :: npos || Message.find( m_GHost->m_CurrentGame->GetLastGameName( ) ) != string :: npos ) m_GHost->m_CurrentGame->AddToSpoofed( m_Server, UserName, false ); else m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofDetectedIsInAnotherGame( UserName ) ); } } } else if( Event == CBNETProtocol :: EID_ERROR ) CONSOLE_Print( "[ERROR: " + m_ServerAlias + "] " + Message ); else if( Event == CBNETProtocol :: EID_EMOTE ) { CONSOLE_Print( "[EMOTE: " + m_ServerAlias + "] [" + User + "] " + Message ); m_GHost->EventBNETEmote( this, User, Message ); } } void CBNET :: SendJoinChannel( string channel ) { if( m_LoggedIn && m_InChat ) m_Socket->PutBytes( m_Protocol->SEND_SID_JOINCHANNEL( channel ) ); } void CBNET :: SendGetFriendsList( ) { if( m_LoggedIn ) m_Socket->PutBytes( m_Protocol->SEND_SID_FRIENDSLIST( ) ); } void CBNET :: SendGetClanList( ) { if( m_LoggedIn ) m_Socket->PutBytes( m_Protocol->SEND_SID_CLANMEMBERLIST( ) ); } void CBNET :: QueueEnterChat( ) { if( m_LoggedIn ) m_OutPackets.push( m_Protocol->SEND_SID_ENTERCHAT( ) ); } void CBNET :: QueueChatCommand( string chatCommand ) { if( chatCommand.empty( ) ) return; if( m_LoggedIn ) { if( m_PasswordHashType == "pvpgn" && chatCommand.size( ) > m_MaxMessageLength ) chatCommand = chatCommand.substr( 0, m_MaxMessageLength ); if( chatCommand.size( ) > 255 ) chatCommand = chatCommand.substr( 0, 255 ); if( m_OutPackets.size( ) > 10 ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] attempted to queue chat command [" + chatCommand + "] but there are too many (" + UTIL_ToString( m_OutPackets.size( ) ) + ") packets queued, discarding" ); else { CONSOLE_Print( "[QUEUED: " + m_ServerAlias + "] " + chatCommand ); m_OutPackets.push( m_Protocol->SEND_SID_CHATCOMMAND( chatCommand ) ); } } } void CBNET :: QueueChatCommand( string chatCommand, string user, bool whisper ) { if( chatCommand.empty( ) ) return; // if whisper is true send the chat command as a whisper to user, otherwise just queue the chat command if( whisper ) QueueChatCommand( "/w " + user + " " + chatCommand ); else QueueChatCommand( chatCommand ); } void CBNET :: QueueGameCreate( unsigned char state, string gameName, string hostName, CMap *map, CSaveGame *savegame, uint32_t hostCounter ) { if( m_LoggedIn && map ) { if( !m_CurrentChannel.empty( ) ) m_FirstChannel = m_CurrentChannel; m_InChat = false; // a game creation message is just a game refresh message with upTime = 0 QueueGameRefresh( state, gameName, hostName, map, savegame, 0, hostCounter ); } } void CBNET :: QueueGameRefresh( unsigned char state, string gameName, string hostName, CMap *map, CSaveGame *saveGame, uint32_t upTime, uint32_t hostCounter ) { if( hostName.empty( ) ) { BYTEARRAY UniqueName = m_Protocol->GetUniqueName( ); hostName = string( UniqueName.begin( ), UniqueName.end( ) ); } if( m_LoggedIn && map ) { BYTEARRAY MapGameType; // construct a fixed host counter which will be used to identify players from this realm // the fixed host counter's 4 most significant bits will contain a 4 bit ID (0-15) // the rest of the fixed host counter will contain the 28 least significant bits of the actual host counter // since we're destroying 4 bits of information here the actual host counter should not be greater than 2^28 which is a reasonable assumption // when a player joins a game we can obtain the ID from the received host counter // note: LAN broadcasts use an ID of 0, battle.net refreshes use an ID of 1-10, the rest are unused uint32_t FixedHostCounter = ( hostCounter & 0x0FFFFFFF ) | ( m_HostCounterID << 28 ); // construct the correct SID_STARTADVEX3 packet if( saveGame ) { MapGameType.push_back( 0 ); MapGameType.push_back( 10 ); MapGameType.push_back( 0 ); MapGameType.push_back( 0 ); BYTEARRAY MapWidth; MapWidth.push_back( 0 ); MapWidth.push_back( 0 ); BYTEARRAY MapHeight; MapHeight.push_back( 0 ); MapHeight.push_back( 0 ); m_OutPackets.push( m_Protocol->SEND_SID_STARTADVEX3( state, MapGameType, map->GetMapGameFlags( ), MapWidth, MapHeight, gameName, hostName, upTime, "Save\\Multiplayer\\" + saveGame->GetFileNameNoPath( ), saveGame->GetMagicNumber( ), map->GetMapSHA1( ), FixedHostCounter ) ); } else { MapGameType.push_back( map->GetMapGameType( ) ); MapGameType.push_back( 32 ); MapGameType.push_back( 73 ); MapGameType.push_back( 0 ); m_OutPackets.push( m_Protocol->SEND_SID_STARTADVEX3( state, MapGameType, map->GetMapGameFlags( ), map->GetMapWidth( ), map->GetMapHeight( ), gameName, hostName, upTime, map->GetMapPath( ), map->GetMapCRC( ), map->GetMapSHA1( ), FixedHostCounter ) ); } } } void CBNET :: QueueGameUncreate( ) { if( m_LoggedIn ) m_OutPackets.push( m_Protocol->SEND_SID_STOPADV( ) ); } void CBNET :: UnqueuePackets( unsigned char type ) { queue<BYTEARRAY> Packets; uint32_t Unqueued = 0; while( !m_OutPackets.empty( ) ) { // todotodo: it's very inefficient to have to copy all these packets while searching the queue BYTEARRAY Packet = m_OutPackets.front( ); m_OutPackets.pop( ); if( Packet.size( ) >= 2 && Packet[1] == type ) Unqueued++; else Packets.push( Packet ); } m_OutPackets = Packets; if( Unqueued > 0 ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] unqueued " + UTIL_ToString( Unqueued ) + " packets of type " + UTIL_ToString( type ) ); } void CBNET :: UnqueueChatCommand( string chatCommand ) { // hackhack: this is ugly code // generate the packet that would be sent for this chat command // then search the queue for that exact packet BYTEARRAY PacketToUnqueue = m_Protocol->SEND_SID_CHATCOMMAND( chatCommand ); queue<BYTEARRAY> Packets; uint32_t Unqueued = 0; while( !m_OutPackets.empty( ) ) { // todotodo: it's very inefficient to have to copy all these packets while searching the queue BYTEARRAY Packet = m_OutPackets.front( ); m_OutPackets.pop( ); if( Packet == PacketToUnqueue ) Unqueued++; else Packets.push( Packet ); } m_OutPackets = Packets; if( Unqueued > 0 ) CONSOLE_Print( "[BNET: " + m_ServerAlias + "] unqueued " + UTIL_ToString( Unqueued ) + " chat command packets" ); } void CBNET :: UnqueueGameRefreshes( ) { UnqueuePackets( CBNETProtocol :: SID_STARTADVEX3 ); } bool CBNET :: IsAdmin( string name ) { transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower ); for( vector<string> :: iterator i = m_Admins.begin( ); i != m_Admins.end( ); i++ ) { if( *i == name ) return true; } return false; } bool CBNET :: IsModerator( string name ) { transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower ); for( vector<string> :: iterator i = m_Moderators.begin( ); i != m_Moderators.end( ); i++ ) { if( *i == name ) return true; } return false; } bool CBNET :: IsRootAdmin( string name ) { // m_RootAdmin was already transformed to lower case in the constructor transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower ); stringstream SS; string s; SS << m_RootAdmin; while( !SS.eof( ) ) { SS >> s; if (name == s) { return true; } } return false; } /* Removed code bool CBNET :: IsRootAdmin( string name ) { // m_RootAdmin was already transformed to lower case in the constructor transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower ); return name == m_RootAdmin ; } */ CDBBan *CBNET :: IsBannedName( string name ) { transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower ); // todotodo: optimize this - maybe use a map? for( vector<CDBBan *> :: iterator i = m_Bans.begin( ); i != m_Bans.end( ); i++ ) { if( (*i)->GetName( ) == name ) return *i; } return NULL; } CDBBan *CBNET :: IsBannedIP( string ip ) { // todotodo: optimize this - maybe use a map? for( vector<CDBBan *> :: iterator i = m_Bans.begin( ); i != m_Bans.end( ); i++ ) { if( (*i)->GetIP( ) == ip ) return *i; } return NULL; } void CBNET :: AddAdmin( string name ) { transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower ); m_Admins.push_back( name ); } void CBNET :: AddBan( string name, string ip, string gamename, string admin, string reason, bool ipban ) { transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower ); m_Bans.push_back( new CDBBan( m_Server, name, ip, "N/A", gamename, admin, reason, ipban ? 1 : 0 ) ); } void CBNET :: RemoveAdmin( string name ) { transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower ); for( vector<string> :: iterator i = m_Admins.begin( ); i != m_Admins.end( ); ) { if( *i == name ) i = m_Admins.erase( i ); else i++; } } void CBNET :: RemoveBan( string name ) { transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower ); for( vector<CDBBan *> :: iterator i = m_Bans.begin( ); i != m_Bans.end( ); ) { if( (*i)->GetName( ) == name ) i = m_Bans.erase( i ); else i++; } } void CBNET :: HoldFriends( CBaseGame *game ) { if( game ) { for( vector<CIncomingFriendList *> :: iterator i = m_Friends.begin( ); i != m_Friends.end( ); i++ ) game->AddToReserved( (*i)->GetAccount( ) ); } } void CBNET :: HoldClan( CBaseGame *game ) { if( game ) { for( vector<CIncomingClanList *> :: iterator i = m_Clans.begin( ); i != m_Clans.end( ); i++ ) game->AddToReserved( (*i)->GetName( ) ); } }
[ "fredrik.sigillet@4a4c9648-eef2-11de-9456-cf00f3bddd4e" ]
[ [ [ 1, 3408 ] ] ]
3f0c1c8c2ccba8033d9604520e4a6356e3d44394
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/GameEngine/Gfx/GUI/GuiWindowEvents.hpp
4a25dad69f832bef406a050ae7a4d1a59d4231f8
[]
no_license
andreparker/spiralengine
aea8b22491aaae4c14f1cdb20f5407a4fb725922
36a4942045f49a7255004ec968b188f8088758f4
refs/heads/master
2021-01-22T12:12:39.066832
2010-05-07T00:02:31
2010-05-07T00:02:31
33,547,546
0
0
null
null
null
null
UTF-8
C++
false
false
454
hpp
#ifndef GUI_WINDOW_EVENTS_HPP #define GUI_WINDOW_EVENTS_HPP #include "../../Core/Sp_DataTypes.hpp" namespace Spiral { namespace GUI { typedef enum { mouse_down = 1, mouse_up, mouse_hover, mouse_move, focus_gained, focus_lost, button_Press, char_input, data_changed }GuiWindowEvent; struct mouse_position { mouse_position( SpReal x_, SpReal y_ ): x(x_),y(y_){} SpReal x,y; }; } } #endif
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 34 ] ] ]
ca1f7b144ccb450ca3c3db5f6cb63de8ca865dff
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/nebula2/src/anim2/ncombinedanimation_main.cc
354e4af40b45f91d432b0352d22ed76eced41bbb
[]
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
4,349
cc
//------------------------------------------------------------------------------ // nmemoryanimation_main.cc // (C) 2003 RadonLabs GmbH //------------------------------------------------------------------------------ #include "anim2/ncombinedanimation.h" #include "kernel/nfileserver2.h" #include "kernel/nfile.h" #include "mathlib/quaternion.h" nNebulaClass(nCombinedAnimation, "nmemoryanimation"); //------------------------------------------------------------------------------ /** */ nCombinedAnimation::nCombinedAnimation() { // empty } //------------------------------------------------------------------------------ /** */ nCombinedAnimation::~nCombinedAnimation() { } //------------------------------------------------------------------------------ /** */ bool nCombinedAnimation::LoadResource() { bool success = false; success = nAnimation::LoadResource(); if (success) { this->SetState(Valid); }; return success; } //------------------------------------------------------------------------------ /** */ void nCombinedAnimation::UnloadResource() { if (!this->IsUnloaded()) { nAnimation::UnloadResource(); this->SetState(Unloaded); } } //------------------------------------------------------------------------------ /** */ void nCombinedAnimation::BeginAnims() { this->animPtrs.Clear(); }; //------------------------------------------------------------------------------ /** */ void nCombinedAnimation::AddAnim(nMemoryAnimation* animation) { this->animPtrs.Append(animation); }; //------------------------------------------------------------------------------ /** */ void nCombinedAnimation::EndAnims() { // calculate space needed int i,k; int numGroups = 0; int numKeys = 0; for (i = 0; i < this->animPtrs.Size(); i++) { numGroups += this->animPtrs[i]->GetNumGroups(); numKeys += this->animPtrs[i]->GetKeyArray().Size(); }; this->SetNumGroups(numGroups); this->keyArray.SetFixedSize(numKeys); // copy all data int currentGroup = 0; int currentKey = 0; int keyAnimOffset; for (i = 0; i < this->animPtrs.Size(); i++) { keyAnimOffset = currentKey; for (k = 0; k < this->animPtrs[i]->GetNumGroups(); k++) { nAnimation::Group &srcGroup = this->animPtrs[i]->GetGroupAt(k); nAnimation::Group &dstGroup = this->GetGroupAt(currentGroup); dstGroup.SetNumCurves(srcGroup.GetNumCurves()); dstGroup.SetStartKey(srcGroup.GetStartKey()); dstGroup.SetNumKeys(srcGroup.GetNumKeys()); dstGroup.SetKeyStride(srcGroup.GetKeyStride()); dstGroup.SetKeyTime(srcGroup.GetKeyTime()); dstGroup.SetLoopType(srcGroup.GetLoopType()); // copy curves int c; for (c = 0; c < srcGroup.GetNumCurves(); c++) { nAnimation::Curve &srcCurve = srcGroup.GetCurveAt(c); nAnimation::Curve &dstCurve = dstGroup.GetCurveAt(c); dstCurve.SetIpolType(srcCurve.GetIpolType()); int srcFirstKey = srcCurve.GetFirstKeyIndex(); if (srcFirstKey != -1) { // add offset srcFirstKey += keyAnimOffset; }; dstCurve.SetFirstKeyIndex(srcFirstKey); dstCurve.SetConstValue(srcCurve.GetConstValue()); dstCurve.SetIsAnimated(srcCurve.IsAnimated()); }; currentGroup++; }; // copy keys for (k = 0; k < this->animPtrs[i]->GetKeyArray().Size(); k++) { this->keyArray[currentKey] = this->animPtrs[i]->GetKeyArray().At(k); currentKey++; }; }; // lets print some stats int numg = this->GetNumGroups(); n_printf("Combined Animation Stats : %i Groups\n",numg); for (i = 0; i < numg; i++) { nAnimation::Group &group = this->GetGroupAt(i); n_printf("Group %i : Duration = %i, NumKeys = %i, StartKey = %i",i,group.GetDuration(),group.GetNumKeys(),group.GetStartKey()); n_printf("\n"); }; };
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 150 ] ] ]
45eb3cfd2f6d5bb870166e262e1bc56dae40ed44
0b55a33f4df7593378f58b60faff6bac01ec27f3
/Konstruct/Client/Dimensions/Projectile.cpp
8dae1b34012cbc282ade5d7a953905e1f79f2958
[]
no_license
RonOHara-GG/dimgame
8d149ffac1b1176432a3cae4643ba2d07011dd8e
bbde89435683244133dca9743d652dabb9edf1a4
refs/heads/master
2021-01-10T21:05:40.480392
2010-09-01T20:46:40
2010-09-01T20:46:40
32,113,739
1
0
null
null
null
null
UTF-8
C++
false
false
2,221
cpp
#include "StdAfx.h" #include "Projectile.h" #include "Grid.h" #include "Level.h" #include "Common/utility/kpuQuadTree.h" #include "Common/utility/kpuBoundingCapsule.h" Projectile::Projectile(ProjectileType eType, int iDamage,int iRange, DamageType eDamageType, Actor* pOwner, kpuVector vLocation, kpuVector vDir) { m_eProjectileType = eType; m_iDamage = iDamage; m_iRange = iRange; m_eDamageType = eDamageType; m_pOwner = pOwner; SetLocation(vLocation); m_vHeading = vDir; //assign speed switch(m_eProjectileType) { case ePT_Arrow: { m_fBaseSpeed = ARROW_SPEED; break; } } m_fRadius = 0.0f; } Projectile::Projectile(ProjectileType eType, int iDamage, int iRange, DamageType eDamageType, Actor* pOwner, kpuVector vLocation, kpuVector vDir, float fRadius, int iResist) { Projectile(eType, iDamage, iRange, eDamageType, pOwner, vLocation, vDir); m_fRadius = fRadius; m_iResistStr = iResist; } Projectile::~Projectile(void) { } bool Projectile::Update(float fGameTime) { if( m_fDistTraveled >= m_iRange ) return false; kpuVector vVelocity; kpuVector vOldLocation = GetLocation(); //move the arrow float fDist = fGameTime * m_fBaseSpeed; vVelocity += GetHeading() * fDist; m_fDistTraveled += fDist; //see what the arror hits and move it kpuBoundingCapsule capsule(vOldLocation, vOldLocation + vVelocity, m_fRadius); kpuCollisionData data = g_pGameState->GetLevel()->GetQuadTree()->GetClosestCollision(capsule); if( data.m_pObject && data.m_pObject != m_pOwner && data.m_pObject != m_pLastHit ) { if( data.m_pObject->HasFlag(ATTACKABLE) ) { Actor* pTarget = (Actor*)data.m_pObject; m_pLastHit = pTarget; pTarget->TakeDamage(m_iDamage, m_eDamageType); Impact(pTarget->GetLocation()); } else if( data.m_pObject->HasFlag(WALL) ) { if( data.m_fDist <= 0 ) return false; SetLocation(vOldLocation + (vVelocity * (data.m_fDist / data.m_fVelLength))); return true; } } SetLocation(vOldLocation + vVelocity); return true; } void Projectile::Impact(kpuVector vImpact) { switch(m_eProjectileType) { case ePT_Arrow: { break; } } }
[ "bflassing@0c57dbdb-4d19-7b8c-568b-3fe73d88484e" ]
[ [ [ 1, 96 ] ] ]
5a7868a26f6afea330d595c784926c9dac49abc2
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/ModelsC/RTTS/OSM.h
00082388719b035782edcadb46dc37460f89893f
[]
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
586
h
#ifndef _DMT_OSM_H #define _DMT_OSM_H //-- OSM.h ------------------------------------------------------------------ // // Common definitions for OSM library. //-- forward references ----------------------------------------------------- class ostream; // allow compilation without <iostream.h> //-- OSM library header files ----------------------------------------------- #include "OSM_math.h" #include "OSM_type.h" #include "OSM_stream.h" #include "OSM_crush.h" //-- end OSM.h -------------------------------------------------------------- #endif
[ [ [ 1, 22 ] ] ]
4de434b6ec8434b1af21fb892d1e0e3dfbc882d2
4d3983366ea8a2886629d9a39536f0cd05edd001
/src/main/string.cpp
fd326061fa5b19ccb30f4ccfeafbd8a48e301feb
[]
no_license
clteng5316/rodents
033a06d5ad11928425a40203a497ea95e98ce290
7be0702d0ad61d9a07295029ba77d853b87aba64
refs/heads/master
2021-01-10T13:05:13.757715
2009-08-07T14:46:13
2009-08-07T14:46:13
36,857,795
1
0
null
null
null
null
UTF-8
C++
false
false
7,297
cpp
// string.cpp #include "stdafx.h" #include "string.hpp" //============================================================================= void str::copy_trim(PWSTR dst, size_t dstlen, PCWSTR src) { while (*src && iswspace(*src)) { ++src; } wcscpy_s(dst, dstlen, src); for (size_t i = wcslen(dst); i > 0 && iswspace(dst[i - 1]); i--) dst[i - 1] = '\0'; } //============================================================================= namespace { inline bool eq(WCHAR lhs, WCHAR rhs) throw() { return ChrCmpI(lhs, rhs) == 0; } inline PCWSTR inc(PCWSTR s) throw() { return s + 1; } } bool MatchContainsI(PCWSTR pattern, PCWSTR text) throw() { return StrStrI(text, pattern) != null; } bool MatchPatternI(PCWSTR pattern, PCWSTR text) throw() { PCWSTR cp = 0; PCWSTR mp = 0; PCWSTR text_ = text; while (*text_ && *pattern != ';' && *pattern != '*') { if (!eq(*pattern, *text_) && (*pattern != '?')) return false; pattern = inc(pattern); text_ = inc(text_); } if (*pattern != ';') { while (*text_) { if (*pattern == '*') { pattern = inc(pattern); if (!*pattern || *pattern == ';') return true; mp = pattern; cp = inc(text_); } else if (eq(*pattern, *text_) || (*pattern == '?')) { pattern = inc(pattern); text_ = inc(text_); } else { pattern = mp; text_ = cp; cp = inc(cp); } } while (*pattern == '*') { pattern = inc(pattern); } } if (*pattern == ';') { return true; } if (*pattern) { mp = pattern; while ((*mp) && (*mp != ';')) { mp = inc(mp); } if (*mp == ';') { pattern = inc(mp); return MatchPatternI(pattern, text); } } return !*pattern; } // Japanese Kanji filter module // Portions Copyright (c) 2002, Atsuo Ishimoto. // Portions Copyright (c) 1995 - 2000 Haruhiko Okumura. // This function is based on pykf. #define iseuc(c) ((c) >= 0xa1 && (c) <= 0xfe) #define isgaiji1(c) ((c) >= 0xf0 && (c) <= 0xf9) #define isibmgaiji1(c) ((c) >= 0xfa && (c) <= 0xfc) #define issjis1(c) (((c) >= 0x81 && (c) <= 0x9f) || ((c) >= 0xe0 && (c) <= 0xef) || isgaiji1(c) || isibmgaiji1(c)) #define issjis2(c) ((c) >= 0x40 && (c) <= 0xfc && (c)!=0x7f) #define ishankana(c) ((c) >= 0xa0 && (c) <= 0xdf) #define isutf8_2byte(c) (0xc0 <= (c) && (c) <= 0xdf) #define isutf8_3byte(c) (0xe0 <= (c) && (c) <= 0xef) #define isutf8_trail(c) (0x80 <= (c) && (c) <= 0xbf) Encoding GetEncoding(PCSTR str, size_t len) { size_t i; int ascii, eucjp, sjis, utf8, bad_eucjp, bad_sjis, bad_utf8; int jis, hankana; const unsigned char* buf = (const unsigned char*)str; ascii = 1; bad_eucjp = eucjp = 0; bad_sjis = sjis = 0; bad_utf8 = utf8 = 0; jis = 0; // check BOM if (len >= 2) { if (buf[0] == 0xff && buf[1] == 0xfe) return ENCODING_UTF16_LE; else if (buf[0] == 0xfe && buf[1] == 0xff) return ENCODING_UTF16_BE; } if (len >= 3 && !memcmp(buf, "\xef\xbb\xbf", 3)) return ENCODING_UTF8_BOM; // check ENCODING_SJIS hankana = 0; for (i = 0; i < len; i++) { if (buf[i] >= 0x80) ascii = 0; if (buf[i] == 0x1b) jis = 1; if (buf[i] == 0x8e && i + 2 < len && buf[i + 2] == 0x8e && ishankana(buf[i + 1])) { bad_sjis += 1; } if (ishankana(buf[i])) { sjis += 0x10/2 - 1; hankana++; } else { if (hankana == 1) bad_sjis++; hankana = 0; if (issjis1(buf[i])) { if (i + 1 < len) { if (issjis2(buf[i + 1])) { sjis += 0x10; i++; } else bad_sjis += 0x100; } } else if (buf[i] >= 0x80) bad_sjis += 0x100; } } if (ascii) return jis ? ENCODING_JIS : ENCODING_ASCII; // check ENCODING_EUCJP - JP hankana = 0; for (i = 0; i < len; i++) { if (buf[i] == 0x8e) { if (i + 1 < len) { if (ishankana(buf[i + 1])) { eucjp += 10; i++; hankana++; } else bad_eucjp += 0x100; } } else { if (hankana == 1) bad_eucjp++; hankana = 0; if (iseuc(buf[i])) { if (i + 1 < len) { if (iseuc(buf[i + 1])) { i++; eucjp += 0x10; } else bad_eucjp += 0x100; } } else if (buf[i] == 0x8f) { if (i + 2 < len) { if (iseuc(buf[i + 1]) && iseuc(buf[i + 2])) { i += 2; eucjp += 0x10; } else bad_eucjp += 100; } } else if (buf[i] >= 0x80) bad_eucjp += 0x100; } } // check UTF-8 for (i = 0; i < len; i++) { if (isutf8_2byte(buf[i])) { if (i + 1 < len) { if (isutf8_trail(buf[i + 1])) { utf8 += 10; i++; } else bad_utf8 += 100; } } else if (isutf8_3byte(buf[i])) { if (i + 2 < len) { if (isutf8_trail(buf[i + 1]) && isutf8_trail(buf[i + 2])) { utf8 += 15; i += 2; } else bad_utf8 += 1000; } } else if (buf[i] >= 0x80) bad_utf8 += 1000; } if (sjis - bad_sjis > eucjp - bad_eucjp) { if (sjis - bad_sjis > utf8 - bad_utf8) return ENCODING_SJIS; else if (sjis - bad_sjis < utf8 - bad_utf8) return ENCODING_UTF8; } if (sjis - bad_sjis < eucjp - bad_eucjp) { if (eucjp - bad_eucjp > utf8 - bad_utf8) return ENCODING_EUCJP; else if (eucjp - bad_eucjp < utf8 - bad_utf8) return ENCODING_UTF8; } return ENCODING_UNKNOWN; } //============================================================================= void StringBuffer::append(WCHAR c) throw() { reserve(m_end + 1); m_buffer[m_end] = c; ++m_end; } void StringBuffer::append(PCWSTR data, size_t ln) throw() { if (ln == 0) return; size_t end = m_end; resize(m_end + ln); memcpy(m_buffer + end, data, ln * sizeof(WCHAR)); } void StringBuffer::append(PCWSTR data) throw() { append(data, wcslen(data)); } void StringBuffer::format(PCWSTR fmt, ...) throw() { WCHAR buffer[1024]; va_list args; va_start(args, fmt); vswprintf_s(buffer, fmt, args); va_end(args); append(buffer); } void StringBuffer::resize(size_t sz) throw() { reserve(sz); m_end = sz; } void StringBuffer::reserve(size_t capacity) throw() { if (m_max >= capacity) return; m_max *= 2; if (m_max < capacity) m_max = capacity; if (m_max < 16) m_max = 16; m_buffer = (PWSTR)realloc(m_buffer, m_max * sizeof(WCHAR)); } //============================================================================= RingBuffer::RingBuffer() { m_buffer = NULL; m_begin = m_end = m_max = 0; } RingBuffer::~RingBuffer() { free(m_buffer); } char* RingBuffer::resize(size_t len) { if (m_begin + len > m_max) { if (m_begin > len / 2) { size_t size = m_end - m_begin; memmove(m_buffer, m_buffer + m_begin, size); m_begin = 0; m_end = size; } if (m_begin + len > m_max) { m_max = max(m_begin + len, m_max * 3 / 2); m_buffer = (char*)realloc(m_buffer, m_max); } } m_end = m_begin + len; return m_buffer + m_begin; } void RingBuffer::shift(size_t len) { ASSERT(m_begin + len <= m_end); m_begin += len; }
[ "itagaki.takahiro@fad0b036-4cad-11de-8d8d-752d95cf3e3c" ]
[ [ [ 1, 377 ] ] ]
fcbe2b7ce6824aae91e9a85edadfd60dc16e8fc2
81e051c660949ac0e89d1e9cf286e1ade3eed16a
/quake3ce/code/q3_ui/ui_qmenu.cpp
2044c30f8fb4d783b082ad4c25cdd9879a4af3e9
[]
no_license
crioux/q3ce
e89c3b60279ea187a2ebcf78dbe1e9f747a31d73
5e724f55940ac43cb25440a65f9e9e12220c9ada
refs/heads/master
2020-06-04T10:29:48.281238
2008-11-16T15:00:38
2008-11-16T15:00:38
32,103,416
5
0
null
null
null
null
UTF-8
C++
false
false
39,081
cpp
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code 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. Quake III Arena source code 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 Foobar; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ // /********************************************************************** UI_QMENU.C Quake's menu framework system. **********************************************************************/ #include"ui_pch.h" sfxHandle_t menu_in_sound; sfxHandle_t menu_move_sound; sfxHandle_t menu_out_sound; sfxHandle_t menu_buzz_sound; sfxHandle_t menu_null_sound; sfxHandle_t weaponChangeSound; static qhandle_t sliderBar; static qhandle_t sliderButton_0; static qhandle_t sliderButton_1; vec4_t menu_text_color = {GFIXED_1, GFIXED_1, GFIXED_1, GFIXED_1}; vec4_t menu_dim_color = {GFIXED_0, GFIXED_0, GFIXED_0, GFIXED(0,75)}; vec4_t color_black = {GFIXED(0,00), GFIXED(0,00), GFIXED(0,00), GFIXED(1,00)}; vec4_t color_white = {GFIXED(1,00), GFIXED(1,00), GFIXED(1,00), GFIXED(1,00)}; vec4_t color_yellow = {GFIXED(1,00), GFIXED(1,00), GFIXED(0,00), GFIXED(1,00)}; vec4_t color_blue = {GFIXED(0,00), GFIXED(0,00), GFIXED(1,00), GFIXED(1,00)}; vec4_t color_lightOrange = {GFIXED(1,00), GFIXED(0,68), GFIXED(0,00), GFIXED(1,00) }; vec4_t color_orange = {GFIXED(1,00), GFIXED(0,43), GFIXED(0,00), GFIXED(1,00)}; vec4_t color_red = {GFIXED(1,00), GFIXED(0,00), GFIXED(0,00), GFIXED(1,00)}; vec4_t color_dim = {GFIXED(0,00), GFIXED(0,00), GFIXED(0,00), GFIXED(0,25)}; // current color scheme vec4_t pulse_color = {GFIXED(1,00), GFIXED(1,00), GFIXED(1,00), GFIXED(1,00)}; vec4_t text_color_disabled = {GFIXED(0,50), GFIXED(0,50), GFIXED(0,50), GFIXED(1,00)}; // light gray vec4_t text_color_normal = {GFIXED(1,00), GFIXED(0,43), GFIXED(0,00), GFIXED(1,00)}; // light orange vec4_t text_color_highlight = {GFIXED(1,00), GFIXED(1,00), GFIXED(0,00), GFIXED(1,00)}; // bright yellow vec4_t listbar_color = {GFIXED(1,00), GFIXED(0,43), GFIXED(0,00), GFIXED(0,30)}; // transluscent orange vec4_t text_color_status = {GFIXED(1,00), GFIXED(1,00), GFIXED(1,00), GFIXED(1,00)}; // bright white // action widget static void Action_Init( menuaction_s *a ); static void Action_Draw( menuaction_s *a ); // radio button widget static void RadioButton_Init( menuradiobutton_s *rb ); static void RadioButton_Draw( menuradiobutton_s *rb ); static sfxHandle_t RadioButton_Key( menuradiobutton_s *rb, int key ); // slider widget static void Slider_Init( menuslider_s *s ); static sfxHandle_t Slider_Key( menuslider_s *s, int key ); static void Slider_Draw( menuslider_s *s ); // spin control widget static void SpinControl_Init( menulist_s *s ); static void SpinControl_Draw( menulist_s *s ); static sfxHandle_t SpinControl_Key( menulist_s *l, int key ); // text widget static void Text_Init( menutext_s *b ); static void Text_Draw( menutext_s *b ); // scrolllist widget static void ScrollList_Init( menulist_s *l ); sfxHandle_t ScrollList_Key( menulist_s *l, int key ); // proportional text widget static void PText_Init( menutext_s *b ); static void PText_Draw( menutext_s *b ); // proportional banner text widget static void BText_Init( menutext_s *b ); static void BText_Draw( menutext_s *b ); /* ================= Text_Init ================= */ static void Text_Init( menutext_s *t ) { t->generic.flags |= QMF_INACTIVE; } /* ================= Text_Draw ================= */ static void Text_Draw( menutext_s *t ) { int x; int y; char buff[512]; gfixed* color; x = t->generic.x; y = t->generic.y; buff[0] = '\0'; // possible label if (t->generic.name) strcpy(buff,t->generic.name); // possible value if (t->string) strcat(buff,t->string); if (t->generic.flags & QMF_GRAYED) color = text_color_disabled; else color = t->color; UI_DrawString( x, y, buff, t->style, color ); } /* ================= BText_Init ================= */ static void BText_Init( menutext_s *t ) { t->generic.flags |= QMF_INACTIVE; } /* ================= BText_Draw ================= */ static void BText_Draw( menutext_s *t ) { int x; int y; gfixed* color; x = t->generic.x; y = t->generic.y; if (t->generic.flags & QMF_GRAYED) color = text_color_disabled; else color = t->color; UI_DrawBannerString( x, y, t->string, t->style, color ); } /* ================= PText_Init ================= */ static void PText_Init( menutext_s *t ) { int x; int y; int w; int h; gfixed sizeScale; sizeScale = UI_ProportionalSizeScale( t->style ); x = t->generic.x; y = t->generic.y; w = FIXED_TO_INT(MAKE_GFIXED(UI_ProportionalStringWidth( t->string )) * sizeScale); h = FIXED_TO_INT(GFIXED(PROP_HEIGHT,0) * sizeScale); if( t->generic.flags & QMF_RIGHT_JUSTIFY ) { x -= w; } else if( t->generic.flags & QMF_CENTER_JUSTIFY ) { x -= w / 2; } t->generic.left = x - FIXED_TO_INT(GFIXED(PROP_GAP_WIDTH,0) * sizeScale); t->generic.right = x + w + FIXED_TO_INT(GFIXED(PROP_GAP_WIDTH ,0)* sizeScale); t->generic.top = y; t->generic.bottom = y + h; } /* ================= PText_Draw ================= */ static void PText_Draw( menutext_s *t ) { int x; int y; gfixed * color; int style; x = t->generic.x; y = t->generic.y; if (t->generic.flags & QMF_GRAYED) color = text_color_disabled; else color = t->color; style = t->style; if( t->generic.flags & QMF_PULSEIFFOCUS ) { if( Menu_ItemAtCursor( t->generic.parent ) == t ) { style |= UI_PULSE; } else { style |= UI_INVERSE; } } UI_DrawProportionalString( x, y, t->string, style, color ); } /* ================= Bitmap_Init ================= */ void Bitmap_Init( menubitmap_s *b ) { int x; int y; int w; int h; x = b->generic.x; y = b->generic.y; w = b->width; h = b->height; if( w < 0 ) { w = -w; } if( h < 0 ) { h = -h; } if (b->generic.flags & QMF_RIGHT_JUSTIFY) { x = x - w; } else if (b->generic.flags & QMF_CENTER_JUSTIFY) { x = x - w/2; } b->generic.left = x; b->generic.right = x + w; b->generic.top = y; b->generic.bottom = y + h; b->shader = 0; b->focusshader = 0; } /* ================= Bitmap_Draw ================= */ void Bitmap_Draw( menubitmap_s *b ) { gfixed x; gfixed y; gfixed w; gfixed h; vec4_t tempcolor; gfixed* color; x = MAKE_GFIXED(b->generic.x); y = MAKE_GFIXED(b->generic.y); w = MAKE_GFIXED(b->width); h = MAKE_GFIXED(b->height); if (b->generic.flags & QMF_RIGHT_JUSTIFY) { x = x - w; } else if (b->generic.flags & QMF_CENTER_JUSTIFY) { x = x - w/GFIXED(2,0); } // used to refresh shader if (b->generic.name && !b->shader) { b->shader = _UI_trap_R_RegisterShaderNoMip( b->generic.name ); if (!b->shader && b->errorpic) b->shader = _UI_trap_R_RegisterShaderNoMip( b->errorpic ); } if (b->focuspic && !b->focusshader) b->focusshader = _UI_trap_R_RegisterShaderNoMip( b->focuspic ); if (b->generic.flags & QMF_GRAYED) { if (b->shader) { _UI_trap_R_SetColor( colorMdGrey ); UI_DrawHandlePic( x, y, w, h, b->shader ); _UI_trap_R_SetColor( NULL ); } } else { if (b->shader) UI_DrawHandlePic( x, y, w, h, b->shader ); // bk001204 - parentheses if ( ( (b->generic.flags & QMF_PULSE) || (b->generic.flags & QMF_PULSEIFFOCUS) ) && (Menu_ItemAtCursor( b->generic.parent ) == b)) { if (b->focuscolor) { tempcolor[0] = b->focuscolor[0]; tempcolor[1] = b->focuscolor[1]; tempcolor[2] = b->focuscolor[2]; color = tempcolor; } else color = pulse_color; color[3] = GFIXED(0,5)+GFIXED(0,5)*FIXED_SIN(MAKE_GFIXED(uis.realtime/PULSE_DIVISOR)); _UI_trap_R_SetColor( color ); UI_DrawHandlePic( x, y, w, h, b->focusshader ); _UI_trap_R_SetColor( NULL ); } else if ((b->generic.flags & QMF_HIGHLIGHT) || ((b->generic.flags & QMF_HIGHLIGHT_IF_FOCUS) && (Menu_ItemAtCursor( b->generic.parent ) == b))) { if (b->focuscolor) { _UI_trap_R_SetColor( b->focuscolor ); UI_DrawHandlePic( x, y, w, h, b->focusshader ); _UI_trap_R_SetColor( NULL ); } else UI_DrawHandlePic( x, y, w, h, b->focusshader ); } } } /* ================= Action_Init ================= */ static void Action_Init( menuaction_s *a ) { int len; // calculate bounds if (a->generic.name) len = strlen(a->generic.name); else len = 0; // left justify text a->generic.left = a->generic.x; a->generic.right = a->generic.x + len*BIGCHAR_WIDTH; a->generic.top = a->generic.y; a->generic.bottom = a->generic.y + BIGCHAR_HEIGHT; } /* ================= Action_Draw ================= */ static void Action_Draw( menuaction_s *a ) { int x, y; int style; gfixed* color; style = 0; color = menu_text_color; if ( a->generic.flags & QMF_GRAYED ) { color = text_color_disabled; } else if (( a->generic.flags & QMF_PULSEIFFOCUS ) && ( a->generic.parent->cursor == a->generic.menuPosition )) { color = text_color_highlight; style = UI_PULSE; } else if (( a->generic.flags & QMF_HIGHLIGHT_IF_FOCUS ) && ( a->generic.parent->cursor == a->generic.menuPosition )) { color = text_color_highlight; } else if ( a->generic.flags & QMF_BLINK ) { style = UI_BLINK; color = text_color_highlight; } x = a->generic.x; y = a->generic.y; UI_DrawString( x, y, a->generic.name, UI_LEFT|style, color ); if ( a->generic.parent->cursor == a->generic.menuPosition ) { // draw cursor UI_DrawChar( x - BIGCHAR_WIDTH, y, 13, UI_LEFT|UI_BLINK, color); } } /* ================= RadioButton_Init ================= */ static void RadioButton_Init( menuradiobutton_s *rb ) { int len; // calculate bounds if (rb->generic.name) len = strlen(rb->generic.name); else len = 0; rb->generic.left = rb->generic.x - (len+1)*SMALLCHAR_WIDTH; rb->generic.right = rb->generic.x + 6*SMALLCHAR_WIDTH; rb->generic.top = rb->generic.y; rb->generic.bottom = rb->generic.y + SMALLCHAR_HEIGHT; } /* ================= RadioButton_Key ================= */ static sfxHandle_t RadioButton_Key( menuradiobutton_s *rb, int key ) { switch (key) { case K_MOUSE1: if (!(rb->generic.flags & QMF_HASMOUSEFOCUS)) break; case K_JOY1: case K_JOY2: case K_JOY3: case K_JOY4: case K_ENTER: case K_KP_ENTER: case K_KP_LEFTARROW: case K_LEFTARROW: case K_KP_RIGHTARROW: case K_RIGHTARROW: rb->curvalue = !rb->curvalue; if ( rb->generic.callback ) rb->generic.callback( rb, QM_ACTIVATED ); return (menu_move_sound); } // key not handled return 0; } /* ================= RadioButton_Draw ================= */ static void RadioButton_Draw( menuradiobutton_s *rb ) { int x; int y; gfixed *color; int style; qboolean focus; x = rb->generic.x; y = rb->generic.y; focus = (rb->generic.parent->cursor == rb->generic.menuPosition); if ( rb->generic.flags & QMF_GRAYED ) { color = text_color_disabled; style = UI_LEFT|UI_SMALLFONT; } else if ( focus ) { color = text_color_highlight; style = UI_LEFT|UI_PULSE|UI_SMALLFONT; } else { color = text_color_normal; style = UI_LEFT|UI_SMALLFONT; } if ( focus ) { // draw cursor UI_FillRect( MAKE_GFIXED(rb->generic.left), MAKE_GFIXED(rb->generic.top), MAKE_GFIXED(rb->generic.right-rb->generic.left+1), MAKE_GFIXED(rb->generic.bottom-rb->generic.top+1), listbar_color ); UI_DrawChar( x, y, 13, UI_CENTER|UI_BLINK|UI_SMALLFONT, color); } if ( rb->generic.name ) UI_DrawString( x - SMALLCHAR_WIDTH, y, rb->generic.name, UI_RIGHT|UI_SMALLFONT, color ); if ( !rb->curvalue ) { UI_DrawHandlePic( MAKE_GFIXED(x + SMALLCHAR_WIDTH), MAKE_GFIXED(y + 2), GFIXED(16,0), GFIXED(16,0), uis.rb_off); UI_DrawString( x + SMALLCHAR_WIDTH + 16, y, "off", style, color ); } else { UI_DrawHandlePic( MAKE_GFIXED(x + SMALLCHAR_WIDTH), MAKE_GFIXED(y + 2), GFIXED(16,0), GFIXED(16,0), uis.rb_on ); UI_DrawString( x + SMALLCHAR_WIDTH + 16, y, "on", style, color ); } } /* ================= Slider_Init ================= */ static void Slider_Init( menuslider_s *s ) { int len; // calculate bounds if (s->generic.name) len = strlen(s->generic.name); else len = 0; s->generic.left = s->generic.x - (len+1)*SMALLCHAR_WIDTH; s->generic.right = s->generic.x + (SLIDER_RANGE+2+1)*SMALLCHAR_WIDTH; s->generic.top = s->generic.y; s->generic.bottom = s->generic.y + SMALLCHAR_HEIGHT; } /* ================= Slider_Key ================= */ static sfxHandle_t Slider_Key( menuslider_s *s, int key ) { sfxHandle_t sound; int x; int oldvalue; switch (key) { case K_MOUSE1: x = uis.cursorx - s->generic.x - 2*SMALLCHAR_WIDTH; oldvalue = FIXED_TO_INT(s->curvalue); s->curvalue = (MAKE_GFIXED(x)/GFIXED(SLIDER_RANGE*SMALLCHAR_WIDTH,0)) * (s->maxvalue-s->minvalue) + s->minvalue; if (s->curvalue < s->minvalue) s->curvalue = s->minvalue; else if (s->curvalue > s->maxvalue) s->curvalue = s->maxvalue; if (s->curvalue != MAKE_GFIXED(oldvalue)) sound = menu_move_sound; else sound = 0; break; case K_KP_LEFTARROW: case K_LEFTARROW: if (s->curvalue > s->minvalue) { s->curvalue--; sound = menu_move_sound; } else sound = menu_buzz_sound; break; case K_KP_RIGHTARROW: case K_RIGHTARROW: if (s->curvalue < s->maxvalue) { s->curvalue++; sound = menu_move_sound; } else sound = menu_buzz_sound; break; default: // key not handled sound = 0; break; } if ( sound && s->generic.callback ) s->generic.callback( s, QM_ACTIVATED ); return (sound); } #if 1 /* ================= Slider_Draw ================= */ static void Slider_Draw( menuslider_s *s ) { int x; int y; int style; gfixed *color; int button; qboolean focus; x = s->generic.x; y = s->generic.y; focus = (s->generic.parent->cursor == s->generic.menuPosition); if( s->generic.flags & QMF_GRAYED ) { color = text_color_disabled; style = UI_SMALLFONT; } else if( focus ) { color = text_color_highlight; style = UI_SMALLFONT | UI_PULSE; } else { color = text_color_normal; style = UI_SMALLFONT; } // draw label UI_DrawString( x - SMALLCHAR_WIDTH, y, s->generic.name, UI_RIGHT|style, color ); // draw slider UI_SetColor( color ); UI_DrawHandlePic( MAKE_GFIXED(x + SMALLCHAR_WIDTH), MAKE_GFIXED(y), GFIXED(96,0), GFIXED(16,0), sliderBar ); UI_SetColor( NULL ); // clamp thumb if( s->maxvalue > s->minvalue ) { s->range = ( s->curvalue - s->minvalue ) / ( s->maxvalue - s->minvalue ); if( s->range < GFIXED_0 ) { s->range = GFIXED_0; } else if( s->range > GFIXED_1) { s->range = GFIXED_1; } } else { s->range = GFIXED_0; } // draw thumb if( style & UI_PULSE) { button = sliderButton_1; } else { button = sliderButton_0; } UI_DrawHandlePic( MAKE_GFIXED( x + 2*SMALLCHAR_WIDTH + FIXED_TO_INT(GFIXED((SLIDER_RANGE-1)*SMALLCHAR_WIDTH,0)* s->range) - 2 ), MAKE_GFIXED(y - 2), GFIXED(12,0), GFIXED(20,0), button ); } #else /* ================= Slider_Draw ================= */ static void Slider_Draw( menuslider_s *s ) { gfixed *color; int style; int i; int x; int y; qboolean focus; x = s->generic.x; y = s->generic.y; focus = (s->generic.parent->cursor == s->generic.menuPosition); style = UI_SMALLFONT; if ( s->generic.flags & QMF_GRAYED ) { color = text_color_disabled; } else if (focus) { color = text_color_highlight; style |= UI_PULSE; } else { color = text_color_normal; } if ( focus ) { // draw cursor UI_FillRect( s->generic.left, s->generic.top, s->generic.right-s->generic.left+1, s->generic.bottom-s->generic.top+1, listbar_color ); UI_DrawChar( x, y, 13, UI_CENTER|UI_BLINK|UI_SMALLFONT, color); } // draw label UI_DrawString( x - SMALLCHAR_WIDTH, y, s->generic.name, UI_RIGHT|style, color ); // draw slider UI_DrawChar( x + SMALLCHAR_WIDTH, y, 128, UI_LEFT|style, color); for ( i = 0; i < SLIDER_RANGE; i++ ) UI_DrawChar( x + (i+2)*SMALLCHAR_WIDTH, y, 129, UI_LEFT|style, color); UI_DrawChar( x + (i+2)*SMALLCHAR_WIDTH, y, 130, UI_LEFT|style, color); // clamp thumb if (s->maxvalue > s->minvalue) { s->range = ( s->curvalue - s->minvalue ) / ( gfixed ) ( s->maxvalue - s->minvalue ); if ( s->range < 0) s->range = 0; else if ( s->range > 1) s->range = 1; } else s->range = 0; // draw thumb if (style & UI_PULSE) { style &= ~UI_PULSE; style |= UI_BLINK; } UI_DrawChar( FIXED_TO_INT( x + 2*SMALLCHAR_WIDTH + (SLIDER_RANGE-1)*SMALLCHAR_WIDTH* s->range ), y, 131, UI_LEFT|style, color); } #endif /* ================= SpinControl_Init ================= */ static void SpinControl_Init( menulist_s *s ) { int len; int l; const char* str; if (s->generic.name) len = strlen(s->generic.name) * SMALLCHAR_WIDTH; else len = 0; s->generic.left = s->generic.x - SMALLCHAR_WIDTH - len; len = s->numitems = 0; while ( (str = s->itemnames[s->numitems]) != 0 ) { l = strlen(str); if (l > len) len = l; s->numitems++; } s->generic.top = s->generic.y; s->generic.right = s->generic.x + (len+1)*SMALLCHAR_WIDTH; s->generic.bottom = s->generic.y + SMALLCHAR_HEIGHT; } /* ================= SpinControl_Key ================= */ static sfxHandle_t SpinControl_Key( menulist_s *s, int key ) { sfxHandle_t sound; sound = 0; switch (key) { case K_MOUSE1: s->curvalue++; if (s->curvalue >= s->numitems) s->curvalue = 0; sound = menu_move_sound; break; case K_KP_LEFTARROW: case K_LEFTARROW: if (s->curvalue > 0) { s->curvalue--; sound = menu_move_sound; } else sound = menu_buzz_sound; break; case K_KP_RIGHTARROW: case K_RIGHTARROW: if (s->curvalue < s->numitems-1) { s->curvalue++; sound = menu_move_sound; } else sound = menu_buzz_sound; break; } if ( sound && s->generic.callback ) s->generic.callback( s, QM_ACTIVATED ); return (sound); } /* ================= SpinControl_Draw ================= */ static void SpinControl_Draw( menulist_s *s ) { gfixed *color; int x,y; int style; qboolean focus; x = s->generic.x; y = s->generic.y; style = UI_SMALLFONT; focus = (s->generic.parent->cursor == s->generic.menuPosition); if ( s->generic.flags & QMF_GRAYED ) color = text_color_disabled; else if ( focus ) { color = text_color_highlight; style |= UI_PULSE; } else if ( s->generic.flags & QMF_BLINK ) { color = text_color_highlight; style |= UI_BLINK; } else color = text_color_normal; if ( focus ) { // draw cursor UI_FillRect( MAKE_GFIXED(s->generic.left), MAKE_GFIXED(s->generic.top), MAKE_GFIXED(s->generic.right-s->generic.left+1), MAKE_GFIXED(s->generic.bottom-s->generic.top+1), listbar_color ); UI_DrawChar( x, y, 13, UI_CENTER|UI_BLINK|UI_SMALLFONT, color); } UI_DrawString( x - SMALLCHAR_WIDTH, y, s->generic.name, style|UI_RIGHT, color ); UI_DrawString( x + SMALLCHAR_WIDTH, y, s->itemnames[s->curvalue], style|UI_LEFT, color ); } /* ================= ScrollList_Init ================= */ static void ScrollList_Init( menulist_s *l ) { int w; l->oldvalue = 0; l->curvalue = 0; l->top = 0; if( !l->columns ) { l->columns = 1; l->seperation = 0; } else if( !l->seperation ) { l->seperation = 3; } w = ( (l->width + l->seperation) * l->columns - l->seperation) * SMALLCHAR_WIDTH; l->generic.left = l->generic.x; l->generic.top = l->generic.y; l->generic.right = l->generic.x + w; l->generic.bottom = l->generic.y + l->height * SMALLCHAR_HEIGHT; if( l->generic.flags & QMF_CENTER_JUSTIFY ) { l->generic.left -= w / 2; l->generic.right -= w / 2; } } /* ================= ScrollList_Key ================= */ sfxHandle_t ScrollList_Key( menulist_s *l, int key ) { int x; int y; int w; int i; int j; int c; int cursorx; int cursory; int column; int index; switch (key) { case K_MOUSE1: if (l->generic.flags & QMF_HASMOUSEFOCUS) { // check scroll region x = l->generic.x; y = l->generic.y; w = ( (l->width + l->seperation) * l->columns - l->seperation) * SMALLCHAR_WIDTH; if( l->generic.flags & QMF_CENTER_JUSTIFY ) { x -= w / 2; } if (UI_CursorInRect( x, y, w, l->height*SMALLCHAR_HEIGHT )) { cursorx = (uis.cursorx - x)/SMALLCHAR_WIDTH; column = cursorx / (l->width + l->seperation); cursory = (uis.cursory - y)/SMALLCHAR_HEIGHT; index = column * l->height + cursory; if (l->top + index < l->numitems) { l->oldvalue = l->curvalue; l->curvalue = l->top + index; if (l->oldvalue != l->curvalue && l->generic.callback) { l->generic.callback( l, QM_GOTFOCUS ); return (menu_move_sound); } } } // absorbed, silent sound effect return (menu_null_sound); } break; case K_KP_HOME: case K_HOME: l->oldvalue = l->curvalue; l->curvalue = 0; l->top = 0; if (l->oldvalue != l->curvalue && l->generic.callback) { l->generic.callback( l, QM_GOTFOCUS ); return (menu_move_sound); } return (menu_buzz_sound); case K_KP_END: case K_END: l->oldvalue = l->curvalue; l->curvalue = l->numitems-1; if( l->columns > 1 ) { c = (l->curvalue / l->height + 1) * l->height; l->top = c - (l->columns * l->height); } else { l->top = l->curvalue - (l->height - 1); } if (l->top < 0) l->top = 0; if (l->oldvalue != l->curvalue && l->generic.callback) { l->generic.callback( l, QM_GOTFOCUS ); return (menu_move_sound); } return (menu_buzz_sound); case K_PGUP: case K_KP_PGUP: if( l->columns > 1 ) { return menu_null_sound; } if (l->curvalue > 0) { l->oldvalue = l->curvalue; l->curvalue -= l->height-1; if (l->curvalue < 0) l->curvalue = 0; l->top = l->curvalue; if (l->top < 0) l->top = 0; if (l->generic.callback) l->generic.callback( l, QM_GOTFOCUS ); return (menu_move_sound); } return (menu_buzz_sound); case K_PGDN: case K_KP_PGDN: if( l->columns > 1 ) { return menu_null_sound; } if (l->curvalue < l->numitems-1) { l->oldvalue = l->curvalue; l->curvalue += l->height-1; if (l->curvalue > l->numitems-1) l->curvalue = l->numitems-1; l->top = l->curvalue - (l->height-1); if (l->top < 0) l->top = 0; if (l->generic.callback) l->generic.callback( l, QM_GOTFOCUS ); return (menu_move_sound); } return (menu_buzz_sound); case K_KP_UPARROW: case K_UPARROW: if( l->curvalue == 0 ) { return menu_buzz_sound; } l->oldvalue = l->curvalue; l->curvalue--; if( l->curvalue < l->top ) { if( l->columns == 1 ) { l->top--; } else { l->top -= l->height; } } if( l->generic.callback ) { l->generic.callback( l, QM_GOTFOCUS ); } return (menu_move_sound); case K_KP_DOWNARROW: case K_DOWNARROW: if( l->curvalue == l->numitems - 1 ) { return menu_buzz_sound; } l->oldvalue = l->curvalue; l->curvalue++; if( l->curvalue >= l->top + l->columns * l->height ) { if( l->columns == 1 ) { l->top++; } else { l->top += l->height; } } if( l->generic.callback ) { l->generic.callback( l, QM_GOTFOCUS ); } return menu_move_sound; case K_KP_LEFTARROW: case K_LEFTARROW: if( l->columns == 1 ) { return menu_null_sound; } if( l->curvalue < l->height ) { return menu_buzz_sound; } l->oldvalue = l->curvalue; l->curvalue -= l->height; if( l->curvalue < l->top ) { l->top -= l->height; } if( l->generic.callback ) { l->generic.callback( l, QM_GOTFOCUS ); } return menu_move_sound; case K_KP_RIGHTARROW: case K_RIGHTARROW: if( l->columns == 1 ) { return menu_null_sound; } c = l->curvalue + l->height; if( c >= l->numitems ) { return menu_buzz_sound; } l->oldvalue = l->curvalue; l->curvalue = c; if( l->curvalue > l->top + l->columns * l->height - 1 ) { l->top += l->height; } if( l->generic.callback ) { l->generic.callback( l, QM_GOTFOCUS ); } return menu_move_sound; } // cycle look for ascii key inside list items if ( !Q_isprint( key ) ) return (0); // force to lower for case insensitive compare if ( Q_isupper( key ) ) { key -= 'A' - 'a'; } // iterate list items for (i=1; i<=l->numitems; i++) { j = (l->curvalue + i) % l->numitems; c = l->itemnames[j][0]; if ( Q_isupper( c ) ) { c -= 'A' - 'a'; } if (c == key) { // set current item, mimic windows listbox scroll behavior if (j < l->top) { // behind top most item, set this as new top l->top = j; } else if (j > l->top+l->height-1) { // past end of list box, do page down l->top = (j+1) - l->height; } if (l->curvalue != j) { l->oldvalue = l->curvalue; l->curvalue = j; if (l->generic.callback) l->generic.callback( l, QM_GOTFOCUS ); return ( menu_move_sound ); } return (menu_buzz_sound); } } return (menu_buzz_sound); } /* ================= ScrollList_Draw ================= */ void ScrollList_Draw( menulist_s *l ) { int x; int u; int y; int i; int base; int column; gfixed* color; qboolean hasfocus; int style; hasfocus = (l->generic.parent->cursor == l->generic.menuPosition); x = l->generic.x; for( column = 0; column < l->columns; column++ ) { y = l->generic.y; base = l->top + column * l->height; for( i = base; i < base + l->height; i++) { if (i >= l->numitems) break; if (i == l->curvalue) { u = x - 2; if( l->generic.flags & QMF_CENTER_JUSTIFY ) { u -= (l->width * SMALLCHAR_WIDTH) / 2 + 1; } UI_FillRect(MAKE_GFIXED(u),MAKE_GFIXED(y),MAKE_GFIXED(l->width*SMALLCHAR_WIDTH),MAKE_GFIXED(SMALLCHAR_HEIGHT+2),listbar_color); color = text_color_highlight; if (hasfocus) style = UI_PULSE|UI_LEFT|UI_SMALLFONT; else style = UI_LEFT|UI_SMALLFONT; } else { color = text_color_normal; style = UI_LEFT|UI_SMALLFONT; } if( l->generic.flags & QMF_CENTER_JUSTIFY ) { style |= UI_CENTER; } UI_DrawString( x, y, l->itemnames[i], style, color); y += SMALLCHAR_HEIGHT; } x += (l->width + l->seperation) * SMALLCHAR_WIDTH; } } /* ================= Menu_AddItem ================= */ void Menu_AddItem( menuframework_s *menu, void *item ) { menucommon_s *itemptr; if (menu->nitems >= MAX_MENUITEMS) _UI_trap_Error ("Menu_AddItem: excessive items"); menu->items[menu->nitems] = item; ((menucommon_s*)menu->items[menu->nitems])->parent = menu; ((menucommon_s*)menu->items[menu->nitems])->menuPosition = menu->nitems; ((menucommon_s*)menu->items[menu->nitems])->flags &= ~QMF_HASMOUSEFOCUS; // perform any item specific initializations itemptr = (menucommon_s*)item; if (!(itemptr->flags & QMF_NODEFAULTINIT)) { switch (itemptr->type) { case MTYPE_ACTION: Action_Init((menuaction_s*)item); break; case MTYPE_FIELD: MenuField_Init((menufield_s*)item); break; case MTYPE_SPINCONTROL: SpinControl_Init((menulist_s*)item); break; case MTYPE_RADIOBUTTON: RadioButton_Init((menuradiobutton_s*)item); break; case MTYPE_SLIDER: Slider_Init((menuslider_s*)item); break; case MTYPE_BITMAP: Bitmap_Init((menubitmap_s*)item); break; case MTYPE_TEXT: Text_Init((menutext_s*)item); break; case MTYPE_SCROLLLIST: ScrollList_Init((menulist_s*)item); break; case MTYPE_PTEXT: PText_Init((menutext_s*)item); break; case MTYPE_BTEXT: BText_Init((menutext_s*)item); break; default: _UI_trap_Error( va("Menu_Init: unknown type %d", itemptr->type) ); } } menu->nitems++; } /* ================= Menu_CursorMoved ================= */ void Menu_CursorMoved( menuframework_s *m ) { void (*callback)( void *self, int notification ); if (m->cursor_prev == m->cursor) return; if (m->cursor_prev >= 0 && m->cursor_prev < m->nitems) { callback = ((menucommon_s*)(m->items[m->cursor_prev]))->callback; if (callback) callback(m->items[m->cursor_prev],QM_LOSTFOCUS); } if (m->cursor >= 0 && m->cursor < m->nitems) { callback = ((menucommon_s*)(m->items[m->cursor]))->callback; if (callback) callback(m->items[m->cursor],QM_GOTFOCUS); } } /* ================= Menu_SetCursor ================= */ void Menu_SetCursor( menuframework_s *m, int cursor ) { if (((menucommon_s*)(m->items[cursor]))->flags & (QMF_GRAYED|QMF_INACTIVE)) { // cursor can't go there return; } m->cursor_prev = m->cursor; m->cursor = cursor; Menu_CursorMoved( m ); } /* ================= Menu_SetCursorToItem ================= */ void Menu_SetCursorToItem( menuframework_s *m, void* ptr ) { int i; for (i=0; i<m->nitems; i++) { if (m->items[i] == ptr) { Menu_SetCursor( m, i ); return; } } } /* ** Menu_AdjustCursor ** ** This function takes the given menu, the direction, and attempts ** to adjust the menu's cursor so that it's at the next available ** slot. */ void Menu_AdjustCursor( menuframework_s *m, int dir ) { menucommon_s *item = NULL; qboolean wrapped = qfalse; wrap: while ( m->cursor >= 0 && m->cursor < m->nitems ) { item = ( menucommon_s * ) m->items[m->cursor]; if (( item->flags & (QMF_GRAYED|QMF_MOUSEONLY|QMF_INACTIVE) ) ) { m->cursor += dir; } else { break; } } if ( dir == 1 ) { if ( m->cursor >= m->nitems ) { if ( m->wrapAround ) { if ( wrapped ) { m->cursor = m->cursor_prev; return; } m->cursor = 0; wrapped = qtrue; goto wrap; } m->cursor = m->cursor_prev; } } else { if ( m->cursor < 0 ) { if ( m->wrapAround ) { if ( wrapped ) { m->cursor = m->cursor_prev; return; } m->cursor = m->nitems - 1; wrapped = qtrue; goto wrap; } m->cursor = m->cursor_prev; } } } /* ================= Menu_Draw ================= */ void Menu_Draw( menuframework_s *menu ) { int i; menucommon_s *itemptr; // draw menu for (i=0; i<menu->nitems; i++) { itemptr = (menucommon_s*)menu->items[i]; if (itemptr->flags & QMF_HIDDEN) continue; if (itemptr->ownerdraw) { // total subclassing, owner draws everything itemptr->ownerdraw( itemptr ); } else { switch (itemptr->type) { case MTYPE_RADIOBUTTON: RadioButton_Draw( (menuradiobutton_s*)itemptr ); break; case MTYPE_FIELD: MenuField_Draw( (menufield_s*)itemptr ); break; case MTYPE_SLIDER: Slider_Draw( (menuslider_s*)itemptr ); break; case MTYPE_SPINCONTROL: SpinControl_Draw( (menulist_s*)itemptr ); break; case MTYPE_ACTION: Action_Draw( (menuaction_s*)itemptr ); break; case MTYPE_BITMAP: Bitmap_Draw( (menubitmap_s*)itemptr ); break; case MTYPE_TEXT: Text_Draw( (menutext_s*)itemptr ); break; case MTYPE_SCROLLLIST: ScrollList_Draw( (menulist_s*)itemptr ); break; case MTYPE_PTEXT: PText_Draw( (menutext_s*)itemptr ); break; case MTYPE_BTEXT: BText_Draw( (menutext_s*)itemptr ); break; default: _UI_trap_Error( va("Menu_Draw: unknown type %d", itemptr->type) ); } } #ifndef NDEBUG if( uis.debug ) { int x; int y; int w; int h; if( !( itemptr->flags & QMF_INACTIVE ) ) { x = itemptr->left; y = itemptr->top; w = itemptr->right - itemptr->left + 1; h = itemptr->bottom - itemptr->top + 1; if (itemptr->flags & QMF_HASMOUSEFOCUS) { UI_DrawRect(MAKE_GFIXED(x), MAKE_GFIXED(y), MAKE_GFIXED(w), MAKE_GFIXED(h), colorYellow ); } else { UI_DrawRect(MAKE_GFIXED(x), MAKE_GFIXED(y), MAKE_GFIXED(w), MAKE_GFIXED(h), colorWhite ); } } } #endif } itemptr = (menucommon_s *)Menu_ItemAtCursor( menu ); if ( itemptr && itemptr->statusbar) itemptr->statusbar( ( void * ) itemptr ); } /* ================= Menu_ItemAtCursor ================= */ void *Menu_ItemAtCursor( menuframework_s *m ) { if ( m->cursor < 0 || m->cursor >= m->nitems ) return 0; return m->items[m->cursor]; } /* ================= Menu_ActivateItem ================= */ sfxHandle_t Menu_ActivateItem( menuframework_s *s, menucommon_s* item ) { if ( item->callback ) { item->callback( item, QM_ACTIVATED ); if( !( item->flags & QMF_SILENT ) ) { return menu_move_sound; } } return 0; } /* ================= Menu_DefaultKey ================= */ sfxHandle_t Menu_DefaultKey( menuframework_s *m, int key ) { sfxHandle_t sound = 0; menucommon_s *item; int cursor_prev; // menu system keys switch ( key ) { case K_MOUSE2: case K_ESCAPE: UI_PopMenu(); return menu_out_sound; } if (!m || !m->nitems) return 0; // route key stimulus to widget item = (menucommon_s *)Menu_ItemAtCursor( m ); if (item && !(item->flags & (QMF_GRAYED|QMF_INACTIVE))) { switch (item->type) { case MTYPE_SPINCONTROL: sound = SpinControl_Key( (menulist_s*)item, key ); break; case MTYPE_RADIOBUTTON: sound = RadioButton_Key( (menuradiobutton_s*)item, key ); break; case MTYPE_SLIDER: sound = Slider_Key( (menuslider_s*)item, key ); break; case MTYPE_SCROLLLIST: sound = ScrollList_Key( (menulist_s*)item, key ); break; case MTYPE_FIELD: sound = MenuField_Key( (menufield_s*)item, &key ); break; } if (sound) { // key was handled return sound; } } // default handling switch ( key ) { #ifndef NDEBUG case K_F11: uis.debug ^= 1; break; case K_F12: _UI_trap_Cmd_ExecuteText(EXEC_APPEND, "screenshot\n"); break; #endif case K_KP_UPARROW: case K_UPARROW: cursor_prev = m->cursor; m->cursor_prev = m->cursor; m->cursor--; Menu_AdjustCursor( m, -1 ); if ( cursor_prev != m->cursor ) { Menu_CursorMoved( m ); sound = menu_move_sound; } break; case K_TAB: case K_KP_DOWNARROW: case K_DOWNARROW: cursor_prev = m->cursor; m->cursor_prev = m->cursor; m->cursor++; Menu_AdjustCursor( m, 1 ); if ( cursor_prev != m->cursor ) { Menu_CursorMoved( m ); sound = menu_move_sound; } break; case K_MOUSE1: case K_MOUSE3: if (item) if ((item->flags & QMF_HASMOUSEFOCUS) && !(item->flags & (QMF_GRAYED|QMF_INACTIVE))) return (Menu_ActivateItem( m, item )); break; case K_JOY1: case K_JOY2: case K_JOY3: case K_JOY4: case K_AUX1: case K_AUX2: case K_AUX3: case K_AUX4: case K_AUX5: case K_AUX6: case K_AUX7: case K_AUX8: case K_AUX9: case K_AUX10: case K_AUX11: case K_AUX12: case K_AUX13: case K_AUX14: case K_AUX15: case K_AUX16: case K_KP_ENTER: case K_ENTER: if (item) if (!(item->flags & (QMF_MOUSEONLY|QMF_GRAYED|QMF_INACTIVE))) return (Menu_ActivateItem( m, item )); break; } return sound; } /* ================= Menu_Cache ================= */ void Menu_Cache( void ) { uis.charset = _UI_trap_R_RegisterShaderNoMip( "gfx/2d/bigchars" ); uis.charsetProp = _UI_trap_R_RegisterShaderNoMip( "menu/art/font1_prop.tga" ); uis.charsetPropGlow = _UI_trap_R_RegisterShaderNoMip( "menu/art/font1_prop_glo.tga" ); uis.charsetPropB = _UI_trap_R_RegisterShaderNoMip( "menu/art/font2_prop.tga" ); uis.cursor = _UI_trap_R_RegisterShaderNoMip( "menu/art/3_cursor2" ); uis.rb_on = _UI_trap_R_RegisterShaderNoMip( "menu/art/switch_on" ); uis.rb_off = _UI_trap_R_RegisterShaderNoMip( "menu/art/switch_off" ); uis.whiteShader = _UI_trap_R_RegisterShaderNoMip( "white" ); if ( uis.glconfig.hardwareType == GLHW_RAGEPRO ) { // the blend effect turns to shit with the normal uis.menuBackShader = _UI_trap_R_RegisterShaderNoMip( "menubackRagePro" ); } else { uis.menuBackShader = _UI_trap_R_RegisterShaderNoMip( "menuback" ); } uis.menuBackNoLogoShader = _UI_trap_R_RegisterShaderNoMip( "menubacknologo" ); menu_in_sound = _UI_trap_S_RegisterSound( "sound/misc/menu1.wav", qfalse ); menu_move_sound = _UI_trap_S_RegisterSound( "sound/misc/menu2.wav", qfalse ); menu_out_sound = _UI_trap_S_RegisterSound( "sound/misc/menu3.wav", qfalse ); menu_buzz_sound = _UI_trap_S_RegisterSound( "sound/misc/menu4.wav", qfalse ); weaponChangeSound = _UI_trap_S_RegisterSound( "sound/weapons/change.wav", qfalse ); // need a nonzero sound, make an empty sound for this menu_null_sound = -1; sliderBar = _UI_trap_R_RegisterShaderNoMip( "menu/art/slider2" ); sliderButton_0 = _UI_trap_R_RegisterShaderNoMip( "menu/art/sliderbutt_0" ); sliderButton_1 = _UI_trap_R_RegisterShaderNoMip( "menu/art/sliderbutt_1" ); }
[ "jack.palevich@684fc592-8442-0410-8ea1-df6b371289ac" ]
[ [ [ 1, 1746 ] ] ]
9de3589de23b07414cfee8b87e2031bc45ab7787
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/SMDK/RTTS/TS_ModelLib/FixedComminution.cpp
9b2c6d8be1a83812e53610ad2c691d0a1823dd35
[]
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
9,498
cpp
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #include "stdafx.h" #define __FixedComminution_CPP #include "FixedComminution.h" //==================================================================================== // Fixed Comminution //==================================================================================== CComminution_Fixed::CComminution_Fixed() { m_lDischargeSel = 0; m_DDPSDDischarge = 0; // Initialise discharge partitions for all possible // PSD Definitions that could be used for this project int n = gs_PSDDefns.Count(); m_CDischarge.SetSize(n); m_DDPSDDischarge = new MDDValueLst[n+1]; m_DDPSDDischarge[n].m_dwFlags = 0; m_DDPSDDischarge[n].m_lVal = 0; m_DDPSDDischarge[n].m_pStr = 0; for (int i=0; i< n; i++) { MPSDDefn& PSDDefn = gs_PSDDefns[i]; int NIntervals = PSDDefn.getSizeCount(); m_CDischarge[i].m_dDischarge.SetSize(NIntervals); m_CDischarge[i].m_dCSS = 0.005; m_CDischarge[i].m_dTestCSS = 0.005; m_CDischarge[i].m_bBypassOn = true; m_CDischarge[i].m_Name = PSDDefn.Name(); m_DDPSDDischarge[i].m_dwFlags = 0; m_DDPSDDischarge[i].m_lVal = i; const LPCSTR s = m_CDischarge[i].m_Name.GetString(); m_DDPSDDischarge[i].m_pStr = (LPTSTR)s; } } //==================================================================================== CComminution_Fixed::~CComminution_Fixed() { delete m_DDPSDDischarge; } //==================================================================================== void CComminution_Fixed::BuildDataFields(MDataDefn &DB) { DB.ObjectBegin("TS_Fixed", "Fixed"); DB.Page("Fixed Discharge"); CString Tg1,Tg2; DB.Long ("Discharge", "", &m_lDischargeSel , MF_PARAMETER, m_DDPSDDischarge ); for (int i = 0; i < m_CDischarge.GetSize() ; i++) { DWORD flags; if ( i == m_lDischargeSel ) flags = MF_PARAMETER; else flags = MF_PARAMETER | MF_NO_VIEW; Tg1.Format("TS_Fixed%02d",i); Tg2.Format("Fixed%02d",i); DB.ObjectBegin(Tg1, Tg2); DB.Double("CSS", "", &m_CDischarge[i].m_dCSS, flags , MC_L("mm")); DB.Double("TCSS", "", &m_CDischarge[i].m_dTestCSS, flags , MC_L("mm")); DB.CheckBox("ByPassOn", "", &m_CDischarge[i].m_bBypassOn, flags); for (int j = (m_CDischarge[i].m_dDischarge.GetSize()-1); j >= 0; j--) { Tg1.Format("I%02d", j); // // Check value is in range i.e. Betwee 0 and 1 and // larger sizes passings are >= smaller size cumulative percents // if (m_CDischarge[i].m_dDischarge[j] > 1.0) m_CDischarge[i].m_dDischarge[j] = 1.0; if (m_CDischarge[i].m_dDischarge[j] < 0.0) m_CDischarge[i].m_dDischarge[j] = 0.0; //if ((j>1) && (m_CDischarge[i].m_dDischarge[j] < m_CDischarge[i].m_dDischarge[j-1])) // m_CDischarge[i].m_dDischarge[j] = m_CDischarge[i].m_dDischarge[j-1]; DB.Double((char*)(const char*)Tg1, "", &m_CDischarge[i].m_dDischarge[j], flags , MC_Frac("%")); } DB.ObjectEnd(); } DB.ObjectEnd(); // Checks for (int i = 0; i < m_CDischarge.GetSize() ; i++) { // Force distribution to ascend int nsizes = m_CDischarge[i].m_dDischarge.GetSize(); for (int j = 0; j < nsizes; j++) { for (int k = j; k < nsizes; k++ ) { double val1 = m_CDischarge[i].m_dDischarge[j]; double val2 = m_CDischarge[i].m_dDischarge[k]; if (val1 > val2) { // Swap m_CDischarge[i].m_dDischarge[j] = val2; m_CDischarge[i].m_dDischarge[k] = val1; } } } m_CDischarge[i].m_dDischarge[nsizes-1] = 1.0; } } //==================================================================================== void CComminution_Fixed::EvalProducts(MBaseMethod &M, MStream &Feed , MStream &Product , bool bInit) { MIPSD & PSDin = *Feed.FindIF<MIPSD>(); MIPSD & PSDout = *Product.FindIF<MIPSD>(); if ( IsNothing(PSDin)==false ) { // Input Stream does have a PSD // which implies that some of the input stream species have associated size data long NumSizes = PSDin.getSizeCount(); long NumComps = PSDin.getPSDVectorCount(); if (bInit) { //m_dDischarge.SetSize(NumSizes); } for (int c=0; c<NumComps; c++) { // Determine which PSD we are using so we can // choose the correct discharge partition // // This is a temporary solution until we expose // PSDin.getDefnIndex(); // int iPSD = 0; MPSDDefn& PSDDefn = PSDin.getDefn(); int ndefs = gs_PSDDefns.Count(); for (int i=0; i< ndefs ; i++) { MPSDDefn& PSDDefSrch = gs_PSDDefns[i]; if (&PSDDefSrch == &PSDDefn) { iPSD = i; break; } } // Extract the specified Discharge PSD int n = m_CDischarge[iPSD].m_dDischarge.GetSize(); double* Fcum = new double[n]; // User specified Cumulative Dischage double* FcumShift = new double[n]; // Shifted Cumulative Discharge with CSS double* Ffrac = new double[n]; // Calculated discharge fractions double* FeedMassRet = new double[n]; // Feed Mass Fractions double* ByPassMassRet = new double[n]; // Calculated Bypass Mass Fractions double* DischargeMassRet = new double[n]; // Final calculated discharge mass double* S = new double[n]; // Size Intervals double* SShifted = new double[n]; // Shifted Size Intervals // Calculate Cumulative discharge PSD from specified fractions for (int i = 0; i < n; i++) { Fcum[i] = m_CDischarge[iPSD].m_dDischarge[i]; FcumShift[i] = Fcum[i]; } // // Optionally Calculate the ByPass Stream from the Feed Stream // PSDin.ExtractMassVector(FeedMassRet,c); PSDin.ExtractSizes(S,1.0); double ByPassTotal = 0.0; if (m_CDischarge[iPSD].m_bBypassOn==true) { double FeedMassCum1 = 0.0; double FeedMassCum2 = 0.0; ByPassMassRet[0] = FeedMassRet[0]; ByPassTotal = ByPassMassRet[0]; for (int i = 1; i < n; i++ ) { double x1 = S[i-1]; if (x1 < 0.0) x1 = 0.0; double x2 = S[i]; FeedMassCum1 += FeedMassRet[i-1]; FeedMassCum2 = FeedMassCum1 + FeedMassRet[i]; if ((x1 < m_CDischarge[iPSD].m_dCSS)&& (x2 > m_CDischarge[iPSD].m_dCSS)) { // CSS lies between 2 size intervals // Calculate split to bypass int xx =0; double logcss = log(GTZ(m_CDischarge[iPSD].m_dCSS)); double logx1 = log(GTZ(x1)); double logx2 = log(GTZ(x2)); double logy1 = log(GTZ(FeedMassCum1)); double logy2 = log(GTZ(FeedMassCum2)); double logBypass = 0.0; double Bypass = 0.0; logBypass = (logy1+(logcss-logx1)*(logy2-logy1)/GTZ(logx2-logx1)); Bypass = exp(logBypass) - FeedMassCum1; ByPassMassRet[i] = Bypass; } else if (x1 < m_CDischarge[iPSD].m_dCSS) { // Everything less than CSS to ByPass ByPassMassRet[i] = FeedMassRet[i]; } else { // Everything Greater than CSS Stays ByPassMassRet[i] = 0.0; } ByPassTotal += ByPassMassRet[i]; } } else { ByPassTotal = 0.0; } // // Calculate Remaining Mass to Be Used in for Fixed Discharge // double TotalFeed = Feed.getM(c); double FixedDischargeFeed = TotalFeed-ByPassTotal; // // Shift the Distribution Based on the Specified CSS // double scale = m_CDischarge[iPSD].m_dCSS/GTZ(m_CDischarge[iPSD].m_dTestCSS); PSDin.ExtractSizes(SShifted,scale); for (int i = 0; i < n; i++ ) { // // Find shifted size intervals that our size lies // between for interpolation // double x = S[i]; for (int j = 0; j < (n-1) ; j++ ) { double x1 = SShifted[j]; if (x1 < 0.0) x1 = 0.0; double x2 = SShifted[j+1]; if ((x < x1)|| ((x >= x1) && ( x <= x2 ))|| (j >= (n-2))) { // Interpolate double y1 = Fcum[j]; double y2 = Fcum[j+1]; double ynew = log(GTZ(y1))+(log(GTZ(x))-log(GTZ(x1)))* (log(GTZ(y2))-log(GTZ(y1)))/GTZ(log(GTZ(x2))-log(GTZ(x1))); ynew = exp(ynew); FcumShift[i] = ynew; if (FcumShift[i] < 0.0) FcumShift[i] = 0.0; if (FcumShift[i] > 1.0) FcumShift[i] = 1.0; break; } } } // Convert Cummulative PSD to Interval Fractions for (int i = 1; i < n; i++) { Ffrac[i] = FcumShift[i] - FcumShift[i-1]; } Ffrac[0] = FcumShift[0]; // Calculate ByPass + Fixed Discharge for (int i = 0; i < n ; i++) { if (m_CDischarge[iPSD].m_bBypassOn==true) DischargeMassRet[i] = ByPassMassRet[i] + Ffrac[i]*FixedDischargeFeed; else DischargeMassRet[i] = Ffrac[i]*FixedDischargeFeed; } // Set the Discharge PSD // SysCAD stores fractions per interval //PSDout.ReplaceFracVector(Ffrac,c); //Replace the Discharge Mass Fractions PSDout.ReplaceMassVector(DischargeMassRet,c); delete []S; delete []SShifted; delete []Fcum; delete []FcumShift; delete []Ffrac; delete []FeedMassRet; delete []ByPassMassRet; delete []DischargeMassRet; } } } //====================================================================================
[ [ [ 1, 139 ], [ 142, 337 ] ], [ [ 140, 141 ] ] ]
92636b3b66b8d2933afce3c77e8622e62ea29d9c
f7ae3e263292448184345cbacedeff56960c0527
/AdminListas.h
9c0bfea8999d6060e26e854eef7d74c47ad82079
[]
no_license
claudiams/QBiblioAgent
ff3012458e1549e4c9456d2a2322fb2348da79fb
3bb9737815da516d162168b71e671577dd63f6f0
refs/heads/master
2021-01-19T06:56:50.555738
2010-10-15T19:50:38
2010-10-15T19:50:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,079
h
/* * File: AdminListas.h * Author: AirZs * * Creado el 11 de octubre de 2010, 22:11 */ #ifndef ADMINLISTAS_H #define ADMINLISTAS_H #include <ctime> #include "ListaEstatica.h" #include "ListaEnlazada.h" #include "Cliente.h" #include "Venta.h" #include "Libro.h" #include "Vendedor.h" #include "ErrorExcep.h" class AdminListas{ public: //Iniciadores y obligatorios AdminListas( ListaEnlazada<Venta> *listVentas, ListaEnlazada<Libro> *listLibros, ListaEstatica<Vendedor> *listVendedor, ListaEnlazada<Cliente> *listClientes); virtual ~AdminListas(); ////////////////////////////////// //Getters ListaEnlazada<Libro> *getListaLibros(); ListaEnlazada<Venta> *getListaVentas(); ListaEnlazada<Cliente> *getListaClientes(); ListaEstatica<Vendedor> *getListaVendedores(); ////////////////////////////////// //Setters void agregarLibro(string strNombre, string isbn, string strAutor, string paginas, string peso, string precio, string stock); void agregarVenta(string boolCorrelativo, int posLibro, int posCliente, int posVendedor, string cantLibros); void agregarCliente(string rut, string nombre, string edad, string direccion, string listTelefonos, string email); void agregarVendedor(string strRut, string nombre, string direccion, string edad, string strEmail, string telefonos); ////////////////////////////////// //Funciones adicionales void editarCliente(int idOrig, string rut, string nombre, string edad, string direccion, string email, string listTelefonos, bool elimTelefonos); void editarVendedor(int idOrig, string strRut, string nombre, string direccion, string edad, string strEmail, string telefonos, bool elimTelefonos); string quitarEspacioExtremos(string texto); ////////////////////////////////// private: ListaEnlazada<Libro> *listBaseLibros; ListaEnlazada<Venta> *listBaseVentas; ListaEnlazada<Cliente> *listBaseClientes; ListaEstatica<Vendedor> *listBaseVendedores; }; #endif // ADMINLISTAS_H
[ [ [ 1, 56 ] ] ]
c38e1e30c87608bfd113d06de82e03f99a0159c0
6247eceeb3d15fd80f27285de6808a11eb66a9e2
/cn/GfxFont.cpp
1664aa38063d77bc943ac057db359c8f7d2cd87a
[]
no_license
sean-m/hgelua
7b48b30271f295f617b6242cb8996f802add0284
d4f94f0b5905cc4fa471bee7d9474ab2779c9a24
refs/heads/master
2021-01-10T04:58:00.146231
2010-04-12T16:27:14
2010-04-12T16:27:14
54,251,268
0
0
null
null
null
null
GB18030
C++
false
false
7,321
cpp
#include "stdafx.h" #include <atlbase.h> #include <stdio.h> __inline float _floor(float f) { static int _n; _asm fld f _asm fistp _n return (float)_n; } // 65级灰度表 const unsigned char g_byAlphaLevel[65] = { 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80, 84, 88, 92, 96,100, 104,108,112,116,120,124,128,132,136,140,144,148,152, 156,160,164,168,172,176,180,184,188,192,196,200,204, 208,212,216,220,224,228,232,236,240,244,248,252,255 }; GfxFont::GfxFont(const char* lpsFontName, int nFaceSize, BOOL bBold, BOOL bItalic, BOOL bAntialias) { m_pHGE = hgeCreate(HGE_VERSION); // 创建GDI相关设备 HDC hDC = GetDC(m_pHGE->System_GetState(HGE_HWND)); m_hMemDC = CreateCompatibleDC(hDC); if (NULL == m_hMemDC) return; ReleaseDC(m_pHGE->System_GetState(HGE_HWND),hDC); ::SetMapMode(m_hMemDC, MM_TEXT); ::SetTextColor(m_hMemDC,RGB(255,255,255)); ::SetBkColor(m_hMemDC,RGB(0,0,0)); m_hFont = CreateFont( -nFaceSize, 0, 0, 0, (bBold) ? FW_BOLD : FW_NORMAL, bItalic, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FF_DONTCARE | DEFAULT_PITCH, lpsFontName); if (NULL == (m_hFont)) return; SelectObject(m_hMemDC, m_hFont); memset(m_Glyphs,0,sizeof(TENGINEFONTGLYPH)*font_count); m_nAntialias = bAntialias ? GGO_GRAY8_BITMAP : GGO_BITMAP; TEXTMETRIC tm; ::GetTextMetrics(m_hMemDC,&tm); m_nAscent = tm.tmAscent; m_nFontSize = static_cast<float>(nFaceSize); m_nKerningWidth = 0; m_nKerningHeight= 0; m_pSprite = new hgeSprite(0, 0, 0, 0, 0); m_pSprite->SetColor(ARGB(255, 255, 255, 255)); } GfxFont::~GfxFont(void) { for (int nIdx = 0; nIdx < font_count; ++nIdx) { if (m_Glyphs[nIdx].t) m_pHGE->Texture_Free(m_Glyphs[nIdx].t); } if ((m_hFont)) DeleteObject(m_hFont); if ((m_hMemDC)) DeleteDC(m_hMemDC); if(m_pSprite) delete m_pSprite; if(m_pHGE) m_pHGE->Release(); } // 渲染文本 void GfxFont::Print( float x, float y, const char *format, ... ) { char sBuffer[10240] = {0}; char *lpsArg=(char*)&format+sizeof(format); vsprintf_s(sBuffer, format, lpsArg); Render(x,y,CA2W(sBuffer)); } void GfxFont::Render(float x, float y, const wchar_t* text ) { float offsetX = x; float offsetY = y; while(*text) { if (*text == L'\n' || *text == L'\r') { offsetX = x; offsetY += (m_nFontSize + m_nKerningHeight); } else { unsigned int idx = GetGlyphByCharacter(*text); if (idx > 0) { m_pSprite->SetTexture(m_Glyphs[idx].t); m_pSprite->SetTextureRect(0, 0, m_Glyphs[idx].w, m_Glyphs[idx].h); m_pSprite->Render(offsetX - m_Glyphs[idx].x, offsetY - m_Glyphs[idx].y); offsetX += (GetWidthFromCharacter(*text) + m_nKerningWidth); } else { offsetX += (GetWidthFromCharacter(*text) + m_nKerningWidth); } } ++text; } } // 设置与获取颜色 void GfxFont::SetColor( DWORD dwColor, int i ) { m_pSprite->SetColor(dwColor,i); } DWORD GfxFont::GetColor(int i) { return m_pSprite->GetColor(i); } // 获取文本宽高 SIZE GfxFont::GetTextSize( const wchar_t* text ) { SIZE dim = {0, static_cast<LONG>(m_nFontSize)}; float nRowWidth = 0; while(*text) { if (*text == L'\n' || *text == L'\r') { dim.cy += static_cast<LONG>(m_nFontSize + m_nKerningHeight); if (dim.cx < static_cast<LONG>(nRowWidth)) dim.cx = static_cast<LONG>(nRowWidth); nRowWidth = 0; } else nRowWidth += (GetWidthFromCharacter(*text) + m_nKerningWidth); ++text; } if (dim.cx < static_cast<LONG>(nRowWidth)) dim.cx = static_cast<LONG>(nRowWidth); return dim; } // 根据坐标获取字符 wchar_t GfxFont::GetCharacterFromPos( const wchar_t* text, float pixel_x, float pixel_y ) { float x = 0; float y = 0; while (*text) { if (*text == L'\n' || *text == L'\r') { x = 0; y += (m_nFontSize+m_nKerningHeight); text++; if (!(*text)) break; } float w = GetWidthFromCharacter(*text); if (pixel_x > x && pixel_x <= x + w && pixel_y > y && pixel_y <= y + m_nFontSize) return *text; x += (w+m_nKerningWidth); text++; } return L'\0'; } // 设置字间距 void GfxFont::SetKerningWidth( float kerning ) { m_nKerningWidth = kerning; } void GfxFont::SetKerningHeight( float kerning ) { m_nKerningHeight = kerning; } // 获取字间距 float GfxFont::GetKerningWidth() { return m_nKerningWidth; } float GfxFont::GetKerningHeight() { return m_nKerningHeight; } // 字体大小 float GfxFont::GetFontSize() { return m_nFontSize; } // 根据字符获取轮廓 unsigned int GfxFont::GetGlyphByCharacter( wchar_t c ) { unsigned int idx = (unsigned int)c; if (NULL == (m_Glyphs[idx].t)) CacheCharacter(idx,c); return idx; } inline float GfxFont::GetWidthFromCharacter( wchar_t c, bool original ) { unsigned int idx = GetGlyphByCharacter(c); if (original && idx > 0 && idx < font_count) return m_Glyphs[idx].c; return (idx >= 0x2000) ? m_nFontSize : _floor(m_nFontSize / 2); } inline void GfxFont::CacheCharacter(unsigned int idx, wchar_t c) { if (idx < font_count && NULL == m_Glyphs[idx].t) { UINT nChar = (UINT)c; MAT2 mat2 = {{0,1},{0,0},{0,0},{0,1}}; GLYPHMETRICS gm; DWORD nLen = ::GetGlyphOutlineW(m_hMemDC,nChar,m_nAntialias,&gm,0,NULL,&mat2); HTEXTURE hTex = m_pHGE->Texture_Create(gm.gmBlackBoxX,gm.gmBlackBoxY); if (NULL == hTex) return; if((signed)nLen > 0) { LPBYTE lpBuf = new BYTE[nLen]; if (nLen == ::GetGlyphOutlineW(m_hMemDC,nChar,m_nAntialias,&gm,nLen,lpBuf,&mat2)) { BYTE* lpSrc = lpBuf; DWORD* lpDst = m_pHGE->Texture_Lock(hTex,FALSE); if (GGO_BITMAP == m_nAntialias) { LONG nSrcPitch = (gm.gmBlackBoxX / 32 + (gm.gmBlackBoxX % 32 == 0 ? 0 : 1)) * 4; LONG nDstPitch = m_pHGE->Texture_GetWidth(hTex); for (UINT y = 0; y < gm.gmBlackBoxY; ++y) { for (UINT x = 0; x < gm.gmBlackBoxX; ++x) { for(UINT k = 0; k < 8; ++k) { UINT i = 8 * x + k; if (i >= gm.gmBlackBoxX) { x+=7; break; } lpDst[i] = ((lpSrc[x] >> (7 - k)) & 1) ? 0xFFFFFFFF : 0x0; } } lpSrc += nSrcPitch; lpDst += nDstPitch; } } else { LONG nSrcPitch = (gm.gmBlackBoxX / 4 + (gm.gmBlackBoxX % 4 == 0 ? 0 : 1)) * 4; LONG nDstPitch = m_pHGE->Texture_GetWidth(hTex); for (UINT y = 0; y < gm.gmBlackBoxY; ++y) { for (UINT x = 0; x < gm.gmBlackBoxX; ++x) { lpDst[x] = ARGB(g_byAlphaLevel[lpSrc[x]],0xFF,0xFF,0xFF); } lpSrc += nSrcPitch; lpDst += nDstPitch; } } m_pHGE->Texture_Unlock(hTex); } delete lpBuf; } else { // 非正常显示字符 } m_Glyphs[idx].t = hTex; m_Glyphs[idx].w = static_cast<float>(gm.gmBlackBoxX); m_Glyphs[idx].h = static_cast<float>(gm.gmBlackBoxY); m_Glyphs[idx].x = static_cast<float>(-gm.gmptGlyphOrigin.x); m_Glyphs[idx].y = static_cast<float>(-m_nAscent + gm.gmptGlyphOrigin.y); m_Glyphs[idx].c = static_cast<float>(gm.gmCellIncX); } }
[ "fengyu05@e74d88d6-4bf9-11de-b850-9977aa68d080" ]
[ [ [ 1, 315 ] ] ]
2842822a46cf7817b5a5e92ca84217dfc97bde0d
44e10950b3bf454080553a5da36bf263e6a62f8f
/src/GeneticAlg/ElPrice_loader.cpp
3f71b55478283d161765ae8f6e52386b997ae29f
[]
no_license
ptrefall/ste6246tradingagent
a515d88683bf5f55f862c0b3e539ad6144a260bb
89c8e5667aec4c74aef3ffe47f19eb4a1b17b318
refs/heads/master
2020-05-18T03:50:47.216489
2011-12-20T19:02:32
2011-12-20T19:02:32
32,448,454
1
0
null
null
null
null
UTF-8
C++
false
false
1,006
cpp
#include <fstream> #include <sstream> #include <iostream> #include "ElPrice_loader.h" std::vector<double> ElSpotPriceLoader::static_prices; void ElSpotPriceLoader::loadPriceData(const char* filename, std::vector<double> &prices) { if(!static_prices.empty()) { prices = static_prices; return; } std::ifstream stream( filename, std::ios::in); if(stream.bad()) { stream.close(); return; } std::streampos stream_length; stream.seekg( 0, std::ios::end ); stream_length = stream.tellg(); stream.seekg( 0, std::ios::beg ); std::vector<char> buffer( stream_length ); stream.read(&buffer[0], stream_length ); stream.close(); std::stringstream ss(&buffer[0]); //Skip header stuff for(unsigned int i = 0; i < 11; i++) { ss.ignore( 256, '\n' ); } //Process actual price data while( !ss.eof() ) { double price_kWh = 0.0; ss >> price_kWh; prices.push_back(price_kWh); static_prices.push_back(price_kWh); } ss.clear(); }
[ "[email protected]@92bc644c-bee7-7203-82ab-e16328aa9dbe" ]
[ [ [ 1, 49 ] ] ]
a0bef56554d7969f29b59aac1d971ad5afbd92ce
cbdc078b00041668dd740917e1e781f74b6ea9f4
/GiftFactory/src/Utils.cpp
8fa35b91d010906160ee760c3f238467a6b797c2
[]
no_license
mireidril/gift-factory
f30d8075575af6a00a42d54bfdd4ad4c953f1936
4888b59b1ee25a107715742d0495e40b81752051
refs/heads/master
2020-04-13T07:19:09.351853
2011-12-16T11:36:05
2011-12-16T11:36:05
32,514,347
0
0
null
null
null
null
UTF-8
C++
false
false
6,706
cpp
#include "Utils.hpp" GLubyte * loadPPM(const char * const fn, unsigned int& w, unsigned int& h) { char head[70]; int i, j; int d; GLubyte * img = NULL; FILE * f; fopen_s(&f, fn, "r"); if(f == NULL) { fprintf(stderr,"Error in function readPPM : %s doesn't exist\n",fn); return 0; } (void)fgets(head,70,f); if(!strncmp(head, "P6", 2) ) { i=0; j=0; while(i<3) { (void)fgets(head,70,f); if(head[0] == '#') { continue; } if(i==0) i += sscanf_s(head, "%d %d %d", &w, &h, &d); else if(i==1) i += sscanf_s(head, "%d %d", &h, &d); else if(i==2) i += sscanf_s(head, "%d", &d); } img = new GLubyte[(size_t)(w) * (size_t)(h) * 3]; if(img==NULL) { fclose(f); return 0; } (void)fread(img, sizeof(GLubyte), (size_t)w*(size_t)h*3,f); invertPicture(img, w, h); fclose(f); } else { fclose(f); fprintf(stderr,"Error in function readPPM : %s isn't a PPM file\n",fn); } return img; } void invertPicture( GLubyte * img, unsigned int& w, unsigned int& h ){ for( unsigned int i = 0 ; i < (w*h*3)/2 ; i+=3){ /*GLubyte temp = img[(w*h*3)-i]; img[(w*h*3)-i] = img[i]; img[i] = temp;*/ for( int k = 0 ; k < 3 ; k++){ GLubyte temp = img[i+k]; img[i+k] = img[(w*h*3)-i-(3-k)]; img[(w*h*3)-i-(3-k)] = temp; } } } // To normalize a vector void normalize (GLfloat * a) { GLfloat norm=sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]); if (norm!=0.0) { a[0]/=norm; a[1]/=norm; a[2]/=norm; } } GLfloat getNorm (GLfloat * a){ return sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]); } // To get the vector product void vectorProduct (GLfloat * a, GLfloat * b, GLfloat * result) { result[0]=a[1]*b[2] - a[2]*b[1]; result[1]=a[2]*b[0] - a[0]*b[2]; result[2]=a[0]*b[1] - a[1]*b[0]; } // Does the multiplication A=A*B : all the matrices are described column-major void multMatrixBtoMatrixA(GLfloat * A, GLfloat * B) { int i=0; // row index int j=0; // column index GLfloat temp[16]; for (int iValue=0 ; iValue<16 ; iValue++) { temp[iValue]=0; //j=iValue%4; // if raw-major //i=iValue/4; // if raw-major i=iValue%4; // if column-major j=iValue/4; // if column-major for (int k=0 ; k<4 ; k++) { int indexik=k*4+i; int indexkj=j*4+k; temp[iValue]+=A[indexik]*B[indexkj]; } } for (int iValue=0 ; iValue<16 ; iValue++) A[iValue]=temp[iValue]; } // Does the multiplication result=A*B : all the matrices are described column-major void multMatrixBtoMatrixA(GLfloat * A, GLfloat * B, GLfloat * result) { int i=0; // row index int j=0; // column index for (int iValue=0 ; iValue<16 ; iValue++) { result[iValue]=0; //j=iValue%4; // if raw-major //i=iValue/4; // if raw-major i=iValue%4; // if column-major j=iValue/4; // if column-major for (int k=0 ; k<4 ; k++) { int indexik=k*4+i; int indexkj=j*4+k; result[iValue]+=A[indexik]*B[indexkj]; } } } // Sets the provided matrix to identity void setToIdentity(GLfloat * matrix) { GLfloat I[]={1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0}; for (int iMatrixCoord=0 ; iMatrixCoord<16 ; iMatrixCoord++) matrix[iMatrixCoord]=I[iMatrixCoord]; } // Sets the provided matrix to a translate matrix on vector t void setToTranslate(GLfloat * matrix, GLfloat * t) { GLfloat T[]={1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, t[0], t[1], t[2], 1.0}; for (int iMatrixCoord=0 ; iMatrixCoord<16 ; iMatrixCoord++) matrix[iMatrixCoord]=T[iMatrixCoord]; } // Sets the provided matrix to a scale matrix by coeficients in s void setToScale(GLfloat * matrix, GLfloat * s) { GLfloat S[]={s[0], 0.0, 0.0, 0.0, 0.0, s[1], 0.0, 0.0, 0.0, 0.0, s[2], 0.0, 0.0, 0.0, 0.0, 1.0}; for (int iMatrixCoord=0 ; iMatrixCoord<16 ; iMatrixCoord++) matrix[iMatrixCoord]=S[iMatrixCoord]; } // Sets the provided matrix to a rotate matrix of angle "angle", around axis "axis" void setToRotate(GLfloat * matrix, GLfloat angle, GLfloat * axis) { GLfloat c=cos(angle); GLfloat s=sin(angle); GLfloat x=axis[0]; GLfloat y=axis[1]; GLfloat z=axis[2]; if ((x==1.0) && (y==0.0) && (z==0.0)) { GLfloat R[]={1.0, 0.0, 0.0, 0.0, 0.0, c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0}; for (int iMatrixCoord=0 ; iMatrixCoord<16 ; iMatrixCoord++) matrix[iMatrixCoord]=R[iMatrixCoord]; } else { if ((x==0.0) && (y==1.0) && (z==0.0)) { GLfloat R[]={c, 0.0, -s, 0.0, 0.0, 1.0, 0.0, 0.0, s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0}; for (int iMatrixCoord=0 ; iMatrixCoord<16 ; iMatrixCoord++) matrix[iMatrixCoord]=R[iMatrixCoord]; } else { if ((x==0.0) && (y==0.0) && (z==1.0)) { GLfloat R[]={c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0}; for (int iMatrixCoord=0 ; iMatrixCoord<16 ; iMatrixCoord++) matrix[iMatrixCoord]=R[iMatrixCoord]; } else { GLfloat R[]={ (1.0-c)*(x*x-1.0) + 1.0, (1.0-c)*x*y + (z*s), (1.0-c)*x*z - (y*s), 0.0, (1.0-c)*x*y - (z*s), (1.0-c)*(y*y-1.0) + 1.0, (1.0-c)*y*z + (x*s), 0.0, (1.0-c)*x*z + (y*s), (1.0-c)*y*z - (x*s), (1.0-c)*(z*z-1.0) + 1.0, 0.0, 0.0, 0.0, 0.0, 1.0}; for (int iMatrixCoord=0 ; iMatrixCoord<16 ; iMatrixCoord++) matrix[iMatrixCoord]=R[iMatrixCoord]; std::cout<<"Rotation on non standard axis."<<std::endl; } } } }
[ "celine.cogny@369dbe5e-add6-1733-379f-dc396ee97aaa", "delau.eleonore@369dbe5e-add6-1733-379f-dc396ee97aaa", "marjory.gaillot@369dbe5e-add6-1733-379f-dc396ee97aaa" ]
[ [ [ 1, 40 ], [ 42, 47 ], [ 49, 57 ], [ 237, 237 ] ], [ [ 41, 41 ], [ 48, 48 ], [ 60, 72 ] ], [ [ 58, 59 ], [ 73, 236 ] ] ]
ec1b10c30b4f82d7dc6c475419d7c1ad12f4d2ac
24bc1634133f5899f7db33e5d9692ba70940b122
/src/ammo/util/profiler.cpp
657777cf9ca9168732e61df79753d84b92987698
[]
no_license
deft-code/ammo
9a9cd9bd5fb75ac1b077ad748617613959dbb7c9
fe4139187dd1d371515a2d171996f81097652e99
refs/heads/master
2016-09-05T08:48:51.786465
2009-10-09T05:49:00
2009-10-09T05:49:00
32,252,326
0
0
null
null
null
null
UTF-8
C++
false
false
414
cpp
#include "ammo/util/profiler.hpp" #ifdef PROFILINGENABLED namespace ammo { float Profiler::_timeSteps[Profiler::Max_Frames] = {0.f}; std::string Profiler::_categories[Profiler::Max_Categories]; ProfileData Profiler::_data[Profiler::Max_Categories][Profiler::Max_Frames]; int Profiler::_numCategories = 0; int Profiler::_currentFrame = -1; bool Profiler::_isFull = false; } #endif
[ "PhillipSpiess@d8b90d80-bb63-11dd-bed2-db724ec49875", "j.nick.terry@d8b90d80-bb63-11dd-bed2-db724ec49875" ]
[ [ [ 1, 7 ], [ 9, 14 ] ], [ [ 8, 8 ], [ 15, 16 ] ] ]
005f2327a7b9aa5642cb8a0a662ab8f1cfc96002
77aa13a51685597585abf89b5ad30f9ef4011bde
/dep/src/boost/boost/fusion/adapted/array/detail/category_of_impl.hpp
f11aef68c0b99b8f24b7171050cbb5fa307eded3
[ "BSL-1.0" ]
permissive
Zic/Xeon-MMORPG-Emulator
2f195d04bfd0988a9165a52b7a3756c04b3f146c
4473a22e6dd4ec3c9b867d60915841731869a050
refs/heads/master
2021-01-01T16:19:35.213330
2009-05-13T18:12:36
2009-05-14T03:10:17
200,849
8
10
null
null
null
null
UTF-8
C++
false
false
1,031
hpp
/*============================================================================= Copyright (c) 2001-2006 Joel de Guzman Copyright (c) 2005-2006 Dan Marsden Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(BOOST_FUSION_CATEGORY_OF_IMPL_27122005_1044) #define BOOST_FUSION_CATEGORY_OF_IMPL_27122005_1044 #include <boost/config/no_tr1/utility.hpp> namespace boost { namespace fusion { struct array_tag; struct random_access_traversal_tag; namespace extension { template<typename T> struct category_of_impl; template<> struct category_of_impl<array_tag> { template<typename T> struct apply { typedef random_access_traversal_tag type; }; }; } }} #endif
[ "pepsi1x1@a6a5f009-272a-4b40-a74d-5f9816a51f88" ]
[ [ [ 1, 35 ] ] ]
162233c04b6774a14846989294158e5e1de43800
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak/String.inl
8a9373a1d35a04ca9605f7551655b98592f92925
[]
no_license
halak/halak-plusplus
d09ba78640c36c42c30343fb10572c37197cfa46
fea02a5ae52c09ff9da1a491059082a34191cd64
refs/heads/master
2020-07-14T09:57:49.519431
2011-07-09T14:48:07
2011-07-09T14:48:07
66,716,624
0
0
null
null
null
null
UTF-8
C++
false
false
11,203
inl
#include <Halak/Assert.h> #include <Halak/NullPointer.h> #include <cstring> #include <stdexcept> namespace Halak { String::String() : buffer(Empty.buffer) { } String::String(const char* s) : buffer((s && s[0] != '\0') ? SharedPointer<StringBuffer>(new StringBuffer(s)) : Empty.buffer) { } String::String(const String& original) : buffer(original.buffer) { } String::String(const String& original, int startIndex) { if (original.buffer->length > startIndex) buffer.Reset(new StringBuffer(&original.buffer->s[startIndex])); else buffer = Empty.buffer; } String::String(const String& original, int startIndex, int length) { if (original.buffer->length > startIndex) { if (startIndex + length <= original.buffer->length) buffer.Reset(new StringBuffer(&original.buffer->s[startIndex], length)); else buffer.Reset(new StringBuffer(&original.buffer->s[startIndex], original.buffer->length - startIndex)); } else buffer = Empty.buffer; } String::~String() { } int String::ReverseFind(char c) const { return buffer->length > 0 ? ReverseFind(c, buffer->length - 1) : -1; } int String::ReverseFind(const char* s) const { return buffer->length > 0 ? ReverseFind(s, buffer->length - 1) : -1; } int String::ReverseFind(const String& s) const { return buffer->length > 0 ? ReverseFind(s, buffer->length - 1) : -1; } int String::ReverseFindIgnoreCase(char c) const { return buffer->length > 0 ? ReverseFindIgnoreCase(c, buffer->length - 1) : -1; } int String::ReverseFindIgnoreCase(const char* s) const { return buffer->length > 0 ? ReverseFindIgnoreCase(s, buffer->length - 1) : -1; } int String::ReverseFindIgnoreCase(const String& s) const { return buffer->length > 0 ? ReverseFindIgnoreCase(s, buffer->length - 1) : -1; } const char* String::CStr() const { return buffer->s; } const char* String::GetCharPointer() const { return buffer->s; } int String::GetLength() const { return buffer->length; } bool String::IsEmpty() const { return buffer->length == 0; } String& String::operator = (char right) { if (right != '\0') { const char s[] = { right, '\0' }; buffer.Reset(new StringBuffer(s, 1)); } else buffer = Empty.buffer; return *this; } String& String::operator = (const char* right) { if (right && right[0] != '\0') buffer.Reset(new StringBuffer(right)); else buffer = Empty.buffer; return *this; } String& String::operator = (const String& right) { buffer = right.buffer; return *this; } String& String::operator += (char right) { const char s[] = { right, '\0' }; Append(s); return *this; } String& String::operator += (const char* right) { Append(right); return *this; } String& String::operator += (const String& right) { Append(right); return *this; } String String::operator + (char right) const { const char s[] = { right, '\0' }; return String(AppendTag(), buffer->s, buffer->length, s, 1); } String String::operator + (const char* right) const { return String(AppendTag(), buffer->s, buffer->length, right, -1); } String String::operator + (const String& right) const { return String(AppendTag(), buffer->s, buffer->length, right.buffer->s, right.buffer->length); } bool String::operator == (const char* right) const { return Equals(right); } bool String::operator == (const String& right) const { return Equals(right); } bool String::operator != (const char* right) const { return !Equals(right); } bool String::operator != (const String& right) const { return !Equals(right); } bool String::operator < (const char* right) const { return Compare(right) < 0; } bool String::operator < (const String& right) const { return Compare(right) < 0; } bool String::operator > (const char* right) const { return Compare(right) > 0; } bool String::operator > (const String& right) const { return Compare(right) > 0; } bool String::operator <= (const char* right) const { return Compare(right) <= 0; } bool String::operator <= (const String& right) const { return Compare(right) <= 0; } bool String::operator >= (const char* right) { return Compare(right) >= 0; } bool String::operator >= (const String& right) const { return Compare(right) >= 0; } String::CharRef String::operator [] (int index) { HKAssertDebug(0 <= index && index < buffer->length); return CharRef(*this, index); } char String::operator [] (int index) const { HKAssertDebug(0 <= index && index < buffer->length); return buffer->s[index]; } bool operator == (const char* left, const String& right) { return right == left; } bool operator != (const char* left, const String& right) { return right != left; } bool operator < (const char* left, const String& right) { return right > left; } bool operator > (const char* left, const String& right) { return right < left; } bool operator <= (const char* left, const String& right) { return right >= left; } bool operator >= (const char* left, const String& right) { return right <= left; } //////////////////////////////////////////////////////////////////////////////////////////////////// inline int CompareString(const char* s1, const char* s2) { return strcmp(s1, s2); } inline int CompareString(const char* s1, const char* s2, int length) { return strncmp(s1, s2, length); } //////////////////////////////////////////////////////////////////////////////////////////////////// String::CharRef::CharRef(String& s, int index) : s(s), index(index) { } String::CharRef::CharRef(const CharRef& original) : s(original.s), index(original.index) { } String::CharRef& String::CharRef::operator = (char c) { if (s.buffer.GetReferenceCount() > 1) s.buffer.Reset(new StringBuffer(*s.buffer)); s.buffer->s[index] = c; return *this; } String::CharRef::operator char () const { return s.buffer->s[index]; } //////////////////////////////////////////////////////////////////////////////////////////////////// String::UTF8CharEnumerator::UTF8CharEnumerator(const char* s) : s(s), length(strlen(s)), index(-1), current(0) { } String::UTF8CharEnumerator::UTF8CharEnumerator(const char* s, int length) : s(s), length(length), index(-1), current(0) { } String::UTF8CharEnumerator::UTF8CharEnumerator(const String& s) : s(s.buffer->s), length(s.GetLength()), index(-1), current(0) { } String::UTF8CharEnumerator::UTF8CharEnumerator(const UTF8CharEnumerator& original) : s(original.s), length(original.length), index(original.index), current(original.current) { } void String::UTF8CharEnumerator::Reset() { index = -1; current = 0; } bool String::UTF8CharEnumerator::MoveNext() { index++; if (index < length) { const byte* buffer = reinterpret_cast<const byte*>(s); byte first = buffer[index]; if (first <= 0x7F) { current = first; return true; } else if (0xC2 <= current && current <= 0xDF) { HKAssertDebug(index + 1 < length); current = (static_cast<uint>(buffer[index + 0]) << 8) | (static_cast<uint>(buffer[index + 1]) << 0); index += 1; return true; } else if (0xE0 <= current && current <= 0xEF) { HKAssertDebug(index + 2 < length); current = (static_cast<uint>(buffer[index + 0]) << 16) | (static_cast<uint>(buffer[index + 1]) << 8) | (static_cast<uint>(buffer[index + 2]) << 0); index += 2; return true; } else if (0xF0 <= current && current <= 0xF4) { HKAssertDebug(index + 3 < length); current = (static_cast<uint>(buffer[index + 0]) << 24) | (static_cast<uint>(buffer[index + 1]) << 16) | (static_cast<uint>(buffer[index + 2]) << 8) | (static_cast<uint>(buffer[index + 3]) << 0); index += 3; return true; } else return false; // Invalid Character } else return false; } int String::UTF8CharEnumerator::GetCurrent() const { return current; } String::UTF8CharEnumerator& String::UTF8CharEnumerator::operator = (const UTF8CharEnumerator& right) { s = right.s; length = right.length; index = right.index; current = right.current; return *this; } //////////////////////////////////////////////////////////////////////////////////////////////////// String::StringBuffer::StringBuffer(const char* s, int length) : s(nullptr), length(0), hashCode(0) { Initialize(s, length); } String::StringBuffer::StringBuffer(const StringBuffer& original) : s(nullptr), length(0), hashCode(0) { Initialize(original.s, original.length); } String::StringBuffer::~StringBuffer() { delete [] s; } String::StringBuffer& String::StringBuffer::operator = (const StringBuffer& original) { delete [] s; Initialize(original.s, original.length); return *this; } }
[ [ [ 1, 436 ] ] ]
73d890505fd597938780c55d624e1eec69e85240
2112057af069a78e75adfd244a3f5b224fbab321
/branches/ref1/src-root/src/ireon_rs/net/rspc/rspc_check_version_state.cpp
25daa1e728209e26c9deed89cbd85c7aa12ef387
[]
no_license
blockspacer/ireon
120bde79e39fb107c961697985a1fe4cb309bd81
a89fa30b369a0b21661c992da2c4ec1087aac312
refs/heads/master
2023-04-15T00:22:02.905112
2010-01-07T20:31:07
2010-01-07T20:31:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,036
cpp
/** * @file ireon_rs/net/rspc/rspc_check_version_state.cpp * root server player context checking version state */ /* Copyright (C) 2005-2006 ireon.org developers council * $Id$ * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #include "ireon_rs/net/rspc/rspc_check_version_state.h" #include "common/net/signal_codes/rspc_codes.h" #include "common/net/signal_codes/pcrs_codes.h" //#include "ireon_rs/accounts/user_account.h" #include "ireon_rs/root_app.h" //#include "ireon_rs/net/root_eserver.h" #include "ireon_client/version.h" #include "ireon_rs/stdafx.h" CRSPCCheckVersionState::CRSPCCheckVersionState(CRSPlayerConnection *ownerConnection): m_ownerConnection(ownerConnection) { setStateName("Check Version State"); registerSlot(ireon::net::rspcCodes::scCheckVersion, (CGenericSlot) &CRSPCCheckVersionState::onCheckVersionRequest); } // --------------------------------------------------------------------- void CRSPCCheckVersionState::onCheckVersionRequest(CData &data) { byte clientVersion[4]; //memset(&clientVersion[0],0,4*sizeof(byte)); for (int i = 0; i < 4; i++) data >> clientVersion[i]; CLog::instance()->log(CLog::msgLvlVerbose, _("Processing received version = '%u.%u.%u.%u' from host %s ... "),clientVersion[0],clientVersion[1],clientVersion[2],clientVersion[3], m_ownerConnection->getConnectionInfo()); bool versionCompareFail = false; // note: this is CLIENT version (from ireon_client/vesrion.h) const byte rsVersion[4]={PRODUCT_VERSION}; for(int i = 0; i < 4; i++) if (clientVersion[i] != rsVersion[i]) versionCompareFail = true; CData answer; // TODO compare client version and server version if (!versionCompareFail) { answer.wrt((ireon::net::commandId) ireon::net::pcrsCodes::scCheckVersionOk); CLog::instance()->log(CLog::msgLvlVerbose, _("OK\n")); m_ownerConnection->setNextState(CRSPlayerConnection::csHello); m_ownerConnection->write(answer); return; } else { answer.wrt((ireon::net::commandId) ireon::net::pcrsCodes::scCheckVersionOld); for(int i = 0; i < 4; i++) answer.wrt((byte) rsVersion[i]); CLog::instance()->log(CLog::msgLvlVerbose, _("Failed\n")); m_ownerConnection->write(answer); return; } return; }; // ---------------------------------------------------------------------
[ [ [ 1, 84 ] ] ]
5de2fc91861d203776384dc64c6419335d1053bf
028d6009f3beceba80316daa84b628496a210f8d
/debuggercdi/com.nokia.carbide.trk.support/Native/GetTRKVersion/TestGetTRKVersion/TestGetTRKVersion.cpp
87b7a3adef9e4c5c52ed8cddccf87bfca31fda11
[]
no_license
JamesLinus/oss.FCL.sftools.dev.ide.carbidecpp
fa50cafa69d3e317abf0db0f4e3e557150fd88b3
4420f338bc4e522c563f8899d81201857236a66a
refs/heads/master
2020-12-30T16:45:28.474973
2010-10-20T16:19:31
2010-10-20T16:19:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
948
cpp
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "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: * */ // TestGetTRKVersion.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "GetTRKVersion.h" int main(int argc, char* argv[]) { printf("Calling GetTRKVersion()\n"); long version[4]; DWORD error = GetTRKVersion("\\\\.\\COM26", -1, 0, 0, 0, 0, version); if (error != 0) printf("Error = %d\n", error); else printf("Version ints = %d, %d, %d, %d\n", version[0], version[1], version[2], version[3]); return 0; }
[ "[email protected]", "none@none" ]
[ [ [ 1, 26 ], [ 29, 32 ], [ 34, 37 ] ], [ [ 27, 28 ], [ 33, 33 ] ] ]
69c428aa9af37abbb4e0fad66d5f8b4987eea372
3128346a72b842c6dd94f2b854170d5daeeedc6f
/src/CoreFlareList.h
3b44e8189a5087b4348baf1cbb5adc1aaf992db1
[]
no_license
Valrandir/Core512
42c3ed02f3f5455a9e0d722c014c80bb2bae17ab
af6b45aa2eded3f32964339ffebdab3491b08561
refs/heads/master
2021-01-22T04:57:15.719013
2011-11-11T05:16:30
2011-11-11T05:16:30
2,607,600
1
1
null
null
null
null
UTF-8
C++
false
false
350
h
#pragma once #include <list> #include "CoreFlare.h" class CoreVector; typedef std::list<CoreFlare*> CoreFlareVec; class CoreFlareList { CoreFlareVec vFlare; public: ~CoreFlareList(); void Add(const CoreVector& Position, const char* ResPath, int SpritePerX, int SpritePerY); void Update(float Delta); void Render() const; };
[ [ [ 1, 17 ] ] ]
1004c8eb2dde005fb3f5be534366c91646034981
b240ccb537657eb72a3ac7634c99e3b8733e454c
/code/api/api_v001rc/networkcommunication/tcpSocket/main.cpp
edceb4b439d7de0f389457a479032b96d4e5dd35
[]
no_license
Jmos/ftofsharing
96c2c77deab4c15da0ec42b14e0c17f5adfeb485
8969c3b33a2173c36f3a282b946b92656d77ad81
refs/heads/master
2021-01-22T23:16:04.198478
2011-06-04T18:46:00
2011-06-04T18:46:00
34,392,347
0
0
null
null
null
null
UTF-8
C++
false
false
1,549
cpp
//================================================================= // Name: main.cpp // Autor: Saxl Georg // Version: 1.0 // Datum: 14.10.2010 // Beschreibung: //================================================================= #include <QStringList> #include <QDomDocument> #include <QString> #include <QFile> #include <QList> #include <QFile> #include <QTextStream> #include <stdio.h> #include <iostream> #include <QObject> #include "pop3client.h" #include "smtpclient.h" using namespace std; int main (int argc, char** argv) { CSmtpClient smtp; REMail mail; mail.To= "[email protected]"; mail.From= "[email protected]"; mail.Subject= "Testmail"; mail.Body.append("Hallo,"); mail.Body.append("Das ist eine Testmail."); mail.Body.append("Test"); mail.Body.append("blablabla"); smtp.SetServerPort(587); smtp.SendMail(&mail, "mailserver", "username", "password"); cout << "\n\nErrorCode: " << smtp.GetLastErrorCode() << endl; /* CPop3Client pop; REMail *mail; mail= pop.GetMail(1 ,"pop.utanet.at", "saxlruth", "coolpix"); if (mail != NULL) { cout << "\n\nTo: " << qPrintable(mail->To); cout << "\nFrom: " << qPrintable(mail->From); cout << "\nSubject: " << qPrintable(mail->Subject) << "\n\nBody:\n\n"; for (int Index= 0; Index < mail->Body.size(); Index++) cout << qPrintable(mail->Body.at(Index)) << endl; } cout << "\n\nErrorCode: " << pop.GetLastErrorCode() << endl; */ getchar(); return 0xDEAD; }
[ "georgsaxl@ed7a1941-e62f-a9da-ef21-68f2f9546975" ]
[ [ [ 1, 71 ] ] ]
45a1ef1749b077d209f55f352795ab9c1aed1e15
3f85fe4138d1384aed1a9be49b63a3fb366e53a1
/networks/multithreading/Socket.h
c06decf1d24abeeb9bf127d58608988f2a92e982
[]
no_license
anisha-agarwal/samples
3554408b63ac249ba27bdd54dacb7c03eb7de35a
ec4969b2510e830de970363be5eb652c71791738
refs/heads/master
2021-01-16T19:34:04.301858
2011-01-22T23:35:22
2011-01-22T23:35:22
1,283,061
1
0
null
null
null
null
UTF-8
C++
false
false
3,849
h
/** * @class : Socket.h * @desc : This implements the socket class */ #ifndef _Socket_h_ #define _Socket_h__ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <arpa/inet.h> #include <pthread.h> class Socket { public: int sockfd,c_id; /** * @brief : Constructor which creates a new socket identifier generated by accept * @param[in] : socket ID * @param[out] : n/a */ Socket(int sock_id) { sockfd = sock_id; } /** * @brief : default constructor */ Socket() { if ((sockfd = socket(AF_INET, SOCK_STREAM,0)) == -1) { perror("socket"); exit(1); } } /** * @brief : desctructor */ ~Socket() {} /** * @brief : Bind the socket with port of local machine */ int Bind(int my_PORT, char* rec) { struct sockaddr_in my_addr; my_addr.sin_family = AF_INET; // host byte order my_addr.sin_port = my_PORT; // short, network byte order my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof my_addr) == -1) { perror("bind"); exit(1); } } /** * @brief : listen to incoming connections */ int Listen() { int backlog = 20; if(listen(sockfd,backlog) == -1) { perror("listen"); exit(1); } } /** * @brief : Accepts a new connection * @param[out] : Returns the new socket if successful, else NULL */ Socket* Accept(char* dest) { int new_fd; socklen_t sin_size; struct hostent *dest_addr; struct sockaddr_in their_addr; if((dest_addr = gethostbyname(dest)) == NULL) { perror("gethostbyname"); exit(1); } their_addr.sin_addr = *((struct in_addr *)dest_addr->h_addr); sin_size = sizeof their_addr; if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) { perror("accept"); } Socket* new_sock = new Socket(new_fd); return new_sock; } /** * @brief : close the socket */ int Close() { if((c_id = close(sockfd)) == -1) { perror("close"); } } /** * @brief : used by client to connect to a remote server */ int Connect(int dest_PORT, char* dest) { struct hostent *dest_addr; struct sockaddr_in their_addr; if((dest_addr = gethostbyname(dest)) == NULL) { perror("gethostbyname"); exit(1); } their_addr.sin_family = AF_INET; // host byte order their_addr.sin_port = dest_PORT; // short,network byte order their_addr.sin_addr = *((struct in_addr *)dest_addr->h_addr); if(connect(sockfd, (struct sockaddr *)&their_addr, sizeof their_addr) == -1) { perror("connect"); exit(1); } } /** * @brief : Read len bytes into buffer, returns actual bytes read */ int Read(char* buffer, int len) { int numbytes; if((numbytes = recv(sockfd,buffer,len,0)) == -1) { perror("recv"); exit(1); } buffer[numbytes] = '\0'; return numbytes; } /** * @brief : send len bytes from buffer. returns actual bytes sent */ int Send(const char* buffer, int len) { if (send(sockfd, buffer, len, 0) == -1) { perror("send"); } return 0; } /** * @brief : Sends an integer to the client when server receives a get call */ }; #endif
[ [ [ 1, 181 ] ] ]
0d6ed145ee6086ff63baa8876bc902e8dc024b24
335783c9e5837a1b626073d1288b492f9f6b057f
/source/fbxcmd/daolib/Model/PHY/DSTJ.h
62c8c9e159b9a03570a4d859d9b732638dda2796
[ "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
1,275
h
/********************************************************************** *< FILE: DSTJ.h DESCRIPTION: PHY File Format HISTORY: *> Copyright (c) 2009, All Rights Reserved. **********************************************************************/ #pragma once #include "PHY/PHYCommon.h" #include "GFF/GFFField.h" #include "GFF/GFFList.h" #include "GFF/GFFStruct.h" namespace DAO { using namespace GFF; namespace PHY { /////////////////////////////////////////////////////////////////// class DSTJ { protected: GFFStructRef impl; static ShortString type; public: DSTJ(GFFStructRef owner); static const ShortString& Type() { return type; } const ShortString& get_type() const { return type; } float get_jointDistanceMinDistance() const; void set_jointDistanceMinDistance(float value); float get_jointDistanceMaxDistance() const; void set_jointDistanceMaxDistance(float value); Vector3f get_jointDistanceSpring() const; void set_jointDistanceSpring(Vector3f value); unsigned long get_jointDistanceDistanceFlags() const; void set_jointDistanceDistanceFlags(unsigned long value); }; typedef ValuePtr<DSTJ> DSTJPtr; typedef ValueRef<DSTJ> DSTJRef; } //namespace PHY } //namespace DAO
[ "tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792" ]
[ [ [ 1, 57 ] ] ]
f650b35eea557c9a5840305433a514ee1fea855a
926ba06ae2c7b672299e04613de62dbc2d8df8ac
/src/main.cpp
747e9b1792f90df83524622083407d2c863402d6
[]
no_license
klusark/ns2browser
4db222b40309d0b41c5e5ff9ecc75dd8af7e847c
ead2ee0cdfb040411828451fb3c0172cdcec85c2
refs/heads/master
2020-04-06T06:24:06.959522
2010-04-12T02:17:41
2010-04-12T02:17:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
220
cpp
#include "Broadcaster.hpp" #include "Proxy.hpp" int main() { Proxy proxy(27040, Poco::Net::SocketAddress("5.99.12.77", 27015)); Broadcaster broadcast; broadcast.Broadcast(); while (1){ Sleep(1); } }
[ [ [ 1, 13 ] ] ]
0156ac245df5b40ef77c07d827d4307e8f93d5e1
aa96d2feea77cd3279120ca5a09c0407a2fbace6
/src/Player.h
1b53072d4aa7d9b169a5e7d8cec4494d3b2d4d47
[]
no_license
uri/2404-mega-project
3287daf53e2bc15aebb4a3f88e4014f7b6c60054
3ce747c9486ace6c02c80ff7df98bf85fd5ac578
refs/heads/master
2016-09-06T10:21:46.835850
2011-11-04T03:05:40
2011-11-04T03:05:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,195
h
/////////////////////////////////////////////////////////////////////////// // --------------------------------------------------------------------- // // // // Developers: Uri Gorelik, Eric Rhodes // // Filename: Player.h // // // // --------------------------------------------------------------------- // /////////////////////////////////////////////////////////////////////////// #ifndef PLAYER_H #define PLAYER_H #include "List.h" #include <vector> class Board; class Statistics; class Position; class Ship; using std::vector; class Player { public: // Constructor Player(void); ~Player(void); // Accessors Board * getBoard(void); Board * getHiddenBoard(void); Statistics * getStats(void); List<Position *> * getHits(void); List<Position *> * getMisses(void); List<Position *> * getHitsAndMisses(void); void addToLists(Position, int); vector<Position> * getRecentHits(); vector<Position> * getRecentMisses(); // Methods void clearOutputLists(); //clears the recentHits and recentMisses lists Position querryTarget(bool); bool firePointMissile(Player * opponent,Position pos); bool fireQuadMissile(Player *opponent, Position pos); bool fireSeekerMissile(Player *opponent); bool fireNuke(Player *opponent, Position pos); int selectMissile(); void destroyShip(Player *, Ship *); bool checkPosition(int, int); bool shoot(Player *, Position pos, int ordnanceType); //for when position is pregenereated (AI or networked foe) bool shoot(Player *); //for when you shoot void printStats(); private: int seekers; char missileName[15]; Board * mBoard; Board * mHiddenBoard; Statistics * mStats; List<Position *> * mHitPos; List<Position *> * mMissPos; List<Position *> * mHitsandMisses; vector<Position> * recentHits; vector<Position> * recentMisses; }; #endif
[ [ [ 1, 74 ] ] ]
0cfd9de996553c8a42241853b96f2d1e014613db
0b7226783e4b70944b4e66ae21eee9a3a0394e81
/src/fsassembler/src/bnfc output/parse.cpp
8d2471985b6d1811219c8216386fa98e89634eff
[]
no_license
LittleEngineer/fridgescript
061e3d3f0d17d8c0c0b8e089a3254c56edfa74e6
55b2e6bab63e826291b8d14f24c40f413f895e54
refs/heads/master
2021-01-10T16:52:37.530928
2009-09-06T10:58:21
2009-09-06T10:58:21
46,175,065
0
0
null
null
null
null
UTF-8
C++
false
false
94,121
cpp
/* A Bison parser, made by GNU Bison 2.1. */ /* Skeleton parser for GLR parsing with Bison, Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* This is the parser code for GLR (Generalized LR) parser. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "2.1" /* Skeleton name. */ #define YYSKELETON_NAME "glr.c" /* Pure parsers. */ #define YYPURE 0 /* Using locations. */ #define YYLSP_NEEDED 0 /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { _ERROR_ = 258, _SYMB_0 = 259, _SYMB_1 = 260, _SYMB_2 = 261, _SYMB_3 = 262, _SYMB_4 = 263, _SYMB_5 = 264, _SYMB_6 = 265, _SYMB_7 = 266, _SYMB_8 = 267, _SYMB_9 = 268, _SYMB_10 = 269, _SYMB_11 = 270, _SYMB_12 = 271, _SYMB_13 = 272, _SYMB_14 = 273, _SYMB_15 = 274, _SYMB_16 = 275, _SYMB_17 = 276, _SYMB_18 = 277, _SYMB_19 = 278, _SYMB_20 = 279, _SYMB_21 = 280, _SYMB_22 = 281, _SYMB_23 = 282, _SYMB_24 = 283, _SYMB_25 = 284, _SYMB_26 = 285, _SYMB_27 = 286, _SYMB_28 = 287, _SYMB_29 = 288, _SYMB_30 = 289, _SYMB_31 = 290, _SYMB_32 = 291, _SYMB_33 = 292, _SYMB_34 = 293, _SYMB_35 = 294, _SYMB_36 = 295, _SYMB_37 = 296, _SYMB_38 = 297, _SYMB_39 = 298, _SYMB_40 = 299, _SYMB_41 = 300, _SYMB_42 = 301, _SYMB_43 = 302, _SYMB_44 = 303, _SYMB_45 = 304, _SYMB_46 = 305, _SYMB_47 = 306, _SYMB_48 = 307, _SYMB_49 = 308, _SYMB_50 = 309, _SYMB_51 = 310, _SYMB_52 = 311, _SYMB_53 = 312, _SYMB_54 = 313, _SYMB_55 = 314, _SYMB_56 = 315, _SYMB_57 = 316, _SYMB_58 = 317, _SYMB_59 = 318, _SYMB_60 = 319, _SYMB_61 = 320, _SYMB_62 = 321, _SYMB_63 = 322, _SYMB_64 = 323, _SYMB_65 = 324, _SYMB_66 = 325, _SYMB_67 = 326, _SYMB_68 = 327, _SYMB_69 = 328, _SYMB_70 = 329, _SYMB_71 = 330, _SYMB_72 = 331, _SYMB_73 = 332, _SYMB_74 = 333, _SYMB_75 = 334, _SYMB_76 = 335, _SYMB_77 = 336, _SYMB_78 = 337, _SYMB_79 = 338, _SYMB_80 = 339, _SYMB_81 = 340, _INTEGER_ = 341, _IDENT_ = 342 }; #endif /* Tokens. */ #define _ERROR_ 258 #define _SYMB_0 259 #define _SYMB_1 260 #define _SYMB_2 261 #define _SYMB_3 262 #define _SYMB_4 263 #define _SYMB_5 264 #define _SYMB_6 265 #define _SYMB_7 266 #define _SYMB_8 267 #define _SYMB_9 268 #define _SYMB_10 269 #define _SYMB_11 270 #define _SYMB_12 271 #define _SYMB_13 272 #define _SYMB_14 273 #define _SYMB_15 274 #define _SYMB_16 275 #define _SYMB_17 276 #define _SYMB_18 277 #define _SYMB_19 278 #define _SYMB_20 279 #define _SYMB_21 280 #define _SYMB_22 281 #define _SYMB_23 282 #define _SYMB_24 283 #define _SYMB_25 284 #define _SYMB_26 285 #define _SYMB_27 286 #define _SYMB_28 287 #define _SYMB_29 288 #define _SYMB_30 289 #define _SYMB_31 290 #define _SYMB_32 291 #define _SYMB_33 292 #define _SYMB_34 293 #define _SYMB_35 294 #define _SYMB_36 295 #define _SYMB_37 296 #define _SYMB_38 297 #define _SYMB_39 298 #define _SYMB_40 299 #define _SYMB_41 300 #define _SYMB_42 301 #define _SYMB_43 302 #define _SYMB_44 303 #define _SYMB_45 304 #define _SYMB_46 305 #define _SYMB_47 306 #define _SYMB_48 307 #define _SYMB_49 308 #define _SYMB_50 309 #define _SYMB_51 310 #define _SYMB_52 311 #define _SYMB_53 312 #define _SYMB_54 313 #define _SYMB_55 314 #define _SYMB_56 315 #define _SYMB_57 316 #define _SYMB_58 317 #define _SYMB_59 318 #define _SYMB_60 319 #define _SYMB_61 320 #define _SYMB_62 321 #define _SYMB_63 322 #define _SYMB_64 323 #define _SYMB_65 324 #define _SYMB_66 325 #define _SYMB_67 326 #define _SYMB_68 327 #define _SYMB_69 328 #define _SYMB_70 329 #define _SYMB_71 330 #define _SYMB_72 331 #define _SYMB_73 332 #define _SYMB_74 333 #define _SYMB_75 334 #define _SYMB_76 335 #define _SYMB_77 336 #define _SYMB_78 337 #define _SYMB_79 338 #define _SYMB_80 339 #define _SYMB_81 340 #define _INTEGER_ 341 #define _IDENT_ 342 /* Copy the first part of user declarations. */ #line 2 "FSAssembler.y" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <iostream> #include "Absyn.H" int yyparse(void); int yylex(void); int yy_mylinenumber; int initialize_lexer(FILE * inp); int yywrap(void) { return 1; } void yyerror(const char *str) { std::cout << "line " << yy_mylinenumber + 1 << std::endl ; fprintf(stderr,"error: %s\n",str); } Code* YY_RESULT_Code_ = 0; Code* pCode(FILE *inp) { initialize_lexer(inp); if (yyparse()) { /* Failure */ return 0; } else { /* Success */ return YY_RESULT_Code_; } } ListOperation* YY_RESULT_ListOperation_ = 0; ListOperation* pListOperation(FILE *inp) { initialize_lexer(inp); if (yyparse()) { /* Failure */ return 0; } else { /* Success */ return YY_RESULT_ListOperation_; } } Operation* YY_RESULT_Operation_ = 0; Operation* pOperation(FILE *inp) { initialize_lexer(inp); if (yyparse()) { /* Failure */ return 0; } else { /* Success */ return YY_RESULT_Operation_; } } Register* YY_RESULT_Register_ = 0; Register* pRegister(FILE *inp) { initialize_lexer(inp); if (yyparse()) { /* Failure */ return 0; } else { /* Success */ return YY_RESULT_Register_; } } Operand* YY_RESULT_Operand_ = 0; Operand* pOperand(FILE *inp) { initialize_lexer(inp); if (yyparse()) { /* Failure */ return 0; } else { /* Success */ return YY_RESULT_Operand_; } } ListOperation* reverseListOperation(ListOperation *l) { ListOperation *prev = 0; ListOperation *tmp = 0; while (l) { tmp = l->listoperation_; l->listoperation_ = prev; prev = l; l = tmp; } return prev; } /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 1 #endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* Enabling the token table. */ #ifndef YYTOKEN_TABLE # define YYTOKEN_TABLE 0 #endif #if ! defined (YYSTYPE) && ! defined (YYSTYPE_IS_DECLARED) #line 111 "FSAssembler.y" typedef union YYSTYPE { int int_; char char_; double double_; char* string_; Code* code_; ListOperation* listoperation_; Operation* operation_; Register* register_; Operand* operand_; } YYSTYPE; /* Line 186 of glr.c. */ #line 367 "parse.cpp" # define YYSTYPE_IS_DECLARED 1 # define YYSTYPE_IS_TRIVIAL 1 #endif #if ! defined (YYLTYPE) && ! defined (YYLTYPE_IS_DECLARED) typedef struct YYLTYPE { char yydummy; } YYLTYPE; # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif /* Default (constant) value used for initialization for null right-hand sides. Unlike the standard yacc.c template, here we set the default value of $$ to a zeroed-out value. Since the default value is undefined, this behavior is technically correct. */ static YYSTYPE yyval_default; /* Copy the second part of user declarations. */ /* Line 217 of glr.c. */ #line 394 "parse.cpp" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #ifndef YY_ # if YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(msgid) dgettext ("bison-runtime", msgid) # endif # endif # ifndef YY_ # define YY_(msgid) msgid # endif #endif #ifndef YYFREE # define YYFREE free #endif #ifndef YYMALLOC # define YYMALLOC malloc #endif #ifndef YYREALLOC # define YYREALLOC realloc #endif #define YYSIZEMAX ((size_t) -1) #ifdef __cplusplus typedef bool yybool; #else typedef unsigned char yybool; #endif #define yytrue 1 #define yyfalse 0 #ifndef YYSETJMP # include <setjmp.h> # define YYJMP_BUF jmp_buf # define YYSETJMP(env) setjmp (env) # define YYLONGJMP(env, val) longjmp (env, val) #endif /*-----------------. | GCC extensions. | `-----------------*/ #ifndef __attribute__ /* This feature is available in gcc versions 2.5 and later. */ # if (!defined (__GNUC__) || __GNUC__ < 2 \ || (__GNUC__ == 2 && __GNUC_MINOR__ < 5) || __STRICT_ANSI__) # define __attribute__(Spec) /* empty */ # endif #endif #ifdef __cplusplus # define YYOPTIONAL_LOC(Name) /* empty */ #else # define YYOPTIONAL_LOC(Name) Name __attribute__ ((__unused__)) #endif #ifndef YYASSERT # define YYASSERT(condition) ((void) ((condition) || (abort (), 0))) #endif /* YYFINAL -- State number of the termination state. */ #define YYFINAL 3 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 243 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 88 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 6 /* YYNRULES -- Number of rules. */ #define YYNRULES 89 /* YYNRULES -- Number of states. */ #define YYNSTATES 121 /* YYMAXRHS -- Maximum number of symbols on right-hand side of rule. */ #define YYMAXRHS 5 /* YYMAXLEFT -- Maximum number of symbols to the left of a handle accessed by $0, $-1, etc., in any rule. */ #define YYMAXLEFT 0 /* YYTRANSLATE(X) -- Bison symbol number corresponding to X. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 342 #define YYTRANSLATE(YYX) \ ((YYX <= 0) ? YYEOF : \ (unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ static const unsigned char yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87 }; #if YYDEBUG /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ static const unsigned char yyprhs[] = { 0, 0, 3, 5, 6, 9, 14, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 48, 51, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 117, 120, 123, 126, 128, 130, 132, 134, 136, 138, 141, 144, 147, 150, 153, 156, 159, 162, 165, 168, 171, 174, 177, 179, 181, 183, 185, 187, 189, 191, 193, 195, 197, 199, 201, 203, 205, 209, 213, 219 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const signed char yyrhs[] = { 89, 0, -1, 90, -1, -1, 90, 91, -1, 18, 92, 4, 86, -1, 84, 92, 4, 86, -1, 87, 5, -1, 77, 93, -1, 74, 93, -1, 75, 93, -1, 76, 93, -1, 78, 93, -1, 80, 93, -1, 79, 93, -1, 19, 93, -1, 83, -1, 82, 93, -1, 81, 93, -1, 29, -1, 32, -1, 30, -1, 31, -1, 68, -1, 69, -1, 70, -1, 58, -1, 44, -1, 45, -1, 64, -1, 42, -1, 60, -1, 61, -1, 59, -1, 65, -1, 62, -1, 63, -1, 28, -1, 72, -1, 73, -1, 41, -1, 33, -1, 34, -1, 35, -1, 36, -1, 37, -1, 38, -1, 39, -1, 40, -1, 51, 93, -1, 47, 93, -1, 51, 6, -1, 51, 7, -1, 57, -1, 52, -1, 56, -1, 53, -1, 55, -1, 54, -1, 66, 93, -1, 49, 93, -1, 67, 93, -1, 50, 93, -1, 67, 6, -1, 46, 6, -1, 46, 7, -1, 46, 8, -1, 46, 9, -1, 46, 10, -1, 46, 11, -1, 46, 12, -1, 46, 13, -1, 71, -1, 48, -1, 43, -1, 20, -1, 23, -1, 25, -1, 22, -1, 27, -1, 21, -1, 26, -1, 24, -1, 92, -1, 85, -1, 87, -1, 14, 85, 15, -1, 14, 92, 15, -1, 14, 92, 16, 86, 15, -1, 14, 92, 17, 86, 15, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const unsigned short int yyrline[] = { 0, 218, 218, 220, 221, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 294, 295, 296, 297, 298, 299, 300, 301, 303, 304, 305, 306, 307, 308, 309 }; #endif #if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "_ERROR_", "_SYMB_0", "_SYMB_1", "_SYMB_2", "_SYMB_3", "_SYMB_4", "_SYMB_5", "_SYMB_6", "_SYMB_7", "_SYMB_8", "_SYMB_9", "_SYMB_10", "_SYMB_11", "_SYMB_12", "_SYMB_13", "_SYMB_14", "_SYMB_15", "_SYMB_16", "_SYMB_17", "_SYMB_18", "_SYMB_19", "_SYMB_20", "_SYMB_21", "_SYMB_22", "_SYMB_23", "_SYMB_24", "_SYMB_25", "_SYMB_26", "_SYMB_27", "_SYMB_28", "_SYMB_29", "_SYMB_30", "_SYMB_31", "_SYMB_32", "_SYMB_33", "_SYMB_34", "_SYMB_35", "_SYMB_36", "_SYMB_37", "_SYMB_38", "_SYMB_39", "_SYMB_40", "_SYMB_41", "_SYMB_42", "_SYMB_43", "_SYMB_44", "_SYMB_45", "_SYMB_46", "_SYMB_47", "_SYMB_48", "_SYMB_49", "_SYMB_50", "_SYMB_51", "_SYMB_52", "_SYMB_53", "_SYMB_54", "_SYMB_55", "_SYMB_56", "_SYMB_57", "_SYMB_58", "_SYMB_59", "_SYMB_60", "_SYMB_61", "_SYMB_62", "_SYMB_63", "_SYMB_64", "_SYMB_65", "_SYMB_66", "_SYMB_67", "_SYMB_68", "_SYMB_69", "_SYMB_70", "_SYMB_71", "_SYMB_72", "_SYMB_73", "_SYMB_74", "_SYMB_75", "_SYMB_76", "_SYMB_77", "_SYMB_78", "_SYMB_79", "_SYMB_80", "_SYMB_81", "_INTEGER_", "_IDENT_", "$accept", "Code", "ListOperation", "Operation", "Register", "Operand", 0 }; #endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const unsigned char yyr1[] = { 0, 88, 89, 90, 90, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 92, 92, 92, 92, 92, 92, 92, 92, 93, 93, 93, 93, 93, 93, 93 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const unsigned char yyr2[] = { 0, 2, 1, 0, 2, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 5, 5 }; /* YYDPREC[RULE-NUM] -- Dynamic precedence of rule #RULE-NUM (0 if none). */ static const unsigned char yydprec[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* YYMERGER[RULE-NUM] -- Index of merging function for rule #RULE-NUM. */ static const unsigned char yymerger[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* YYDEFACT[S] -- default rule to reduce with in state S when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const unsigned char yydefact[] = { 3, 0, 2, 1, 0, 0, 37, 19, 21, 22, 20, 41, 42, 43, 44, 45, 46, 47, 48, 40, 30, 74, 27, 28, 0, 0, 73, 0, 0, 0, 54, 56, 58, 57, 55, 53, 26, 33, 31, 32, 35, 36, 29, 34, 0, 0, 23, 24, 25, 72, 38, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 4, 75, 80, 78, 76, 82, 77, 81, 79, 0, 0, 84, 85, 83, 15, 64, 65, 66, 67, 68, 69, 70, 71, 50, 60, 62, 51, 52, 49, 59, 63, 61, 9, 10, 11, 8, 12, 14, 13, 18, 17, 0, 7, 0, 0, 0, 0, 5, 86, 87, 0, 0, 6, 0, 0, 88, 89 }; /* YYPDEFGOTO[NTERM-NUM]. */ static const signed char yydefgoto[] = { -1, 1, 2, 64, 77, 78 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ #define YYPACT_NINF -77 static const short int yypact[] = { -77, 6, 90, -77, 166, 30, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, 188, 30, -77, 30, 30, -6, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, 30, 16, -77, -77, -77, -77, -77, -77, 30, 30, 30, 30, 30, 30, 30, 30, 30, -77, 166, 2, -77, -77, -77, -77, -77, -77, -77, -77, -77, 5, 158, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, -77, 7, -77, -76, -3, -12, -73, -77, -77, -77, -63, -62, -77, 10, 11, -77, -77 }; /* YYPGOTO[NTERM-NUM]. */ static const signed char yypgoto[] = { -77, -77, -77, -77, -2, 38 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If zero, do what YYDEFACT says. If YYTABLE_NINF, syntax error. */ #define YYTABLE_NINF -1 static const unsigned char yytable[] = { 90, 91, 73, 113, 114, 115, 3, 106, 74, 107, 111, 110, 112, 116, 65, 66, 67, 68, 69, 70, 71, 72, 94, 117, 118, 119, 120, 0, 0, 0, 74, 0, 0, 0, 0, 0, 65, 66, 67, 68, 69, 70, 71, 72, 74, 0, 0, 0, 0, 0, 65, 66, 67, 68, 69, 70, 71, 72, 0, 0, 105, 0, 0, 87, 0, 88, 89, 92, 0, 0, 0, 0, 109, 0, 0, 0, 0, 0, 0, 75, 0, 76, 93, 95, 0, 0, 0, 0, 0, 0, 96, 97, 98, 99, 100, 101, 102, 103, 104, 0, 0, 75, 0, 76, 0, 0, 0, 0, 4, 5, 0, 0, 0, 0, 0, 75, 0, 76, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 0, 0, 63, 65, 66, 67, 68, 69, 70, 71, 72, 65, 66, 67, 68, 69, 70, 71, 72, 79, 80, 81, 82, 83, 84, 85, 86, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 108 }; /* YYCONFLP[YYPACT[STATE-NUM]] -- Pointer into YYCONFL of start of list of conflicting reductions corresponding to action entry for state STATE-NUM in yytable. 0 means no conflicts. The list in yyconfl is terminated by a rule number of 0. */ static const unsigned char yyconflp[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* YYCONFL[I] -- lists of conflicting rule numbers, each terminated by 0, pointed into by YYCONFLP. */ static const short int yyconfl[] = { 0 }; static const signed char yycheck[] = { 6, 7, 4, 15, 16, 17, 0, 5, 14, 4, 86, 4, 15, 86, 20, 21, 22, 23, 24, 25, 26, 27, 6, 86, 86, 15, 15, -1, -1, -1, 14, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 14, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, 62, -1, -1, 25, -1, 27, 28, 29, -1, -1, -1, -1, 74, -1, -1, -1, -1, -1, -1, 85, -1, 87, 44, 45, -1, -1, -1, -1, -1, -1, 52, 53, 54, 55, 56, 57, 58, 59, 60, -1, -1, 85, -1, 87, -1, -1, -1, -1, 18, 19, -1, -1, -1, -1, -1, 85, -1, 87, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, -1, -1, 87, 20, 21, 22, 23, 24, 25, 26, 27, 20, 21, 22, 23, 24, 25, 26, 27, 6, 7, 8, 9, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 85 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const unsigned char yystos[] = { 0, 89, 90, 0, 18, 19, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 87, 91, 20, 21, 22, 23, 24, 25, 26, 27, 92, 14, 85, 87, 92, 93, 6, 7, 8, 9, 10, 11, 12, 13, 93, 93, 93, 6, 7, 93, 93, 6, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 92, 5, 4, 85, 92, 4, 86, 15, 15, 16, 17, 86, 86, 86, 15, 15 }; /* Prevent warning if -Wmissing-prototypes. */ int yyparse (void); /* Error token number */ #define YYTERROR 1 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) ((void) 0) #endif #ifndef YY_LOCATION_PRINT # define YY_LOCATION_PRINT(File, Loc) ((void) 0) #endif /* YYLEX -- calling `yylex' with the right arguments. */ #define YYLEX yylex () YYSTYPE yylval; YYLTYPE yylloc; int yynerrs; int yychar; static const int YYEOF = 0; static const int YYEMPTY = -2; typedef enum { yyok, yyaccept, yyabort, yyerr } YYRESULTTAG; #define YYCHK(YYE) \ do { YYRESULTTAG yyflag = YYE; if (yyflag != yyok) return yyflag; } \ while (0) #if YYDEBUG #if ! defined (YYFPRINTF) # define YYFPRINTF fprintf #endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (0) /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ static void yysymprint (FILE *yyoutput, int yytype, YYSTYPE *yyvaluep) { /* Pacify ``unused variable'' warnings. */ (void) yyvaluep; if (yytype < YYNTOKENS) YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); else YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # endif switch (yytype) { default: break; } YYFPRINTF (yyoutput, ")"); } # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yysymprint (stderr, \ Type, Value); \ YYFPRINTF (stderr, "\n"); \ } \ } while (0) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if SIZE_MAX < YYMAXDEPTH * sizeof (GLRStackItem) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif /* Minimum number of free items on the stack allowed after an allocation. This is to allow allocation and initialization to be completed by functions that call yyexpandGLRStack before the stack is expanded, thus insuring that all necessary pointers get properly redirected to new data. */ #define YYHEADROOM 2 #ifndef YYSTACKEXPANDABLE # if (! defined (__cplusplus) \ || (defined (YYSTYPE_IS_TRIVIAL) && YYSTYPE_IS_TRIVIAL)) # define YYSTACKEXPANDABLE 1 # else # define YYSTACKEXPANDABLE 0 # endif #endif #if YYERROR_VERBOSE # ifndef yystpcpy # if defined (__GLIBC__) && defined (_STRING_H) && defined (_GNU_SOURCE) # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ static char * yystpcpy (char *yydest, const char *yysrc) { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static size_t yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { size_t yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return strlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif #endif /* !YYERROR_VERBOSE */ /** State numbers, as in LALR(1) machine */ typedef int yyStateNum; /** Rule numbers, as in LALR(1) machine */ typedef int yyRuleNum; /** Grammar symbol */ typedef short int yySymbol; /** Item references, as in LALR(1) machine */ typedef short int yyItemNum; typedef struct yyGLRState yyGLRState; typedef struct yySemanticOption yySemanticOption; typedef union yyGLRStackItem yyGLRStackItem; typedef struct yyGLRStack yyGLRStack; typedef struct yyGLRStateSet yyGLRStateSet; struct yyGLRState { /** Type tag: always true. */ yybool yyisState; /** Type tag for yysemantics. If true, yysval applies, otherwise * yyfirstVal applies. */ yybool yyresolved; /** Number of corresponding LALR(1) machine state. */ yyStateNum yylrState; /** Preceding state in this stack */ yyGLRState* yypred; /** Source position of the first token produced by my symbol */ size_t yyposn; union { /** First in a chain of alternative reductions producing the * non-terminal corresponding to this state, threaded through * yynext. */ yySemanticOption* yyfirstVal; /** Semantic value for this state. */ YYSTYPE yysval; } yysemantics; /** Source location for this state. */ YYLTYPE yyloc; }; struct yyGLRStateSet { yyGLRState** yystates; size_t yysize, yycapacity; }; struct yySemanticOption { /** Type tag: always false. */ yybool yyisState; /** Rule number for this reduction */ yyRuleNum yyrule; /** The last RHS state in the list of states to be reduced. */ yyGLRState* yystate; /** Next sibling in chain of options. To facilitate merging, * options are chained in decreasing order by address. */ yySemanticOption* yynext; }; /** Type of the items in the GLR stack. The yyisState field * indicates which item of the union is valid. */ union yyGLRStackItem { yyGLRState yystate; yySemanticOption yyoption; }; struct yyGLRStack { int yyerrState; yySymbol* yytokenp; YYJMP_BUF yyexception_buffer; yyGLRStackItem* yyitems; yyGLRStackItem* yynextFree; size_t yyspaceLeft; yyGLRState* yysplitPoint; yyGLRState* yylastDeleted; yyGLRStateSet yytops; }; static void yyexpandGLRStack (yyGLRStack* yystack); static void yyFail (yyGLRStack* yystack, const char* yymsg) __attribute__ ((__noreturn__)); static void yyFail (yyGLRStack* yystack, const char* yymsg) { if (yymsg != NULL) yyerror (yymsg); YYLONGJMP (yystack->yyexception_buffer, 1); } static void yyMemoryExhausted (yyGLRStack* yystack) __attribute__ ((__noreturn__)); static void yyMemoryExhausted (yyGLRStack* yystack) { YYLONGJMP (yystack->yyexception_buffer, 2); } #if YYDEBUG || YYERROR_VERBOSE /** A printable representation of TOKEN. */ static inline const char* yytokenName (yySymbol yytoken) { if (yytoken == YYEMPTY) return ""; return yytname[yytoken]; } #endif /** Fill in YYVSP[YYLOW1 .. YYLOW0-1] from the chain of states starting * at YYVSP[YYLOW0].yystate.yypred. Leaves YYVSP[YYLOW1].yystate.yypred * containing the pointer to the next state in the chain. Assumes * YYLOW1 < YYLOW0. */ static void yyfillin (yyGLRStackItem *, int, int) __attribute__ ((__unused__)); static void yyfillin (yyGLRStackItem *yyvsp, int yylow0, int yylow1) { yyGLRState* s; int i; s = yyvsp[yylow0].yystate.yypred; for (i = yylow0-1; i >= yylow1; i -= 1) { YYASSERT (s->yyresolved); yyvsp[i].yystate.yyresolved = yytrue; yyvsp[i].yystate.yysemantics.yysval = s->yysemantics.yysval; yyvsp[i].yystate.yyloc = s->yyloc; s = yyvsp[i].yystate.yypred = s->yypred; } } /* Do nothing if YYNORMAL or if *YYLOW <= YYLOW1. Otherwise, fill in YYVSP[YYLOW1 .. *YYLOW-1] as in yyfillin and set *YYLOW = YYLOW1. For convenience, always return YYLOW1. */ static inline int yyfill (yyGLRStackItem *, int *, int, yybool) __attribute__ ((__unused__)); static inline int yyfill (yyGLRStackItem *yyvsp, int *yylow, int yylow1, yybool yynormal) { if (!yynormal && yylow1 < *yylow) { yyfillin (yyvsp, *yylow, yylow1); *yylow = yylow1; } return yylow1; } /** Perform user action for rule number YYN, with RHS length YYRHSLEN, * and top stack item YYVSP. YYLVALP points to place to put semantic * value ($$), and yylocp points to place for location information * (@$). Returns yyok for normal return, yyaccept for YYACCEPT, * yyerr for YYERROR, yyabort for YYABORT. */ static YYRESULTTAG yyuserAction (yyRuleNum yyn, int yyrhslen, yyGLRStackItem* yyvsp, YYSTYPE* yyvalp, YYLTYPE* YYOPTIONAL_LOC (yylocp), yyGLRStack* yystack ) { yybool yynormal __attribute__ ((__unused__)) = (yystack->yysplitPoint == NULL); int yylow; # undef yyerrok # define yyerrok (yystack->yyerrState = 0) # undef YYACCEPT # define YYACCEPT return yyaccept # undef YYABORT # define YYABORT return yyabort # undef YYERROR # define YYERROR return yyerrok, yyerr # undef YYRECOVERING # define YYRECOVERING (yystack->yyerrState != 0) # undef yyclearin # define yyclearin (yychar = *(yystack->yytokenp) = YYEMPTY) # undef YYFILL # define YYFILL(N) yyfill (yyvsp, &yylow, N, yynormal) # undef YYBACKUP # define YYBACKUP(Token, Value) \ return yyerror (YY_("syntax error: cannot back up")), \ yyerrok, yyerr yylow = 1; if (yyrhslen == 0) *yyvalp = yyval_default; else *yyvalp = yyvsp[YYFILL (1-yyrhslen)].yystate.yysemantics.yysval; YYLLOC_DEFAULT (*yylocp, yyvsp - yyrhslen, yyrhslen); switch (yyn) { case 2: #line 218 "FSAssembler.y" { ((*yyvalp).code_) = new Main(reverseListOperation((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.listoperation_))); YY_RESULT_Code_= ((*yyvalp).code_); ;} break; case 3: #line 220 "FSAssembler.y" { ((*yyvalp).listoperation_) = 0; ;} break; case 4: #line 221 "FSAssembler.y" { ((*yyvalp).listoperation_) = new ListOperation((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.operation_), (((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.listoperation_)); ;} break; case 5: #line 223 "FSAssembler.y" { ((*yyvalp).operation_) = new OAddC((((yyGLRStackItem const *)yyvsp)[YYFILL (-2)].yystate.yysemantics.yysval.register_), (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.int_)); ;} break; case 6: #line 224 "FSAssembler.y" { ((*yyvalp).operation_) = new OSubC((((yyGLRStackItem const *)yyvsp)[YYFILL (-2)].yystate.yysemantics.yysval.register_), (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.int_)); ;} break; case 7: #line 225 "FSAssembler.y" { ((*yyvalp).operation_) = new OLbl((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.string_)); ;} break; case 8: #line 226 "FSAssembler.y" { ((*yyvalp).operation_) = new OJmp((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.operand_)); ;} break; case 9: #line 227 "FSAssembler.y" { ((*yyvalp).operation_) = new OJb((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.operand_)); ;} break; case 10: #line 228 "FSAssembler.y" { ((*yyvalp).operation_) = new OJbe((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.operand_)); ;} break; case 11: #line 229 "FSAssembler.y" { ((*yyvalp).operation_) = new OJe((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.operand_)); ;} break; case 12: #line 230 "FSAssembler.y" { ((*yyvalp).operation_) = new OJne((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.operand_)); ;} break; case 13: #line 231 "FSAssembler.y" { ((*yyvalp).operation_) = new OJz((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.operand_)); ;} break; case 14: #line 232 "FSAssembler.y" { ((*yyvalp).operation_) = new OJnz((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.operand_)); ;} break; case 15: #line 233 "FSAssembler.y" { ((*yyvalp).operation_) = new OCall((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.operand_)); ;} break; case 16: #line 234 "FSAssembler.y" { ((*yyvalp).operation_) = new ORet(); ;} break; case 17: #line 235 "FSAssembler.y" { ((*yyvalp).operation_) = new OPush((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.operand_)); ;} break; case 18: #line 236 "FSAssembler.y" { ((*yyvalp).operation_) = new OPop((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.operand_)); ;} break; case 19: #line 237 "FSAssembler.y" { ((*yyvalp).operation_) = new OFabs(); ;} break; case 20: #line 238 "FSAssembler.y" { ((*yyvalp).operation_) = new OFchs(); ;} break; case 21: #line 239 "FSAssembler.y" { ((*yyvalp).operation_) = new OFadd(); ;} break; case 22: #line 240 "FSAssembler.y" { ((*yyvalp).operation_) = new OFaddp(); ;} break; case 23: #line 241 "FSAssembler.y" { ((*yyvalp).operation_) = new OFsub(); ;} break; case 24: #line 242 "FSAssembler.y" { ((*yyvalp).operation_) = new OFsubp(); ;} break; case 25: #line 243 "FSAssembler.y" { ((*yyvalp).operation_) = new OFsubrp(); ;} break; case 26: #line 244 "FSAssembler.y" { ((*yyvalp).operation_) = new OFmulp(); ;} break; case 27: #line 245 "FSAssembler.y" { ((*yyvalp).operation_) = new OFdivp(); ;} break; case 28: #line 246 "FSAssembler.y" { ((*yyvalp).operation_) = new OFdivrp(); ;} break; case 29: #line 247 "FSAssembler.y" { ((*yyvalp).operation_) = new OFsin(); ;} break; case 30: #line 248 "FSAssembler.y" { ((*yyvalp).operation_) = new OFcos(); ;} break; case 31: #line 249 "FSAssembler.y" { ((*yyvalp).operation_) = new OFprem(); ;} break; case 32: #line 250 "FSAssembler.y" { ((*yyvalp).operation_) = new OFptan(); ;} break; case 33: #line 251 "FSAssembler.y" { ((*yyvalp).operation_) = new OFpatan(); ;} break; case 34: #line 252 "FSAssembler.y" { ((*yyvalp).operation_) = new OFsqrt(); ;} break; case 35: #line 253 "FSAssembler.y" { ((*yyvalp).operation_) = new OFrndint(); ;} break; case 36: #line 254 "FSAssembler.y" { ((*yyvalp).operation_) = new OFscale(); ;} break; case 37: #line 255 "FSAssembler.y" { ((*yyvalp).operation_) = new OFtxmo(); ;} break; case 38: #line 256 "FSAssembler.y" { ((*yyvalp).operation_) = new OFyltx(); ;} break; case 39: #line 257 "FSAssembler.y" { ((*yyvalp).operation_) = new OFyltxpo(); ;} break; case 40: #line 258 "FSAssembler.y" { ((*yyvalp).operation_) = new OFcomi(); ;} break; case 41: #line 259 "FSAssembler.y" { ((*yyvalp).operation_) = new OFcmovb(); ;} break; case 42: #line 260 "FSAssembler.y" { ((*yyvalp).operation_) = new OFcmovbe(); ;} break; case 43: #line 261 "FSAssembler.y" { ((*yyvalp).operation_) = new OFcmove(); ;} break; case 44: #line 262 "FSAssembler.y" { ((*yyvalp).operation_) = new OFcmovnb(); ;} break; case 45: #line 263 "FSAssembler.y" { ((*yyvalp).operation_) = new OFcmovnbe(); ;} break; case 46: #line 264 "FSAssembler.y" { ((*yyvalp).operation_) = new OFcmovne(); ;} break; case 47: #line 265 "FSAssembler.y" { ((*yyvalp).operation_) = new OFcmovnu(); ;} break; case 48: #line 266 "FSAssembler.y" { ((*yyvalp).operation_) = new OFcmovu(); ;} break; case 49: #line 267 "FSAssembler.y" { ((*yyvalp).operation_) = new OFld((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.operand_)); ;} break; case 50: #line 268 "FSAssembler.y" { ((*yyvalp).operation_) = new OFild((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.operand_)); ;} break; case 51: #line 269 "FSAssembler.y" { ((*yyvalp).operation_) = new OFldt(); ;} break; case 52: #line 270 "FSAssembler.y" { ((*yyvalp).operation_) = new OFldn(); ;} break; case 53: #line 271 "FSAssembler.y" { ((*yyvalp).operation_) = new OFldz(); ;} break; case 54: #line 272 "FSAssembler.y" { ((*yyvalp).operation_) = new OFldo(); ;} break; case 55: #line 273 "FSAssembler.y" { ((*yyvalp).operation_) = new OFldpi(); ;} break; case 56: #line 274 "FSAssembler.y" { ((*yyvalp).operation_) = new OFldlte(); ;} break; case 57: #line 275 "FSAssembler.y" { ((*yyvalp).operation_) = new OFldlnt(); ;} break; case 58: #line 276 "FSAssembler.y" { ((*yyvalp).operation_) = new OFldlgt(); ;} break; case 59: #line 277 "FSAssembler.y" { ((*yyvalp).operation_) = new OFst((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.operand_)); ;} break; case 60: #line 278 "FSAssembler.y" { ((*yyvalp).operation_) = new OFist((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.operand_)); ;} break; case 61: #line 279 "FSAssembler.y" { ((*yyvalp).operation_) = new OFstp((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.operand_)); ;} break; case 62: #line 280 "FSAssembler.y" { ((*yyvalp).operation_) = new OFistp((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.operand_)); ;} break; case 63: #line 281 "FSAssembler.y" { ((*yyvalp).operation_) = new OFstpt(); ;} break; case 64: #line 282 "FSAssembler.y" { ((*yyvalp).operation_) = new OFfree(); ;} break; case 65: #line 283 "FSAssembler.y" { ((*yyvalp).operation_) = new OFfreea(); ;} break; case 66: #line 284 "FSAssembler.y" { ((*yyvalp).operation_) = new OFfreeb(); ;} break; case 67: #line 285 "FSAssembler.y" { ((*yyvalp).operation_) = new OFfreec(); ;} break; case 68: #line 286 "FSAssembler.y" { ((*yyvalp).operation_) = new OFfreed(); ;} break; case 69: #line 287 "FSAssembler.y" { ((*yyvalp).operation_) = new OFfreee(); ;} break; case 70: #line 288 "FSAssembler.y" { ((*yyvalp).operation_) = new OFfreef(); ;} break; case 71: #line 289 "FSAssembler.y" { ((*yyvalp).operation_) = new OFfreeg(); ;} break; case 72: #line 290 "FSAssembler.y" { ((*yyvalp).operation_) = new OFxchg(); ;} break; case 73: #line 291 "FSAssembler.y" { ((*yyvalp).operation_) = new OFincstp(); ;} break; case 74: #line 292 "FSAssembler.y" { ((*yyvalp).operation_) = new OFdecstp(); ;} break; case 75: #line 294 "FSAssembler.y" { ((*yyvalp).register_) = new REax(); ;} break; case 76: #line 295 "FSAssembler.y" { ((*yyvalp).register_) = new REcx(); ;} break; case 77: #line 296 "FSAssembler.y" { ((*yyvalp).register_) = new REdx(); ;} break; case 78: #line 297 "FSAssembler.y" { ((*yyvalp).register_) = new REbx(); ;} break; case 79: #line 298 "FSAssembler.y" { ((*yyvalp).register_) = new REsp(); ;} break; case 80: #line 299 "FSAssembler.y" { ((*yyvalp).register_) = new REbp(); ;} break; case 81: #line 300 "FSAssembler.y" { ((*yyvalp).register_) = new REsi(); ;} break; case 82: #line 301 "FSAssembler.y" { ((*yyvalp).register_) = new REdi(); ;} break; case 83: #line 303 "FSAssembler.y" { ((*yyvalp).operand_) = new OReg((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.register_)); ;} break; case 84: #line 304 "FSAssembler.y" { ((*yyvalp).operand_) = new OHex((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.string_)); ;} break; case 85: #line 305 "FSAssembler.y" { ((*yyvalp).operand_) = new OLab((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.string_)); ;} break; case 86: #line 306 "FSAssembler.y" { ((*yyvalp).operand_) = new OLitAdd((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.string_)); ;} break; case 87: #line 307 "FSAssembler.y" { ((*yyvalp).operand_) = new ORegAdd((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.register_)); ;} break; case 88: #line 308 "FSAssembler.y" { ((*yyvalp).operand_) = new ORelAddP((((yyGLRStackItem const *)yyvsp)[YYFILL (-3)].yystate.yysemantics.yysval.register_), (((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.int_)); ;} break; case 89: #line 309 "FSAssembler.y" { ((*yyvalp).operand_) = new ORelAddS((((yyGLRStackItem const *)yyvsp)[YYFILL (-3)].yystate.yysemantics.yysval.register_), (((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.int_)); ;} break; default: break; } return yyok; # undef yyerrok # undef YYABORT # undef YYACCEPT # undef YYERROR # undef YYBACKUP # undef yyclearin # undef YYRECOVERING /* Line 872 of glr.c. */ #line 1697 "parse.cpp" } static void yyuserMerge (int yyn, YYSTYPE* yy0, YYSTYPE* yy1) { /* `Use' the arguments. */ (void) yy0; (void) yy1; switch (yyn) { default: break; } } /* Bison grammar-table manipulation. */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep) { /* Pacify ``unused variable'' warnings. */ (void) yyvaluep; if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { default: break; } } /** Number of symbols composing the right hand side of rule #RULE. */ static inline int yyrhsLength (yyRuleNum yyrule) { return yyr2[yyrule]; } static void yydestroyGLRState (char const *yymsg, yyGLRState *yys) { if (yys->yyresolved) yydestruct (yymsg, yystos[yys->yylrState], &yys->yysemantics.yysval); else { #if YYDEBUG if (yydebug) { YYFPRINTF (stderr, "%s unresolved ", yymsg); yysymprint (stderr, yystos[yys->yylrState], &yys->yysemantics.yysval); YYFPRINTF (stderr, "\n"); } #endif if (yys->yysemantics.yyfirstVal) { yySemanticOption *yyoption = yys->yysemantics.yyfirstVal; yyGLRState *yyrh; int yyn; for (yyrh = yyoption->yystate, yyn = yyrhsLength (yyoption->yyrule); yyn > 0; yyrh = yyrh->yypred, yyn -= 1) yydestroyGLRState (yymsg, yyrh); } } } /** Left-hand-side symbol for rule #RULE. */ static inline yySymbol yylhsNonterm (yyRuleNum yyrule) { return yyr1[yyrule]; } #define yyis_pact_ninf(yystate) \ ((yystate) == YYPACT_NINF) /** True iff LR state STATE has only a default reduction (regardless * of token). */ static inline yybool yyisDefaultedState (yyStateNum yystate) { return yyis_pact_ninf (yypact[yystate]); } /** The default reduction for STATE, assuming it has one. */ static inline yyRuleNum yydefaultAction (yyStateNum yystate) { return yydefact[yystate]; } #define yyis_table_ninf(yytable_value) \ 0 /** Set *YYACTION to the action to take in YYSTATE on seeing YYTOKEN. * Result R means * R < 0: Reduce on rule -R. * R = 0: Error. * R > 0: Shift to state R. * Set *CONFLICTS to a pointer into yyconfl to 0-terminated list of * conflicting reductions. */ static inline void yygetLRActions (yyStateNum yystate, int yytoken, int* yyaction, const short int** yyconflicts) { int yyindex = yypact[yystate] + yytoken; if (yyindex < 0 || YYLAST < yyindex || yycheck[yyindex] != yytoken) { *yyaction = -yydefact[yystate]; *yyconflicts = yyconfl; } else if (! yyis_table_ninf (yytable[yyindex])) { *yyaction = yytable[yyindex]; *yyconflicts = yyconfl + yyconflp[yyindex]; } else { *yyaction = 0; *yyconflicts = yyconfl + yyconflp[yyindex]; } } static inline yyStateNum yyLRgotoState (yyStateNum yystate, yySymbol yylhs) { int yyr; yyr = yypgoto[yylhs - YYNTOKENS] + yystate; if (0 <= yyr && yyr <= YYLAST && yycheck[yyr] == yystate) return yytable[yyr]; else return yydefgoto[yylhs - YYNTOKENS]; } static inline yybool yyisShiftAction (int yyaction) { return 0 < yyaction; } static inline yybool yyisErrorAction (int yyaction) { return yyaction == 0; } /* GLRStates */ static void yyaddDeferredAction (yyGLRStack* yystack, yyGLRState* yystate, yyGLRState* rhs, yyRuleNum yyrule) { yySemanticOption* yynewItem; yynewItem = &yystack->yynextFree->yyoption; yystack->yyspaceLeft -= 1; yystack->yynextFree += 1; yynewItem->yyisState = yyfalse; yynewItem->yystate = rhs; yynewItem->yyrule = yyrule; yynewItem->yynext = yystate->yysemantics.yyfirstVal; yystate->yysemantics.yyfirstVal = yynewItem; if (yystack->yyspaceLeft < YYHEADROOM) yyexpandGLRStack (yystack); } /* GLRStacks */ /** Initialize SET to a singleton set containing an empty stack. */ static yybool yyinitStateSet (yyGLRStateSet* yyset) { yyset->yysize = 1; yyset->yycapacity = 16; yyset->yystates = (yyGLRState**) YYMALLOC (16 * sizeof yyset->yystates[0]); if (! yyset->yystates) return yyfalse; yyset->yystates[0] = NULL; return yytrue; } static void yyfreeStateSet (yyGLRStateSet* yyset) { YYFREE (yyset->yystates); } /** Initialize STACK to a single empty stack, with total maximum * capacity for all stacks of SIZE. */ static yybool yyinitGLRStack (yyGLRStack* yystack, size_t yysize) { yystack->yyerrState = 0; yynerrs = 0; yystack->yyspaceLeft = yysize; yystack->yyitems = (yyGLRStackItem*) YYMALLOC (yysize * sizeof yystack->yynextFree[0]); if (!yystack->yyitems) return yyfalse; yystack->yynextFree = yystack->yyitems; yystack->yysplitPoint = NULL; yystack->yylastDeleted = NULL; return yyinitStateSet (&yystack->yytops); } #define YYRELOC(YYFROMITEMS,YYTOITEMS,YYX,YYTYPE) \ &((YYTOITEMS) - ((YYFROMITEMS) - (yyGLRStackItem*) (YYX)))->YYTYPE /** If STACK is expandable, extend it. WARNING: Pointers into the stack from outside should be considered invalid after this call. We always expand when there are 1 or fewer items left AFTER an allocation, so that we can avoid having external pointers exist across an allocation. */ static void yyexpandGLRStack (yyGLRStack* yystack) { #if YYSTACKEXPANDABLE yyGLRStackItem* yynewItems; yyGLRStackItem* yyp0, *yyp1; size_t yysize, yynewSize; size_t yyn; yysize = yystack->yynextFree - yystack->yyitems; if (YYMAXDEPTH <= yysize) yyMemoryExhausted (yystack); yynewSize = 2*yysize; if (YYMAXDEPTH < yynewSize) yynewSize = YYMAXDEPTH; yynewItems = (yyGLRStackItem*) YYMALLOC (yynewSize * sizeof yynewItems[0]); if (! yynewItems) yyMemoryExhausted (yystack); for (yyp0 = yystack->yyitems, yyp1 = yynewItems, yyn = yysize; 0 < yyn; yyn -= 1, yyp0 += 1, yyp1 += 1) { *yyp1 = *yyp0; if (*(yybool *) yyp0) { yyGLRState* yys0 = &yyp0->yystate; yyGLRState* yys1 = &yyp1->yystate; if (yys0->yypred != NULL) yys1->yypred = YYRELOC (yyp0, yyp1, yys0->yypred, yystate); if (! yys0->yyresolved && yys0->yysemantics.yyfirstVal != NULL) yys1->yysemantics.yyfirstVal = YYRELOC(yyp0, yyp1, yys0->yysemantics.yyfirstVal, yyoption); } else { yySemanticOption* yyv0 = &yyp0->yyoption; yySemanticOption* yyv1 = &yyp1->yyoption; if (yyv0->yystate != NULL) yyv1->yystate = YYRELOC (yyp0, yyp1, yyv0->yystate, yystate); if (yyv0->yynext != NULL) yyv1->yynext = YYRELOC (yyp0, yyp1, yyv0->yynext, yyoption); } } if (yystack->yysplitPoint != NULL) yystack->yysplitPoint = YYRELOC (yystack->yyitems, yynewItems, yystack->yysplitPoint, yystate); for (yyn = 0; yyn < yystack->yytops.yysize; yyn += 1) if (yystack->yytops.yystates[yyn] != NULL) yystack->yytops.yystates[yyn] = YYRELOC (yystack->yyitems, yynewItems, yystack->yytops.yystates[yyn], yystate); YYFREE (yystack->yyitems); yystack->yyitems = yynewItems; yystack->yynextFree = yynewItems + yysize; yystack->yyspaceLeft = yynewSize - yysize; #else yyMemoryExhausted (yystack); #endif } static void yyfreeGLRStack (yyGLRStack* yystack) { YYFREE (yystack->yyitems); yyfreeStateSet (&yystack->yytops); } /** Assuming that S is a GLRState somewhere on STACK, update the * splitpoint of STACK, if needed, so that it is at least as deep as * S. */ static inline void yyupdateSplit (yyGLRStack* yystack, yyGLRState* yys) { if (yystack->yysplitPoint != NULL && yystack->yysplitPoint > yys) yystack->yysplitPoint = yys; } /** Invalidate stack #K in STACK. */ static inline void yymarkStackDeleted (yyGLRStack* yystack, size_t yyk) { if (yystack->yytops.yystates[yyk] != NULL) yystack->yylastDeleted = yystack->yytops.yystates[yyk]; yystack->yytops.yystates[yyk] = NULL; } /** Undelete the last stack that was marked as deleted. Can only be done once after a deletion, and only when all other stacks have been deleted. */ static void yyundeleteLastStack (yyGLRStack* yystack) { if (yystack->yylastDeleted == NULL || yystack->yytops.yysize != 0) return; yystack->yytops.yystates[0] = yystack->yylastDeleted; yystack->yytops.yysize = 1; YYDPRINTF ((stderr, "Restoring last deleted stack as stack #0.\n")); yystack->yylastDeleted = NULL; } static inline void yyremoveDeletes (yyGLRStack* yystack) { size_t yyi, yyj; yyi = yyj = 0; while (yyj < yystack->yytops.yysize) { if (yystack->yytops.yystates[yyi] == NULL) { if (yyi == yyj) { YYDPRINTF ((stderr, "Removing dead stacks.\n")); } yystack->yytops.yysize -= 1; } else { yystack->yytops.yystates[yyj] = yystack->yytops.yystates[yyi]; if (yyj != yyi) { YYDPRINTF ((stderr, "Rename stack %lu -> %lu.\n", (unsigned long int) yyi, (unsigned long int) yyj)); } yyj += 1; } yyi += 1; } } /** Shift to a new state on stack #K of STACK, corresponding to LR state * LRSTATE, at input position POSN, with (resolved) semantic value SVAL. */ static inline void yyglrShift (yyGLRStack* yystack, size_t yyk, yyStateNum yylrState, size_t yyposn, YYSTYPE yysval, YYLTYPE* yylocp) { yyGLRStackItem* yynewItem; yynewItem = yystack->yynextFree; yystack->yynextFree += 1; yystack->yyspaceLeft -= 1; yynewItem->yystate.yyisState = yytrue; yynewItem->yystate.yylrState = yylrState; yynewItem->yystate.yyposn = yyposn; yynewItem->yystate.yyresolved = yytrue; yynewItem->yystate.yypred = yystack->yytops.yystates[yyk]; yystack->yytops.yystates[yyk] = &yynewItem->yystate; yynewItem->yystate.yysemantics.yysval = yysval; yynewItem->yystate.yyloc = *yylocp; if (yystack->yyspaceLeft < YYHEADROOM) yyexpandGLRStack (yystack); } /** Shift stack #K of YYSTACK, to a new state corresponding to LR * state YYLRSTATE, at input position YYPOSN, with the (unresolved) * semantic value of YYRHS under the action for YYRULE. */ static inline void yyglrShiftDefer (yyGLRStack* yystack, size_t yyk, yyStateNum yylrState, size_t yyposn, yyGLRState* rhs, yyRuleNum yyrule) { yyGLRStackItem* yynewItem; yynewItem = yystack->yynextFree; yynewItem->yystate.yyisState = yytrue; yynewItem->yystate.yylrState = yylrState; yynewItem->yystate.yyposn = yyposn; yynewItem->yystate.yyresolved = yyfalse; yynewItem->yystate.yypred = yystack->yytops.yystates[yyk]; yynewItem->yystate.yysemantics.yyfirstVal = NULL; yystack->yytops.yystates[yyk] = &yynewItem->yystate; yystack->yynextFree += 1; yystack->yyspaceLeft -= 1; yyaddDeferredAction (yystack, &yynewItem->yystate, rhs, yyrule); } /** Pop the symbols consumed by reduction #RULE from the top of stack * #K of STACK, and perform the appropriate semantic action on their * semantic values. Assumes that all ambiguities in semantic values * have been previously resolved. Set *VALP to the resulting value, * and *LOCP to the computed location (if any). Return value is as * for userAction. */ static inline YYRESULTTAG yydoAction (yyGLRStack* yystack, size_t yyk, yyRuleNum yyrule, YYSTYPE* yyvalp, YYLTYPE* yylocp) { int yynrhs = yyrhsLength (yyrule); if (yystack->yysplitPoint == NULL) { /* Standard special case: single stack. */ yyGLRStackItem* rhs = (yyGLRStackItem*) yystack->yytops.yystates[yyk]; YYASSERT (yyk == 0); yystack->yynextFree -= yynrhs; yystack->yyspaceLeft += yynrhs; yystack->yytops.yystates[0] = & yystack->yynextFree[-1].yystate; return yyuserAction (yyrule, yynrhs, rhs, yyvalp, yylocp, yystack); } else { int yyi; yyGLRState* yys; yyGLRStackItem yyrhsVals[YYMAXRHS + YYMAXLEFT + 1]; yys = yyrhsVals[YYMAXRHS + YYMAXLEFT].yystate.yypred = yystack->yytops.yystates[yyk]; for (yyi = 0; yyi < yynrhs; yyi += 1) { yys = yys->yypred; YYASSERT (yys); } yyupdateSplit (yystack, yys); yystack->yytops.yystates[yyk] = yys; return yyuserAction (yyrule, yynrhs, yyrhsVals + YYMAXRHS + YYMAXLEFT - 1, yyvalp, yylocp, yystack); } } #if !YYDEBUG # define YY_REDUCE_PRINT(K, Rule) #else # define YY_REDUCE_PRINT(K, Rule) \ do { \ if (yydebug) \ yy_reduce_print (K, Rule); \ } while (0) /*----------------------------------------------------------. | Report that the RULE is going to be reduced on stack #K. | `----------------------------------------------------------*/ static inline void yy_reduce_print (size_t yyk, yyRuleNum yyrule) { int yyi; YYFPRINTF (stderr, "Reducing stack %lu by rule %d (line %lu), ", (unsigned long int) yyk, yyrule - 1, (unsigned long int) yyrline[yyrule]); /* Print the symbols being reduced, and their result. */ for (yyi = yyprhs[yyrule]; 0 <= yyrhs[yyi]; yyi++) YYFPRINTF (stderr, "%s ", yytokenName (yyrhs[yyi])); YYFPRINTF (stderr, "-> %s\n", yytokenName (yyr1[yyrule])); } #endif /** Pop items off stack #K of STACK according to grammar rule RULE, * and push back on the resulting nonterminal symbol. Perform the * semantic action associated with RULE and store its value with the * newly pushed state, if FORCEEVAL or if STACK is currently * unambiguous. Otherwise, store the deferred semantic action with * the new state. If the new state would have an identical input * position, LR state, and predecessor to an existing state on the stack, * it is identified with that existing state, eliminating stack #K from * the STACK. In this case, the (necessarily deferred) semantic value is * added to the options for the existing state's semantic value. */ static inline YYRESULTTAG yyglrReduce (yyGLRStack* yystack, size_t yyk, yyRuleNum yyrule, yybool yyforceEval) { size_t yyposn = yystack->yytops.yystates[yyk]->yyposn; if (yyforceEval || yystack->yysplitPoint == NULL) { YYSTYPE yysval; YYLTYPE yyloc; YY_REDUCE_PRINT (yyk, yyrule); YYCHK (yydoAction (yystack, yyk, yyrule, &yysval, &yyloc)); yyglrShift (yystack, yyk, yyLRgotoState (yystack->yytops.yystates[yyk]->yylrState, yylhsNonterm (yyrule)), yyposn, yysval, &yyloc); } else { size_t yyi; int yyn; yyGLRState* yys, *yys0 = yystack->yytops.yystates[yyk]; yyStateNum yynewLRState; for (yys = yystack->yytops.yystates[yyk], yyn = yyrhsLength (yyrule); 0 < yyn; yyn -= 1) { yys = yys->yypred; YYASSERT (yys); } yyupdateSplit (yystack, yys); yynewLRState = yyLRgotoState (yys->yylrState, yylhsNonterm (yyrule)); YYDPRINTF ((stderr, "Reduced stack %lu by rule #%d; action deferred. Now in state %d.\n", (unsigned long int) yyk, yyrule - 1, yynewLRState)); for (yyi = 0; yyi < yystack->yytops.yysize; yyi += 1) if (yyi != yyk && yystack->yytops.yystates[yyi] != NULL) { yyGLRState* yyp, *yysplit = yystack->yysplitPoint; yyp = yystack->yytops.yystates[yyi]; while (yyp != yys && yyp != yysplit && yyp->yyposn >= yyposn) { if (yyp->yylrState == yynewLRState && yyp->yypred == yys) { yyaddDeferredAction (yystack, yyp, yys0, yyrule); yymarkStackDeleted (yystack, yyk); YYDPRINTF ((stderr, "Merging stack %lu into stack %lu.\n", (unsigned long int) yyk, (unsigned long int) yyi)); return yyok; } yyp = yyp->yypred; } } yystack->yytops.yystates[yyk] = yys; yyglrShiftDefer (yystack, yyk, yynewLRState, yyposn, yys0, yyrule); } return yyok; } static size_t yysplitStack (yyGLRStack* yystack, size_t yyk) { if (yystack->yysplitPoint == NULL) { YYASSERT (yyk == 0); yystack->yysplitPoint = yystack->yytops.yystates[yyk]; } if (yystack->yytops.yysize >= yystack->yytops.yycapacity) { yyGLRState** yynewStates; if (! ((yystack->yytops.yycapacity <= (YYSIZEMAX / (2 * sizeof yynewStates[0]))) && (yynewStates = (yyGLRState**) YYREALLOC (yystack->yytops.yystates, ((yystack->yytops.yycapacity *= 2) * sizeof yynewStates[0]))))) yyMemoryExhausted (yystack); yystack->yytops.yystates = yynewStates; } yystack->yytops.yystates[yystack->yytops.yysize] = yystack->yytops.yystates[yyk]; yystack->yytops.yysize += 1; return yystack->yytops.yysize-1; } /** True iff Y0 and Y1 represent identical options at the top level. * That is, they represent the same rule applied to RHS symbols * that produce the same terminal symbols. */ static yybool yyidenticalOptions (yySemanticOption* yyy0, yySemanticOption* yyy1) { if (yyy0->yyrule == yyy1->yyrule) { yyGLRState *yys0, *yys1; int yyn; for (yys0 = yyy0->yystate, yys1 = yyy1->yystate, yyn = yyrhsLength (yyy0->yyrule); yyn > 0; yys0 = yys0->yypred, yys1 = yys1->yypred, yyn -= 1) if (yys0->yyposn != yys1->yyposn) return yyfalse; return yytrue; } else return yyfalse; } /** Assuming identicalOptions (Y0,Y1), destructively merge the * alternative semantic values for the RHS-symbols of Y1 and Y0. */ static void yymergeOptionSets (yySemanticOption* yyy0, yySemanticOption* yyy1) { yyGLRState *yys0, *yys1; int yyn; for (yys0 = yyy0->yystate, yys1 = yyy1->yystate, yyn = yyrhsLength (yyy0->yyrule); yyn > 0; yys0 = yys0->yypred, yys1 = yys1->yypred, yyn -= 1) { if (yys0 == yys1) break; else if (yys0->yyresolved) { yys1->yyresolved = yytrue; yys1->yysemantics.yysval = yys0->yysemantics.yysval; } else if (yys1->yyresolved) { yys0->yyresolved = yytrue; yys0->yysemantics.yysval = yys1->yysemantics.yysval; } else { yySemanticOption** yyz0p; yySemanticOption* yyz1; yyz0p = &yys0->yysemantics.yyfirstVal; yyz1 = yys1->yysemantics.yyfirstVal; while (yytrue) { if (yyz1 == *yyz0p || yyz1 == NULL) break; else if (*yyz0p == NULL) { *yyz0p = yyz1; break; } else if (*yyz0p < yyz1) { yySemanticOption* yyz = *yyz0p; *yyz0p = yyz1; yyz1 = yyz1->yynext; (*yyz0p)->yynext = yyz; } yyz0p = &(*yyz0p)->yynext; } yys1->yysemantics.yyfirstVal = yys0->yysemantics.yyfirstVal; } } } /** Y0 and Y1 represent two possible actions to take in a given * parsing state; return 0 if no combination is possible, * 1 if user-mergeable, 2 if Y0 is preferred, 3 if Y1 is preferred. */ static int yypreference (yySemanticOption* y0, yySemanticOption* y1) { yyRuleNum r0 = y0->yyrule, r1 = y1->yyrule; int p0 = yydprec[r0], p1 = yydprec[r1]; if (p0 == p1) { if (yymerger[r0] == 0 || yymerger[r0] != yymerger[r1]) return 0; else return 1; } if (p0 == 0 || p1 == 0) return 0; if (p0 < p1) return 3; if (p1 < p0) return 2; return 0; } static YYRESULTTAG yyresolveValue (yySemanticOption* yyoptionList, yyGLRStack* yystack, YYSTYPE* yyvalp, YYLTYPE* yylocp); static YYRESULTTAG yyresolveStates (yyGLRState* yys, int yyn, yyGLRStack* yystack) { YYRESULTTAG yyflag; if (0 < yyn) { YYASSERT (yys->yypred); yyflag = yyresolveStates (yys->yypred, yyn-1, yystack); if (yyflag != yyok) return yyflag; if (! yys->yyresolved) { yyflag = yyresolveValue (yys->yysemantics.yyfirstVal, yystack, &yys->yysemantics.yysval, &yys->yyloc ); if (yyflag != yyok) return yyflag; yys->yyresolved = yytrue; } } return yyok; } static YYRESULTTAG yyresolveAction (yySemanticOption* yyopt, yyGLRStack* yystack, YYSTYPE* yyvalp, YYLTYPE* yylocp) { yyGLRStackItem yyrhsVals[YYMAXRHS + YYMAXLEFT + 1]; int yynrhs; yynrhs = yyrhsLength (yyopt->yyrule); YYCHK (yyresolveStates (yyopt->yystate, yynrhs, yystack)); yyrhsVals[YYMAXRHS + YYMAXLEFT].yystate.yypred = yyopt->yystate; return yyuserAction (yyopt->yyrule, yynrhs, yyrhsVals + YYMAXRHS + YYMAXLEFT - 1, yyvalp, yylocp, yystack); } #if YYDEBUG static void yyreportTree (yySemanticOption* yyx, int yyindent) { int yynrhs = yyrhsLength (yyx->yyrule); int yyi; yyGLRState* yys; yyGLRState* yystates[YYMAXRHS]; yyGLRState yyleftmost_state; for (yyi = yynrhs, yys = yyx->yystate; 0 < yyi; yyi -= 1, yys = yys->yypred) yystates[yyi] = yys; if (yys == NULL) { yyleftmost_state.yyposn = 0; yystates[0] = &yyleftmost_state; } else yystates[0] = yys; if (yyx->yystate->yyposn < yys->yyposn + 1) YYFPRINTF (stderr, "%*s%s -> <Rule %d, empty>\n", yyindent, "", yytokenName (yylhsNonterm (yyx->yyrule)), yyx->yyrule); else YYFPRINTF (stderr, "%*s%s -> <Rule %d, tokens %lu .. %lu>\n", yyindent, "", yytokenName (yylhsNonterm (yyx->yyrule)), yyx->yyrule, (unsigned long int) (yys->yyposn + 1), (unsigned long int) yyx->yystate->yyposn); for (yyi = 1; yyi <= yynrhs; yyi += 1) { if (yystates[yyi]->yyresolved) { if (yystates[yyi-1]->yyposn+1 > yystates[yyi]->yyposn) YYFPRINTF (stderr, "%*s%s <empty>\n", yyindent+2, "", yytokenName (yyrhs[yyprhs[yyx->yyrule]+yyi-1])); else YYFPRINTF (stderr, "%*s%s <tokens %lu .. %lu>\n", yyindent+2, "", yytokenName (yyrhs[yyprhs[yyx->yyrule]+yyi-1]), (unsigned long int) (yystates[yyi - 1]->yyposn + 1), (unsigned long int) yystates[yyi]->yyposn); } else yyreportTree (yystates[yyi]->yysemantics.yyfirstVal, yyindent+2); } } #endif static void yyreportAmbiguity (yySemanticOption* yyx0, yySemanticOption* yyx1, yyGLRStack* yystack) __attribute__ ((__noreturn__)); static void yyreportAmbiguity (yySemanticOption* yyx0, yySemanticOption* yyx1, yyGLRStack* yystack) { /* `Unused' warnings. */ (void) yyx0; (void) yyx1; #if YYDEBUG YYFPRINTF (stderr, "Ambiguity detected.\n"); YYFPRINTF (stderr, "Option 1,\n"); yyreportTree (yyx0, 2); YYFPRINTF (stderr, "\nOption 2,\n"); yyreportTree (yyx1, 2); YYFPRINTF (stderr, "\n"); #endif yyFail (yystack, YY_("syntax is ambiguous")); } /** Resolve the ambiguity represented by OPTIONLIST, perform the indicated * actions, and return the result. */ static YYRESULTTAG yyresolveValue (yySemanticOption* yyoptionList, yyGLRStack* yystack, YYSTYPE* yyvalp, YYLTYPE* yylocp) { yySemanticOption* yybest; yySemanticOption** yypp; yybool yymerge; yybest = yyoptionList; yymerge = yyfalse; for (yypp = &yyoptionList->yynext; *yypp != NULL; ) { yySemanticOption* yyp = *yypp; if (yyidenticalOptions (yybest, yyp)) { yymergeOptionSets (yybest, yyp); *yypp = yyp->yynext; } else { switch (yypreference (yybest, yyp)) { case 0: yyreportAmbiguity (yybest, yyp, yystack); break; case 1: yymerge = yytrue; break; case 2: break; case 3: yybest = yyp; yymerge = yyfalse; break; default: /* This cannot happen so it is not worth a YYASSERT (yyfalse), but some compilers complain if the default case is omitted. */ break; } yypp = &yyp->yynext; } } if (yymerge) { yySemanticOption* yyp; int yyprec = yydprec[yybest->yyrule]; YYCHK (yyresolveAction (yybest, yystack, yyvalp, yylocp)); for (yyp = yybest->yynext; yyp != NULL; yyp = yyp->yynext) { if (yyprec == yydprec[yyp->yyrule]) { YYSTYPE yyval1; YYLTYPE yydummy; YYCHK (yyresolveAction (yyp, yystack, &yyval1, &yydummy)); yyuserMerge (yymerger[yyp->yyrule], yyvalp, &yyval1); } } return yyok; } else return yyresolveAction (yybest, yystack, yyvalp, yylocp); } static YYRESULTTAG yyresolveStack (yyGLRStack* yystack) { if (yystack->yysplitPoint != NULL) { yyGLRState* yys; int yyn; for (yyn = 0, yys = yystack->yytops.yystates[0]; yys != yystack->yysplitPoint; yys = yys->yypred, yyn += 1) continue; YYCHK (yyresolveStates (yystack->yytops.yystates[0], yyn, yystack )); } return yyok; } static void yycompressStack (yyGLRStack* yystack) { yyGLRState* yyp, *yyq, *yyr; if (yystack->yytops.yysize != 1 || yystack->yysplitPoint == NULL) return; for (yyp = yystack->yytops.yystates[0], yyq = yyp->yypred, yyr = NULL; yyp != yystack->yysplitPoint; yyr = yyp, yyp = yyq, yyq = yyp->yypred) yyp->yypred = yyr; yystack->yyspaceLeft += yystack->yynextFree - yystack->yyitems; yystack->yynextFree = ((yyGLRStackItem*) yystack->yysplitPoint) + 1; yystack->yyspaceLeft -= yystack->yynextFree - yystack->yyitems; yystack->yysplitPoint = NULL; yystack->yylastDeleted = NULL; while (yyr != NULL) { yystack->yynextFree->yystate = *yyr; yyr = yyr->yypred; yystack->yynextFree->yystate.yypred = & yystack->yynextFree[-1].yystate; yystack->yytops.yystates[0] = &yystack->yynextFree->yystate; yystack->yynextFree += 1; yystack->yyspaceLeft -= 1; } } static YYRESULTTAG yyprocessOneStack (yyGLRStack* yystack, size_t yyk, size_t yyposn, YYSTYPE* yylvalp, YYLTYPE* yyllocp ) { int yyaction; const short int* yyconflicts; yyRuleNum yyrule; yySymbol* const yytokenp = yystack->yytokenp; while (yystack->yytops.yystates[yyk] != NULL) { yyStateNum yystate = yystack->yytops.yystates[yyk]->yylrState; YYDPRINTF ((stderr, "Stack %lu Entering state %d\n", (unsigned long int) yyk, yystate)); YYASSERT (yystate != YYFINAL); if (yyisDefaultedState (yystate)) { yyrule = yydefaultAction (yystate); if (yyrule == 0) { YYDPRINTF ((stderr, "Stack %lu dies.\n", (unsigned long int) yyk)); yymarkStackDeleted (yystack, yyk); return yyok; } YYCHK (yyglrReduce (yystack, yyk, yyrule, yyfalse)); } else { if (*yytokenp == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; *yytokenp = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", *yytokenp, yylvalp, yyllocp); } yygetLRActions (yystate, *yytokenp, &yyaction, &yyconflicts); while (*yyconflicts != 0) { size_t yynewStack = yysplitStack (yystack, yyk); YYDPRINTF ((stderr, "Splitting off stack %lu from %lu.\n", (unsigned long int) yynewStack, (unsigned long int) yyk)); YYCHK (yyglrReduce (yystack, yynewStack, *yyconflicts, yyfalse)); YYCHK (yyprocessOneStack (yystack, yynewStack, yyposn, yylvalp, yyllocp)); yyconflicts += 1; } if (yyisShiftAction (yyaction)) { YYDPRINTF ((stderr, "On stack %lu, ", (unsigned long int) yyk)); YY_SYMBOL_PRINT ("shifting", *yytokenp, yylvalp, yyllocp); yyglrShift (yystack, yyk, yyaction, yyposn+1, *yylvalp, yyllocp); YYDPRINTF ((stderr, "Stack %lu now in state #%d\n", (unsigned long int) yyk, yystack->yytops.yystates[yyk]->yylrState)); break; } else if (yyisErrorAction (yyaction)) { YYDPRINTF ((stderr, "Stack %lu dies.\n", (unsigned long int) yyk)); yymarkStackDeleted (yystack, yyk); break; } else YYCHK (yyglrReduce (yystack, yyk, -yyaction, yyfalse)); } } return yyok; } static void yyreportSyntaxError (yyGLRStack* yystack, YYSTYPE* yylvalp, YYLTYPE* yyllocp) { /* `Unused' warnings. */ (void) yylvalp; (void) yyllocp; if (yystack->yyerrState == 0) { #if YYERROR_VERBOSE yySymbol* const yytokenp = yystack->yytokenp; int yyn; yyn = yypact[yystack->yytops.yystates[0]->yylrState]; if (YYPACT_NINF < yyn && yyn < YYLAST) { size_t yysize0 = yytnamerr (NULL, yytokenName (*yytokenp)); size_t yysize = yysize0; size_t yysize1; yybool yysize_overflow = yyfalse; char* yymsg = NULL; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; int yyx; char *yyfmt; char const *yyf; static char const yyunexpected[] = "syntax error, unexpected %s"; static char const yyexpecting[] = ", expecting %s"; static char const yyor[] = " or %s"; char yyformat[sizeof yyunexpected + sizeof yyexpecting - 1 + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2) * (sizeof yyor - 1))]; char const *yyprefix = yyexpecting; /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yycount = 1; yyarg[0] = yytokenName (*yytokenp); yyfmt = yystpcpy (yyformat, yyunexpected); for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; yyformat[sizeof yyunexpected - 1] = '\0'; break; } yyarg[yycount++] = yytokenName (yyx); yysize1 = yysize + yytnamerr (NULL, yytokenName (yyx)); yysize_overflow |= yysize1 < yysize; yysize = yysize1; yyfmt = yystpcpy (yyfmt, yyprefix); yyprefix = yyor; } yyf = YY_(yyformat); yysize1 = yysize + strlen (yyf); yysize_overflow |= yysize1 < yysize; yysize = yysize1; if (!yysize_overflow) yymsg = (char *) YYMALLOC (yysize); if (yymsg) { char *yyp = yymsg; int yyi = 0; while ((*yyp = *yyf)) { if (*yyp == '%' && yyf[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyf += 2; } else { yyp++; yyf++; } } yyerror (yymsg); YYFREE (yymsg); } else { yyerror (YY_("syntax error")); yyMemoryExhausted (yystack); } } else #endif /* YYERROR_VERBOSE */ yyerror (YY_("syntax error")); yynerrs += 1; } } /* Recover from a syntax error on YYSTACK, assuming that YYTOKENP, YYLVALP, and YYLLOCP point to the syntactic category, semantic value, and location of the look-ahead. */ static void yyrecoverSyntaxError (yyGLRStack* yystack, YYSTYPE* yylvalp, YYLTYPE* YYOPTIONAL_LOC (yyllocp) ) { yySymbol* const yytokenp = yystack->yytokenp; size_t yyk; int yyj; if (yystack->yyerrState == 3) /* We just shifted the error token and (perhaps) took some reductions. Skip tokens until we can proceed. */ while (yytrue) { if (*yytokenp == YYEOF) yyFail (yystack, NULL); if (*yytokenp != YYEMPTY) { yydestruct ("Error: discarding", *yytokenp, yylvalp); } YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; *yytokenp = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", *yytokenp, yylvalp, yyllocp); yyj = yypact[yystack->yytops.yystates[0]->yylrState]; if (yyis_pact_ninf (yyj)) return; yyj += *yytokenp; if (yyj < 0 || YYLAST < yyj || yycheck[yyj] != *yytokenp) { if (yydefact[yystack->yytops.yystates[0]->yylrState] != 0) return; } else if (yytable[yyj] != 0 && ! yyis_table_ninf (yytable[yyj])) return; } /* Reduce to one stack. */ for (yyk = 0; yyk < yystack->yytops.yysize; yyk += 1) if (yystack->yytops.yystates[yyk] != NULL) break; if (yyk >= yystack->yytops.yysize) yyFail (yystack, NULL); for (yyk += 1; yyk < yystack->yytops.yysize; yyk += 1) yymarkStackDeleted (yystack, yyk); yyremoveDeletes (yystack); yycompressStack (yystack); /* Now pop stack until we find a state that shifts the error token. */ yystack->yyerrState = 3; while (yystack->yytops.yystates[0] != NULL) { yyGLRState *yys = yystack->yytops.yystates[0]; yyj = yypact[yys->yylrState]; if (! yyis_pact_ninf (yyj)) { yyj += YYTERROR; if (0 <= yyj && yyj <= YYLAST && yycheck[yyj] == YYTERROR && yyisShiftAction (yytable[yyj])) { /* Shift the error token having adjusted its location. */ YYLTYPE yyerrloc; YY_SYMBOL_PRINT ("Shifting", yystos[yytable[yyj]], yylvalp, &yyerrloc); yyglrShift (yystack, 0, yytable[yyj], yys->yyposn, *yylvalp, &yyerrloc); yys = yystack->yytops.yystates[0]; break; } } yydestroyGLRState ("Error: popping", yys); yystack->yytops.yystates[0] = yys->yypred; yystack->yynextFree -= 1; yystack->yyspaceLeft += 1; } if (yystack->yytops.yystates[0] == NULL) yyFail (yystack, NULL); } #define YYCHK1(YYE) \ do { \ switch (YYE) { \ case yyok: \ break; \ case yyabort: \ goto yyabortlab; \ case yyaccept: \ goto yyacceptlab; \ case yyerr: \ goto yyuser_error; \ default: \ goto yybuglab; \ } \ } while (0) /*----------. | yyparse. | `----------*/ int yyparse (void) { int yyresult; yySymbol yytoken; yyGLRStack yystack; size_t yyposn; YYSTYPE* const yylvalp = &yylval; YYLTYPE* const yyllocp = &yylloc; YYDPRINTF ((stderr, "Starting parse\n")); yytoken = YYEMPTY; yylval = yyval_default; if (! yyinitGLRStack (&yystack, YYINITDEPTH)) goto yyexhaustedlab; switch (YYSETJMP (yystack.yyexception_buffer)) { case 0: break; case 1: goto yyabortlab; case 2: goto yyexhaustedlab; default: goto yybuglab; } yystack.yytokenp = &yytoken; yyglrShift (&yystack, 0, 0, 0, yylval, &yylloc); yyposn = 0; while (yytrue) { /* For efficiency, we have two loops, the first of which is specialized to deterministic operation (single stack, no potential ambiguity). */ /* Standard mode */ while (yytrue) { yyRuleNum yyrule; int yyaction; const short int* yyconflicts; yyStateNum yystate = yystack.yytops.yystates[0]->yylrState; YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) goto yyacceptlab; if (yyisDefaultedState (yystate)) { yyrule = yydefaultAction (yystate); if (yyrule == 0) { yyreportSyntaxError (&yystack, yylvalp, yyllocp); goto yyuser_error; } YYCHK1 (yyglrReduce (&yystack, 0, yyrule, yytrue)); } else { if (yytoken == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, yylvalp, yyllocp); } yygetLRActions (yystate, yytoken, &yyaction, &yyconflicts); if (*yyconflicts != 0) break; if (yyisShiftAction (yyaction)) { YY_SYMBOL_PRINT ("Shifting", yytoken, yylvalp, yyllocp); if (yytoken != YYEOF) yytoken = YYEMPTY; yyposn += 1; yyglrShift (&yystack, 0, yyaction, yyposn, yylval, yyllocp); if (0 < yystack.yyerrState) yystack.yyerrState -= 1; } else if (yyisErrorAction (yyaction)) { yyreportSyntaxError (&yystack, yylvalp, yyllocp); goto yyuser_error; } else YYCHK1 (yyglrReduce (&yystack, 0, -yyaction, yytrue)); } } while (yytrue) { size_t yys; size_t yyn = yystack.yytops.yysize; for (yys = 0; yys < yyn; yys += 1) YYCHK1 (yyprocessOneStack (&yystack, yys, yyposn, yylvalp, yyllocp)); yytoken = YYEMPTY; yyposn += 1; yyremoveDeletes (&yystack); if (yystack.yytops.yysize == 0) { yyundeleteLastStack (&yystack); if (yystack.yytops.yysize == 0) yyFail (&yystack, YY_("syntax error")); YYCHK1 (yyresolveStack (&yystack)); YYDPRINTF ((stderr, "Returning to deterministic operation.\n")); yyreportSyntaxError (&yystack, yylvalp, yyllocp); goto yyuser_error; } else if (yystack.yytops.yysize == 1) { YYCHK1 (yyresolveStack (&yystack)); YYDPRINTF ((stderr, "Returning to deterministic operation.\n")); yycompressStack (&yystack); break; } } continue; yyuser_error: yyrecoverSyntaxError (&yystack, yylvalp, yyllocp); yyposn = yystack.yytops.yystates[0]->yyposn; } yyacceptlab: yyresult = 0; goto yyreturn; yybuglab: YYASSERT (yyfalse); /* Fall through. */ yyabortlab: yyresult = 1; goto yyreturn; yyexhaustedlab: yyerror (YY_("memory exhausted")); yyresult = 2; /* Fall through. */ yyreturn: if (yytoken != YYEOF && yytoken != YYEMPTY) yydestruct ("Cleanup: discarding lookahead", yytoken, yylvalp); /* If the stack is well-formed, pop the stack until it is empty, destroying its entries as we go. But free the stack regardless of whether it is well-formed. */ if (yystack.yyitems) { yyGLRState** yystates = yystack.yytops.yystates; if (yystates) while (yystates[0]) { yyGLRState *yys = yystates[0]; yydestroyGLRState ("Cleanup: popping", yys); yystates[0] = yys->yypred; yystack.yynextFree -= 1; yystack.yyspaceLeft += 1; } yyfreeGLRStack (&yystack); } return yyresult; } /* DEBUGGING ONLY */ #ifdef YYDEBUG static void yypstack (yyGLRStack* yystack, size_t yyk) __attribute__ ((__unused__)); static void yypdumpstack (yyGLRStack* yystack) __attribute__ ((__unused__)); static void yy_yypstack (yyGLRState* yys) { if (yys->yypred) { yy_yypstack (yys->yypred); fprintf (stderr, " -> "); } fprintf (stderr, "%d@%lu", yys->yylrState, (unsigned long int) yys->yyposn); } static void yypstates (yyGLRState* yyst) { if (yyst == NULL) fprintf (stderr, "<null>"); else yy_yypstack (yyst); fprintf (stderr, "\n"); } static void yypstack (yyGLRStack* yystack, size_t yyk) { yypstates (yystack->yytops.yystates[yyk]); } #define YYINDEX(YYX) \ ((YYX) == NULL ? -1 : (yyGLRStackItem*) (YYX) - yystack->yyitems) static void yypdumpstack (yyGLRStack* yystack) { yyGLRStackItem* yyp; size_t yyi; for (yyp = yystack->yyitems; yyp < yystack->yynextFree; yyp += 1) { fprintf (stderr, "%3lu. ", (unsigned long int) (yyp - yystack->yyitems)); if (*(yybool *) yyp) { fprintf (stderr, "Res: %d, LR State: %d, posn: %lu, pred: %ld", yyp->yystate.yyresolved, yyp->yystate.yylrState, (unsigned long int) yyp->yystate.yyposn, (long int) YYINDEX (yyp->yystate.yypred)); if (! yyp->yystate.yyresolved) fprintf (stderr, ", firstVal: %ld", (long int) YYINDEX (yyp->yystate.yysemantics.yyfirstVal)); } else { fprintf (stderr, "Option. rule: %d, state: %ld, next: %ld", yyp->yyoption.yyrule, (long int) YYINDEX (yyp->yyoption.yystate), (long int) YYINDEX (yyp->yyoption.yynext)); } fprintf (stderr, "\n"); } fprintf (stderr, "Tops:"); for (yyi = 0; yyi < yystack->yytops.yysize; yyi += 1) fprintf (stderr, "%lu: %ld; ", (unsigned long int) yyi, (long int) YYINDEX (yystack->yytops.yystates[yyi])); fprintf (stderr, "\n"); } #endif
[ "jheriko@78b37d4e-3566-11de-a9fe-ad1e22fc3a8a" ]
[ [ [ 1, 3128 ] ] ]
1db24d474fab45d3ec5a5cd9fe53b6feae7db03e
21da454a8f032d6ad63ca9460656c1e04440310e
/src/wcpp/util/element/wsuKey.cpp
6f94c246f6486e6588a01756a74c0758ad9cce3c
[]
no_license
merezhang/wcpp
d9879ffb103513a6b58560102ec565b9dc5855dd
e22eb48ea2dd9eda5cd437960dd95074774b70b0
refs/heads/master
2021-01-10T06:29:42.908096
2009-08-31T09:20:31
2009-08-31T09:20:31
46,339,619
0
0
null
null
null
null
UTF-8
C++
false
false
999
cpp
#include "wsuKeyValue.h" #include <wcpp/lang/helper/ws_runtime.h> #include <wcpp/lang/wsiObject.h> wsuKey::wsuKey(wsiObject * src) : m_object(WS_NULL) { if (src) { src->AddRef(); m_object = src; } } wsuKey::wsuKey(const wsuKey &src) : m_object(WS_NULL) { wsiObject * obj = src.m_object; if (obj) { obj->AddRef(); m_object = obj; } } wsuKey::~wsuKey(void) { wsiObject * obj = m_object; m_object = WS_NULL; if (obj) ws_runtime::getRuntime()->PreRelease( obj ); } wsuKey::operator long(void) const { wsiObject * obj = m_object; if (obj) { return obj->HashCode(); } else { return 0; } } bool wsuKey::operator ==(const wsuKey &other) const { wsiObject * o1 = m_object; wsiObject * o2 = other.m_object; if ((o1==WS_NULL) || (o2==WS_NULL)) { return (o1==o2); } else { return o1->Equals( o2 ); } }
[ "xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8" ]
[ [ [ 1, 57 ] ] ]
d22c88e4464f9fc8db586a471acbc3683e709208
3eae8bea68fd2eb7965cca5afca717b86700adb5
/Engine/Project/Core/GnMesh/Source/GnIButton.cpp
56c7770e7cdc6b675c39a76e007d38c8042f174f
[]
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
5,428
cpp
#include "GnMeshPCH.h" #include "GnInterfacePCH.h" #include "GnIButton.h" #include "GnIProgressBar.h" GnImplementRTTI(GnIButton, GnInterface); GnIButton::GnIButton(const gchar* pcDefaultImage, const gchar* pcClickImage , const gchar* pcDisableImage, GnIButton::eButtonType eDefaultType) : mpProgressTime(NULL) { SetIsEnableCoolTime( false ); SetIsDisableCantpushBlind( true ); SetIsHidePushDefaultButton( true ); SetIsHidePushUpClickButton( true ); switch( (gint)eDefaultType ) { case TYPE_NORMAL: case TYPE_PUSH: { if( pcDefaultImage == NULL ) return; GnVerify( CreateDefaultImage( pcDefaultImage ) ); if( pcClickImage ) { GnVerify( CreateClickImage( pcClickImage ) ); if( mpsPushMesh ) mpsPushMesh->SetVisible( false ); } if( pcDisableImage ) { CreateDisableImage( pcDisableImage ); if( mpsDisableMesh ) mpsDisableMesh->SetVisible( false ); } } break; case TYPE_DISABLE: { GnVerify( CreateDisableImage( pcDisableImage ) ); SetIsDisable( true ); if( pcDefaultImage ) { CreateDefaultImage( pcDefaultImage ); if( mpsDefaultMesh ) mpsDefaultMesh->SetVisible( false ); } if( pcClickImage ) { CreateClickImage( pcClickImage ); if( mpsPushMesh ) mpsPushMesh->SetVisible( false ); } } break; default: GnAssert( false ); } SetIsCantPush( false ); } GnIButton::~GnIButton() { if( mpProgressTime ) GnDelete mpProgressTime; } bool GnIButton::CreateClickImage(const gchar* pcImageName) { mpsPushMesh = Gn2DMeshObject::CreateFromTextureFile( pcImageName ); if( mpsPushMesh == NULL ) return false; AddMeshToParentNode( mpsPushMesh ); return true; } bool GnIButton::CreateDisableImage(const gchar* pcImageName) { mpsDisableMesh = Gn2DMeshObject::CreateFromTextureFile( pcImageName ); if( mpsDisableMesh == NULL ) return false; if( mpsDefaultMesh == NULL ) SetContentSize( mpsDisableMesh->GetSize().x, mpsDisableMesh->GetSize().y ); AddMeshToParentNode( mpsDisableMesh ); SetPosition( GetPosition() ); return true; } void GnIButton::SetCoolTime(float fTime) { if( mpProgressTime == NULL ) CreateProgressBar(); mpProgressTime->SetProgressTime( fTime ); } void GnIButton::Update(float fTime) { if( mpProgressTime ) mpProgressTime->Update( fTime ); } bool GnIButton::Push(float fPointX, float fPointY) { if( ( mpProgressTime && mpProgressTime->GetPlayPlag() == GnIProgressBar::PLAY ) || GnInterface::Push(fPointX, fPointY) == false ) return false; return true; } bool GnIButton::PushMove(float fPointX, float fPointY) { return GnInterface::PushMove( fPointX, fPointY ); } void GnIButton::Push() { GnInterface::Push(); if( IsEnableCoolTime() ) { if( mpProgressTime ) mpProgressTime->Start(); } if( mpsPushMesh ) { if( IsHidePushDefaultButton() ) mpsDefaultMesh->SetVisible( false ); mpsPushMesh->SetVisible( true ); } // else // mpsDefaultMesh->SetColor( GnColor( 0.0f, 1.0f, 0.0f ) ); } void GnIButton::PushUp() { GnInterface::PushUp(); if( IsPush() == false ) { } if( IsHidePushUpClickButton() ) { mpsDefaultMesh->SetVisible( true ); if( mpsPushMesh ) mpsPushMesh->SetVisible( false ); } } void GnIButton::SetIsDisable(bool val) { GnInterface::SetIsDisable( val ); if( mpsDisableMesh == NULL ) return; SetVisibleNormal( !val ); mpsDisableMesh->SetVisible( val ); } void GnIButton::SetIsCantPush(bool val) { GnInterface::SetIsCantPush( val ); if( IsDisableCantpushBlind() ) return; if( mpProgressTime == NULL ) CreateProgressBar(); if( mpProgressTime ) mpProgressTime->SetVisibleBackground( val ); } void GnIButton::SetPosition(GnVector2& cPos) { GnInterface::SetPosition( cPos ); if( mpsPushMesh ) mpsPushMesh->SetPosition( cPos ); if( mpsDisableMesh ) mpsDisableMesh->SetPosition( cPos ); if( mpProgressTime ) mpProgressTime->SetPosition( cPos); } void GnIButton::SetAlpha(guchar ucAlpha) { GnInterface::SetAlpha( ucAlpha ); if( mpsPushMesh ) mpsPushMesh->SetAlpha( ucAlpha ); if( mpsDisableMesh ) mpsDisableMesh->SetAlpha( ucAlpha ); } void GnIButton::SetVisibleNormal(bool val) { if( val ) { // if( mpsDefaultMesh == NULL ) // { // if( mMeshNames[TYPE_NORMAL].Exists() ) // CreateDefaultImage( mMeshNames[TYPE_NORMAL] ); // if( mMeshNames[TYPE_PUSH].Exists() ) // CreateClickImage( mMeshNames[TYPE_PUSH] ); // } if( mpsDefaultMesh ) { mpsDefaultMesh->SetVisible( true ); if( mpsPushMesh ) mpsPushMesh->SetVisible( false ); } } else { if( mpsDefaultMesh ) { mpsDefaultMesh->SetVisible( false ); if( mpsPushMesh ) mpsPushMesh->SetVisible( false ); } } } void GnIButton::CreateProgressBar() { GnAssert( mpsDefaultMesh || mpsDisableMesh ); GnAssert( mpProgressTime == NULL ); if( ( mpsDefaultMesh || mpsDisableMesh ) ) { Gn2DMeshObject* baseMesh = mpsDefaultMesh ? mpsDefaultMesh : mpsDisableMesh; GnVector2 size = baseMesh->GetSize(); mpProgressTime = GnIProgressBar::Create( GnIProgressBar::eHorizontalFromLeft, size.x, size.y ); GetParentUseNode()->addChild( mpProgressTime->GetParentUseNode(), 1 ); mpProgressTime->SetPosition( GetPosition() ); } }
[ [ [ 1, 235 ] ] ]
15032ac9b6bc5284d1dbfebacf03debda0812d8c
f695ff54770f828d18e0013d12d9d760ec6363a3
/sort/CountSort.h
162ea3fcea64465ad7a7711c59ed239e34c78475
[]
no_license
dbremner/airhan
377e1b1f446a44170f745d3a3a47e0a30bc917e1
a436fda7799c1032d060c30355c309ec1589e058
refs/heads/master
2021-01-10T19:42:16.321886
2010-05-29T02:16:25
2010-05-29T02:16:25
34,024,271
0
0
null
null
null
null
UTF-8
C++
false
false
2,308
h
/*************************************************************** Copyright (c) 2008 Michael Liang Han Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************/ #ifndef AIRHAN_SORT_COUNTSORT_H_ #define AIRHAN_SORT_COUNTSORT_H_ #include <iostream> #include <assert.h> namespace lianghancn { namespace air { namespace sort { // it only works for positive integer array template<class T> void CountSort(T a[], int n, int k) { T* pCount = new T[k]; T* pOld = new T[n]; // initialize count array for (int i = 0; i < k; i ++) { pCount[i] = 0; } // copy original array and 1st pass over count array for (int i = 0; i < n; i ++) { pOld[i] = a[i]; pCount[a[i]] ++; } // 2nd pass over count array to make it accumulative for (int i = 1; i < k; i ++) { pCount[i] = pCount[i - 1] + pCount[i]; } // final pass over both array to directly put element to its deserved position for (int i = n - 1; i >= 0; i --) { a[pCount[pOld[i]] - 1] = pOld[i]; pCount[pOld[i]] -- ; } delete[] pCount; delete[] pOld; } }; }; }; #endif
[ "lianghancn@29280b2a-3d39-11de-8f11-b9fadefa0f10" ]
[ [ [ 1, 79 ] ] ]
dbf48238d59fc3ca5c0bb01ed204d76602c9f471
8a3fce9fb893696b8e408703b62fa452feec65c5
/GServerEngine/GameAi/GameAi/Entity/StatePro/DeadState.h
9318351075609d1dc6fe9cb523204ce2112a0ce1
[]
no_license
win18216001/tpgame
bb4e8b1a2f19b92ecce14a7477ce30a470faecda
d877dd51a924f1d628959c5ab638c34a671b39b2
refs/heads/master
2021-04-12T04:51:47.882699
2011-03-08T10:04:55
2011-03-08T10:04:55
42,728,291
0
2
null
null
null
null
UTF-8
C++
false
false
430
h
#pragma once #include "../../Public/State.h" class CDeadState : public CState { //typedef entity_name Entity; public: virtual void Enter(CBaseGameEntity* ); virtual void Execute(CBaseGameEntity* ); virtual void Exit(CBaseGameEntity* ); virtual bool HandleEvent( eEventAi e , CBaseGameEntity*) ; // return state virtual eStateAi GetState() { return Ent_DeadState ; } private: };
[ [ [ 1, 27 ] ] ]
8f8c3c53adcf80a2478b2a2c36c555a22c25068d
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/iostreams/test/line_filter_test.cpp
5381459393dd453827f47bee788733667ac2bdb0
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
2,923
cpp
// (C) Copyright Jonathan Turkanis 2004 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.) // See http://www.boost.org/libs/iostreams for documentation. #include <cctype> #include <boost/iostreams/copy.hpp> #include <boost/iostreams/device/file.hpp> #include <boost/iostreams/filter/line.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/test/test_tools.hpp> #include <boost/test/unit_test.hpp> #include "detail/constants.hpp" #include "detail/filters.hpp" #include "detail/temp_file.hpp" #include "detail/verification.hpp" // Must come last. #include <boost/iostreams/detail/config/disable_warnings.hpp> // BCC 5.x. using namespace std; using namespace boost; using namespace boost::iostreams; using namespace boost::iostreams::test; using boost::unit_test::test_suite; struct toupper_line_filter : line_filter { std::string do_filter(const std::string& line) { std::string result(line); for ( std::string::size_type z = 0, len = line.size(); z < len; ++z ) { result[z] = std::toupper((unsigned char) result[z]); } return result; } }; bool compare_streams_in_lines(std::istream& first, std::istream& second) { do { std::string line_one; std::string line_two; std::getline(first, line_one); std::getline(second, line_two); if (line_one != line_two || first.eof() != second.eof()) return false; } while (!first.eof()); return true; } void read_line_filter() { test_file src; uppercase_file upper; filtering_istream first; first.push(toupper_line_filter()); first.push(file_source(src.name(), in_mode)); ifstream second(upper.name().c_str(), in_mode); BOOST_CHECK_MESSAGE( compare_streams_in_lines(first, second), "failed reading from a line_filter" ); } void write_line_filter() { test_file data; temp_file dest; uppercase_file upper; filtering_ostream out; out.push(toupper_line_filter()); out.push(file_sink(dest.name(), out_mode)); copy(file_source(data.name(), in_mode), out); out.reset(); ifstream first(dest.name().c_str()); ifstream second(upper.name().c_str()); BOOST_CHECK_MESSAGE( compare_streams_in_lines(first, second), "failed writing to a line_filter" ); } test_suite* init_unit_test_suite(int, char* []) { test_suite* test = BOOST_TEST_SUITE("line_filter test"); test->add(BOOST_TEST_CASE(&read_line_filter)); test->add(BOOST_TEST_CASE(&write_line_filter)); return test; } #include <boost/iostreams/detail/config/enable_warnings.hpp> // BCC 5.x.
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 98 ] ] ]
16ad9429fa408a1177b9182ea68771ff192a5abe
af9524b76162da55a8d44fb50ffbb8f1dc8fa98c
/examples/cloud-setup/sources/common/Matrix2Dlc.h
5ec8686272a845f8fb07ba82c1389ade7c398a7e
[ "GPL-1.0-or-later", "MIT" ]
permissive
GaretJax/pop-utils
e72c5b387541d05cd35d599294184d1ca6673330
2cdfaf24c2f8678edfab1f430c07611d488247d5
refs/heads/master
2022-07-22T17:48:15.798181
2011-05-19T21:46:19
2011-05-19T21:46:19
1,735,213
0
0
MIT
2022-07-06T19:17:17
2011-05-11T20:34:07
C++
UTF-8
C++
false
false
511
h
#ifndef _MATRIX2DLC_H #define _MATRIX2DLC_H #include "Matrix2D.h" class Matrix2Dlc : virtual public Matrix2D { public: Matrix2Dlc(); Matrix2Dlc(int line, int col); ValueType get(int line, int col); void set(int line, int col, ValueType v); void display(); void display(int n); Matrix2Dlc getLinesBloc(int noLine, int nbLines); void setLinesBloc(int noLine, Matrix2Dlc v); void setBloc(int noLine, int noCol, Matrix2Dlc v); }; #endif
[ [ [ 1, 21 ] ] ]
b7ce4859c99ec3e537b912ebbca28e967e6596d5
41371839eaa16ada179d580f7b2c1878600b718e
/SPOJ/obi/TRILHAS.cpp
8ce3e92e66a2817366303dfcac071231cf712f3c
[]
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
494
cpp
#include <cstdio> #define MIN(a,b) ((a<b)?(a):(b)) int c, cost, costL, costR, i, idx, j, min, n, p, pts; int main(void){ scanf("%d",&n); min = 1<<30; for(i = 0; i < n; i++){ scanf("%d",&pts); p = c = costR = costL = 0; for(j = 0; j < pts; j++){ p = c; scanf("%d",&c); if(j){ if(c > p) costR += (c-p); else if(c < p) costL += (p-c); } } cost = MIN(costL,costR); if(min > cost) min = cost, idx = i+1; } printf("%d\n",idx); return 0; }
[ [ [ 1, 23 ] ] ]
40f53af26a2313cc3a6818019b81faea0eb91dcb
c7dcd4b321428c91074d6802b8a655a40fbb283b
/ObjectDetection/ObjectDetection/ObjectDetection.cpp
3fbc2df45331bbb372fb1b35a54e59ec3407d1f4
[]
no_license
buubui/imgdetection
7c12576ef6ddc06d788183f4261bc070e13ee2fb
feeb9b5233c2a0bd35b60bf7792bd05005cc0409
refs/heads/master
2016-09-05T11:45:33.588669
2011-04-27T16:08:34
2011-04-27T16:08:34
32,272,304
0
0
null
null
null
null
UTF-8
C++
false
false
22,366
cpp
// ObjectDetection.cpp : main project file. #include "stdafx.h" #include "MainWindow.h" //using namespace System; using namespace ObjectDetection; // TestOpenCv.cpp : Defines the entry point for the console application. // //#include "imFilter.h" //#include <math.h> //#include "HOG.h" #include "ctime" #include "glbVars.h" //#include "meanshift.h" //#include "HardSample.h" extern int useTech; extern string weightFile; void takefalseImg(string ffile) { ifstream in1,in2; in1.open(ffile.c_str()); in2.open("input/testPos.txt"); if(!in1.is_open()) return; string tmp1,tmp2; bool b=true; string path; getline(in2,path); for(int i=1;;i++) { if(b) { getline(in1,tmp1); if(tmp1.size()<1) break; b=false; } getline(in2,tmp2); if(i==atoi(tmp1.c_str())) { // Mat img = imread(path+tmp2); imwrite("output/false/"+tmp2,img,vector<int>(CV_IMWRITE_PNG_COMPRESSION,4)); imshow("img_"+tmp2,img); b=true; } } } void takeHardList(string fileresult,string fileData) { ifstream inResult,inData; stringstream strstreams; // inList.open(filelist.c_str()); inResult.open(fileresult.c_str()); inData.open(fileData.c_str()); int i=0; string lineResult,lineData; while(!inResult.eof()){ // cout<<i++<<endl; getline(inResult,lineResult); // getline(inList,lineList); if(lineResult.length()<1) break; getline(inData,lineData); if(lineData[0]=='+'){ double d; d=atof(lineResult.c_str()); if(d<0) strstreams<<lineData<<endl; } else if(lineData[0]=='-'){ double d; d=atof(lineResult.c_str()); if(d>0) strstreams<<lineData<<endl; } } inData.close(); inResult.close(); ofstream outHard; outHard.open("output/hard.txt"); outHard<<strstreams.str(); outHard.close(); } void takeHardEx(string filelist, string filedata){ ifstream inList, inData; stringstream strstreams; inList.open(filelist.c_str()); inData.open(filedata.c_str()); int i=0; string lineList,lineData; while(!inList.eof()){ getline(inList,lineList); if(lineList.length()<1) break; int line = atoi(lineList.c_str()); for (;i<=line;i++) { getline(inData,lineData); if(i==line) strstreams<<lineData<<endl; } } inData.close(); inList.close(); ofstream outHard; outHard.open("output/hard.txt"); outHard<<strstreams.str(); outHard.close(); } void takeType(string fnamein,string fnameout,char type) { ifstream inData; ofstream outData; inData.open(fnamein.c_str()); outData.open(fnameout.c_str()); string lineData; while(!inData.eof()){ getline(inData,lineData); if(lineData.length()<1) break; if(lineData[0]!=type) continue; outData <<lineData<<endl; } inData.close(); outData.close(); } void splitList(string fname, int n_part) { ifstream inData; inData.open(fname.c_str()); ofstream* outData = new ofstream[n_part]; for (int i=0;i<n_part;i++) { stringstream strName; strName<<"output/list_"<<i<<".txt"; outData[i].open(strName.str().c_str()); } string lineData; getline(inData,lineData); for (int i=0;i<n_part;i++) { outData[i]<<lineData<<endl; } int iLine=0; while(!inData.eof()){ getline(inData,lineData); if(lineData.length()<1) break; // for (int i=0;i<n_part;i++) // { outData[iLine%n_part]<<lineData<<endl; // } iLine++; } inData.close(); for (int i=0;i<n_part;i++) { outData[i].close(); } } [STAThreadAttribute] int main(array<System::String ^> ^args) { clock_t t1,t2; t1 = clock(); loadConfig(); /*Mat img=imread("d:\\Lectures\\Luan_van\\DATASET\\INRIAPerson\\train_64x128_H96\\pos\\person_and_bike_209a.png"); Mat* imFils; Mat G; int n_channels=img.channels(); imFils = imFilterChannels(img,true); G = calcGradientOfPixelsMaxChannel(imFils,n_channels); int* x_corr=NULL;int* y_corr=NULL; int n_x=0, n_y=0; Mat his_cells_wnd ; HIS his_wind; HIS* h_ws=NULL; cv::Rect slideWnd(0,0,64,128); slideWnd.x = (img.rows - slideWnd.height)/2; slideWnd.y = (img.cols - slideWnd.width)/2; svmClassify( img, G,slideWnd, cellSize, 1., n_x, n_y, x_corr,y_corr, his_cells_wnd, his_wind,h_ws, 3, true,false,false,4); compressPCA(his_wind,0)*/ /*cout.precision(4); cout << 1.23456789<<endl; cout << 1.23456789<<endl;*/ // takeHardList("D:\\Lectures\\Luan_van\\tool\\svm_light_windows\\classify_result1.txt","D:\\Lectures\\Luan_van\\tool\\svm_light_windows\\val_1.txt"); // splitList("input/trainNeg.txt",2); // int a[4]={0,1,0,1}; // cout << bin2dec(a,4); // Mat img = imread("D:\\Lectures\\Luan_van\\DATASET\\INRIAPerson\\70X134H96\\Test\\pos\\crop_000002b.png"); // Mat img2; // cvtColor(img,img,CV_BGR2HSV); //// cout<<img2.channels()<<img2.type()<<endl; // imshow("hsv",img); // //Vec3b v; // //v= img2.at<Vec3b>(5,5); // //cout<<(int)v[0]<<" "<<(int)v[1]<<" "<<(int)v[2]<<endl; // waitKey(0); //img=img(Rect(0,0,64,128)); //int n_channels=1; //Mat* imFils; //Mat G; // //n_channels=img.channels(); //imFils = imFilterChannels(img,true); //G = calcGradientOfPixelsMaxChannel(imFils,n_channels); //Mat* h_w=NULL; //int*x_corr=NULL;int*y_corr=NULL; //int n_x=0, n_y=0; //float scale=1.; //int n_bins=9; //HIS his_wind; //if(n_x==0) // calcGrid(G,blockSize,cellSize, cv::Size(blockSize.width*cellSize.width/2,blockSize.height*cellSize.height/2),x_corr,y_corr, n_x, n_y); //Mat m_tmp; //while(true) //{ //// HIS* h_w=NULL; //// HIS H=calcHistOfWndNew(img,cellSize,9,h_w); // // calcHisOfGrid(G,blockSize,cellSize,cv::Size(blockSize.width*cellSize.width/2,blockSize.height*cellSize.height/2),x_corr,y_corr,n_x,n_y,scale, n_bins,his_wind,m_tmp); // //// H.release(); //} /*printf("%d %d\n",H.rows,H.cols); for (int i=0;i <200;i++) { cout<<H.at<float>(0,i)<<"; "; } waitKey(0);*/ /* Mat* imgfils=imFilterChannels(im,true); int n_channels=im.channels(); Mat G = calcGradientOfPixelsMaxChannel(imgfils,n_channels); Mat T; GaussianBlur(G,T,cv::Size(3,3),0.5*8*3); for (int i=100;i<300;i++) { printf("%f %f %f %f\n",G.at<Gradient>(i,i)[0],G.at<Gradient>(i,i)[1],T.at<Gradient>(i,i)[0],T.at<Gradient>(i,i)[1]); } for (int j=0;j<im.channels();j++) { imgfils[j].release(); imgfils[j+1].release(); } G.release(); delete[] imgfils;*/ // } /*imshow("0",imgfils[0]); imshow("1",imgfils[1]); imshow("2",imgfils[2]); imshow("3",imgfils[3]); imshow("4",imgfils[4]); imshow("5",imgfils[5]); waitKey(0);*/ /*srand(time(NULL)); for (int i=0;i<20;i++) { cout<<rand()%100<<endl; }*/ // GenHardSample("input/thu/train.txt","input/thu/index.txt","input/thu/NegHardSample.txt"); /************************************************************************/ /* Generating data for SVM */ /************************************************************************/ // Rect r(100,100,33,33); //for (int i=0;i<100000000000;i++) //{ // r= getRect(0,0,2); //} // svmGenerateData2("input/Train_Pos.txt","input/Train_Neg_P1.txt",1,8); // svmGenerateData2("input/Test_Pos.txt","input/Test_Neg.txt",1,8); // svmGenerateData2("input/a.txt","input/b.txt",1,3,3, 1., 1.05, true,false,false,1); // svmGenerateData2("input/trainPos.txt","input/trainNeg.txt",1,2,3,1.,1.1,true,false,false,1); // svmGenerateData2("input/NULL.txt","input/trainNeg_0.txt",1,1,true,false,false); // svmGenerateData2("input/NULL.txt","input/trainNeg_1.txt",1,1,true,false,false); // svmGenerateData2("input/NULL.txt","input/trainNeg.txt",1,6,true,false,false,-1); // svmGenerateData2("input/NULL.txt","input/trainNeg.txt",1,6,true,false,false,-1); /* svmGenerateData2("input/NULL.txt","input/trainNeg.txt",1,6,true,false,false,-1); svmGenerateData2("input/NULL.txt","input/trainNeg.txt",1,6,true,false,false,-1); svmGenerateData2("input/NULL.txt","input/trainNeg.txt",1,6,true,false,false,-1);*/ // svmGenerateData2("input/testPosF.txt","input/testNegF.txt",1,10,true,false,false,-1); //computePCA("input/trainPos.txt","input/trainNeg.txt",1,1,3,1.,1.5,true,false,false,3); /*PCA p=computePCA("input/a.txt","input/b.txt",1,5,3,1.,1.1,true,false,false,4,700); backupPCA(p,"output/pca.yml"); PCA p1=restorePCA("output/pca.yml"); cout <<p1.eigenvalues.rows<<" "<<p1.eigenvalues.cols<<endl; cout <<p1.eigenvectors.rows<<" "<<p1.eigenvectors.cols<<endl; cout <<p1.mean.rows<<" "<<p1.mean.cols<<endl;*/ // svmGenHardList("input/weight.txt","input/a.txt","input/b.txt","temp",1,4,1.,100,true,false,false,-1); // svmGenHardList("input/weight4p_1.5-2.txt","input/trainPos.txt","input/trainNeg.txt","train",1,400,3,1.,1.05,true,false,false,1); // svmGenHardList("input/weight.txt","input/testPosF.txt","input/testNegF.txt","test",1,350,3,1.,1.05,true,false,false,1); /************************************************************************/ /* Test new mean shift */ /************************************************************************/ //Mat* means; //int n_mean; //int p_mean; //newMeanshiftFromFile("output/crop001501b_multiscale_2.txt",0.,1,means,n_mean,p_mean); /************************************************************************/ /* Test XML */ /************************************************************************/ // XmlDocument ^ doc = gcnew XmlDocument; // // doc->Load("input/file.xml"); //// XmlTextReader^ reader= gcnew XmlTextReader("input/test.xml"); //// cout<<msclr::interop::marshal_as<std::string>(reader->); // XmlNodeList^ nl= doc->GetElementsByTagName("object"); // XmlNodeList^ att=nl->Item(0)->ChildNodes->Item(4)->ChildNodes; // for (int i=0;i<att->Count;i++) // { // Console::WriteLine(att->Item(i)->InnerText); // } //////////////////////////////////VOC////////////////////////////////////////////////////// System::String^ annpath="D:\\Lectures\\Luan_van\\DATASET\\VOC\\VOCdevkit\\VOC2010\\Annotations\\"; Rect* rects; int n_rect; // VOCAnnRects("D:\\My Documents\\VOC2009\\Annotations\\2009_005311.xml","person",rects,n_rect); // cout<<n_rect<<endl; std::string filelist="D:\\Lectures\\Luan_van\\DATASET\\VOC\\VOCdevkit\\VOC2010\\ImageSets\\Main\\person_val.txt"; // VOCSvmGenerateData2(annpath,"D:\\Lectures\\Luan_van\\DATASET\\VOC\\VOCdevkit\\VOC2010\\JPEGImages\\",".jpg","person",filelist,1,5,2.,5.,true,false,false); // takeType("output/train_person.txt","output/train_person_pos.txt",'+'); // takeType("output/train_person.txt","output/train_person_neg.txt",'-'); /////////////////////////////////////////////////////////////////////////////////////////////// //ifstream inputFile; //printf("%s\n",posfilelist.c_str()); //inputFile.open (posfilelist.c_str()); ////inputNegFile.open (negfilelist.c_str()); //string filepath,filename; //Rect slideWnd(0,0,wndSize.width,wndSize.height); //float scale=1.,step=1.2; //string tmp; //std::vector<std::string> strs; //while (!inputFile.eof()) //{ // getline (inputFile,tmp); // // char* s = (char*)(tmp.c_str()); // boost::split(strs,s , boost::is_any_of(" ")); // if (strs.size()>2){ // int _i=atoi(strs[strs.size()-1].c_str()); // if(_i!=-1) // { // VOCAnnRects(annpath+gcnew System::String(strs[0].c_str())+gcnew System::String(".xml"),"person",rects,n_rect); // printf("%s: %d \n",strs[0].c_str(),n_rect); // } // } //} /************************************************************************/ /* Load GUI */ /************************************************************************/ // Enabling Windows XP visual effects before any controls are created Application::EnableVisualStyles(); Application::SetCompatibleTextRenderingDefault(false); // Create the main window and run it Application::Run(gcnew MainWindow()); // t2 = clock(); printf("Running time: %f (mins)\n",(float)(t2-t1)/(60*CLOCKS_PER_SEC)); return 0; } //int main(array<System::String ^> ^args) //{ // loadConfig(); // //// svmGenerateData2("input/trainPos.txt","input/trainNeg2.txt",1,10); // //// string path="D:\\Lectures\\Luan_van\\DATASET\\INRIAPerson\\Test\\pos\\"; // string path="D:\\Lectures\\Luan_van\\DATASET\\INRIAPerson\\Train\\pos\\"; // string fname="person_117"; // string ext=".png"; // Mat imgOrg = imread(path+fname+ext); // Mat img; // float maxSz=500*400.; // float minSz = wndSize.width*wndSize.height; // float t=(float)imgOrg.rows*imgOrg.cols; // float resizeScale=t>maxSz?sqrt(maxSz/t):1.; // resizeScale=t<minSz?sqrt(minSz/t):resizeScale; // resize(imgOrg,img,Size(imgOrg.cols*resizeScale,imgOrg.rows*resizeScale),resizeScale,resizeScale); // cout<<img.rows<<" "<<img.cols<<" "<<resizeScale<<endl; // imgOrg.release(); //// multiscaleExp(path+fname+ext,1.2,0.); // // // int n_mean,p_mean; // float*means; // meanshiftFromFile("output/"+fname+"_multiscale.txt",100,8,means,n_mean,p_mean); // // for (int i=0;i<n_mean*p_mean;i++) // { // cout<<means[i]<<", "; // if(i>0&&i%p_mean==p_mean-1) // cout<<endl; // } // drawRect2Img(img,"output/"+fname+"_meanshift.txt"); // imwrite("output/"+fname+"_meanshift.png",img,vector<int>(CV_IMWRITE_PNG_COMPRESSION,4)); // imshow(fname+"_meanshift",img); // // // takefalseImg("input/false_pos.txt"); // //CHECK MEMORY LEAKING //// while(1){ //// Mat img = imread("E:\crop_000027.png"); //// Mat* imFils = imFilter(img); //// Mat G = calcGradientOfPixels(imFils[0],imFils[1]); //// Mat his_wnd = calcHisOfCellsInWnd2(G,Rect(0,0,img.cols,img.rows),cellSize,9); //// //// //// HIS* h_w = calcHistOfWnd(his_wnd,blockSize,Vec2i(1,1),2); ////// float* vv = &(h_w->vector_weight[0]); ////// cout<<*vv<<endl; ////// delete[] h_w->vector_weight; ////// cout<<*vv<<endl; //// delete h_w; //// //// for (int i=0;i<his_wnd.rows;i++) //// { //// for (int j=0;j<his_wnd.cols;j++) //// { //// HIS* hh=his_wnd.at<HIS*>(i,j); //// // delete[] hh->vector_weight; //// delete hh; //// } //// } //// his_wnd.release(); //// img.release(); //// imFils[0].release(); //// imFils[1].release(); //// G.release(); //// } // // // //// generateData("input/filelist_pos.txt",1,1); //// generateData("input/filelist_neg.txt",-1,2); // // ifstream inputfile; // // inputfile.open ("input/filelist.txt"); // // string filepath,filename; // // if (inputfile.is_open()) // // { // //// while (! inputfile.eof() ) // //// { // // getline (inputfile,filepath); // // getline (inputfile,filename); // // // //// } // // } // // inputfile.close(); // // // // ifstream conffile; // // conffile.open ("input/config.txt"); // // string tmp; // // Size cellSize,blockSize; // // if (conffile.is_open()) // // { // // // while (! inputfile.eof() ) // // // { // // getline (conffile,tmp);//cell // // getline (conffile,tmp); // // cellSize.width = atoi(tmp.c_str()); // // getline (conffile,tmp); // // cellSize.height = atoi(tmp.c_str()); // // getline (conffile,tmp);//block // // getline (conffile,tmp); // // blockSize.width = atoi(tmp.c_str()); // // getline (conffile,tmp); // // blockSize.height = atoi(tmp.c_str()); // // // // // } // // } // // conffile.close(); // // Mat img = imread(filepath+filename); // // imshow("asdasd",img); // // Mat* imFils = imFilter(img); // // /*Mat img_gray; // // cvtColor(img,img_gray,CV_BGR2GRAY); // // equalizeHist(img_gray,img_gray); // // */ // // // // //imshow("filter x",imFils[0]); // // //imshow("filter y",imFils[1]); // // // // Mat G = calcGradientOfPixels(imFils[0],imFils[1]); // // // // printf("\nGRADIENT:\n"); // //// for(int i=0;i<30;i++) // //// for(int j=0;j<20;j++) // //// printf("%f: %f \n",G.at<Gradient>(i,j)[0],G.at<Gradient>(i,j)[1]); // // // // /*HIS* his = calcHisOfCell(G,Rect(50,50,10,10),9); // // for (int i=0;i<9;i++) // // { // // printf("%f, ",his->vector_weight[i]); // // }*/ // //// Mat his_wnd = calcHisOfCellsInWnd(G,Rect(0,0,64,128),Size(8,8),9); // // Rect R(0,0,img.cols,img.rows); // // cout <<"RECT:"<< R.width << ";"<<img.cols<<";"<<G.cols; // // Mat his_wnd = calcHisOfCellsInWnd2(G,Rect(0,0,img.cols,img.rows),cellSize,9); // // ofstream myfile; // //// SYSTEMTIME st; // //// GetSystemTime(&st); // // time_t curr; // // tm local; // // time(&curr); // get current time_t value // // local=*(localtime(&curr)); // dereference and assign // // stringstream outputfile; // // outputfile<<"output/hisCell_"<<filename<<"_cell"<<cellSize.width<<"x"<<cellSize.height<<"_block"<<blockSize.width<<"x"<<blockSize.height<<"_"<<local.tm_year+1900<<"_"<<local.tm_mon+1<<"_"<<local.tm_mday<<"_"<<local.tm_hour<<"_"<<local.tm_min<<".txt" ; // // myfile.open(outputfile.str().c_str()); // // printf("\ncalcHisOfCellsInWnd\n"); // // //myfile <<"["; // // myfile <<his_wnd.rows<<", "<<his_wnd.cols<<"\n"; // // for(int ii =0; ii<his_wnd.rows;ii++) // // { // // for(int jj =0; jj<his_wnd.cols;jj++) // // { // // // // // // for (int i=0;i<9;i++) // // { // // printf("%2.2f, ",his_wnd.at<HIS*>(ii,jj)->vector_weight[i]); // // myfile << his_wnd.at<HIS*>(ii,jj)->vector_weight[i] ; // // if(i == 8) continue; // // myfile<<", "; // // } // // //if(ii==his_wnd.rows-1 && jj == his_wnd.cols-1) continue; // // myfile << "\n"; // // // // printf("\n"); // // } // // // // // // } // // // // myfile.close(); // // printf("\n %d %d",his_wnd.rows,his_wnd.cols); // // // // // //// calcHistOfBlockInWnd(his_wnd,Rect(2,2,3,3)); // // /*HIS* h_n = NormalizeBlock(his,2); // // for (int i=0;i<h_n->n_bins;i++) // // { // // printf("%f, ",h_n->vector_weight[i]); // // }*/ // // /*HIS* h_w = calcHistOfWnd(his_wnd,Size(3,3),Vec2i(2,2),2); // // // // // // printf("\ncalcHistOfWnd\n"); // // for (int i=0;i<h_w->n_bins;i++) // // { // // printf("%f ; ",h_w->vector_weight[i]); // // } // // printf("\n n_BIN %d\n",h_w->n_bins);*/ // // // // // // /*Mat aa(2,5,DataType<Gradient>::type); // // for (int i=0;i<aa.rows;i++) // // { // // for (int j=0;j<aa.cols;j++) // // { // // aa.at<Gradient>(i,j) = Gradient(2,3); // // } // // }*/ // // // // /*Mat aa(20,7,DataType<Gradient>::type); // // for (int i=0;i<aa.rows;i++) // // { // // for (int j=0;j<aa.cols;j++) // // { // // aa.at<Gradient>(i,j) = Gradient(2,3); // // } // // }*/ // // /*int n =9; // // Vec<int,5> a; // // float * b = new float[10]; // // float c[10]; // // printf("size %d",sizeof(c));*/ // // //G.release(); // // // cvWaitKey(); // return 0; //} // // //int _tmain(int argc, _TCHAR* argv[]) //{ // clock_t start, stop; // start = clock(); // IplImage* img = cvLoadImage("e:\\2009_003218.jpg"); // int w = img->width -1; // int h = img->height -1; // for (int x=0;x<100;x++) // for (int i=0;i<w;i++) // for (int j=0;j<h;j++){ // CvScalar a =cvGet2D(img, i, j); // // printf("%f",a.val[1]); // } // stop = clock(); // printf("%f", (float)(stop - start)/CLOCKS_PER_SEC); // // return 0; //} //#include <windows.h> //#include <tchar.h> //#include <stdio.h> //#include <strsafe.h> // //void DisplayErrorBox(LPTSTR lpszFunction); // //int _tmain(int argc, TCHAR *argv[]) //{ // WIN32_FIND_DATA ffd; // LARGE_INTEGER filesize; // TCHAR szDir[MAX_PATH]; // size_t length_of_arg; // HANDLE hFind = INVALID_HANDLE_VALUE; // DWORD dwError=0; // // // If the directory is not specified as a command-line argument, // // print usage. // // if(argc != 2) // { // _tprintf(TEXT("\nUsage: %s <directory name>\n"), argv[0]); // return (-1); // } // // // Check that the input path plus 3 is not longer than MAX_PATH. // // Three characters are for the "\*" plus NULL appended below. // // StringCchLength(argv[1], MAX_PATH, &length_of_arg); // // if (length_of_arg > (MAX_PATH - 3)) // { // _tprintf(TEXT("\nDirectory path is too long.\n")); // return (-1); // } // // _tprintf(TEXT("\nTarget directory is %s\n\n"), argv[1]); // // // Prepare string for use with FindFile functions. First, copy the // // string to a buffer, then append '\*' to the directory name. // // StringCchCopy(szDir, MAX_PATH, argv[1]); // StringCchCat(szDir, MAX_PATH, TEXT("\\*")); // // // Find the first file in the directory. // // hFind = FindFirstFile(szDir, &ffd); // // if (INVALID_HANDLE_VALUE == hFind) // { // DisplayErrorBox(TEXT("FindFirstFile")); // return dwError; // } // // // List all the files in the directory with some info about them. // // do // { // if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) // { // _tprintf(TEXT(" %s <DIR>\n"), ffd.cFileName); // } // else // { // filesize.LowPart = ffd.nFileSizeLow; // filesize.HighPart = ffd.nFileSizeHigh; // _tprintf(TEXT(" %s %ld bytes\n"), ffd.cFileName, filesize.QuadPart); // } // } // while (FindNextFile(hFind, &ffd) != 0); // // dwError = GetLastError(); // if (dwError != ERROR_NO_MORE_FILES) // { // DisplayErrorBox(TEXT("FindFirstFile")); // } // // FindClose(hFind); // return dwError; //} // // //void DisplayErrorBox(LPTSTR lpszFunction) //{ // // Retrieve the system error message for the last-error code // // LPVOID lpMsgBuf; // LPVOID lpDisplayBuf; // DWORD dw = GetLastError(); // // FormatMessage( // FORMAT_MESSAGE_ALLOCATE_BUFFER | // FORMAT_MESSAGE_FROM_SYSTEM | // FORMAT_MESSAGE_IGNORE_INSERTS, // NULL, // dw, // MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // (LPTSTR) &lpMsgBuf, // 0, NULL ); // // // Display the error message and clean up // // lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, // (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR)); // StringCchPrintf((LPTSTR)lpDisplayBuf, // LocalSize(lpDisplayBuf) / sizeof(TCHAR), // TEXT("%s failed with error %d: %s"), // lpszFunction, dw, lpMsgBuf); // MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK); // // LocalFree(lpMsgBuf); // LocalFree(lpDisplayBuf); //} // //
[ "bhlbuu@b6243d83-3e35-bad2-eac4-1d342526e9e5", "[email protected]@b6243d83-3e35-bad2-eac4-1d342526e9e5", "dangtruongkhanhlinh@b6243d83-3e35-bad2-eac4-1d342526e9e5" ]
[ [ [ 1, 5 ], [ 7, 15 ], [ 18, 175 ], [ 193, 269 ], [ 277, 285 ], [ 287, 287 ], [ 289, 289 ], [ 291, 299 ], [ 309, 309 ], [ 312, 333 ], [ 335, 343 ], [ 345, 376 ], [ 380, 380 ], [ 384, 745 ] ], [ [ 6, 6 ], [ 16, 17 ], [ 176, 192 ], [ 288, 288 ], [ 290, 290 ], [ 300, 308 ], [ 310, 311 ], [ 378, 379 ], [ 381, 383 ] ], [ [ 270, 276 ], [ 286, 286 ], [ 334, 334 ], [ 344, 344 ], [ 377, 377 ] ] ]
3004ea5ef41d22b18c0295d46bb84c036cf96b92
515e917815568d213e75bfcbd3fb9f0e08cf2677
/raytracer/raytracer.h
b0b911baa7d9f8638595d7ade9206ed8be0a8a10
[ "BSD-2-Clause" ]
permissive
dfk789/CodenameInfinite
bd183aec6b9e60e20dda6764d99f4e8d8a945add
aeb88b954b65f6beca3fb221fe49459b75e7c15f
refs/heads/master
2020-05-30T15:46:20.450963
2011-10-15T00:21:38
2011-10-15T00:21:38
5,652,791
2
0
null
null
null
null
UTF-8
C++
false
false
3,721
h
#ifndef LW_RAYTRACE_H #define LW_RAYTRACE_H #include <modelconverter/convmesh.h> #include <geometry.h> namespace raytrace { class CTraceResult { public: Vector m_vecHit; CConversionFace* m_pFace; CConversionMeshInstance* m_pMeshInstance; }; class CKDTri { public: CKDTri(); CKDTri(Vector v1, Vector v2, Vector v3, CConversionFace* pFace, CConversionMeshInstance* pMeshInstance = NULL); public: Vector v[3]; CConversionFace* m_pFace; CConversionMeshInstance* m_pMeshInstance; }; class CKDNode { public: CKDNode(CKDNode* pParent = NULL, AABB oBounds = AABB(), class CKDTree* pTree = NULL); ~CKDNode(); public: // Reserves memory for triangles all at once, for faster allocation void ReserveTriangles(size_t iEstimatedTriangles); void AddTriangle(Vector v1, Vector v2, Vector v3, CConversionFace* pFace, CConversionMeshInstance* pMeshInstance = NULL); void RemoveArea(const AABB& oBox); void CalcBounds(); void BuildTriList(); void PassTriList(); void Build(); bool Raytrace(const Ray& rayTrace, CTraceResult* pTR = NULL); bool Raytrace(const Vector& vecStart, const Vector& vecEnd, CTraceResult* pTR = NULL); float Closest(const Vector& vecPoint); const CKDNode* GetLeftChild() const { return m_pLeft; }; const CKDNode* GetRightChild() const { return m_pRight; }; AABB GetBounds() const { return m_oBounds; }; size_t GetSplitAxis() const { return m_iSplitAxis; }; float GetSplitPos() const { return m_flSplitPos; }; protected: CKDNode* m_pParent; CKDNode* m_pLeft; CKDNode* m_pRight; CKDTree* m_pTree; size_t m_iDepth; eastl::vector<CKDTri> m_aTris; size_t m_iTriangles; // This node and all child nodes AABB m_oBounds; size_t m_iSplitAxis; float m_flSplitPos; }; class CKDTree { public: CKDTree(size_t iMaxDepth = 15); ~CKDTree(); public: // Reserves memory for triangles all at once, for faster allocation void ReserveTriangles(size_t iEstimatedTriangles); void AddTriangle(Vector v1, Vector v2, Vector v3, CConversionFace* pFace = NULL, CConversionMeshInstance* pMeshInstance = NULL); void RemoveArea(const AABB& oBox); void BuildTree(); bool Raytrace(const Ray& rayTrace, CTraceResult* pTR = NULL); bool Raytrace(const Vector& vecStart, const Vector& vecEnd, CTraceResult* pTR = NULL); float Closest(const Vector& vecPoint); const CKDNode* GetTopNode() const { return m_pTop; }; bool IsBuilt() { return m_bBuilt; }; size_t GetMaxDepth() { return m_iMaxDepth; }; protected: CKDNode* m_pTop; bool m_bBuilt; size_t m_iMaxDepth; }; class CRaytracer { public: CRaytracer(CConversionScene* pScene = NULL, size_t iMaxDepth = 15); ~CRaytracer(); public: bool Raytrace(const Ray& rayTrace, CTraceResult* pTR = NULL); bool Raytrace(const Vector& vecStart, const Vector& vecEnd, CTraceResult* pTR = NULL); bool RaytraceBruteForce(const Ray& rayTrace, CTraceResult* pTR = NULL); float Closest(const Vector& vecPoint); void AddMeshesFromNode(CConversionSceneNode* pNode); void AddMeshInstance(CConversionMeshInstance* pMeshInstance); void AddTriangle(Vector v1, Vector v2, Vector v3); void BuildTree(); void RemoveArea(const AABB& oBox); const CKDTree* GetTree() const { return m_pTree; }; protected: CConversionScene* m_pScene; CKDTree* m_pTree; size_t m_iMaxDepth; }; }; #endif
[ [ [ 1, 142 ] ] ]
39c0c3d461a9145a42bf6f27cf9d351078748a1f
89a595fc77ec711cb7218b0830f9053e4febe4aa
/ofxSVG.h
9cb20fa258f1f95ddc22e00374e4ad120033bed6
[]
no_license
ammalgamma/ofxSVG
956ccb333700e31a79fc38f4911dcbfd3fa718fb
c461b21310b66ab239c069af519fb16c40d99820
refs/heads/master
2020-05-18T04:09:42.010826
2011-10-10T11:14:06
2011-10-10T11:14:06
2,585,084
1
0
null
null
null
null
UTF-8
C++
false
false
4,780
h
#pragma mark once #include "ofMain.h" #include "ofXSVGPathParser.h" #include "ofxSVGXml.h" #include "ofxSVGTypes.h" #include "ofxSVGUtils.h" //------------------------------------------------- class ofxSVG{ public: ofxSVG( ofFbo &fbo ); ofxSVG( ofFbo *fbo ); ofxSVG( ofVbo &vbo ); ofxSVG( ofVbo *vbo ); ofxSVG( ofTexture &tex ); ofxSVG( ofTexture *tex ); ofxSVG( ); ~ofxSVG(); void setDrawingMode( SVGDrawingMode mode ) { drawingMode = mode; } // Loading //---------------------------------- void load(string svgPath); void loadLayer(string svgPath, string layer); /*not implemented*/ // Debug //---------------------------------- void setVerbose(bool verbose); /*not implemented*/ // Drawing to screen //---------------------------------- void draw(); void drawLayer(string layerName); void drawLayer(int i); // Save & Drawing to svg //---------------------------------- void save(string svgPath); void addLayer(string layerName); void rect(float x, float y, float w, float h); void ellipse(float x, float y, float rx, float ry); void circle(float x, float y, float r); void beginPolygon(); void endPolygon(); void beginPath(); void endPath(); void vertex(float x, float y); //void bezierVertex(float x, float y); void bezierVertex(float x0, float y0, float x1, float y1); void bezierQuadraticVertex(float x0, float y0, float x1, float y1); void bezierVertex(float x0, float y0, float x1, float y1, float x2, float y2); void stroke(string colorHex, int weight); void fill(string colorHex); void noFill(); void noStroke(); void setOpacity(float percent); void translate(float tx, float ty); void rotate(float r); void pushMatrix(); /*not implemented*/ void popMatrix(); /*not implemented*/ void setLayerActive(string layerName); /*not implemented*/ string getLayerActive(string layerName); /*not implemented*/ void saveToFile(string filename); ofVec2f scaleFromMatrix(string matrix); float scale(string scaleVal); vector< ofxSVGLayer > layers; bool isInsidePolygon(ofxSVGPath *path, ofPoint p); void beginRenderer(); void endRenderer(); void parseFill(ofxSVGXml *svgXml, ofxSVGObject *obj, string opacity, string fill); void parseStroke(ofxSVGXml *svgXml, ofxSVGObject *obj, string stroke, string fill); private: // utilities GLint getImageColorType(ofImage &image); // Parsing //---------------------------------- void parseLayer(); void parseRect(); void parseEllipse(); void parseCircle(); void parseLine(); void parsePolyline(); /*not implemented*/ void parsePolygon(); void parseText(); void parsePath(); //void parsePathExperimental(); void parseImage(); void drawVectorDataExperimental(ofPath* object); // Matrix parsing //---------------------------------- ofPoint posFromMatrix(string matrix); float rotFromMatrix(string matrix); // Fonts map //-------------------------------------------- map<string, ofTrueTypeFont> fonts; // drawing SVGDrawingMode drawingMode; ofFbo fboForDrawing; ofTexture texForDrawing; ofVbo vboForDrawing; // SVG Data/Infos //---------------------------------- string svgVersion; int docWidth; int docHeight; int currentIteration; // XML Stuffs //---------------------------------- ofxSVGXml svgXml; // save stuffs int currentSaveNode; ofxSVGXml saveXml; map<string, string> currentAttributes; vector<ofMatrix3x3> matrices; string createAttribute(string element, ...); void matrixFromString(string smat, ofMatrix3x3 mat); void stringFromMatrix(string* smat, ofMatrix3x3 mat); // create root //---------------------------------- void createRootSvg(); // Debug //---------------------------------- bool bVerbose; };
[ [ [ 1, 8 ], [ 11, 15 ], [ 30, 81 ], [ 84, 85 ], [ 95, 95 ], [ 101, 113 ], [ 115, 116 ], [ 118, 126 ], [ 135, 152 ], [ 154, 154 ], [ 157, 165 ] ], [ [ 9, 10 ], [ 16, 29 ], [ 82, 83 ], [ 86, 94 ], [ 96, 100 ], [ 114, 114 ], [ 117, 117 ], [ 127, 134 ], [ 153, 153 ], [ 155, 156 ] ] ]
211f7f45186d70894bb5421b2beb44e5265ebe77
01fadae9f2a6d3f19bc843841a7faa9c40fc4a20
/CG/code_CG/EX10_06.CPP
13bfd3a917ff4b480b2b0492dfef2386bae88013
[]
no_license
passzenith/passzenithproject
9999da29ac8df269c41d280137113e1e2638542d
67dd08f4c3a046889319170a89b45478bfd662d2
refs/heads/master
2020-12-24T14:36:46.389657
2010-09-05T02:34:42
2010-09-05T02:34:42
32,310,266
0
0
null
null
null
null
UTF-8
C++
false
false
2,853
cpp
#include <GL/glut.h> #include <math.h> #include <stdlib.h> #include <stdio.h> static GLint fogMode; /* Initialize depth buffer, fog, light source, * material property, and lighting model. */ static void init(void) { GLfloat position[] = { 0.5, 0.5, 3.0, 0.0 }; glEnable(GL_DEPTH_TEST); glLightfv(GL_LIGHT0, GL_POSITION, position); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); { GLfloat mat[3] = {0.1745, 0.01175, 0.01175}; glMaterialfv (GL_FRONT, GL_AMBIENT, mat); mat[0] = 0.61424; mat[1] = 0.04136; mat[2] = 0.04136; glMaterialfv (GL_FRONT, GL_DIFFUSE, mat); mat[0] = 0.727811; mat[1] = 0.626959; mat[2] = 0.626959; glMaterialfv (GL_FRONT, GL_SPECULAR, mat); glMaterialf (GL_FRONT, GL_SHININESS, 0.6*128.0); } glEnable(GL_FOG); { GLfloat fogColor[4] = {0.5, 0.5, 0.5, 1.0}; fogMode = GL_EXP; glFogi (GL_FOG_MODE, fogMode); glFogfv (GL_FOG_COLOR, fogColor); glFogf (GL_FOG_DENSITY, 0.35); glHint (GL_FOG_HINT, GL_DONT_CARE); glFogf (GL_FOG_START, 1.0); glFogf (GL_FOG_END, 5.0); } glClearColor(0.5, 0.5, 0.5, 1.0); /* fog color */ } static void renderSphere (GLfloat x, GLfloat y, GLfloat z) { glPushMatrix(); glTranslatef (x, y, z); glutSolidSphere(0.4, 326, 16); glPopMatrix(); } /* display() draws 5 spheres at different z positions. */ void display(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); renderSphere (-2., -0.5, -1.0); renderSphere (-1., -0.5, -2.0); renderSphere (0., -0.5, -3.0); renderSphere (1., -0.5, -4.0); renderSphere (2., -0.5, -5.0); glFlush(); } void reshape(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (w <= h) glOrtho (-2.5, 2.5, -2.5*h/w, 2.5*h/w, -10.0, 10.0); else glOrtho (-2.5*w/h, 2.5*w/h, -2.5, 2.5, -10.0, 10.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity (); } void keyboard(unsigned char key, int x, int y) { switch (key) { case 'f': case 'F': if (fogMode == GL_EXP) { fogMode = GL_EXP2; printf ("Fog mode is GL_EXP2\n"); } else if (fogMode == GL_EXP2) { fogMode = GL_LINEAR; printf ("Fog mode is GL_LINEAR\n"); } else if (fogMode == GL_LINEAR) { fogMode = GL_EXP; printf ("Fog mode is GL_EXP\n"); } glFogi (GL_FOG_MODE, fogMode); glutPostRedisplay(); break; case 27: exit(0); break; default: break; } } void main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(500, 500); glutInitWindowPosition (50, 50); glutCreateWindow("Fog : Press F or f for change Fog mode"); init(); glutReshapeFunc (reshape); glutKeyboardFunc (keyboard); glutDisplayFunc (display); glutMainLoop(); }
[ "passzenith@00fadc5f-a3f2-dbaa-0561-d91942954633" ]
[ [ [ 1, 122 ] ] ]
ccdace77475b777dc0329c9c4341e758e115f147
6e563096253fe45a51956dde69e96c73c5ed3c18
/dhnetsdk/netsdk/StdAfx.h
924e2ac7b5755fef5a9a45fa2f0209a89e403e50
[]
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
1,331
h
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #if !defined(AFX_STDAFX_H__31AC7DFE_0537_45E0_BEA1_7DB6EEA627A7__INCLUDED_) #define AFX_STDAFX_H__31AC7DFE_0537_45E0_BEA1_7DB6EEA627A7__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifdef WIN32 // Insert your headers here #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #include <windows.h> #include <Winsock2.h> #pragma comment(lib, "Ws2_32.lib") #pragma warning(disable:4786) #else //linux #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <fcntl.h> #endif #include "../dvr/osIndependent.h" #include "../dvr/mutex.h" #include "../dvr/ReadWriteMutex.h" #include "../dvr/kernel/afkdef.h" #include "../dvr/kernel/afkinc.h" #include "../dvr/dvrdevice/dvr2cfg.h" #include "../dvr/versionctl.h" #include <list> #include <algorithm> using namespace std; // TODO: reference additional headers your program requires here //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_STDAFX_H__31AC7DFE_0537_45E0_BEA1_7DB6EEA627A7__INCLUDED_)
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 48 ] ] ]
f64b528d0005b3e10094ef361eb62f6c469456cc
f53b18d7b296aa67d2a35c69465e2f644c08bfa0
/trunk/working Src/UI/mainFrame.h
27edbe307edd054ab1744b723a675bc19fb2d021
[]
no_license
BackupTheBerlios/rigo-svn
82d67b992a128c111335ac78be9ab9ec6dde8e70
a510f30ec4da0f0493d47f7164f9bbfffb566616
refs/heads/master
2016-09-05T21:13:49.432123
2006-08-12T03:59:01
2006-08-12T03:59:01
40,800,289
0
0
null
null
null
null
UTF-8
C++
false
false
5,292
h
///////////////////////////////////////////////////////////////////////////// // Name: mainFrame.h // Purpose: // Author: Jeremy W // Modified by: // Created: 07/18/06 20:02:50 // RCS-ID: // Copyright: Copyright (C) 2006 // Licence: GPL v2 ///////////////////////////////////////////////////////////////////////////// // Generated by DialogBlocks (Personal Edition), 07/18/06 20:02:50 #ifndef _MAINFRAME_H_ #define _MAINFRAME_H_ #if defined(__GNUG__) && !defined(__APPLE__) #pragma interface "mainFrame.cpp" #endif /*! * Includes */ ////@begin includes #include "wx/frame.h" #include "wx/toolbar.h" #include "wx/notebook.h" #include "wx/statusbr.h" #include "wx/combobox.h" ////@end includes /*! * Forward declarations */ ////@begin forward declarations ////@end forward declarations /*! * Control identifiers */ ////@begin control identifiers #define Rigo 10000 #define SYMBOL_RIGOMAINFRAME_STYLE wxCAPTION|wxRESIZE_BORDER|wxSYSTEM_MENU|wxMAXIMIZE|wxMINIMIZE_BOX|wxMAXIMIZE_BOX|wxCLOSE_BOX #define SYMBOL_RIGOMAINFRAME_TITLE _(".::R.I.G.O::.") #define SYMBOL_RIGOMAINFRAME_IDNAME Rigo #define SYMBOL_RIGOMAINFRAME_SIZE wxSize(800, 600) #define SYMBOL_RIGOMAINFRAME_POSITION wxDefaultPosition #define New 10003 #define Save 10017 #define Quit 10009 #define Cut 10006 #define Copy 10007 #define Profile 10004 #define Export 10014 #define NewSource 10005 #define NewQuote 10008 #define NewAnnotation 10018 #define Rigo_Toolbar 10001 #define Open 10011 #define Print 10015 #define Writebiblo 10016 #define ID_COMBOBOX 10002 #define ID_PANEL 10012 #define ID_NOTEBOOK 10010 #define ID_STATUSBAR 10013 #define wxUSE_GUI 1 ////@end control identifiers /*! * Compatibility */ #ifndef wxCLOSE_BOX #define wxCLOSE_BOX 0x1000 #endif #ifndef wxFIXED_MINSIZE #define wxFIXED_MINSIZE 0 #endif /*! * rigoMainFrame class declaration */ class rigoMainFrame: public wxFrame { DECLARE_CLASS( rigoMainFrame ) DECLARE_EVENT_TABLE() public: /// Class Data wxArrayString sourceList; /// Constructors rigoMainFrame( ); rigoMainFrame( wxWindow* parent, wxWindowID id = SYMBOL_RIGOMAINFRAME_IDNAME, const wxString& caption = SYMBOL_RIGOMAINFRAME_TITLE, const wxPoint& pos = SYMBOL_RIGOMAINFRAME_POSITION, const wxSize& size = SYMBOL_RIGOMAINFRAME_SIZE, long style = SYMBOL_RIGOMAINFRAME_STYLE ); bool Create( wxWindow* parent, wxWindowID id = SYMBOL_RIGOMAINFRAME_IDNAME, const wxString& caption = SYMBOL_RIGOMAINFRAME_TITLE, const wxPoint& pos = SYMBOL_RIGOMAINFRAME_POSITION, const wxSize& size = SYMBOL_RIGOMAINFRAME_SIZE, long style = SYMBOL_RIGOMAINFRAME_STYLE ); /// Creates the controls and sizers void CreateControls(); ////@begin rigoMainFrame event handler declarations /// wxEVT_CLOSE_WINDOW event handler for Rigo void OnCloseWindow( wxCloseEvent& event ); /// wxEVT_COMMAND_MENU_SELECTED event handler for New void OnNewClick( wxCommandEvent& event ); /// wxEVT_COMMAND_MENU_SELECTED event handler for Save void OnSaveClick( wxCommandEvent& event ); /// wxEVT_COMMAND_MENU_SELECTED event handler for Quit void OnQuitClick( wxCommandEvent& event ); /// wxEVT_COMMAND_MENU_SELECTED event handler for Cut void OnCutClick( wxCommandEvent& event ); /// wxEVT_COMMAND_MENU_SELECTED event handler for Copy void OnCopyClick( wxCommandEvent& event ); /// wxEVT_COMMAND_MENU_SELECTED event handler for Profile void OnProfileClick( wxCommandEvent& event ); /// wxEVT_COMMAND_MENU_SELECTED event handler for Export void OnExportClick( wxCommandEvent& event ); /// wxEVT_COMMAND_MENU_SELECTED event handler for NewSource void OnNewsourceClick( wxCommandEvent& event ); /// wxEVT_COMMAND_MENU_SELECTED event handler for NewQuote void OnNewquoteClick( wxCommandEvent& event ); /// wxEVT_COMMAND_MENU_SELECTED event handler for NewAnnotation void OnNewannotationClick( wxCommandEvent& event ); /// wxEVT_COMMAND_MENU_SELECTED event handler for Open void OnOpenClick( wxCommandEvent& event ); /// wxEVT_COMMAND_MENU_SELECTED event handler for Print void OnPrintClick( wxCommandEvent& event ); /// wxEVT_COMMAND_MENU_SELECTED event handler for Writebiblo void OnWritebibloClick( wxCommandEvent& event ); /// wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_COMBOBOX void OnComboboxSelected( wxCommandEvent& event ); /// wxEVT_UPDATE_UI event handler for ID_COMBOBOX void OnComboboxUpdate( wxUpdateUIEvent& event ); ////@end rigoMainFrame event handler declarations ////@begin rigoMainFrame member function declarations /// Retrieves bitmap resources wxBitmap GetBitmapResource( const wxString& name ); /// Retrieves icon resources wxIcon GetIconResource( const wxString& name ); ////@end rigoMainFrame member function declarations /// Should we show tooltips? static bool ShowToolTips(); ////@begin rigoMainFrame member variables ////@end rigoMainFrame member variables }; #endif // _MAINFRAME_H_
[ "siafu86@a8ebc1f5-d704-0410-a9ec-c9bfc824b517" ]
[ [ [ 1, 183 ] ] ]
60de9142650fa06bd78305e995950141809e319f
14a00dfaf0619eb57f1f04bb784edd3126e10658
/Lab2/SupportCode/Vector4.h
21219548292654dc59665df2fd5c871ba905e8c0
[]
no_license
SHINOTECH/modanimation
89f842262b1f552f1044d4aafb3d5a2ce4b587bd
43d0fde55cf75df9d9a28a7681eddeb77460f97c
refs/heads/master
2021-01-21T09:34:18.032922
2010-04-07T12:23:13
2010-04-07T12:23:13
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
2,095
h
/************************************************************************************************* * * Modeling and animation (TNM079) 2007 * Code base for lab assignments. Copyright: * Gunnar Johansson ([email protected]) * Ken Museth ([email protected]) * Michael Bang Nielsen ([email protected]) * Ola Nilsson ([email protected]) * Andreas Söderström ([email protected]) * *************************************************************************************************/ #ifndef _vector4_h #define _vector4_h #include <iostream> template <typename Real> class Vector4 { public: Vector4() { v[0] = v[1] = v[2] = v[3] = Real(0.0); } Vector4(Real c) { v[0] = v[1] = v[2] = v[3] = c; } Vector4(Real v0, Real v1, Real v2, Real v3) { v[0] = v0; v[1] = v1; v[2] = v2; v[3] = v3; } ~Vector4() { } void load(std::istream& is) { is >> v[0] >> v[1] >> v[2] >> v[3]; } void save(std::ostream& os) const { os << v[0] << " " << v[1] << " " << v[2] << " " << v[3]; } Real& operator[](unsigned int i) { return v[i]; } Real operator[](unsigned int i) const { return v[i]; } Real& operator()(unsigned int i) { return v[i]; } Real operator()(unsigned int i) const { return v[i]; } Vector4 operator+(const Vector4& vec4) const { return Vector4(v[0]+vec4.v[0],v[1]+vec4.v[1],v[2]+vec4.v[2],v[3]+vec4.v[3]); } Vector4 operator-(const Vector4& vec4) const { return Vector4(v[0]-vec4.v[0],v[1]-vec4.v[1],v[2]-vec4.v[2],v[3]-vec4.v[3]); } Vector4 entryMult(const Vector4& vec4) const { return Vector4(v[0]*vec4.v[0],v[1]*vec4.v[1],v[2]*vec4.v[2],v[3]*vec4.v[3]); } protected: Real v[4]; }; template <typename Real1, typename Real2> Vector4<Real2> operator*(Real1 r, const Vector4<Real2>& v) { Vector4<Real2> res; res[0] = v[0]*r; res[1] = v[1]*r; res[2] = v[2]*r; res[3] = v[3]*r; return res; } template <typename Real> Real operator*(const Vector4<Real> &v1, const Vector4<Real>& v2) { return v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2]+v1[3]*v2[3]; } #endif
[ "jpjorge@da195381-492e-0410-b4d9-ef7979db4686" ]
[ [ [ 1, 60 ] ] ]
c9bbd732aebcc6616131fdd08b8d13cde5f08fe1
c930c888dd96cc3fb7f12f6d6ecb6bd4b2218869
/Software/PC/HomeSecurityGUI/HomeSecurityGUI/HomeSecurity.cpp
605d143a601f083039e9168c67e682633de0ffd0
[]
no_license
dmjensen/iha-projectb
3782dc99eb6776a6d3fe2da88975d6f58eb8e712
c193ad0b8273ba1f92ffcc06ff225e52a9147b89
refs/heads/master
2021-01-13T01:49:31.766029
2011-08-15T17:54:48
2011-08-15T17:54:48
35,090,073
0
0
null
null
null
null
UTF-8
C++
false
false
5,493
cpp
#pragma once #include "stdafx.h" #include "XML\XMLFile.h" #include "Entities\Device.h" #include "Entities\Event.h" #include "Serial\Serial.h" #ifdef _UNICODE #define std_out std::wcout #else #define std_out std::cout #endif using namespace std; bool loadConf(LPTSTR path); bool parseConf(CXMLFile* xml_file, list<Device*>& devices); bool programConf(list<Device*>& devices, int port, int baudRate); //int _tmain(int argc, _TCHAR* argv[]) //{ // int choice = -1; // // while (choice != 0) // { // system("CLS"); // // std_out << _T("Home Security System v0.1\n") // << _T("Enter choice:\n") // << _T("1. Load configuration\n") // << _T("2. Save configuration\n") // << _T("\n0. Exit\n") // << endl; // // cin >> choice; // // switch(choice) // { // case 0: std_out << _T("Exiting...\n"); // break; // case 1: std_out << _T("Loading Configuration...\n"); // if(!loadConf(_T(conf_file))) // std_out << _T("Error loading Configuration...\n"); // break; // default: std_out << _T("Invalid command\n"); // } // // Sleep(1000); // } // // system("CLS"); // return 0; //} //Loads configuration XML file from "path" and checks if it is well formed. If it is this configuration is sent to the STK500. bool loadConf(LPTSTR path) { CXMLFile xml_file;// = new CXMLFile(); if( !xml_file.LoadFromFile(path) ) return false; //Error reading XML, maybe badly formed? //Check if the XML configuration file is formed as expected and if so get a list of devices. list<Device*> devices; if( !parseConf(&xml_file, devices) ) return false; //Error parsing the XML Configuration file, not formed as expected? if( !programConf(devices, 3, 115200) ) return false; //Error programming STK500 //Destroy file in memory xml_file.~CXMLFile(); return true; } //Checks if the xml file is formed as expected bool parseConf(CXMLFile* xml_file, list<Device*>& devices) { stack<CXMLElement*> elem_stack; //XML_root elem_stack.push(xml_file->GetRoot()); //Configuration root elem_stack.push(elem_stack.top()->GetLastChild()); //Check if it actually is the configuration root if(lstrcmp(elem_stack.top()->GetElementName(), _T("configuration")) != 0) return false; //Loop through devices in the configuration elem_stack.push(elem_stack.top()->GetFirstChild()); while(elem_stack.top() != NULL) { //Check if it actually is a device: if(lstrcmp(elem_stack.top()->GetElementName(), _T("device")) != 0) return false; //First child should be an id elem_stack.push(elem_stack.top()->GetFirstChild()); if(lstrcmp(elem_stack.top()->GetElementName(), _T("id")) != 0) return false; //Create new Device object using the id from XML file devices.push_back(new Device((char)_ttoi(elem_stack.top()->GetValue()))); elem_stack.pop(); //Pop id //Following children should be events char type, hour, minute; elem_stack.push(elem_stack.top()->GetNextChild()); while(elem_stack.top() != NULL) { if(lstrcmp(elem_stack.top()->GetElementName(), _T("event")) != 0) return false; //First child should be a type elem_stack.push(elem_stack.top()->GetFirstChild()); //Push type if(elem_stack.top() == NULL || lstrcmp(elem_stack.top()->GetElementName(), _T("type")) != 0) return false; type = _ttoi(elem_stack.top()->GetValue()); //Save type elem_stack.pop(); //Pop Type //Second child should be an hour elem_stack.push(elem_stack.top()->GetNextChild()); //Push hour if(elem_stack.top() == NULL || lstrcmp(elem_stack.top()->GetElementName(), _T("hour")) != 0) return false; hour = _ttoi(elem_stack.top()->GetFirstChild()->GetElementName()); //Save hour elem_stack.pop(); //Pop Hour //Third child should be a minute elem_stack.push(elem_stack.top()->GetNextChild()); //Push Minute if(elem_stack.top() == NULL || lstrcmp(elem_stack.top()->GetElementName(), _T("minute")) != 0) return false; minute = _ttoi(elem_stack.top()->GetFirstChild()->GetElementName()); //Save minute elem_stack.pop(); //Pop Minute //We expect no more children elem_stack.push(elem_stack.top()->GetNextChild()); if(elem_stack.top() != NULL) return false; elem_stack.pop(); devices.back()->addEvent(Event(type, hour, minute)); elem_stack.pop(); //Pop current Event elem_stack.push(elem_stack.top()->GetNextChild()); //Proceed to next event } elem_stack.pop(); //Pop NULL (Event) elem_stack.pop(); //Pop current device elem_stack.push(elem_stack.top()->GetNextChild()); //Proceed to next device } elem_stack.pop(); //Pop NULL (Device) return true; } bool programConf(list<Device*>& devices, int port, int baudRate) { char data[3]; CSerial* s = new CSerial(); if(!s->Open(port, baudRate)) { std_out << _T("Could not open COM") << port << endl; return false; } #define C_Reset 0xB0 #define C_CONF 0xB1 while(!devices.empty()) { list<Event> events = devices.front()->getEvents(); data[0] = C_CONF; data[1] = devices.front()->getID(); data[2] = events.size(); s->SendData(data, 3); while(!events.empty()) { data[0] = events.front().getType(); data[1] = events.front().getHour(); data[2] = events.front().getMinute(); s->SendData(data, 3); events.pop_front(); } devices.pop_front(); } s->Close(); return true; }
[ "[email protected]@03037290-6654-1fc7-fe71-60be2f6569b4" ]
[ [ [ 1, 198 ] ] ]
bdad4c89fff7af6287c23dbf89ab73b4f0541ac0
7ba7440b6a7b6068c900d561ad03c3ff86439c09
/GalDemo/GalDemo/BackGroundMusic.h
4ba374cdb4c02c2e927813ff659de4abb00babe2
[]
no_license
weimingtom/gal-demo
96dc06f8f02b4c767412aac7fcf050e241b40c04
f2b028591a195516af3ce33d084b7b29cbea84aa
refs/heads/master
2021-01-20T11:47:07.598476
2011-08-10T23:48:43
2011-08-10T23:48:43
42,379,726
2
0
null
null
null
null
UTF-8
C++
false
false
118
h
#pragma once class CBackGroundMusic { public: CBackGroundMusic(void); virtual ~CBackGroundMusic(void); };
[ [ [ 1, 8 ] ] ]
4ca17ca842f39e2655570ee3a3c93d71a5a87ed5
c2c93fc3fd90bd77764ac3016d816a59b2370891
/Incomplited/Hooks module SA-MP 0.1/hooks/hooks.h
a3be042ed08c5970a1917d4760396e0431e761a5
[]
no_license
MsEmiNeko/samp-alex009-projects
a1d880ee3116de95c189ef3f79ce43b163b91603
9b9517486b28411c8b747fae460266a88d462e51
refs/heads/master
2021-01-10T16:22:34.863725
2011-04-30T04:01:15
2011-04-30T04:01:15
43,719,520
0
1
null
2018-01-19T16:55:45
2015-10-05T23:23:37
SourcePawn
UTF-8
C++
false
false
1,056
h
/* * Copyright (C) 2011 Alex009 * License read in license.txt */ #include "functions.h" #include "os.h" #define VERSION "0.1" // class class CHooks { public: // functions CHooks(unsigned long s_version); ~CHooks(); unsigned long Search_ClientConnect(); unsigned long Search_ClientDisconnect(); unsigned long Search_ClientSpawn(); unsigned long Search_ClientDeath(); unsigned long Search_SetPlaybackDir(); void Search_ThreadAddresses(unsigned long* addr1,unsigned long* addr2); void ClientConnect(void* players,int id,char* name,int npc_flag); void ClientDisconnect(void* players,int id,int reason); void ClientSpawn(void* player); void ClientDeath(void* player,int reason,int killerid); void SetPlaybackDir(char* string); void DeleteLogFile(); int GetLogFileLength(); void DisableBadCharsCheck(); void DisableChangeNameLogging(); void TargetAdminTeleportTo(unsigned long function); MUTEX_IDENTIFY(GetMutex()); // vars unsigned int server_version; MUTEX_IDENTIFY(ThreadMutex); };
[ [ [ 1, 43 ] ] ]
44e1564c3ee1795d8fa6aa3a95ec73661d898eb2
d64ed1f7018aac768ddbd04c5b465c860a6e75fa
/drawing_element/dle_oval.cpp
241c3bcc882670f990a64856c1e87d75bfe52262
[]
no_license
roc2/archive-freepcb-codeproject
68aac46d19ac27f9b726ea7246cfc3a4190a0136
cbd96cd2dc81a86e1df57b86ce540cf7c120c282
refs/heads/master
2020-03-25T00:04:22.712387
2009-06-13T04:36:32
2009-06-13T04:36:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,316
cpp
#include "stdafx.h" #include "dle_oval.h" // filled oval void CDLE_OVAL::_Draw(CDrawInfo const &di) const { if( onScreen() ) { int h = abs(f.x-i.x); int v = abs(f.y-i.y); int r = min(h,v); if( gtype == DL_HOLLOW_OVAL ) di.DC->SelectObject( GetStockObject( HOLLOW_BRUSH ) ); di.DC->RoundRect( i.x, i.y, f.x, f.y, r, r ); if( gtype == DL_HOLLOW_OVAL ) di.DC->SelectObject( di.fill_brush ); if( holew != 0 ) { di.DC->SelectObject( di.erase_brush ); di.DC->SelectObject( di.erase_pen ); di.DC->Ellipse( org.x - holew/2, org.y - holew/2, org.x + holew/2, org.y + holew/2 ); di.DC->SelectObject( di.fill_brush ); di.DC->SelectObject( di.line_pen ); } } } void CDLE_OVAL::_DrawClearance(CDrawInfo const &di) const { int _xi = i.x; int _yi = i.y; int _xf = f.x; int _yf = f.y; if( _xf < _xi ) { _xf = _xi; _xi = f.x; } if( _yf < _yi ) { _yf = _yi; _yi = f.y; } int h = _xf-_xi; int v = _yf-_yi; int r = min(h,v) + 2*clearancew; di.DC->SelectObject( di.erase_brush ); di.DC->SelectObject( di.erase_pen ); di.DC->RoundRect( _xi - clearancew, _yi - clearancew, _xf + clearancew, _yf + clearancew, r, r ); di.DC->SelectObject( di.fill_brush ); di.DC->SelectObject( di.line_pen ); }
[ "jamesdily@9bfb2a70-7351-0410-8a08-c5b0c01ed314" ]
[ [ [ 1, 64 ] ] ]
274894e5047bc6a8ed204be6d2b1384c94d5b9ed
3bf3c2da2fd334599a80aa09420dbe4c187e71a0
/BasicUnit.h
ed8e7dafed6612ccfeb58feab1a6c72593457581
[]
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
250
h
#pragma once #include "Unit.h" #include "Camera.h" extern Camera cam; class BasicUnit : public Unit { public: float increment; BasicUnit(float inx, float iny, float inz); //BasicUnit(void); ~BasicUnit(void); void draw(); };
[ "jtrobins@05766cc9-4f33-4ba7-801d-bd015708efd9", "kehung@05766cc9-4f33-4ba7-801d-bd015708efd9", "agonza40@05766cc9-4f33-4ba7-801d-bd015708efd9" ]
[ [ [ 1, 2 ], [ 6, 10 ], [ 14, 16 ] ], [ [ 3, 5 ], [ 11, 11 ] ], [ [ 12, 13 ] ] ]
778aba76cd2d5f6710f76b3a7a0b11dd79668e9d
0454def9ffc8db9884871a7bccbd7baa4322343b
/src/plugins/lyric/QULyricTaskFactory.cpp
860f7e25daa50270b76be8a8060ac9a1281f88d0
[]
no_license
escaped/uman
e0187d1d78e2bb07dade7ef6ef041b6ed424a2d3
bedc1c6c4fc464be4669f03abc9bac93e7e442b0
refs/heads/master
2016-09-05T19:26:36.679240
2010-07-26T07:55:31
2010-07-26T07:55:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,438
cpp
#include "QULyricTaskFactory.h" #include "QULyricTask.h" #include <QDir> #include <QLocale> #include <QCoreApplication> QULyricTaskFactory::QULyricTaskFactory(QObject *parent): QUSimpleTaskFactory(parent) {} QString QULyricTaskFactory::name() const { return tr("Lyric Tasks"); } QString QULyricTaskFactory::description() const { return tr("Modify a song's lyrics."); } QUTask* QULyricTaskFactory::createTask(int type) { return new QULyricTask((QULyricTask::TaskModes)type); } QList<int> QULyricTaskFactory::types() const { QList<int> result; result << QULyricTask::ConvertRelativeToAbsolute; result << QULyricTask::ConvertAbsoluteToRelative; result << QULyricTask::FixTimeStamps; result << QULyricTask::FixSpaces; result << QULyricTask::RemoveEmptySyllables; result << QULyricTask::ConvertSyllablePlaceholder1; result << QULyricTask::ConvertSyllablePlaceholder2; return result; } QMap<QString, QString> QULyricTaskFactory::translationLocations() const { QDir dir = QCoreApplication::applicationDirPath(); QMap<QString, QString> locations; if(dir.cd("plugins") && dir.cd("languages")) { locations.insert(QLocale(QLocale::German, QLocale::Germany).name(), dir.filePath("lyric.de.qm")); locations.insert(QLocale(QLocale::Polish, QLocale::Poland).name(), dir.filePath("lyric.pl.qm")); } return locations; } Q_EXPORT_PLUGIN2(qulyrictaskfactory, QULyricTaskFactory);
[ [ [ 1, 46 ] ] ]
8ec50db6565acdd6977fa5e6fbcbfffe6c6e146f
58ef4939342d5253f6fcb372c56513055d589eb8
/LemonPlayer_2nd/Source/CustomControl/src/CustomControlScroll.cpp
ff9e48b0858daead394185f2bd8680883253cd6a
[]
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
GB18030
C++
false
false
2,880
cpp
/* ============================================================================ Name : CustomControlScroll.cpp Author : zengcity Version : 1.0 Copyright : Your copyright notice Description : CCustomControlScroll implementation ============================================================================ */ #include "CustomControlScroll.h" #include <aknutils.h> #include <CCScroll.mbg> CCustomControlScroll::CCustomControlScroll() { // No implementation required } CCustomControlScroll::~CCustomControlScroll() { delete iBitmapDirection[0]; delete iBitmapDirection[1]; delete iBitmapScroller; } CCustomControlScroll* CCustomControlScroll::NewLC() { CCustomControlScroll* self = new (ELeave)CCustomControlScroll(); CleanupStack::PushL(self); self->ConstructL(); return self; } CCustomControlScroll* CCustomControlScroll::NewL() { CCustomControlScroll* self=CCustomControlScroll::NewLC(); CleanupStack::Pop(); // self; return self; } void CCustomControlScroll::ConstructL() { LoadL(); } void CCustomControlScroll::LoadL() { TFileName file(KMultiBitmapFilename); User::LeaveIfError(CompleteWithAppPath(file)); iBitmapDirection[0] = new (ELeave)CFbsBitmap; iBitmapDirection[0]->Load(file, EMbmCcscrollScrollup); iBitmapDirection[1] = new (ELeave)CFbsBitmap; iBitmapDirection[1]->Load(file, EMbmCcscrollScrolldown); iBitmapScroller = new (ELeave)CFbsBitmap; iBitmapScroller->Load(file, EMbmCcscrollScroller); iBitmapWidth = iBitmapScroller->SizeInPixels().iWidth; iBitmapHeight = iBitmapScroller->SizeInPixels().iHeight; } //初始化数据 void CCustomControlScroll::InitData(TPoint aDisplayPoint, TSize aDisplaySize, TSize aOriginalSize) { iDisplayPoint = aDisplayPoint; iDisplaySize = aDisplaySize; iOffset = ((TReal)iDisplaySize.iHeight)/ ((TReal)aOriginalSize.iHeight); iScrollerPosY = iBitmapHeight; } void CCustomControlScroll::Draw(CWindowGc& gc) { TInt x, y; //上图标 x = iDisplayPoint.iX; y = iDisplayPoint.iY; if (iBitmapDirection[0]) gc.BitBlt(TPoint(x, y), iBitmapDirection[0]); //下图标 y += iDisplaySize.iHeight-iBitmapHeight; if (iBitmapDirection[1]) gc.BitBlt(TPoint(x, y), iBitmapDirection[1]); //滚动条 y = iDisplayPoint.iY+iScrollerPosY; if (iBitmapScroller) gc.BitBlt(TPoint(x, y), iBitmapScroller); } void CCustomControlScroll::Update(EScrollDirection aDirection, TInt aPixel) { if (aDirection == KScrollUp) { iScrollerPosY -= iOffset*aPixel; if (iScrollerPosY < iBitmapHeight) { iScrollerPosY = iBitmapHeight; } } else if (aDirection == KScrollDown) { iScrollerPosY += iOffset*aPixel; if (iScrollerPosY > iDisplaySize.iHeight-iBitmapHeight*2) { iScrollerPosY = iDisplaySize.iHeight-iBitmapHeight*2; } } }
[ "zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494" ]
[ [ [ 1, 111 ] ] ]
33b117b07b28a78b591ba719d80ca258d43baf04
17ebdb307b9e503a9df5c86db264e060695f9cb9
/include/mousegesturerecognizer.h
009734b0ce3db9582d09befdd647f945ad27866d
[]
no_license
e8johan/mouse-gesture-recognizer
a5224f0353f651489cafb70cdb80f828449d6275
983537fc7ddbaf5e04afffc300b104b4805593f2
refs/heads/master
2020-03-27T05:04:47.602603
2009-05-06T13:08:08
2009-05-06T13:08:08
32,892,845
1
0
null
null
null
null
UTF-8
C++
false
false
3,611
h
/* * This file is part of the mouse gesture package. * Copyright (C) 2006 Johan Thelin <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the * following conditions are met: * * - 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. * - The names of its contributors may be used to endorse * or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #ifndef MOUSEGESTURERECOGNIZER_H #define MOUSEGESTURERECOGNIZER_H #include <list> #include <vector> namespace Gesture { /* * Sub-class and implement callback method and register along a gesture description. */ class MouseGestureCallback { public: virtual void callback() = 0; }; /* * The available directions. */ typedef enum { Up, Down, Left, Right, AnyHorizontal, AnyVertical, UpLeft, UpRight, DownLeft, DownRight, NoMatch } Direction; /* * A list of directions. */ typedef std::list<Direction> DirectionList; /* * Create lists of directions and connect to a callback. */ struct GestureDefinition { GestureDefinition( const DirectionList &d, MouseGestureCallback *c ) : directions( d ), callbackClass( c ) {} DirectionList directions; MouseGestureCallback *callbackClass; }; /* * Data types for internal use */ struct Pos { Pos( int ix, int iy ) : x(ix), y(iy) {} int x, y; }; typedef std::vector<Pos> PosList; typedef std::vector<GestureDefinition> GestureList; class MouseGestureRecognizer { public: MouseGestureRecognizer( int minimumMovement = 5, double minimumMatch = 0.9, bool allowDiagonals = false ); ~MouseGestureRecognizer(); void addGestureDefinition( const GestureDefinition &gesture ); void clearGestureDefinitions(); void startGesture( int x, int y ); void addPoint( int x, int y ); void endGesture( int x, int y ); void abortGesture(); PosList currentPath() const; private: void recognizeGesture(); static PosList limitDirections( const PosList &positions, bool allowDiagnonals ); static PosList simplify( const PosList &positions ); static PosList removeShortest( const PosList &positions ); static int calcLength( const PosList &positions ); struct Private; Private *d; }; }; #endif // MOUSEGESTURERECOGNIZER_H
[ "e8johan@2c227689-8b1f-0410-847e-0d0e51d0f70e" ]
[ [ [ 1, 117 ] ] ]
07ba36f024f92805174e341e30368716574469bd
105cc69f4207a288be06fd7af7633787c3f3efb5
/HovercraftUniverse/HovercraftUniverse/CheckpointEvent.cpp
25f0ae45913d4b6fc9eaefb95ed7e4273aa4959f
[]
no_license
allenjacksonmaxplayio/uhasseltaacgua
330a6f2751e1d6675d1cf484ea2db0a923c9cdd0
ad54e9aa3ad841b8fc30682bd281c790a997478d
refs/heads/master
2020-12-24T21:21:28.075897
2010-06-09T18:05:23
2010-06-09T18:05:23
56,725,792
0
0
null
null
null
null
UTF-8
C++
false
false
957
cpp
#include "CheckpointEvent.h" #include "GameEventType.h" namespace HovUni { CheckpointEvent::CheckpointEvent(unsigned int user, unsigned int checkpoint, long time) : GameEvent(checkPoint), mUser(user), mCheckpoint(checkpoint), mTimestamp(time) { } CheckpointEvent::CheckpointEvent() : GameEvent(checkPoint), mUser(0), mCheckpoint(-1), mTimestamp(-1) { } CheckpointEvent::~CheckpointEvent() { } void CheckpointEvent::write(ZCom_BitStream* stream) const { stream->addInt(mUser, 32); stream->addInt(mCheckpoint, 32); // TODO Replicate the whole long stream->addInt(mTimestamp, 32); } void CheckpointEvent::read(ZCom_BitStream* stream) { mUser = stream->getInt(32); mCheckpoint = stream->getInt(32); mTimestamp = stream->getInt(32); } CheckpointEvent * CheckpointEvent::parse(ZCom_BitStream* stream) { CheckpointEvent * result = new CheckpointEvent(); result->deserialize(stream); return result; } }
[ "berghmans.olivier@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c" ]
[ [ [ 1, 39 ] ] ]
33428d77b84a90c863568afbeeab4dd6b3f4535a
9d1cb48ec6f6c1f0e342f0f8f819cbda74ceba6e
/src/SAPrefsSubDlg.cpp
7c5efec1d1135fdff5000c66cf2d8488dfc73428
[]
no_license
correosdelbosque/veryie
e7a5ad44c68dc0b81d4afcff3be76eb8f83320ff
6ea5a68d0a6eb6c3901b70c2dc806d1e2e2858f1
refs/heads/master
2021-01-10T13:17:59.755108
2010-06-16T04:23:26
2010-06-16T04:23:26
53,365,953
1
1
null
null
null
null
UTF-8
C++
false
false
3,671
cpp
/********************************************************************* SAPrefsSubDlg Copyright (C) 2002 Smaller Animals Software, Inc. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. http://www.smalleranimals.com [email protected] **********************************************************************/ // SAPrefsSubDlg.cpp: implementation of the CSAPrefsSubDlg class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "SAPrefsSubDlg.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// IMPLEMENT_DYNCREATE(CSAPrefsSubDlg, CDialog) CSAPrefsSubDlg::CSAPrefsSubDlg() { ASSERT(0); // don't use this constructor! } ////////////////////////////////////////////////////////////////////// CSAPrefsSubDlg::CSAPrefsSubDlg(UINT nID, CWnd *pParent /*=NULL*/) : CDialog(nID) { m_id = nID; } ////////////////////////////////////////////////////////////////////// CSAPrefsSubDlg::~CSAPrefsSubDlg() { } ////////////////////////////////////////////////////////////////////// BEGIN_MESSAGE_MAP(CSAPrefsSubDlg, CDialog) //{{AFX_MSG_MAP(CSAPrefsSubDlg) //}}AFX_MSG_MAP END_MESSAGE_MAP() ////////////////////////////////////////////////////////////////////// void CSAPrefsSubDlg::OnOK() { EndDialog(IDOK); } ////////////////////////////////////////////////////////////////////// void CSAPrefsSubDlg::OnCancel() { EndDialog(IDCANCEL); } ////////////////////////////////////////////////////////////////////// BOOL CSAPrefsSubDlg::PreTranslateMessage(MSG* pMsg) { // Don't let CDialog process the Escape key. if ((pMsg->message == WM_KEYDOWN) && (pMsg->wParam == VK_ESCAPE)) { CWnd* pWnd = GetParent(); if (pWnd != NULL) return pWnd->PreTranslateMessage(pMsg); } // Don't let CDialog process the Return key, if a multi-line edit has focus if ((pMsg->message == WM_KEYDOWN) && (pMsg->wParam == VK_RETURN)) { // Special case: if control with focus is an edit control with // ES_WANTRETURN style, let it handle the Return key. TCHAR szClass[10]; CWnd* pWndFocus = GetFocus(); if (((pWndFocus = GetFocus()) != NULL) && IsChild(pWndFocus) && (pWndFocus->GetStyle() & ES_WANTRETURN) && GetClassName(pWndFocus->m_hWnd, szClass, 10) && (lstrcmpi(szClass, _T("EDIT")) == 0)) { pWndFocus->SendMessage(WM_CHAR, pMsg->wParam, pMsg->lParam); return TRUE; } return FALSE; } return CDialog::PreTranslateMessage(pMsg); } //////////////////////////////////////////////////////////////////////
[ "songbohr@af2e6244-03f2-11de-b556-9305e745af9e" ]
[ [ [ 1, 125 ] ] ]
8cbad478afe635f3905478b6e4dc671bd27a8605
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Scada/scOPCsrv/OPCSrvr/SrvCallback.cpp
38b665abc7316eeefbe42683eb01a10d6e80e783
[]
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
51,619
cpp
//************************************************************************** // // Copyright (c) FactorySoft, INC. 1997, All Rights Reserved // //************************************************************************** // // Filename : Callback.cpp // $Author : Jim Hansen // // Subsystem : Callback object for OPC Server DLL // // Description: This class interfaces to the application's data // //************************************************************************** #include "stdafx.h" #include "sc_defs.h" //#include "xafxtempl.h" #include "srvCallback.h" #if WITHOPC #include "OPCError.h" #include "OPCProps.h" #include "scd_wm.h" #include "srvmngr.h" #include "atlconv.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define dbgOPCSrvr 0 long giBrowseTagCount; long giBranchCount; extern CTagTrees TagTrees; /*class ValuesData { public: char ValueName[256]; DWORD ValueNameLen; BYTE Data[1024]; DWORD DataLen; DWORD DataTyp; };*/ //========================================================================== CScdOPCTag::CScdOPCTag(CScdOPCCallBack * pCB, LPCTSTR name, Branch* branch) : m_pCallBack(pCB) { #if dbgOPCSrvr dbgpln("CScdOPCTag::CScdOPCTag(?,%s,?)", name); #endif TaggedObject::SplitTagCnv(LPTSTR(name), m_sTagOnly, m_sCnvTxt); #ifndef _RELEASE if (m_sTagOnly.XStrICmp("Train1.O:030/05")==0) { int b=0; } #endif if (m_sCnvTxt()) m_name.Format("%s (%s)", m_sTagOnly(), m_sCnvTxt()); else m_name=m_sTagOnly(); m_fullname = branch->GetPath() + m_name; m_bChecked=false; m_bIsValid=false; m_nativeType=VT_NULL; CheckTag(); } //-------------------------------------------------------------------------- CScdOPCTag::~CScdOPCTag() { #if dbgOPCSrvr dbgpln("CScdOPCTag::~CScdOPCTag(%s)", m_sTagOnly()); #endif } //-------------------------------------------------------------------------- bool CScdOPCTag::CheckTag() { if (m_sTagOnly.Len()>0) { char *s = m_fullname.GetBuffer( m_fullname.GetLength() ); CXM_ObjectTag ObjTag(s , TABOpt_AllInfoOnce); m_fullname.ReleaseBuffer(); CXM_ObjectData ObjData; CXM_Route Route; CPkDataItem * pItem = NULL; m_cType = VT_NULL; m_CnvInx = 0; //m_sCnvTxt = ""; m_nativeType = VT_NULL; if (CScdOPCManager::sm_pTheMngr->Enabled()) { m_bChecked=true; if (m_pCallBack->XReadTaggedItem(ObjTag, ObjData, Route)) { m_bIsValid=true; pItem = ObjData.FirstItem(); m_cType = pItem->Type(); m_CnvInx = pItem->CnvIndex(); if (m_sCnvTxt()) { // User has specified conversion text with tag check that it is valid if (!gs_CnvsMngr.FindSecCnv((m_CnvInx), m_sCnvTxt())) { // The provided conversion is not valid mark tag as invalid m_bIsValid=false; m_sCnvTxt="???"; } } else { // Use the Items Default SI Conversion m_sCnvTxt = pItem->CnvTxt(); } m_nativeType = VT_NULL; switch (m_cType) { case tt_Char : m_nativeType = VT_UI1; break; case tt_Bool : m_nativeType = VT_UI1; break; case tt_Bit : m_nativeType = VT_UI1; break; case tt_Byte : m_nativeType = VT_UI1; break; case tt_Word : m_nativeType = VT_UI2; break; case tt_DWord : m_nativeType = VT_UI4; break; case tt_Int : m_nativeType = VT_I4; break; case tt_Short : m_nativeType = VT_I2; break; case tt_Long : m_nativeType = VT_I4; break; case tt_Flt16 : m_nativeType = VT_R4; break; case tt_Float : m_nativeType = VT_R4; break; case tt_Double : m_nativeType = VT_R8; break; case tt_pChar : m_nativeType = VT_BSTR; break; case tt_Strng : m_nativeType = VT_BSTR; break; default : m_nativeType = VT_NULL; m_bIsValid=false; break; } } } if (CScdOPCManager::sm_pTheMngr->AllowInvalidTags() || m_bIsValid) { SYSTEMTIME ST; FILETIME FT; //__time64_t t = (__time64_t)gs_TimeCB.m_Time; __time64_t t = (__time64_t)gs_TimeCB.m_TheTime.Seconds; struct tm *pT = _localtime64(&t); ST.wSecond = pT->tm_sec; ST.wMinute = pT->tm_min; ST.wHour = pT->tm_hour; ST.wDay = pT->tm_mday; ST.wMonth = pT->tm_mon; ST.wYear = pT->tm_year+1900; ST.wMilliseconds = 0; SystemTimeToFileTime(&ST, &FT); CSLock wait( &m_pCallBack->m_CS ); // protect tag access LoadLocal(pItem, FT); } } return m_bIsValid; } //-------------------------------------------------------------------------- void CScdOPCTag::LoadLocal(CPkDataItem* pItem , FILETIME & FT) { #if dbgOPCSrvr dbgpln("CScdOPCTag::LoadLocal(%s)", m_sTagOnly()); #endif if (!m_bChecked)//CScdOPCManager::sm_pTheMngr->Enabled()) { m_timestamp = FT; m_quality = OPC_QUALITY_NOT_CONNECTED; m_nativeType = VT_NULL;// stops FS OPC Client from working //m_LclValue.Clear(); //m_LclValue=CString("Bad Data Type"); return; } PkDataUnion* pData = pItem->Value(); if (pData==NULL) {//problem with tag (eg no longer exists?) m_timestamp = FT; m_quality = OPC_QUALITY_LAST_KNOWN;//OPC_QUALITY_BAD; return; } if ((IsIntData(m_cType) || IsUnSgnData(m_cType)) && pItem->Contains(PDI_StrList)) { if (pItem->IndexedStrList()) { m_nativeType = VT_BSTR; pItem->GetStrList(m_StrLst); } } if (IsData(m_cType)) { if (m_nativeType == VT_BSTR) { CString temp; if (IsStrng(m_cType)) { temp=pData->GetString(); } else if (IsIntData(m_cType) || IsUnSgnData(m_cType)) { temp = "?"; int i=pData->GetLong(); for (pStrng p= m_StrLst.First(); p; p=p->pNxt) if (p->Index()==i) { temp=p->Str(); break; } } else { temp = "Bad Data Type"; //DoBreak(); } m_LclValue.Clear(); //m_LclValue.vt = m_nativeType; //if this line is included line below causes ""user breakpoint"" FIRST time LoadLocal is called ! trys to "free" old invalid string! m_LclValue=temp; //m_LclValue.SetString((const char*)temp, VT_BSTRT); //m_LclValue.SetString((const char*)temp, VT_BSTR); } else { m_LclValue.Clear(); m_LclValue.vt = m_nativeType; switch (m_cType) { case tt_Char : case tt_Bool : case tt_Bit : case tt_Byte : case tt_Word : case tt_DWord : case tt_Int : case tt_Short : case tt_Long : m_LclValue.lVal=pData->GetLong(); break; case tt_Flt16 : case tt_Float : m_LclValue.fltVal=(float)pData->GetDouble(m_CnvInx, m_sCnvTxt()); break; case tt_Double : m_LclValue.dblVal=pData->GetDouble(m_CnvInx, m_sCnvTxt()); break; default : //DoBreak(); break; }; } m_timestamp = FT; m_quality = OPC_QUALITY_GOOD; } } //-------------------------------------------------------------------------- //========================================================================== //******************************************************************* Branch::Branch( LPCTSTR name ) : m_name(name),m_parent(NULL) { } //******************************************************************* Branch::~Branch() { while (!m_tags.IsEmpty()) delete m_tags.RemoveTail(); while (!m_branches.IsEmpty()) delete m_branches.RemoveTail(); } //******************************************************************* void Branch::AddTag(CScdOPCTag* pTag) { #if FlatBranchStructure m_tags.AddTail(pTag); #else m_tags.AddTail(pTag); #endif } //******************************************************************* // Recursive function to search for a fully qualified tag name CScdOPCTag* Branch::FindTag( const CString& target ) { #if FlatBranchStructure POSITION pos = m_tags.GetHeadPosition(); while (pos) { CScdOPCTag* pTag = m_tags.GetNext(pos); if (pTag->m_name.CompareNoCase(target) == 0) return pTag; } return NULL; #else //needs to be implemented properly... int delimiter = target.Find( _T('.') ); //delimiter = -1; // Disable delimiters as they are a valid char in SysCAD Tags M.W. 24/6/3 // Need to write code to handle this case... simple as assuming not fully qualified // and searching all tags. If one is not found then we traverse the branches searching??? //if (delimiter == -1) // tag name if no delimiter // { // Check tag exists on this branch POSITION pos = m_tags.GetHeadPosition(); while (pos) { CScdOPCTag* pTag = m_tags.GetNext(pos); if (pTag->m_name.CompareNoCase(target) == 0) return pTag; } // } //else // { // Did not exist on this branch so search branches CString branchName( target.Left( delimiter ) ); /*POSITION*/ pos = m_branches.GetHeadPosition(); while( pos ) { Branch* pBranch = m_branches.GetNext( pos ); if( pBranch->m_name.CompareNoCase( branchName ) == 0 ) return pBranch->FindTag( target.Mid( delimiter+1 ) ); } // } return NULL; #endif } //******************************************************************* // Recursive function to search for a tag name or group name CString Branch::FindTagName(const CString& target) { #if FlatBranchStructure POSITION pos = m_tags.GetHeadPosition(); while (pos) { CScdOPCTag* pTag = m_tags.GetNext(pos); if (pTag->m_name.CompareNoCase(target) == 0) return GetPath() + target; } return ""; #else //needs to be implemented properly... int delimiter = target.Find( /*_T('.')*/ "." ); // M.W. 23/06/03 BOOL bFoundTag = TRUE; // Testing : Assume no delimiters at all times - SysCAD Tags can have . in them M.W. 24/6/03 // Need to write code to handle this case //delimiter = -1; // if (delimiter == -1) // tag name if no delimiter // { if (bFoundTag) { POSITION pos = m_tags.GetHeadPosition(); while (pos) { CScdOPCTag* pTag = m_tags.GetNext(pos); if (pTag->m_name.CompareNoCase(target) == 0) { bFoundTag = FALSE; return GetPath() + target; } } } if(bFoundTag) { CString branchName = target; POSITION pos = m_branches.GetHeadPosition(); while (pos) { Branch* pBranch = m_branches.GetNext(pos); if (pBranch->m_name.CompareNoCase( branchName ) == 0) return target; } } // } // else // { CString branchName(target.Left(delimiter)); POSITION pos = m_branches.GetHeadPosition(); while (pos) { Branch* pBranch = m_branches.GetNext(pos); if (pBranch->m_name.CompareNoCase( branchName ) == 0) return pBranch->FindTagName(target.Mid(delimiter+1)); } // } return ""; #endif } //******************************************************************* CString Branch::GetPath() { if( m_parent ) { return CString(m_parent->GetPath() + m_name + "."); } return ""; } //========================================================================== //******************************************************************* //******************************************************************* // overrides for all COPCCallback virtual functions... CScdOPCCallBack::CScdOPCCallBack(/*CScd * Plc*/) : m_SubscribedTagsRoot( "scd" ), m_BrowseTagsRoot( "scd" ) //: m_root( "Scd" ) { #if dbgOPCSrvr dbgpln("CallBack::CallBack()"); #endif //CScdOPCTag* pTag = NULL; iTagCnt = 0; iExecuteCnt = 0; bForceReadRqd = false; dwMeasScanRate = 0; dwLastScan = GetTickCount(); StatsCntReset(); EO_Register("OPC", EOWrite_Msg|EORead_Msg|EOExec_Msg, /*Pri*/THREAD_PRIORITY_NORMAL, /*Stack*/10000); } //******************************************************************* CScdOPCCallBack::~CScdOPCCallBack() { #if dbgOPCSrvr dbgpln("CallBack::~CallBack()"); #endif /*if (1) { CSLock wait( &m_CS ); // protect tag access while (!m_root.m_tags.IsEmpty()) delete m_root.m_tags.RemoveTail(); while (!m_root.m_branches.IsEmpty()) delete m_root.m_branches.RemoveTail(); }*/ EO_DeRegister(); } //******************************************************************* void CScdOPCCallBack::ConnectNotify(bool Connecting) { dwMeasScanRate = 0; dwLastScan = GetTickCount(); StatsCntReset(); if (CScdOPCManager::sm_pTheMngr->bShowStatsOnConnect) // ScdMainWnd()->PostMessage(WMU_CMD, SUB_CMD_OPCSRVRSTATS, (LPARAM)0); ::PostMessage(CScdCOCmdBase::s_hWnd4Msgs, WMU_CMD, SUB_CMD_OPCSRVRSTATS, (LPARAM)0); else CScdOPCManager::sm_pTheMngr->UpdateStatusWnd((WPARAM)SUB_UPDATE_REDRAW); if (CScdOPCManager::sm_pTheMngr->LogNotes()) LogNote("OPC", 0, "OPC Client %s", Connecting ? "Connect" : "Disconnect"); } //******************************************************************* void CScdOPCCallBack::BuildBrowserBranchRecursive( char* pBranchName , Branch* pParentBranch , CTagTreeItem *pRoot ) // // pBranchName - Name of new branch // pParentBranch - Pointer to parent branch // pRoot - Pointer to parent TagTreeItem // { CTagTreeItem* pItem; Branch* pBranch; //Strng tempS; // Traverse the children of the Root Tag Tree Item pItem = pRoot->Child(); if ( pItem == NULL ) { // Leaf MakeTag( pRoot->Tag() , pParentBranch ); } else { // New branch pBranch = new Branch(pRoot->Tag()); pParentBranch->AddBranch(pBranch); while (pItem != NULL) { if (pItem->Child()) { // Has children so create another branch BuildBrowserBranchRecursive( pItem->Tag() , pBranch , pItem ); } else { // Must be a leaf //pItem->GetFullTag(tempS); MakeTag( pItem->Tag() , pBranch ); } pItem = pItem->Next(); } } } //******************************************************************* void CScdOPCCallBack::PopulateBrowserBranch( Branch* pBranch , CTagTreeItem *pRoot ) // // pBranch - Branch to populate // pRoot - Pointer to corresponding TagTreeItem // { CTagTreeItem* pItem; Branch* pChildBranch; // Traverse the children of the Root Tag Tree Item pItem = pRoot->Child(); if ( pItem == NULL ) { // Do nothing // This should not happen } else { while (pItem != NULL) { if (pItem->Child()) { // Has children - Just create the unpopulated branch at this stage // Only populate if traversed pChildBranch = new Branch(pItem->Tag()); giBranchCount++; pBranch->AddBranch(pChildBranch); } else { // Must be a leaf giBrowseTagCount++; MakeTag( pItem->Tag() , pBranch ); } pItem = pItem->Next(); } } } //******************************************************************* COPCBrowser* CScdOPCCallBack::CreateBrowser() { #if dbgOPCSrvr dbgpln("CallBack::CreateBrowser(?)"); #endif giBrowseTagCount = 0; giBranchCount = 0; class ShellBrowser* sb = new ShellBrowser(this); //#ifdef NEVER // Moved this code to ShellBrowse::MoveUp method // Moved it back as it was going all the way back to the top // when browsing making it very slow. // Clean up existing BrowseTags branch lists to avoid duplication CSLock wait( &m_CS ); // protect tag access while (!m_BrowseTagsRoot.m_tags.IsEmpty()) delete m_BrowseTagsRoot.m_tags.RemoveTail(); while (!m_BrowseTagsRoot.m_branches.IsEmpty()) delete m_BrowseTagsRoot.m_branches.RemoveTail(); // Rebuild our top level tag/model list from SysCAD TagTrees.Rebuild(RQ_Tags); // Build the first level branches // Shell Browse->Move Down will create the rest dynamically as required // CModelTypeListArray& List = TagTrees.GetList(); CModelTypeList* pTagList = List[0]; for (int i=0; i< pTagList->GetSize(); i++) { Branch* pChildBranch = new Branch(pTagList->GetTagAt(i)); sb->m_pBranch->AddBranch(pChildBranch); } //#endif // Testing /* CTagTree* T; CModelTypeListArray& List = TagTrees.GetList(); CModelTypeList* pTagList = List[0]; for (int i=0; i< pTagList->GetSize(); i++) { T = new CTagTree; T->Build( this , pTagList->GetTagAt(i) ); delete T; } */ return sb; } //******************************************************************* OPCSERVERSTATE CScdOPCCallBack::GetServerState() { #if dbgOPCSrvr dbgpln("CallBack::GetServerState(?)"); #endif if (!OPCServerAllowed()) return OPC_STATUS_FAILED; //return failed because not licensed, or valid project with OPC not loaded if (XRunning()) return OPC_STATUS_RUNNING; return OPC_STATUS_RUNNING; //return OPC_STATUS_SUSPENDED; some OPC clients don't like this state flag!?!?! } //******************************************************************* // SetUpdateRate returns a modified update rate DWORD CScdOPCCallBack::SetUpdateRate( DWORD newUpdateRate ) { #if dbgOPCSrvr dbgpln("CallBack::SetUpdateRate(?)"); #endif if( newUpdateRate==0 ) return 100; //a default if( newUpdateRate > 10 ) return newUpdateRate; return 10; //minimum } //******************************************************************* // AddTag creates a new tag or returns a pointer to an existing tag. // // Return NULL if the tag could not be created (bad name or accessPath) // or the requested type is incompatible. The requested type is for this // client, do not change the tag's type. CTag* CScdOPCCallBack::AddTag( LPCTSTR name, LPCTSTR accessPath, VARTYPE requestedType) { #if dbgOPCSrvr dbgpln("CallBack::AddTag(%s,%s)", name, accessPath); #endif //DumpBranchs(); CSLock wait( &m_CS ); // protect tag access CScdOPCTag * pTag = m_SubscribedTagsRoot.FindTag(name); if (pTag) { if (CScdOPCManager::sm_pTheMngr->LogNotes()) LogNote("OPC", 0, "Add Tag: allready exists (%s)", name); return (CTag*)pTag; } // Initialize the tag's type, etc. // should store in a list if (pTag==NULL) { pTag = TryMakeTag(name, &m_SubscribedTagsRoot); if (pTag) { if (CScdOPCManager::sm_pTheMngr->LogNotes()) LogNote("OPC", 0, "Add Tag (%s)", name); XBuildMyDataLists(); CScdOPCManager::sm_pTheMngr->UpdateStatusWnd((WPARAM)SUB_UPDATE_REDRAW); } else { if (CScdOPCManager::sm_pTheMngr->LogNotes()) LogNote("OPC", 0, "Add Tag: Failed to add tag (%s)", name); } } return (CTag*)pTag; } //******************************************************************* // ValidateTag modifies pTag to contain the nativeType and access rights // if successful. If the name and access path do not specify a valid tag, // then return OPC_E_UNKNOWNITEMID or OPC_E_UNKNOWNPATH. // If the data type is incompatible, return OPC_E_BADTYPE. HRESULT CScdOPCCallBack::ValidateTag( CTag* pTag, LPCTSTR name, LPCTSTR accessPath, VARTYPE requestedType) { #if dbgOPCSrvr dbgpln("CallBack::ValidateTag(?,%s,%s)", name, accessPath); #endif CSLock wait( &m_CS ); // protect tag access CScdOPCTag* pFoundTag = m_BrowseTagsRoot.FindTag(name); if( pFoundTag ) { pTag->m_nativeType = pFoundTag->m_nativeType; pTag->m_accessRights = pFoundTag->m_accessRights; // can use VariantChangeType to test data types: // get a current value for this tag and convert it to the requested type. // If VariantChangeType returns an error, return OPC_E_BADTYPE. return S_OK; } else { // This does not mean it does not exist in SysCAD // It just has not been added to the browse tree yet // For example the user may have specified units. i.e. Qm (t/h) instead of Qm // Check in subscribed tags pFoundTag = m_SubscribedTagsRoot.FindTag(name); if( pFoundTag ) { pTag->m_nativeType = pFoundTag->m_nativeType; pTag->m_accessRights = pFoundTag->m_accessRights; // can use VariantChangeType to test data types: // get a current value for this tag and convert it to the requested type. // If VariantChangeType returns an error, return OPC_E_BADTYPE. return S_OK; } // Not subscribed already so may still be a valid tag. // Find out by adding the tag. AddTag will fail if it does not exist // NB: This is a cheat. We need a way of just testing the tag exists in // SysCAD....TO DO. CTag* pNewTag = AddTag(name,accessPath,requestedType); if( pNewTag ) { pTag->m_nativeType = pNewTag->m_nativeType; pTag->m_accessRights = pNewTag->m_accessRights; // can use VariantChangeType to test data types: // get a current value for this tag and convert it to the requested type. // If VariantChangeType returns an error, return OPC_E_BADTYPE. return S_OK; } } return OPC_E_UNKNOWNITEMID; } //******************************************************************* // Remove is called when tags are released. This function must check // if the tags are in use if AddTag may ever return a pointer to an // existing tag. Additional clean up should occur here. HRESULT CScdOPCCallBack::Remove( DWORD dwNumItems, CTag ** ppTags) { #if dbgOPCSrvr dbgpln("CallBack::Remove(?,)"); #endif CSLock wait( &m_CS ); // protect tag access for( DWORD index=0; index<dwNumItems; index++ ) { // Not needed because CScdOPCTags are static CTag* pTag = ppTags[index]; XBuildMyDataLists(); // if( !pTag->InUse() ) // delete pTag; } if (dwNumItems>0) XBuildMyDataLists(); CScdOPCManager::sm_pTheMngr->UpdateStatusWnd((WPARAM)SUB_UPDATE_REDRAW); return S_OK; } //******************************************************************* LPCTSTR CScdOPCCallBack::GetTagName( CTag * pTag ) { #if dbgOPCSrvr dbgpln("CallBack::GetTagName(?,)"); #endif return ((CScdOPCTag*)pTag)->m_fullname; } //******************************************************************* // GetTagLimits should return TRUE if this tags has known limits. BOOL CScdOPCCallBack::GetTagLimits( CTag * pTag, double *pHigh, double *pLow ) { #if dbgOPCSrvr dbgpln("CallBack::GetTagLimits(?,)"); #endif *pHigh = 1.0; *pLow = -1.0; //return TRUE; return FALSE; } //******************************************************************* // Read each of these tags as a periodic scan HRESULT CScdOPCCallBack::Scan( DWORD dwNumItems, CTag ** ppTags, HRESULT * pErrors) { #if dbgOPCSrvr dbgp("CallBack::Scan(%d", dwNumItems); #endif HRESULT hr = Read(dwNumItems, ppTags, pErrors); iScanCnt++; const DWORD Now = GetTickCount(); dwMeasScanRate = Now - dwLastScan; dwLastScan = Now; bForceReadRqd = false; return hr; } //******************************************************************* HRESULT CScdOPCCallBack::ReadTag(CTag * pTag) { #if dbgOPCSrvr dbgp("CallBack::ReadTag("); #endif //#define OPC_E_INVALIDHANDLE ((HRESULT)0xC0040001L) /*if (m_root.m_tags.IsEmpty()) return S_OK;//OPC_E_???;*/ // The work to set the data is done in EO_WriteSubsData // This does the actual data transfer to the OPC client CSLock wait( &m_CS ); // protect tag access CScdOPCTag* pScdTag = (CScdOPCTag*)(pTag); #if dbgOPCSrvr dbgpln("%s)", pScdTag->m_name); #endif #ifndef _RELEASE if (pScdTag->m_sTagOnly.XStrICmp("Train1.O:030/05")==0) { int b=0; } #endif if (bForceReadRqd) { //after a ReadTag, the ScdOpcSrvDLL only sends data to client if value (subject to bandwidth) or quality changed! //todo: extend functionality of CTag to have a m_ForceReadOnce flag. pTag->m_quality = OPC_QUALITY_LAST_KNOWN; //temporary } VariantCopy(&pTag->m_value, pScdTag->m_LclValue); iClientReadOKCnt++; return S_OK; } //******************************************************************* // The variant may contain data in any format the client sent. // Use VariantChangeType to convert to a usable format. HRESULT CScdOPCCallBack::WriteTag( CTag * pTag, VARIANT & value) { #if dbgOPCSrvr dbgpln("CallBack::WriteTag(?,)"); #endif iClientWriteOKCnt++; CScdOPCTag &T=*((CScdOPCTag*)(pTag)); HRESULT hr = S_OK; bool UseCnv=T.m_sCnvTxt.GetLength()>0; CXM_ObjectTag ObjTag(T.m_sTagOnly(), (UseCnv ? TABOpt_ValCnvsOnce : 0)); CXM_ObjectData ObjData; CXM_Route Route; if (XReadTaggedItem(ObjTag, ObjData, Route)) { PkDataUnion DU; switch (value.vt) { case VT_BOOL: DU.SetTypeLong(T.m_cType, value.boolVal); break; case VT_UI1: DU.SetTypeLong(T.m_cType, value.bVal); break; case VT_UI2: DU.SetTypeLong(T.m_cType, value.iVal); break; case VT_UI4: DU.SetTypeLong(T.m_cType, value.lVal); break; case VT_I2: DU.SetTypeLong(T.m_cType, value.iVal); break; case VT_I4: DU.SetTypeLong(T.m_cType, value.lVal); break; case VT_R4: if (UseCnv) DU.SetTypeDouble(T.m_cType, value.fltVal, (T.m_CnvInx), T.m_sCnvTxt()); else DU.SetTypeDouble(T.m_cType, value.fltVal); break; case VT_R8: if (UseCnv) DU.SetTypeDouble(T.m_cType, value.dblVal, (T.m_CnvInx), T.m_sCnvTxt()); else DU.SetTypeDouble(T.m_cType, value.dblVal); break; case VT_BSTR: { USES_CONVERSION; //COleVariant X(value.bstrVal); DU.SetTypeString(tt_Generic, OLE2T(value.bstrVal)); break; } default : break; } CXM_ObjectData ObjData(0, 0, T.m_sTagOnly(), 0, DU); if (XWriteTaggedItem(ObjData, Route)==TOData_OK) { iScdWriteOKCnt++; } else { hr = E_INVALIDARG; iWriteFailCnt++; } } else { iWriteFailCnt++; } if (SUCCEEDED(hr)) {//update our copy of this tag... CSLock wait( &m_CS ); // protect tag access T.m_LclValue.Clear(); VariantCopy(&T.m_LclValue, &value); } else { //warning message? } return hr; } //******************************************************************* // If the name is valid, return the number of item properties supported. // If this returns successfully, QueryAvailableProperties will be called. // To save lookups, put a hint into ppVoid. HRESULT CScdOPCCallBack::QueryNumProperties( LPCTSTR name, DWORD * pdwNumItems, LPVOID * ppVoid) { #if dbgOPCSrvr dbgpln("CallBack::QueryNumProperties(?,)"); #endif CScdOPCTag* pFoundTag = m_BrowseTagsRoot.FindTag(name); if( pFoundTag ) { *pdwNumItems = 6; *ppVoid = (LPVOID)pFoundTag; return S_OK; } return OPC_E_UNKNOWNITEMID; } //******************************************************************* // The properties (from QueryNumProperties) now get filled in. // pVoid contains the hint from QueryNumProperties. // AllocString allocates COM memory to hold a string. HRESULT CScdOPCCallBack::QueryAvailableProperties( LPCTSTR name, DWORD dwNumItems, LPVOID pVoid, DWORD * pPropertyIDs, LPWSTR * pDescriptions, VARTYPE * pDataTypes) { #if dbgOPCSrvr dbgpln("CallBack::QueryAvailableProperties(?,)"); #endif if( pVoid == NULL ) return OPC_E_UNKNOWNITEMID; CScdOPCTag* pTag = (CScdOPCTag*)pVoid; CString description; DWORD index=0; description = _T("Item Canonical DataType"); pPropertyIDs[index] = OPC_PROP_CDT; pDescriptions[index] = AllocString(description); pDataTypes[index] = VT_I2; index++; if( index==dwNumItems ) return S_OK; description = _T("Item Value"); pPropertyIDs[index] = OPC_PROP_VALUE; pDescriptions[index] = AllocString(description); pDataTypes[index] = pTag->m_nativeType; index++; if( index==dwNumItems ) return S_OK; description = _T("Item Quality"); pPropertyIDs[index] = OPC_PROP_QUALITY; pDescriptions[index] = AllocString(description); pDataTypes[index] = VT_I2; index++; if( index==dwNumItems ) return S_OK; description = _T("Item Timestamp"); pPropertyIDs[index] = OPC_PROP_TIME; pDescriptions[index] = AllocString(description); pDataTypes[index] = VT_DATE; index++; if( index==dwNumItems ) return S_OK; description = _T("Item Access Rights"); pPropertyIDs[index] = OPC_PROP_RIGHTS; pDescriptions[index] = AllocString(description); pDataTypes[index] = VT_I4; index++; if( index==dwNumItems ) return S_OK; description = _T("Item Description"); pPropertyIDs[index] = OPC_PROP_DESC; pDescriptions[index] = AllocString(description); pDataTypes[index] = VT_BSTR; return S_OK; } //******************************************************************* HRESULT CScdOPCCallBack::GetItemProperties( LPCTSTR name, DWORD dwNumItems, DWORD * pPropertyIDs, VARIANT * pData, HRESULT * pErrors) { #if dbgOPCSrvr dbgpln("CallBack::GetItemProperties(?,)"); #endif CScdOPCTag* pTag = m_BrowseTagsRoot.FindTag(name); if (!pTag) return OPC_E_UNKNOWNITEMID; DATE date; //WORD dosDate=0, dosTime=0; for (DWORD index=0; index<dwNumItems; index++) { pErrors[index] = S_OK; switch(pPropertyIDs[index]) { case OPC_PROP_CDT: pData[index].vt = VT_I2; pData[index].iVal = pTag->m_nativeType; break; case OPC_PROP_VALUE: VariantCopy( &pData[index], &pTag->m_value ); break; case OPC_PROP_QUALITY: pData[index].vt = VT_I2; pData[index].iVal = pTag->m_quality; break; case OPC_PROP_TIME: { FILETIME filetimeLocal; if (FileTimeToLocalFileTime(&pTag->m_timestamp, &filetimeLocal)) { SYSTEMTIME systime; if (FileTimeToSystemTime(&filetimeLocal, &systime)) { SystemTimeToVariantTime(&systime, &date); } } pData[index].vt = VT_DATE; pData[index].date = date; break; } /*case OPC_PROP_TIME: pData[index].vt = VT_DATE; FileTimeToDosDateTime( &pTag->m_timestamp, &dosDate, &dosTime); DosDateTimeToVariantTime( dosDate, dosTime, &date); pData[index].date = date; break;*/ case OPC_PROP_RIGHTS: pData[index].vt = VT_I4; pData[index].lVal = OPC_READABLE | OPC_WRITEABLE; break; case OPC_PROP_DESC: { CString description(_T("Item Description goes here")); pData[index].vt = VT_BSTR; pData[index].bstrVal = description.AllocSysString(); break; } } } return S_OK; } //******************************************************************* HRESULT CScdOPCCallBack::LookupItemIDs( LPCTSTR name, DWORD dwNumItems, DWORD * pPropertyIDs, LPWSTR * pszNewItemIDs, HRESULT * pErrors) { //Chandra add functionality to get itemID DWORD index = 0; CString description; CScdOPCTag* pTag = m_BrowseTagsRoot.FindTag(name); if (!pTag) return OPC_E_UNKNOWNITEMID; // The name is valid _tcscpy( description.GetBuffer(_MAX_PATH),m_BrowseTagsRoot.GetPath() + name); pszNewItemIDs[index] = AllocString(description); return S_OK; } //******************************************************************* // return a string if the error code is recognized LPCTSTR CScdOPCCallBack::GetErrorString( HRESULT dwError, LCID dwLocale) { #if dbgOPCSrvr dbgpln("CallBack::GetErrorString(?,)"); #endif error = _T("Unknown SysCAD OPC Server Error"); return error; } //******************************************************************* // return your vendor string LPCTSTR CScdOPCCallBack::GetVendorString() { #if dbgOPCSrvr dbgpln("CallBack::GetVendorString(?,)"); #endif return _T("Kenwalt (Pty) Ltd."); } //-------------------------------------------------------------------------- inline CScdOPCTag * CScdOPCCallBack::TryMakeTag(LPCTSTR Name, Branch * pBrnch/*, CScd * Plc*/) { #if dbgOPCSrvr dbgpln("CallBack::TryMakeTag(%s,)", Name); #endif CScdOPCTag * pTag = new CScdOPCTag(this, Name, pBrnch); if (CScdOPCManager::sm_pTheMngr->AllowInvalidTags() || pTag->m_bIsValid) //if (1) // always add pTag->m_bIsValid) { pBrnch->AddTag(pTag); iTagCnt++; } else { LogWarning("OPC", 0, "Failed to add tag (%s)", Name); delete pTag; pTag = NULL; } return pTag; } //-------------------------------------------------------------------------- inline CScdOPCTag * CScdOPCCallBack::MakeTag(LPCTSTR Name, Branch * pBrnch/*, CScd * Plc*/) { #if dbgOPCSrvr dbgpln("CallBack::MakeTag(%s,)", Name); #endif CScdOPCTag * pTag = new CScdOPCTag(this, Name, pBrnch); pBrnch->AddTag(pTag); return pTag; } //-------------------------------------------------------------------------- void CScdOPCCallBack::DumpBranchs() { #ifndef _RELEASE CSLock wait( &m_CS ); // protect tag access const int Cnt = m_BrowseTagsRoot.m_tags.GetCount(); POSITION Pos = m_BrowseTagsRoot.m_tags.GetHeadPosition(); while (Pos!=NULL) { CScdOPCTag * pTag = m_BrowseTagsRoot.m_tags.GetNext(Pos); dbgpln("Tag:%s", pTag->m_name); } #endif } void CScdOPCCallBack::SetEnable(bool On) { CSLock wait( &m_CS ); // protect tag access const int Cnt = m_SubscribedTagsRoot.m_tags.GetCount(); POSITION Pos = m_SubscribedTagsRoot.m_tags.GetHeadPosition(); while (Pos!=NULL) { CScdOPCTag * pTag = m_SubscribedTagsRoot.m_tags.GetNext(Pos); if (On && !pTag->m_bChecked) { pTag->CheckTag(); } else if (!On && pTag->m_bIsValid) { pTag->m_bIsValid=false; pTag->m_bChecked=false; pTag->m_quality=OPC_QUALITY_NOT_CONNECTED; } } } //-------------------------------------------------------------------------- //******************************************************************* // CExecObj Overrides //******************************************************************* flag CScdOPCCallBack::EO_QueryTime(CXM_TimeControl &CB, CTimeValue &TimeRqd, CTimeValue &dTimeRqd) { #if dbgOPCSrvr dbgpln("CallBack::EO_QueryTime(?,)"); #endif return true; }; flag CScdOPCCallBack::EO_Start(CXM_TimeControl &CB) { #if dbgOPCSrvr dbgpln("CallBack::EO_Start(?,)"); #endif if (CScdOPCManager::sm_pTheMngr->bForceOnStart) bForceReadRqd = true; CScdOPCManager::sm_pTheMngr->UpdateStatusWnd((WPARAM)SUB_UPDATE_EOSTART); return true; }; void CScdOPCCallBack::EO_QuerySubsReqd(CXMsgLst &XM) { #if dbgOPCSrvr dbgpln("CallBack::EO_QuerySubsReqd(?,)"); #endif CSLock wait( &m_CS ); // protect tag access CXM_ReadIndexedData* pMsg=(CXM_ReadIndexedData *)XM.MsgPtr(XM_ReadIndexedData); if (pMsg->Start) { long thisIndex=0; m_TagA.SetSize(m_SubscribedTagsRoot.m_tags.GetCount()); POSITION Pos=m_SubscribedTagsRoot.m_tags.GetHeadPosition(); while (Pos!=NULL) m_TagA[thisIndex++]=m_SubscribedTagsRoot.m_tags.GetNext(Pos); } flag ReadAll=pMsg->ReadAll; long DataIndex=pMsg->Start ? 0 : pMsg->LastIndex+1; Strng Tg; XM.Clear(); for ( ; DataIndex<m_TagA.GetSize(); DataIndex++) { CXM_DataRequest *DRqst=new CXM_DataRequest (DataIndex, LPTSTR(LPCTSTR(m_TagA[DataIndex]->m_name)), TABOpt_AllInfoOnce, XIO_In); if (!XM.PackMsg(DRqst)) { delete DRqst; break; } } }; void CScdOPCCallBack::EO_QuerySubsAvail(CXMsgLst &XM, CXMsgLst &XMRet) { #if dbgOPCSrvr dbgpln("CallBack::EO_QuerySubsAvail(?,)"); #endif //XM.Clear(); }; flag CScdOPCCallBack::EO_ReadSubsData(CXMsgLst &XM) { #if dbgOPCSrvr dbgpln("CallBack::EO_ReadSubsData(?,)"); #endif flag DataRead=0; return DataRead; }; flag CScdOPCCallBack::EO_WriteSubsData(CXMsgLst &XM, flag FirstBlock, flag LastBlock) { #if dbgOPCSrvr dbgpln("CallBack::EO_WriteSubsData(%d,)", XM.NoMsgs()); #endif if (FirstBlock) { } static SYSTEMTIME STMem;// System Time converted from SysCAD Time SYSTEMTIME ST;// System Time converted from SysCAD Time FILETIME FT; // Local File Time based on SysCAD time FILETIME UTCFT; // File time @ UTC //__time64_t t=(__time64_t)gs_TimeCB.m_Time; __time64_t t = (__time64_t)gs_TimeCB.m_TheTime.Seconds; struct tm *pT=_localtime64(&t); // struct tm //int tm_sec; /* seconds after the minute - [0,59] */ //int tm_min; /* minutes after the hour - [0,59] */ //int tm_hour; /* hours since midnight - [0,23] */ //int tm_mday; /* day of the month - [1,31] */ //int tm_mon; /* months since January - [0,11] */ //int tm_year; /* years since 1900 */ //int tm_wday; /* days since Sunday - [0,6] */ //int tm_yday; /* days since January 1 - [0,365] */ //int tm_isdst; /* daylight savings time flag */ // SYSTEMTIME //wYear Specifies the current year. //wMonth Specifies the current month; January = 1, February = 2, and so on. //wDayOfWeek Specifies the current day of the week; Sunday = 0, Monday = 1, and so on. //wDay Specifies the current day of the month. //wHour Specifies the current hour. //wMinute Specifies the current minute. //wSecond Specifies the current second. //wMilliseconds Specifies the current millisecond. if (pT) { ST.wSecond = pT->tm_sec; /* seconds after the minute - [0,59] */ ST.wMinute = pT->tm_min; /* minutes after the hour - [0,59] */ ST.wHour = pT->tm_hour;/* hours since midnight - [0,23] */ ST.wDay = pT->tm_mday;/* day of the month - [1,31] */ ST.wDayOfWeek = pT->tm_wday; /* days since Sunday - [0,6] */ ST.wMonth = pT->tm_mon+1; /* months since January - [0,11] *//* Need to add 1 */ ST.wYear = pT->tm_year+1900;/* years since 1900 */ ST.wMilliseconds = 0; STMem=ST; } else { LogError("OPCCallBack", 0, "Time Wrap around"); //STMem.wSecond++; ST=STMem; } DWORD lerr = SystemTimeToFileTime(&ST, &FT); lerr = LocalFileTimeToFileTime(&FT,&UTCFT); //todo: conversion between SysCAD time and local/GMT time not correct!!! for (long i=0; i<XM.NoMsgs(); i++) { CXM_ObjectData* pMsg=XM.ObjectData(); long DataIndex=pMsg->Index; CPkDataItem* pItem=pMsg->FirstItem(); PkDataUnion* pData=pMsg->FirstItem()->Value(); CSLock wait( &m_CS ); // protect tag access CScdOPCTag & T=*m_TagA[DataIndex]; T.LoadLocal(pItem, UTCFT); iScdReadOKCnt++; } //if (FirstBlock) { iExecuteCnt++; if (CScdOPCManager::sm_pTheMngr->iForceCnt>0 && iExecuteCnt>=CScdOPCManager::sm_pTheMngr->iForceCnt) { iExecuteCnt = 0; bForceReadRqd = true; } CScdOPCManager::sm_pTheMngr->UpdateStatusWnd((WPARAM)(SUB_UPDATE_SENDMSG|SUB_UPDATE_EOWRITE)); } #if dbgOPCSrvr dbgpln("CallBack::EO_WriteSubsData(?,) ---Done---"); #endif return true; }; flag CScdOPCCallBack::EO_Execute(CXM_TimeControl &CB, CEOExecReturn &EORet) { #if dbgOPCSrvr dbgpln("CallBack::EO_Execute(?,)"); #endif //iExecuteCnt++; //CScdOPCManager::sm_pTheMngr->UpdateStatusWnd((WPARAM)(SUB_UPDATE_SENDMSG|SUB_UPDATE_EOEXEC)); return false; }; flag CScdOPCCallBack::EO_Stop(CXM_TimeControl &CB) { #if dbgOPCSrvr dbgpln("CallBack::EO_Stop(?,)"); #endif if (CScdOPCManager::sm_pTheMngr->bForceOnStop) bForceReadRqd = true; CScdOPCManager::sm_pTheMngr->UpdateStatusWnd((WPARAM)SUB_UPDATE_EOSTOP); return true; }; int CScdOPCCallBack::EO_CanClose(Strng_List & Problems) { /*if (1) { CSLock wait( &m_CS ); // protect tag access while (!m_root.m_tags.IsEmpty()) delete m_root.m_tags.RemoveTail(); while (!m_root.m_branches.IsEmpty()) delete m_root.m_branches.RemoveTail(); }*/ return EO_CanClose_Yes; } //-------------------------------------------------------------------------- flag CScdOPCCallBack::ForceWriteSubsDataAll() { #if dbgOPCSrvr dbgpln("CallBack::ForceWriteSubsDataAll()"); #endif bForceReadRqd = true; return true; } //--------------------------------------------------------------------------- char* GetVariantAsStr(COleVariant & Var, Strng &s) { switch (Var.vt) { case VT_EMPTY: case VT_NULL: s = ""; break; case VT_R8: s.Set("%g", Var.dblVal); break; case VT_I4: case VT_UI4: s.Set("%d", Var.lVal); break; case VT_I2: case VT_UI2: s.Set("%d", Var.iVal); break; case VT_BSTR: { USES_CONVERSION; LPCTSTR S=OLE2T(Var.bstrVal); s = S;//OLE2T(Var.bstrVal); break; } case VT_BOOL: s.Set("%d", Var.boolVal); break; case VT_R4: s.Set("%g", Var.fltVal); break; case VT_UI1: s.Set("%d", Var.bVal); break; default: ASSERT_ALWAYS(FALSE, "Variant Data Type?", __FILE__, __LINE__); s="?"; break; } return s(); } void CScdOPCCallBack::BuildSubsList(CListBox* pList) { char Buff[1024]; Strng s; CSLock wait( &m_CS ); // protect tag access for (long DataIndex=0; DataIndex<m_TagA.GetSize(); DataIndex++) { CScdOPCTag & T=*m_TagA[DataIndex]; sprintf(Buff, "%s (%s)", T.m_sTagOnly(), GetVariantAsStr(T.m_LclValue, s)); pList->AddString(Buff); } //sprintf(Buff, "Subscription count : %d", m_TagA.GetSize()); //pList->InsertString(0, Buff); } //-------------------------------------------------------------------------- //========================================================================== //For now, browser only provides list of tags already subscribed by OPC client, //in future this should be extended to support ALL tags in SysCAD....... //******************************************************************* // ShellBrowser class //******************************************************************* ShellBrowser::ShellBrowser(CScdOPCCallBack* parent) : m_parent(parent) { m_pBranch = &m_parent->m_BrowseTagsRoot; Reset(); } //******************************************************************* OPCNAMESPACETYPE ShellBrowser::QueryOrganization() { //return OPC_NS_HIERARCHIAL; //return OPC_NS_FLAT; return OPC_NS_HIERARCHIAL; } //******************************************************************* HRESULT ShellBrowser::GetNames( OPCBROWSETYPE type, LPCTSTR stringFilter, VARTYPE dataTypeFilter, DWORD accessFilter ) { #if dbgOPCSrvr dbgpln("ShellBrowser::GetNames(?)"); #endif m_type = type; m_stringFilter = stringFilter; m_dataTypeFilter = dataTypeFilter; m_accessFilter = accessFilter; m_bDoStringFilter = (m_stringFilter.GetLength()>0 && m_stringFilter!="*"); m_iFilterLen = m_stringFilter.GetLength(); if (m_bDoStringFilter && m_stringFilter[m_iFilterLen-1]=='*') m_iFilterLen--; if( m_type == OPC_FLAT ) { m_paths.RemoveAll(); m_pBranch = &m_parent->m_BrowseTagsRoot; AddTags( m_pBranch ); } Reset(); return S_OK; } //******************************************************************* // Recursive function to add tag names from all groups to a list. // This is only called when browsing OPC_FLAT // Added 2.0 void ShellBrowser::AddTags( Branch* pBranch ) { #if dbgOPCSrvr dbgpln("ShellBrowser::AddTags(?)"); #endif // First add full path names for this group's tags CString path(pBranch->GetPath()); POSITION pos = pBranch->m_tags.GetHeadPosition(); while( pos ) { CScdOPCTag* pTag = pBranch->m_tags.GetNext( pos ); if (m_dataTypeFilter==VT_EMPTY || m_dataTypeFilter==pTag->m_nativeType) { CString name( path + pTag->m_name ); if (m_bDoStringFilter) { if (name.GetLength()>=m_iFilterLen && _strnicmp((const char*)name, (const char*)m_stringFilter, m_iFilterLen)==0) m_paths.AddTail(name); } else m_paths.AddTail(name); } } // And recurse into the child groups pos = pBranch->m_branches.GetHeadPosition(); while( pos ) { AddTags( pBranch->m_branches.GetNext( pos ) ); } } //************************************************************************** BOOL ShellBrowser::MoveUp() { #if dbgOPCSrvr dbgpln("ShellBrowser::MoveUp(?)"); #endif CSLock wait( &m_parent->m_CS ); if( m_pBranch->m_parent ) { m_pBranch = m_pBranch->m_parent; Reset(); return TRUE; } // at the "root" level, can't go up // We create the top level every time we browse to the top // level - no it seems to start at the top every time you browse down a level????? // Clean up existing BrowseTags branch lists to avoid duplication /* while (!m_pBranch->m_tags.IsEmpty()) delete m_pBranch->m_tags.RemoveTail(); while (!m_pBranch->m_branches.IsEmpty()) delete m_pBranch->m_branches.RemoveTail(); giBrowseTagCount = 0; giBranchCount = 0; // Rebuild our top level tag/model list from SysCAD TagTrees.Rebuild(RQ_Tags); // Build the first level branches // Shell Browse->Move Down will create the rest dynamically as required // CModelTypeListArray& List = TagTrees.GetList(); CModelTypeList* pTagList = List[0]; for (int i=0; i< pTagList->GetSize(); i++) { Branch* pChildBranch = new Branch(pTagList->GetTagAt(i)); m_pBranch->AddBranch(pChildBranch); } */ return FALSE; } //************************************************************************** BOOL ShellBrowser::MoveDown(LPCTSTR branch) { #if dbgOPCSrvr dbgpln("ShellBrowser::MoveDown(?)"); #endif CSLock wait( &m_parent->m_CS ); POSITION pos = m_pBranch->m_branches.GetHeadPosition(); while( pos ) { Branch* pBranch = m_pBranch->m_branches.GetNext( pos ); if( pBranch->m_name.CompareNoCase( branch ) == 0 ) { m_pBranch = pBranch; if ( pBranch->m_branches.IsEmpty() && pBranch->m_tags.IsEmpty() ) { // Dynamically Create Next Level CTagTree* T = new CTagTree; CString full_name; full_name = pBranch->GetPath(); T->Build( m_parent , full_name.GetBuffer( full_name.GetLength()) ); full_name.ReleaseBuffer(); m_parent->PopulateBrowserBranch(pBranch, T->Root() ); delete T; } Reset(); return TRUE; } } return FALSE; } //******************************************************************* // if name is valid, return the path+name LPCTSTR ShellBrowser::GetItemID( LPCTSTR name ) { #if dbgOPCSrvr dbgpln("ShellBrowser::GetItemID(?)"); #endif CSLock wait( &m_parent->m_CS ); // Search for the name CString tagName = m_pBranch->FindTagName(name); // The name is valid _tcscpy(m_name, tagName.GetBuffer(_MAX_PATH)); return m_name; } //******************************************************************* LPCTSTR ShellBrowser::Next() { #if dbgOPCSrvr dbgpln("ShellBrowser::Next(?)"); #endif CSLock wait( &m_parent->m_CS ); while( m_pos ) { if( m_type==OPC_BRANCH ) { Branch* pBranch = m_pBranch->m_branches.GetNext(m_pos); _tcscpy( m_name, pBranch->m_name ); if( m_stringFilter.IsEmpty() || MatchPattern( m_name, m_stringFilter, FALSE) ) return m_name; } else if( m_type==OPC_LEAF ) { CScdOPCTag* pTag = m_pBranch->m_tags.GetNext(m_pos); _tcscpy( m_name, pTag->m_name ); if( m_stringFilter.IsEmpty() || MatchPattern( m_name, m_stringFilter, FALSE) ) return m_name; } else if( m_type == OPC_FLAT ) { CString name = m_paths.GetNext( m_pos ); _tcscpy( m_name, name ); if( m_stringFilter.IsEmpty() || MatchPattern( m_name, m_stringFilter, FALSE) ) return m_name; } else m_pos = NULL; } return _T(""); } //******************************************************************* void ShellBrowser::Reset() { #if dbgOPCSrvr dbgpln("ShellBrowser::Reset(?)"); #endif CSLock wait( &m_parent->m_CS ); if( m_type==OPC_BRANCH ) m_pos = m_pBranch->m_branches.GetHeadPosition(); else if( m_type==OPC_LEAF ) m_pos = m_pBranch->m_tags.GetHeadPosition(); else if( m_type == OPC_FLAT ) m_pos = m_paths.GetHeadPosition(); } //******************************************************************* HRESULT ShellBrowser::GetAccessPaths( LPCTSTR name ) { name = GetItemID(name); _tcscpy(m_name, name); if(_tcscmp(m_name, "") != 0) return S_OK; else return E_INVALIDARG; } //******************************************************************* LPCTSTR ShellBrowser::NextAccessPath() { return _T(""); } #endif
[ [ [ 1, 164 ], [ 167, 489 ], [ 491, 1282 ], [ 1284, 1290 ], [ 1292, 1366 ], [ 1369, 1450 ], [ 1452, 1460 ], [ 1462, 1520 ], [ 1522, 1611 ], [ 1613, 1800 ] ], [ [ 165, 166 ], [ 490, 490 ], [ 1283, 1283 ], [ 1291, 1291 ], [ 1367, 1368 ], [ 1451, 1451 ], [ 1461, 1461 ], [ 1521, 1521 ], [ 1612, 1612 ] ] ]
73d1e0fbbed35328a382c64a961e8a7dec1adf06
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Stellar_/code/Render/coregraphics/memoryindexbufferloader.cc
f3e08343e83344d4f7395d4db981d5056e952e1d
[]
no_license
dzw/stellarengine
2b70ddefc2827be4f44ec6082201c955788a8a16
2a0a7db2e43c7c3519e79afa56db247f9708bc26
refs/heads/master
2016-09-01T21:12:36.888921
2008-12-12T12:40:37
2008-12-12T12:40:37
36,939,169
0
0
null
null
null
null
UTF-8
C++
false
false
538
cc
//------------------------------------------------------------------------------ // memoryindexbufferloader.cc // (C) 2007 Radon Labs GmbH //------------------------------------------------------------------------------ #include "stdneb.h" #include "coregraphics/memoryindexbufferloader.h" #if __WIN32__ namespace CoreGraphics { ImplementClass(CoreGraphics::MemoryIndexBufferLoader, 'MIBL', Direct3D9::D3D9MemoryIndexBufferLoader); } #else #error "MemoryIndexBufferLoader class not implemented on this platform!" #endif
[ "ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38" ]
[ [ [ 1, 15 ] ] ]
7faebc07dfed05da444469cb7bebd8347e79a0b6
bdb8fc8eb5edc84cf92ba80b8541ba2b6c2b0918
/TPs CPOO/Gareth & Maxime/Projet/CanonNoir/CanonNoirLib/GeneratedCode/EtatTir.h
9174a91cfaefdcea538f1a1cefa3e745520d1120
[]
no_license
Issam-Engineer/tp4infoinsa
3538644b40d19375b6bb25f030580004ed4a056d
1576c31862ffbc048890e72a81efa11dba16338b
refs/heads/master
2021-01-10T17:53:31.102683
2011-01-27T07:46:51
2011-01-27T07:46:51
55,446,817
0
0
null
null
null
null
UTF-8
C++
false
false
791
h
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /// <remarks>execute() => Ouvre une fenêtre, lance la selection de la puissance et de l'angle du tir, puis créer le tir grace a la fonction du canon</remarks> class EtatTir : public Etat { private : protected : Moteur motor; object puissance : int; object angle; bool Duel; public : private : protected : public : virtual void tirCanon(); virtual void init(int p, int a); virtual void execute(); };
[ "havez.maxime.01@9f3b02c3-fd90-5378-97a3-836ae78947c6" ]
[ [ [ 1, 37 ] ] ]
3ff2cbf1c26e4cf5d579745af433de419c083941
076413cfd054131591ae7b4ef0b769c48b6d967b
/tetris/TetrominoO.h
31071050b5e3b0039a9d38206bdd9c673975ba0d
[ "MIT" ]
permissive
oliverzheng/tetris
9ef134266ea528303f9fb6b8c28095575ef7b882
8a0c629e7378fd90c6b6f40a904b58e7110c4040
refs/heads/master
2020-06-03T15:08:26.444621
2010-02-02T03:54:40
2010-02-02T03:54:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,626
h
/****************************************************************************** TetrominoO.h Created for: Tetris Copyright (C) 2006-2007 Oliver Zheng. All rights reserved. No part of this software may be used or reproduced in any form by any means without prior written permission. - - - - Inherited from Tetromino ******************************************************************************/ #include "Tetromino.h" class TetrominoO : public Tetromino { Block* blocks; Block* blocks_buffer; static const int block_count = 4; static const blockColor block_color = BLUE; int rotation_state; static const int rotation_count = 1; // can't be 0 since array size > 0 static int setup_positions_x[block_count]; static int setup_positions_y[block_count]; static int next_positions_x[block_count]; static int next_positions_y[block_count]; // relative positions that each block should move to static int rotation_positions_x[rotation_count][block_count]; static int rotation_positions_y[rotation_count][block_count]; public: TetrominoO(); ~TetrominoO(); bool setup(void); void nextSetup(void); int getBlockCount(void) const { return block_count; }; Block* getBlocks(void) const { return blocks; }; Block* getBlocksBuffer(void) const { return blocks_buffer; }; blockColor getBlockColor(void) const { return block_color; }; int getRotationState(void) const { return rotation_state; }; int getRotationCount(void) const { return rotation_count; }; void setRotationState(int s) { rotation_state = s; }; void rotate_map(void); };
[ [ [ 1, 57 ] ] ]
c2b4d555c198d6988a96ebbb630984a66fdc5d88
3856c39683bdecc34190b30c6ad7d93f50dce728
/LastProject/Source/Sliding.cpp
1e63fe0a178aed4c27bb659991236b7e4dc82ff2
[]
no_license
yoonhada/nlinelast
7ddcc28f0b60897271e4d869f92368b22a80dd48
5df3b6cec296ce09e35ff0ccd166a6937ddb2157
refs/heads/master
2021-01-20T09:07:11.577111
2011-12-21T22:12:36
2011-12-21T22:12:36
34,231,967
0
0
null
null
null
null
UHC
C++
false
false
1,247
cpp
#include "stdafx.h" #include "Sliding.h" #include "Stiffen.h" #include "Monster.h" Sliding* Sliding::GetInstance() { static Sliding Instance; return &Instance; } VOID Sliding::Enter( CMonster* a_pMonster ) { // Sliding 애니메이션으로 변경 a_pMonster->ChangeAnimation( CMonster::ANIM_SLIDING ); #ifdef _DEBUG //CDebugConsole::GetInstance()->Messagef( L"Sliding : ANIM_SLIDING \n" ); #endif } VOID Sliding::Execute( CMonster* a_pMonster ) { // 사운드 if( a_pMonster->Get_MonsterNumber() == 2 ) { a_pMonster->Set_UpdateSoundTime(); FLOAT fSoundTime = a_pMonster->Get_SoundTime(); if( fSoundTime >= 1.0f ) { a_pMonster->Set_ClearSoundTime(); CSound::GetInstance()->PlayEffect( CSound::EFFECT_CLOWN_DOWN ); // 공격 충돌 박스 생성 a_pMonster->CreateAttackBoundBox(); } } if( a_pMonster->Get_AnimationEndCheck() == FALSE ) { a_pMonster->Set_ClearSoundTime(); // 경직 상태로 a_pMonster->GetFSM()->ChangeState( Stiffen::GetInstance() ); /* if( a_pMonster->Get_MonsterNumber() == 2 ) { CSound::GetInstance()->PlayEffect( CSound::EFFECT_CLOWN_DOWN ); }*/ } } VOID Sliding::Exit( CMonster* a_pMonster ) { }
[ "[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0", "[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0" ]
[ [ [ 1, 21 ], [ 23, 63 ] ], [ [ 22, 22 ] ] ]
d2313e11920f37320f307617d81c8971f300e353
e1f7c2f6dd66916fe5b562d9dd4c0a5925197ec4
/Engine/Project/src/AGCamera.cpp
2d4e4c0bd7bfd5755dc569ff83de3d49dc614a2a
[]
no_license
OtterOrder/agengineproject
de990ad91885b54a0c63adf66ff2ecc113e0109d
0b92a590af4142369e2946f692d5f30a06d32135
refs/heads/master
2020-05-27T07:44:25.593878
2011-05-01T14:52:05
2011-05-01T14:52:05
32,115,301
0
0
null
null
null
null
UTF-8
C++
false
false
472
cpp
#include "AGCamera.h" //------------------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------------------ AGCamera::AGCamera() { } //------------------------------------------------------------------------------------------------------------------------------ AGCamera::~AGCamera() { }
[ "alban.chagnoleau@fe70d4ac-e33c-11de-8d18-5b59c22968bc" ]
[ [ [ 1, 12 ] ] ]
563d0078053802aff32478e0771fbe578c6d48d6
e6960d26699857b7eb203ab7847ad1f385fc99f9
/src/OBJECTS.CC
9ace17929d34700536bb1392ba0de5fb0ed6bfaf
[]
no_license
tomekc/raycaster3d
7d74990379969cc0b328728df1b4b83637bcb893
4a0935458e4b180eb016a3631fa1bdf5a45ced42
refs/heads/master
2020-05-29T11:16:06.157909
2011-08-19T11:48:47
2011-08-19T11:48:47
2,233,237
1
1
null
null
null
null
UTF-8
C++
false
false
3,527
cc
#include "game.h" #include "defs.h" #include "fixed.h" //=========================================================================== // // ACTOR OBJECT // //=========================================================================== ActorObj::ActorObj (Game *gam) { parent = gam; objtype = o_actor; } void ActorObj::position (int x, int y, int a) { xpos = x; ypos = y; angle = a & (ANGLES-1); gridx = x >> GRIDSHIFT; gridy = y >> GRIDSHIFT; } void ActorObj::rotate (int a) { angle += a; angle &= (ANGLES-1); } // funkcja check Move zwraca TRUE, jesli ruch jest poprawny int ActorObj::checkMove (int x,int y) { int xl,xh,yl,yh; int cx,cy; xl = (x - PLAYERSIZE)>> GRIDSHIFT; yl = (y - PLAYERSIZE)>> GRIDSHIFT; xh = (x + PLAYERSIZE)>> GRIDSHIFT; yh = (y + PLAYERSIZE)>> GRIDSHIFT; // sprawdz czy wlazi na sciane for ( cx=xl; cx<=xh; cx++ ) { for ( cy=yl; cy<=yh; cy++ ) { if ( parent->tileat(cx,cy) ) return FALSE; } } return TRUE; } void ActorObj::move (int speed) { int dx,dy; dx = mnoz( speed, cosinus[angle] ); dy = mnoz( speed, sinus[angle] ); if ( checkMove(xpos+dx, ypos+dy) ) { xpos += dx; ypos += dy; return; } // sprawdzenie, czy jest mozliwy ruch po chociaz jednej osi if ( checkMove(xpos+dx, ypos) ) { xpos += dx; return; } if ( checkMove(xpos, ypos+dy) ) { ypos += dy; return; } } void ActorObj::strafe (int speed) { } //=========================================================================== // // PLAYER OBJECT // //=========================================================================== PlayerObj::PlayerObj (Game *g) : ActorObj(g) { objtype = o_player; fisheye = pixdelta = NULL; double_buffer = NULL; } PlayerObj::~PlayerObj () { } void PlayerObj::destroy_view () { delete [] fisheye; delete [] pixdelta; destroy_bitmap (double_buffer); } void PlayerObj::init_view (int x,int y,int w,int h) { view_x = x; view_y = y; view_w = w; view_h = h; destroy_view (); // zniszcz stary wju double_buffer = create_bitmap (w,h); if ( double_buffer == NULL ) { Error ("PlayerObj: not enough memory for double buffer."); } fisheye = new int[w]; pixdelta = new int[w]; generateViewTables (w, fisheye, pixdelta); } void PlayerObj::render () { clear (double_buffer); fisheye_table = fisheye; pixel_delta = pixdelta; DC_ScreenSetup (view_w,view_h/2,double_buffer->dat); parent->draw (this); } void PlayerObj::toscreen () { blit (double_buffer, screen, 0,0, view_x, view_y, view_w, view_h ); } //=========================================================================== // // DOOR OBJECT // //=========================================================================== DoorObj::DoorObj (Game *g, int x, int y, doortype_t typ) { parent = g; objtype = o_door; state = d_closed; gridx = x; gridy = y; type = typ; pos = 63; } inline void DoorObj::open () { if ( d_open || d_locked ) return; state = d_opening; } inline void DoorObj::close () { if ( d_closed || d_locked ) return; state = d_closing; } void DoorObj::act () { switch ( state ) { case d_opening: if (pos>0) pos--; else state = d_open; case d_closing: if (pos<63) pos++; else state = d_closed; } }
[ [ [ 1, 184 ] ] ]
100309531563b2f6ec4081e2f8a83a32f443e0e5
cc336f796b029620d6828804a866824daa6cc2e0
/libexif/IptcParse.cpp
3ae31d0a897894fcd79aac0b9aad812f660e8899
[]
no_license
tokyovigilante/xbmc-sources-fork
84fa1a4b6fec5570ce37a69d667e9b48974e3dc3
ac3c6ef8c567f1eeb750ce6e74c63c2d53fcde11
refs/heads/master
2021-01-19T10:11:37.336476
2009-03-09T20:33:58
2009-03-09T20:33:58
29,232
2
0
null
null
null
null
UTF-8
C++
false
false
7,810
cpp
/* * Copyright (C) 2005-2007 Team XboxMediaCenter * http://www.xboxmediacenter.com * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Make; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ //-------------------------------------------------------------------------- // Module to pull IPTC information out of various types of digital images. //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Process IPTC data. //-------------------------------------------------------------------------- #ifndef _LINUX #include <windows.h> #else #include <string.h> #define min(a,b) (a)>(b)?(b):(a) #endif #include <stdio.h> #include "IptcParse.h" #include "ExifParse.h" // Supported IPTC entry types #define IPTC_SUPLEMENTAL_CATEGORIES 0x14 #define IPTC_KEYWORDS 0x19 #define IPTC_CAPTION 0x78 #define IPTC_AUTHOR 0x7A #define IPTC_HEADLINE 0x69 #define IPTC_SPECIAL_INSTRUCTIONS 0x28 #define IPTC_CATEGORY 0x0F #define IPTC_BYLINE 0x50 #define IPTC_BYLINE_TITLE 0x55 #define IPTC_CREDIT 0x6E #define IPTC_SOURCE 0x73 #define IPTC_COPYRIGHT_NOTICE 0x74 #define IPTC_OBJECT_NAME 0x05 #define IPTC_CITY 0x5A #define IPTC_STATE 0x5F #define IPTC_COUNTRY 0x65 #define IPTC_TRANSMISSION_REFERENCE 0x67 #define IPTC_DATE 0x37 #define IPTC_COPYRIGHT 0x0A #define IPTC_COUNTRY_CODE 0x64 #define IPTC_REFERENCE_SERVICE 0x2D //-------------------------------------------------------------------------- // Process IPTC marker. Return FALSE if unable to process marker. // // IPTC block consists of: // - Marker: 1 byte (0xED) // - Block length: 2 bytes // - IPTC Signature: 14 bytes ("Photoshop 3.0\0") // - 8BIM Signature 4 bytes ("8BIM") // - IPTC Block start 2 bytes (0x04, 0x04) // - IPTC Header length 1 byte // - IPTC header Header is padded to even length, counting the length byte // - Length 4 bytes // - IPTC Data which consists of a number of entries, each of which has the following format: // - Signature 2 bytes (0x1C02) // - Entry type 1 byte (for defined entry types, see #defines above) // - entry length 2 bytes // - entry data 'entry length' bytes // //-------------------------------------------------------------------------- bool CIptcParse::Process (const unsigned char* const Data, const unsigned short itemlen, IPTCInfo_t *info) { if (!info) return false; const char IptcSignature1[] = "Photoshop 3.0"; const char IptcSignature2[] = "8BIM"; const char IptcSignature3[] = {0x04, 0x04}; // Check IPTC signatures char* pos = (char*)(Data + sizeof(short)); // position data pointer after length field if (memcmp(pos, IptcSignature1, strlen(IptcSignature1)) != 0) return false; pos += strlen(IptcSignature1) + 1; // move data pointer to the next field if (memcmp(pos, IptcSignature2, strlen(IptcSignature2)) != 0) return false; pos += strlen(IptcSignature2); // move data pointer to the next field if (memcmp(pos, IptcSignature3, sizeof(IptcSignature3)) != 0) return false; pos += sizeof(IptcSignature3); // move data pointer to the next field // IPTC section found // Skip header unsigned char headerLen = *pos++; // get header length and move data pointer to the next field pos += headerLen + 1 - (headerLen % 2); // move data pointer to the next field (Header is padded to even length, counting the length byte) // Get length (Motorola format) unsigned long length = CExifParse::Get32(pos); pos += sizeof(long); // move data pointer to the next field // Now read IPTC data while (pos < (char*)(Data + itemlen-5)) { short signature = (*pos << 8) + (*(pos+1)); pos += sizeof(short); if (signature != 0x1C02) break; unsigned char type = *pos++; unsigned short length = (*pos << 8) + (*(pos+1)); pos += sizeof(short); // Skip tag length // Process tag here char *tag = NULL; switch (type) { case IPTC_SUPLEMENTAL_CATEGORIES: tag = info->SupplementalCategories; break; case IPTC_KEYWORDS: tag = info->Keywords; break; case IPTC_CAPTION: tag = info->Caption; break; case IPTC_AUTHOR: tag = info->Author; break; case IPTC_HEADLINE: tag = info->Headline; break; case IPTC_SPECIAL_INSTRUCTIONS: tag = info->SpecialInstructions; break; case IPTC_CATEGORY: tag = info->Category; break; case IPTC_BYLINE: tag = info->Byline; break; case IPTC_BYLINE_TITLE: tag = info->BylineTitle; break; case IPTC_CREDIT: tag = info->Credit; break; case IPTC_SOURCE: tag = info->Source; break; case IPTC_COPYRIGHT_NOTICE: tag = info->CopyrightNotice; break; case IPTC_OBJECT_NAME: tag = info->ObjectName; break; case IPTC_CITY: tag = info->City; break; case IPTC_STATE: tag = info->State; break; case IPTC_COUNTRY: tag = info->Country; break; case IPTC_TRANSMISSION_REFERENCE: tag = info->TransmissionReference; break; case IPTC_DATE: tag = info->Date; break; case IPTC_COPYRIGHT: tag = info->Copyright; break; case IPTC_REFERENCE_SERVICE: tag = info->ReferenceService; break; case IPTC_COUNTRY_CODE: tag = info->CountryCode; break; default: printf("IptcParse: Unrecognised IPTC tag: 0x%02x", type); break; } if (tag) { if (type != IPTC_KEYWORDS || *tag == 0) { strncpy(tag, pos, min(length, MAX_IPTC_STRING - 1)); tag[min(length, MAX_IPTC_STRING - 1)] = 0; } else if (type == IPTC_KEYWORDS) { // there may be multiple keywords - lets join them size_t maxLen = MAX_IPTC_STRING - strlen(tag); if (maxLen > 2) strcat(tag, ", "); strncat(tag, pos, min(length, MAX_IPTC_STRING - maxLen - 3)); } /* if (id == SLIDE_IPTC_CAPTION) { CExifParse::FixComment(m_IptcInfo[id]); // Ensure comment is printable }*/ } pos += length; } return true; }
[ "jmarshallnz@568bbfeb-2a22-0410-94d2-cc84cf5bfa90", "spiff_@568bbfeb-2a22-0410-94d2-cc84cf5bfa90" ]
[ [ [ 1, 28 ], [ 30, 30 ], [ 35, 178 ] ], [ [ 29, 29 ], [ 31, 34 ] ] ]
52ef7ede2a5f4d8d4a32462ca78bff49e8293f7f
990e19b7ae3d9bd694ebeae175c50be589abc815
/src/cwapp/FontMgr.H
023cc15623c3322293994ec764377b4372179762
[]
no_license
shadoof/CW2
566b43cc2bdea2c86bd1ccd1e7b7e7cd85b8f4f5
a3986cb28270a702402c197cdb16373bf74b9d03
refs/heads/master
2020-05-16T23:39:56.007788
2011-12-08T06:10:22
2011-12-08T06:10:22
2,389,647
1
0
null
null
null
null
UTF-8
C++
false
false
810
h
#ifndef _FONT_H_ #define _FONT_H_ #include "main.h" #include <FTGLExtrdFont.h> #include <FTGLOutlineFont.h> #include <FTGLPolygonFont.h> #include <FTGLTextureFont.h> #include <FTGLPixmapFont.h> #include <FTGLBitmapFont.h> #include <FTGlyph.h> #include <FTVectoriser.h> #include <FTPoint.h> //=========================================== struct FontEntry { string name; float depth; FTFont* the_font; bool operator==(const FontEntry& font) const { return (name == font.name) && fuzzyEq(depth, font.depth); } }; //=========================================== class FontMgr { public: void close(); FontEntry get_font(const string& filename, float depth = 0); FTFont* load_font(const FontEntry& entry); private: Array<FontEntry> font_entries; }; #endif
[ [ [ 1, 39 ] ] ]
efe7ecc1acde67f1eb0016c94eadf47c2c8a7920
d9a78f212155bb978f5ac27d30eb0489bca87c3f
/PB/src/PbFt/GeneratedFiles/Debug/moc_ftlist.cpp
d646824344d6ce5c187adae512b243b5c5839237
[]
no_license
marchon/pokerbridge
1ed4a6a521f8644dcd0b6ec66a1ac46879b8473c
97d42ef318bf08f3bc0c0cb1d95bd31eb2a3a8a9
refs/heads/master
2021-01-10T07:15:26.496252
2010-05-17T20:01:29
2010-05-17T20:01:29
36,398,892
0
0
null
null
null
null
UTF-8
C++
false
false
4,207
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'ftlist.h' ** ** Created: Wed 31. Mar 16:08:18 2010 ** by: The Qt Meta Object Compiler version 61 (Qt 4.5.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "stdafx.h" #include "..\..\ftlist.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'ftlist.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 61 #error "This file was generated using the moc from 4.5.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_FTLists[] = { // content: 2, // revision 0, // classname 0, 0, // classinfo 2, 12, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors // signals: signature, parameters, type, tag, flags 14, 9, 8, 8, 0x05, 40, 9, 8, 8, 0x05, 0 // eod }; static const char qt_meta_stringdata_FTLists[] = { "FTLists\0\0list\0listUpdatedEvent(FTList*)\0" "paintDoneEvent(FTList*)\0" }; const QMetaObject FTLists::staticMetaObject = { { &FTWidgetHook::staticMetaObject, qt_meta_stringdata_FTLists, qt_meta_data_FTLists, 0 } }; const QMetaObject *FTLists::metaObject() const { return &staticMetaObject; } void *FTLists::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_FTLists)) return static_cast<void*>(const_cast< FTLists*>(this)); return FTWidgetHook::qt_metacast(_clname); } int FTLists::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = FTWidgetHook::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: listUpdatedEvent((*reinterpret_cast< FTList*(*)>(_a[1]))); break; case 1: paintDoneEvent((*reinterpret_cast< FTList*(*)>(_a[1]))); break; default: ; } _id -= 2; } return _id; } // SIGNAL 0 void FTLists::listUpdatedEvent(FTList * _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void FTLists::paintDoneEvent(FTList * _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } static const uint qt_meta_data_FTList[] = { // content: 2, // revision 0, // classname 0, 0, // classinfo 1, 12, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors // signals: signature, parameters, type, tag, flags 8, 7, 7, 7, 0x05, 0 // eod }; static const char qt_meta_stringdata_FTList[] = { "FTList\0\0listUpdatedEvent()\0" }; const QMetaObject FTList::staticMetaObject = { { &FTWidgetHook::staticMetaObject, qt_meta_stringdata_FTList, qt_meta_data_FTList, 0 } }; const QMetaObject *FTList::metaObject() const { return &staticMetaObject; } void *FTList::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_FTList)) return static_cast<void*>(const_cast< FTList*>(this)); return FTWidgetHook::qt_metacast(_clname); } int FTList::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = FTWidgetHook::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: listUpdatedEvent(); break; default: ; } _id -= 1; } return _id; } // SIGNAL 0 void FTList::listUpdatedEvent() { QMetaObject::activate(this, &staticMetaObject, 0, 0); } QT_END_MOC_NAMESPACE
[ "[email protected]", "mikhail.mitkevich@a5377438-2eb2-11df-b28a-19025b8c0740" ]
[ [ [ 1, 3 ], [ 5, 26 ], [ 28, 33 ], [ 35, 40 ], [ 42, 69 ], [ 71, 72 ], [ 74, 83 ], [ 91, 96 ], [ 98, 108 ], [ 110, 139 ], [ 141, 150 ] ], [ [ 4, 4 ], [ 27, 27 ], [ 34, 34 ], [ 41, 41 ], [ 70, 70 ], [ 73, 73 ], [ 84, 90 ], [ 97, 97 ], [ 109, 109 ], [ 140, 140 ] ] ]
2e9de0c0640c78b7e48d1eaea6b2615aa03c82cc
aa5491d8b31750da743472562e85dd4987f1258a
/Main/client/game/game.h
9af81193ffd8fde027c97d26cb5ccd02f3f0a75b
[]
no_license
LBRGeorge/jmnvc
d841ad694eaa761d0a45ab95b210758c50750d17
064402f0a9f1536229b99cf45f6e7536e1ae7bb5
refs/heads/master
2016-08-04T03:12:18.402941
2009-05-31T18:40:42
2009-05-31T18:40:42
39,416,169
2
0
null
null
null
null
UTF-8
C++
false
false
2,014
h
#pragma once #include "address.h" #include "common.h" #include "vehicle.h" #include "playerped.h" #include "camera.h" #include "scripting.h" //----------------------------------------------------------- class CGame { public: CPlayerPed *NewPlayer(int iPlayerID, int iModel,float fPosX,float fPosY,float fPosZ,float fRotation); CVehicle *NewVehicle(int iType,float fPosX,float fPosY,float fPosZ,float fRotation); int GetWeaponModelFromWeapon(int iWeaponID); void ToggleKeyInputsDisabled(BOOL bDisable); void StartGame(BOOL NewspapersDisabled); BOOL IsMenuActive(); void RequestModel(int iModelID); void LoadRequestedModels(); BOOL IsModelLoaded(int iModelID); void DisplayHud(BOOL bSwitch); void ToggleFrameLimiterState(BOOL bState); DWORD GetD3DDevice() { return *(DWORD *)ADDR_ID3D8DEVICE; }; void SetD3DDevice(DWORD pD3DDevice) { *(DWORD *)ADDR_ID3D8DEVICE = pD3DDevice; }; DWORD GetD3D() { return *(DWORD *)ADDR_ID3D8DEVICE; }; void SetD3D(DWORD pD3D) { *(DWORD *)ADDR_ID3D8 = pD3D; }; HWND GetMainWindowHwnd() { return *(HWND *)ADDR_HWND; }; void DisplayTextMessage(PCHAR szText); void ChangeTime(int iHour, int iMinute); void SelectInterior(int iInterior); //----------------------------------------------------------- CPlayerPed *FindPlayerPed() { if(m_pInternalPlayer==NULL) m_pInternalPlayer = new CPlayerPed(); return m_pInternalPlayer; }; CCamera *GetCamera() { return m_pInternalCamera; }; //----------------------------------------------------------- void EnablePassengerEngineAudio() { *(BYTE *)0x5F2175 = 0x3B; *(BYTE *)0x5F2176 = 0xC2; }; void DisablePassengerEngineAudio() { *(BYTE *)0x5F2175 = 0x39; *(BYTE *)0x5F2176 = 0xF0; }; //----------------------------------------------------------- CGame(); ~CGame() {}; private: CCamera *m_pInternalCamera; CPlayerPed *m_pInternalPlayer; }; //-----------------------------------------------------------
[ "jacks.mini.net@45e629aa-34f5-11de-82fb-7f665ef830f7" ]
[ [ [ 1, 72 ] ] ]
6cdd0b84f567663b62b6e70f4fdb973369c911a3
b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2
/source/graphics/core/win32/direct3d09/texture2dd3d09.h
7087f1832cdaf6e26c876421832515fb4f294534
[]
no_license
roxygen/maid2
230319e05d6d6e2f345eda4c4d9d430fae574422
455b6b57c4e08f3678948827d074385dbc6c3f58
refs/heads/master
2021-01-23T17:19:44.876818
2010-07-02T02:43:45
2010-07-02T02:43:45
38,671,921
0
0
null
null
null
null
UTF-8
C++
false
false
863
h
#ifndef maid2_graphics_core_texture2dd3d09_h #define maid2_graphics_core_texture2dd3d09_h #include"../../../../config/define.h" #include"../../itexture2d.h" #include"common.h" #include"id3d09object.h" namespace Maid { namespace Graphics { class Texture2DD3D09 : public ITexture2D , public ID3D09Object { public: Texture2DD3D09( const CREATERETEXTURE2DPARAM& param, const SPD3D09TEXTURE& pTex ); Texture2DD3D09( const CREATERETEXTURE2DPARAM& param, const SPD3D09TEXTURE& pTex, const SPD3D09SURFACE& pSurf ); Texture2DD3D09( const CREATERETEXTURE2DPARAM& param, const SPD3D09SURFACE& pSurf, bool sw ); SPD3D09TEXTURE pTexture; SPD3D09SURFACE pSurface; const bool IsSwapChainSurface; protected: void Escape(); void Restore( DeviceD3D09& Device ); }; }} #endif
[ [ [ 1, 34 ] ] ]