Example #1
0
main(int argc, char *argv[])
{
    IPaddress serverIP;
    int i;

        /* Initialize SDL */
        if ( SDL_Init(0) < 0 ) {
                fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
                exit(1);
    }

    /* Initialize the network */
    if ( SDLNet_Init() < 0 ) {
        fprintf(stderr, "Couldn't initialize net: %s\n",
                        SDLNet_GetError());
        SDL_Quit();
        exit(1);
    }

    /* Initialize the channels */
    for ( i=0; i<CHAT_MAXPEOPLE; ++i ) {
        people[i].active = 0;
        people[i].sock = NULL;
    }

    /* Allocate the socket set */
    socketset = SDLNet_AllocSocketSet(CHAT_MAXPEOPLE+1);
    if ( socketset == NULL ) {
        fprintf(stderr, "Couldn't create socket set: %s\n",
                        SDLNet_GetError());
        cleanup(2);
    }

    /* Create the server socket */
    SDLNet_ResolveHost(&serverIP, NULL, CHAT_PORT);
printf("Server IP: %x, %d\n", serverIP.host, serverIP.port);
    servsock = SDLNet_TCP_Open(&serverIP);
    if ( servsock == NULL ) {
        fprintf(stderr, "Couldn't create server socket: %s\n",
                        SDLNet_GetError());
        cleanup(2);
    }
    SDLNet_TCP_AddSocket(socketset, servsock);

    /* Loop, waiting for network events */
    for ( ; ; ) {
        /* Wait for events */
        SDLNet_CheckSockets(socketset, ~0);

        /* Check for new connections */
        if ( SDLNet_SocketReady(servsock) ) {
            HandleServer();
        }

        /* Check for events on existing clients */
        for ( i=0; i<CHAT_MAXPEOPLE; ++i ) {
            if ( SDLNet_SocketReady(people[i].sock) ) {
                HandleClient(i);
            }
        }
    }
    cleanup(0);

    /* Not reached, but fixes compiler warnings */
    return 0;
}
Example #2
0
//-----------------------------------------------------------------------------
int main(int argc, char *argv[]) {
	libInit();

	// NOTE: open socket file descriptor
	serverFD = SDLNet_UDP_Open(3490);
	if(!serverFD) {
		fprintf(stderr, "SDLNet_UDP_Open: %s\n", SDLNet_GetError());
		libQuit();
		return -1;
	}

	// NOTE: setup a socket set
	socketSet = SDLNet_AllocSocketSet(1);
	SDLNet_UDP_AddSocket(socketSet, serverFD);
	printf("\nServer open on port: %d\n\n", 3490);

	// NOTE: initialize the player manager
	plManager = initPlayerManager("diamond_collector.db");

	/*
		LISTEN FOR PACKETS
	*/

	for(;;) {
		// NOTE: wait for a connection
		int n = SDLNet_CheckSockets(socketSet, 0);

		if(n==-1) {
			fprintf(stderr, "SDLNet_CheckSockets: %s\n", SDLNet_GetError());
			break;
		} if(!n) {
			// NOTE: if the server doesn't have anything to do then run through
			// a few regular routines
			switch(serverState) {
				case 0x00: {
					if((time(NULL)-lastTimePingsWentOut)>20) {
						// NOTE: if the server is idle in its freetime then start sending out
						// ping packets for the client to respond to
						serverState = 0x01;
						lastTimePingsWentOut = time(NULL);
					}
				} break;
				case 0x01: {
					if(waitingForPong) {
						if(!plManager->pl_indMask[nodeToPing][playerToPing]) {
							playerToPing++;
							waitingForPong = SDL_FALSE;
						} else if((time(NULL)-timeOfPing)>120) {
							// NOTE: if we hear nothing back after 5 secs then disconnect the player
							DB_Player *pl = &plManager->pl_dbInfo[nodeToPing][playerToPing];
							printf("player %s didn't respond to ping logging them out.\n", pl->username);

							// NOTE: set the player state and log the player out
							pl->state = 0x00;

							// NOTE: send a packet out to everyone on this node
							// letting them know that the player is leaving.
							UDPpacket _packet = {};

							/*
							- flag (1) 0x05
							- id   (4)
							====== (5)
							*/

							_packet.maxlen = 0x05; // 5 bytes
							_packet.data = (uint8_t *)malloc(0x05);

							uint8_t offset = 0;

							memset(_packet.data+offset, 0x05, 1);
							offset += 1;
							memcpy(_packet.data+offset, &pl->id, 4);
							offset += 4;

							// NOTE: set the packet length to the offset point
							_packet.len = offset;

							// NOTE: send the packet out to everyone but the player disconnecting
							int i;
							for(i=0; i<PLAYER_MAX; i++) {
								if(!plManager->pl_indMask[pl->node][i])
									continue;

								_packet.address.host = plManager->pl_dbInfo[pl->node][i].host;
								_packet.address.port = plManager->pl_dbInfo[pl->node][i].port;

								if(!SDLNet_UDP_Send(serverFD, -1, &_packet))
									fprintf(stderr, "SDLNet_UDP_Send: %s\n", SDLNet_GetError());
							}

							// NOTE: free the packet
							free(_packet.data);

							// NOTE: save the new player state
							pl_save(plManager, pl);

							if(pl_removePlayer(plManager, pl) != -1) {
								printf("Logout success!\n");
							} else {
								// NOTE: player was never in the players array should
								// probably log this sort of thing
							}

							playerToPing++;
							waitingForPong = SDL_FALSE;
						} else {
							// TODO: keep sending the ping packet
						}
					} else {
						// NOTE: make sure there are people on this node - else go to the
						// next node
						int n = pl_numOnNode(plManager, nodeToPing);

						if(n <= 0) {
							nodeToPing++;
							playerToPing = 0;

							if(nodeToPing==NODE_MAX) {
								nodeToPing = 0;
								serverState = 0x00;
							}

							break;
						}

						// NOTE: if there isn't a player at this point in the pool then
						// go to the next point in the pool
						if(!plManager->pl_indMask[nodeToPing][playerToPing]) {
							playerToPing++;

							if(playerToPing == PLAYER_MAX) {

								nodeToPing++;
								playerToPing = 0;

								if(nodeToPing == NODE_MAX) {
									nodeToPing = 0;
									serverState = 0x00;
								}
							}

							break;
						}

						// NOTE: get the player and send out the ping
						DB_Player *pl = &plManager->pl_dbInfo[nodeToPing][playerToPing];

						// NOTE: send a ping packet
						uint8_t flag = 0x0A;
						UDPpacket _packet = {};

						_packet.data = &flag;

						_packet.len = 1;
						_packet.maxlen = 1;

						_packet.address.host = pl->host;
						_packet.address.port = pl->port;

						if(!SDLNet_UDP_Send(serverFD, -1, &_packet))
							fprintf(stderr, "SDLNet_UDP_Send: %s\n", SDLNet_GetError());

						timeOfPing = time(NULL);
						waitingForPong = SDL_TRUE;
					}
				} break;
			}
			continue;
		}

		// NOTE: does the server have packets waiting?
		if(SDLNet_SocketReady(serverFD)) {
			// NOTE: setup a packet which is big enough to store any client message
			UDPpacket packet;

			// NOTE: allocate space for packet
			packet.maxlen = 0xAA; // 170 bytes
			packet.data = (uint8_t *)malloc(0xAA);

			// NOTE: get the packet
			int recv = SDLNet_UDP_Recv(serverFD, &packet);
			if(!recv) {
				free(packet.data);
				continue;
			}

			// NOTE: read the flag for packet identity
			uint8_t flag = 0;
			uint32_t offset = 0;

			memcpy(&flag, packet.data, 1);
			offset += 1;

			// NOTE: process the packet
			switch(flag) {
				case 0x01: {

					net_login(plManager, &packet, &offset);

				} break;
				case 0x02: {
					
					net_logout(plManager, &packet, &offset);

				} break;
				case 0x07: {
					
					net_moveUp(plManager, &packet, &offset);

				} break;
				case 0x08: {
					
					net_moveDown(plManager, &packet, &offset);

				} break;
				case 0x09: {
					
					net_moveLeft(plManager, &packet, &offset);

				} break;
				case 0x0A: {
					
					net_moveRight(plManager, &packet, &offset);

				} break;
				case 0x0B: {

					net_sendOutPlInfo(plManager, &packet, &offset);
					
				} break;
				case 0x0C: {
					// NOTE: get the player which is logged in on the incoming address
					DB_Player *pl = pl_getDBInfo(plManager, packet.address);
					if(pl == NULL) break;

					// NOTE: need to make sure the pong is from the right player
					int ind = pl_getIndex(plManager, pl);

					// NOTE: player responding with a pong packet
					if(ind==playerToPing) {
						playerToPing++;
						waitingForPong = SDL_FALSE;
					}
				} break;
				case 0x0D: {
					
					net_sendOutNodeInfo(plManager, &packet, &offset);

				} break;
			}

			// NOTE: free the packet when done processing
			free(packet.data);
		}
	}

	// NOTE: free the player manager
	freePlayerManager(plManager);

	// NOTE: free socketset
	SDLNet_FreeSocketSet(socketSet);

	// NOTE: close the socket file descriptor
	SDLNet_UDP_Close(serverFD);

	libQuit();

	return 0;
}
Example #3
0
int main(int argc, char *argv[])
{
	UNUSED(argc);
	UNUSED(argv);

	if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) != 0)
	{
		fprintf(stderr, "Could not initialise SDL: %s\n", SDL_GetError());
		return -1;
	}
	if (SDLNet_Init() == -1)
	{
		fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
	}
	if (!SDL_SetVideoMode(320, 200, 0, 0))
	{
		fprintf(stderr, "Could not set video mode: %s\n", SDL_GetError());
		SDL_Quit();
		exit(-1);
	}

	ConfigLoadDefault(&gConfig);
	ConfigLoad(&gConfig, GetConfigFilePath(CONFIG_FILE));
	EventInit(&gEventHandlers, NULL, false);

	NetInputClient client;
	NetInputClientInit(&client);
	NetInputClientConnect(&client, 0x7F000001);	// localhost

	printf("Press esc to exit\n");

	Uint32 ticksNow = SDL_GetTicks();
	Uint32 ticksElapsed = 0;
	for (;;)
	{
		Uint32 ticksThen = ticksNow;
		ticksNow = SDL_GetTicks();
		ticksElapsed += ticksNow - ticksThen;
		if (ticksElapsed < 1000 / FPS_FRAMELIMIT)
		{
			SDL_Delay(1);
			debug(D_VERBOSE, "Delaying 1 ticksNow %u elapsed %u\n", ticksNow, ticksElapsed);
			continue;
		}
		EventPoll(&gEventHandlers, SDL_GetTicks());
		int cmd = GetOnePlayerCmd(
			&gEventHandlers,
			&gConfig.Input.PlayerKeys[0],
			false,
			INPUT_DEVICE_KEYBOARD,
			0);
		if (cmd)
		{
			printf("Sending %s + %s\n",
				CmdStr(cmd & (CMD_LEFT | CMD_RIGHT | CMD_UP | CMD_DOWN)),
				CmdStr(cmd & (CMD_BUTTON1 | CMD_BUTTON2 | CMD_BUTTON3 | CMD_BUTTON4 | CMD_ESC)));
			NetInputClientSend(&client, cmd);
		}

		// Check keyboard escape
		if (KeyIsPressed(&gEventHandlers.keyboard, SDLK_ESCAPE))
		{
			break;
		}

		ticksElapsed -= 1000 / FPS_FRAMELIMIT;
	}

	NetInputClientTerminate(&client);
	EventTerminate(&gEventHandlers);
	SDLNet_Quit();
	SDL_Quit();
	return 0;
}
Example #4
0
int main(int argc, char** argv)
{
  try {
    std::string port;
    CommandLine argp;

    argp.add_usage("[OPTIONS] PORT");
    argp.add_group("General:");
    argp.add_option('v', "version", "", "Print the netBrush server version");
    argp.add_option('h', "help", "", "Print this help");

    argp.parse_args(argc, argv);
    while(argp.next())
      {
        switch(argp.get_key())
          {
          case 'h':
            argp.print_help();
            return 0;
            break;

          case 'v':
            std::cout << "netBrush Server 0.1.0" << std::endl;
            return 0;
            break;

          case CommandLine::REST_ARG:
            if (!port.empty())
              {
                std::cout << "Invalid argument: " << argp.get_argument() << std::endl;
                return 1;
              }
            else
              {
                port = argp.get_argument();
              }
            break;
          }
      }

    if (port.empty())
      {
        argp.print_help();
        return 1;
      }

    if(SDL_Init(0)==-1) {
      printf("SDL_Init: %s\n", SDL_GetError());
      exit(1);
    }

    if(SDLNet_Init()==-1) {
      printf("SDLNet_Init: %s\n", SDLNet_GetError());
      exit(2);
    }

    atexit(SDL_Quit);
    atexit(SDLNet_Quit);

    std::ostringstream filename;
    filename << "sessions/session-" << time(NULL) << ".nbr";

    std::cout << "# writing log to " << filename.str() << std::endl;
    outfile = new std::ofstream(filename.str().c_str());

    if (argc == 2)
      {
        std::cout << "# listening on: " << port << std::endl;
        connect(atoi(port.c_str()));
      }
    else
      {
        std::cout << "Usage: " << argv[0] << " PORT" << std::endl;
      }

    outfile->close();
    delete outfile;
  } catch (std::exception& err) {
    std::cout << "Exception: " << err.what() << std::endl;
  }
  return 0;
}
Example #5
0
		if( (client_socket = SDLNet_TCP_Accept(net_server->Socket)) )
		{
			ConnectedClient *connected_client = new ConnectedClient( client_socket, net_server->UseOutThreads, net_server->NetRate, net_server->Precision );
			
			if( (remote_ip = SDLNet_TCP_GetPeerAddress(client_socket)) )
			{
				connected_client->IP = Endian::ReadBig32(&(remote_ip->host));
				connected_client->Port = Endian::ReadBig16(&(remote_ip->port));
				
				char cstr[ 1024 ] = "";
				snprintf( cstr, 1024, "Client connected: %i.%i.%i.%i:%i", (connected_client->IP & 0xFF000000) >> 24, (connected_client->IP & 0x00FF0000) >> 16, (connected_client->IP & 0x0000FF00) >> 8, connected_client->IP & 0x000000FF, connected_client->Port );
				Raptor::Server->ConsolePrint( cstr );
			}
			else
			{
				fprintf( stderr, "SDLNet_TCP_GetPeerAddress: %s\n", SDLNet_GetError() );
				Raptor::Server->ConsolePrint( "Client connected from unknown IP!\n" );
			}
			
			if( ! net_server->Lock.Lock() )
				fprintf( stderr, "NetServerThread: net_server->Lock.Lock: %s\n", SDL_GetError() );
			net_server->Clients.push_back( connected_client );
			if( ! net_server->Lock.Unlock() )
				fprintf( stderr, "NetServerThread: net_server->Lock.Unlock: %s\n", SDL_GetError() );
		}
		
		// Let the thread rest a bit.  This thread only handles new connections, so it can be a long delay.
		SDL_Delay( 100 );
	}
	
	// Set the thread pointer to NULL so we can delete the NetServer object.
Example #6
0
void Networking::Send(TCPsocket socket, char *msg, int len) {
        if (SDLNet_TCP_Send(socket, (void*)msg, len) < len) {
                printf("SDLNet_TCP_Send: %s\n", SDLNet_GetError());
        }
}
Example #7
0
int net_http_upload(const char* filename, char* fmt, ...) {

  va_list args;
  va_start(args, fmt);
  vsnprintf(url_buffer, 500, fmt, args);
  va_end(args);
  
  int parts = sscanf(url_buffer, "http://%[^/]%s", host_buffer, path_buffer);
  
  if (parts != 2) {
    warning("Couldn't resolve parts of URL '%s'", url_buffer);
    return HTTP_ERR_URL;
  }
  
  IPaddress ip;
  if ( SDLNet_ResolveHost(&ip, host_buffer, 80) == -1) {
    warning("Couldn't Resolve Host: %s", SDLNet_GetError());
    return HTTP_ERR_HOST;
  }

  TCPsocket sock = SDLNet_TCP_Open(&ip);
  
  if (!sock) {
    warning("Couldn't open socket: %s", SDLNet_GetError());
    return HTTP_ERR_SOCKET;
  }
  
  SDL_RWops* file = SDL_RWFromFile(filename, "r");
  
  if (file == NULL) {
    warning("Couldn't Open File '%s' to upload", filename);
    return HTTP_ERR_NOFILE;
  }
  
  size_t size = SDL_RWseek(file,0,SEEK_END);
  char* contents = malloc(size+1);
  contents[size] = '\0';
  
  SDL_RWseek(file, 0, SEEK_SET);
  SDL_RWread(file, contents, size, 1);
  SDL_RWclose(file);
  
  char sockbody[size + 1024 * 4];
  char sockheaders[1024*4];
  
  snprintf(sockbody,((size + 1024 * 4) - 1),
    "--CorangeUploadBoundary\r\n"
    "content-disposition: form-data; name=\"corangeupload\"; filename=\"%s\"\r\n"
    "Content-Type: text/plain\r\n"
    "\r\n"
    "%s\r\n"
    "--CorangeUploadBoundary--\r\n"
    "\r\n", filename, contents);
  
  snprintf(sockheaders,((1024 * 4) - 1),
    "POST %s HTTP/1.1\r\n"
    "Host: %s\r\n"
    "Content-Length: %i\r\n"
    "Content-Type: multipart/form-data; boundary=CorangeUploadBoundary\r\n"
    "\r\n" , path_buffer, host_buffer, (int)strlen(sockbody));
  
  int result = 0;
  
  result = SDLNet_TCP_Send(sock, sockheaders, strlen(sockheaders));
  if (result < strlen(sockheaders)) {
    warning("Error sending http request: %s", SDLNet_GetError());
    return HTTP_ERR_DATA;
  }

  result = SDLNet_TCP_Send(sock, sockbody, strlen(sockbody));
  if (result < strlen(sockbody)) {
    warning("Error sending http request: %s", SDLNet_GetError());
    return HTTP_ERR_DATA;
  }
  
  char line[1024];  
  while (SDLNet_TCP_RecvLine(sock, line, 1023)) {
    //debug("Recived: %s", line);
  }
  
  return HTTP_ERR_NONE;

}
Example #8
0
int main(int argc, char* argv[]) {

  bool running = true;
  int i, j, xfrog, yfrog, xfly, yfly, leech[MAX_PLAYERS], tadswim = 0, swavenum[MAX_PLAYERS], swave_clk[MAX_PLAYERS], cls, kk;
  float dist;
  int nfrogs = 7; // Number of frogs
  int sp = 1;    // Speed (1-3)
  int a_i = 3;  // AI (1-3)
  FILE *fp;

  // Open hiscores.txt

  if((fp = fopen("hiscores.txt","r")) == NULL) {
    printf("Can't find file: hiscores.txt\n");
    return 1;
  }

  for(kk = 0; kk < 32; kk++) {
    hiscores[kk].name = (char*)malloc(MAX_NAME_LENGTH*sizeof(char));
    hiscores[kk].time = 0;
  }

  
  int ret = 1;
  kk = 0;
  while(ret != EOF) {
    ret = fscanf(fp,"%s %d", hiscores[kk].name, &hiscores[kk].time);
    kk++;
  }

  // Close hiscores.txt
  fclose(fp);

  // Bubble sort
  for(i=0; i<31; i++) {
    for(j=31; j > i; j--) {
      if(hiscores[j].time > hiscores[j-1].time) {
	strcpy(buf,hiscores[j-1].name);
	kk = hiscores[j-1].time;
	strcpy(hiscores[j-1].name,hiscores[j].name);
	hiscores[j-1].time = hiscores[j].time;
	strcpy(hiscores[j].name,buf);
	hiscores[j].time = kk;
      }
    }
  }

  
#ifdef TADPOLE_COLLISIONS  

  int tempvel;
  int collisions[MAX_PLAYERS][MAX_PLAYERS];

  for(i=0;i<MAX_PLAYERS;i++) {
    for(j=0;j<MAX_PLAYERS;j++) {
      collisions[i][j] = 0;
    }
  }

#endif


  for(i=0;i<MAX_PLAYERS;i++) {
    leech[i] = 0;
    swavenum[i] = 0;
    swave_clk[i] = 0;
    leaderboard_rank[i] = -1;
  }
  
  int bwavenum = 0, bwave_clk, mm_clk = 0, suwavenum = 0, suwave_clk = 0;  // various wave clocks and wave counters (storing latest wave to be animated)

  int nherd[10], nflychasers = 0; // nherd[i] counts number of close frogs to ith frog in jumpstate 0.
  int tadflip = 0, mmtadx = SCREEN_WIDTH/2, mmtady = SCREEN_HEIGHT/2+BANNER_HEIGHT/2;

  float ran; // random number storing
  char Tadname[MAX_NAME_LENGTH];


  strcpy(Tadname,"Player_0"); // Name of local player, no spaces

  set_frogclips();
  set_tadclips();
  set_flyclips();
  set_swaveclips();
  set_bwaveclips();
  set_suwaveclips();
  
  Timer fps;  
  Timer gameclock;
  Timer flyspan;
  std::vector<Timer> warpspan(nfrogs);
  
//    Setting wave flags to 'not animate / done animation'

  for(j=0; j<NUMWAVES; j++) {
    nherd[j] = 0;
    for(kk=0; kk<MAX_PLAYERS; kk++) {
      smallwaves[kk][j][0] = 6;
    }
  }

  for(j=0; j<NUMWAVES; j++) {
    bigwaves[j][0] = 24;
    suwaves[j][0] = 24;
  }

  
  if (init() == false) return 1;

  if (load_files() == false) return 1;

  // Spawn Tadpole
  //  Tadpole myTad;
  std::vector<Tadpole> myTad(MAX_PLAYERS);


  // Spawn fly
  xfly = 10+drand48()*(SCREEN_WIDTH-LEADER_WIDTH-HISCORE_WIDTH-20)+LEADER_WIDTH;
  yfly = 10+drand48()*(SCREEN_HEIGHT-BANNER_HEIGHT-20) + BANNER_HEIGHT;
  Fly myfly( xfly, yfly );

  // Spawn Frogs
  std::vector<Frog> myfrogs(nfrogs);


  for(i = 0; i < nfrogs; i++ ) {
    xfrog = drand48()*(SCREEN_WIDTH-LEADER_WIDTH-HISCORE_WIDTH-20)+LEADER_WIDTH;
    yfrog = drand48()*(SCREEN_HEIGHT-BANNER_HEIGHT-20) + BANNER_HEIGHT;
    if(distance(xfrog, yfrog, mmtadx, mmtady) < (SCREEN_HEIGHT-BANNER_HEIGHT)/4) {
      i--;
    }
    myfrogs[i].Frog_set(xfrog, yfrog, sp, a_i);
  }


  for(i=0; i<nfrogs; i++)
    myfrogs[i].show(sp);

  myfly.show();


  if(SDL_Flip(screen) == -1) return 1;

  SDL_Delay(500);

  gameclock.start();
  
#ifdef PRINT_MESSAGES  
  printf("Tadpole server is up!\n");
#endif
  

#ifdef WITH_SOUND
//    if(Mix_PlayMusic(ambience, -1) == -1)
    if(Mix_FadeInMusic(ambience, -1, 2000) == -1)
	return 1;
#endif
  

  // Game Server loop
  while (running) {

    fps.start();

    // Listen for connections, argument 0 means no wait-time
    int numActiveSockets = SDLNet_CheckSockets(socketSet, 0);

    if(numActiveSockets > 0) {

      // Check help socket. If activity detected, then open temporary socket and dump help text. Then close socket.
      int helpSocketActivity = SDLNet_SocketReady(helpSocket);
      if(helpSocketActivity != 0) {
	TCPsocket tempSock = SDLNet_TCP_Accept(helpSocket);
	SDLNet_TCP_Send(tempSock,(void*)reply,strlen(reply)+1);
	// Close temporary connection
	SDLNet_TCP_Close(tempSock);
      }

      
      // Check if our server socket has received any data
      // Note: SocketReady can only be called on a socket which is part of a set and that has CheckSockets called on it (the set, that is)
      // SDLNet_SocketRead returns non-zero for activity, and zero is returned for no activity.
      int serverSocketActivity = SDLNet_SocketReady(serverSocket);
      // All server activity interpreted as request for TCP connection
      if(serverSocketActivity != 0) {
	// If we have room for more clients...
	if(ntads < MAX_PLAYERS) {
	  int freeSpot = -99;
	  for(int i = 0; i < MAX_PLAYERS; i++) {
	    if(!myTad[i].alive && !myTad[i].TCP_limbo) {
	      freeSpot = i;
	      break;
	    }
	  }
	  // Accept the client connection
	  myTad[freeSpot].socket = SDLNet_TCP_Accept(serverSocket);

	  // get clients IP
	  remoteip = SDLNet_TCP_GetPeerAddress(myTad[freeSpot].socket);
	  if(!remoteip) {
#ifdef SERVER_DEBUG
	    printf("SDLNet_TCP_GetPeerAddress: %s\n",SDLNet_GetError());
#endif
	    // No remote ip?! NO CONNECTION!
	    SDLNet_TCP_Close(myTad[freeSpot].socket);	  
	  } else {
#ifdef SERVER_DEBUG	  
	    ipaddr=SDL_SwapBE32(remoteip->host);
	    printf("Accepted a connection from %d.%d.%d.%d port %hu.",
		   ipaddr>>24,
		   (ipaddr>>16)&0xff,
		   (ipaddr>>8)&0xff,
		   ipaddr&0xff,
		   remoteip->port);
	    printf(" There are now %d client(s) online.\n",
		   ntads+1);
#endif
	    ntads++;
	    myTad[freeSpot].TCP_limbo = true;
	    // Add new client socket to socket set, to check activity
	    SDLNet_TCP_AddSocket(socketSet, myTad[freeSpot].socket);
	    // Send 'N' asking for name
	    strcpy(buf,"N");
	    SDLNet_TCP_Send(myTad[freeSpot].socket,(void*)buf,2);
	  }
	} else { // No new room for clients
#ifdef SERVER_DEBUG
	  printf("No room. Rejecting client.\n");
#endif
	  // Accept client connection to clear it from incoming list
	  TCPsocket tempSock = SDLNet_TCP_Accept(serverSocket);
	  // Send 'X' telling that there is no room
	  strcpy(buf,"X");
	  SDLNet_TCP_Send(tempSock,(void*)buf,2);
	  // Close temporary connection
	  SDLNet_TCP_Close(tempSock);
	}
      }
Example #9
0
connection accept_connection()
{
	if(!server_socket) {
		return 0;
	}

	// A connection isn't considered 'accepted' until it has sent its initial handshake.
	// The initial handshake is a 4 byte value, which is 0 for a new connection,
	// or the handle of the connection if it's trying to recover a lost connection.

	/**
	 * A list of all the sockets which have connected,
	 * but haven't had their initial handshake received.
	 */
	static std::vector<TCPsocket> pending_sockets;
	static SDLNet_SocketSet pending_socket_set = 0;

	const TCPsocket sock = SDLNet_TCP_Accept(server_socket);
	if(sock) {
#if !defined(_WIN32) && !defined(__WIN32__) && !defined (WIN32)
		_TCPsocket* raw_sock = reinterpret_cast<_TCPsocket*>(sock);
		int fd_flags = fcntl(raw_sock->channel, F_GETFD, 0);
		fd_flags |= FD_CLOEXEC;
		if (fcntl(raw_sock->channel, F_SETFD, fd_flags) == -1) {
			WRN_NW << "could not make socket " << sock << " close-on-exec: " << strerror(errno);
		} else {
			DBG_NW << "made socket " << sock << " close-on-exec\n";
		}
#endif

		DBG_NW << "received connection. Pending handshake...\n";

		if(pending_socket_set == 0) {
			pending_socket_set = SDLNet_AllocSocketSet(32);
		}

		if(pending_socket_set != 0) {
			int res = SDLNet_TCP_AddSocket(pending_socket_set,sock);

			if (res != -1) {
				pending_sockets.push_back(sock);
			} else {
				ERR_NW << "Pending socket set is full! Disconnecting " << sock << " connection" << std::endl;
				ERR_NW << "SDLNet_GetError(): " << SDLNet_GetError() << std::endl;

				SDLNet_TCP_Close(sock);
			}
		} else {
			ERR_NW << "Error in SDLNet_AllocSocketSet" << std::endl;
		}
	}

	if(pending_socket_set == 0) {
		return 0;
	}

	const int set_res = SDLNet_CheckSockets(pending_socket_set,0);
	if(set_res <= 0) {
		return 0;
	}

	return accept_connection_pending(pending_sockets, pending_socket_set);
}
Server::Server(int width, int height){
    
    windowWidth  = width;
    windowHeight = height;
    
    // initialize SDL
    if (SDL_Init(SDL_INIT_EVERYTHING) < 0){
        printf("SDL could not initialize! SDL_Error %s\n", SDL_GetError());
    } else {
        // initialize SDLnet
        if (SDLNet_Init() < 0){
            printf("SDLNet could not initilaize! SDLNet_Error %s\n", SDLNet_GetError());
        } else {
            // create window
            window = SDL_CreateWindow("Utz Stauder - Server", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_SHOWN);
            if (window == NULL){
                printf("Window could not be created! SDL_Error %s\n", SDL_GetError());
            } else {
                //Create renderer for window
                renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED );
                if( renderer == NULL )
                {
                    printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
                }
                
                // initialize network
                SDLNet_ResolveHost(&ip, NULL, port);
                server_socket = SDLNet_TCP_Open(&ip);
                
                // allocate socket set
                client_sockets = SDLNet_AllocSocketSet(MAX_PLAYERS);
                
                
                // create ball object
                ball = new BallObject(24);
                ball->loadTexture(renderer, "ball.png");
                ball->SetScale(*new Vector2(0.5, 0.5));
                gameObjects.push_back(ball);
                
                // create UI
                TTF_Init();
                
                ui_background = SDL_CreateRGBSurface(0, ui_background_width, ui_background_height, 32, 0, 0, 0, 0);
                ui_background_rect.x = ui_background_x;
                ui_background_rect.y = ui_background_y;
                ui_background_rect.w = ui_background_width;
                ui_background_rect.h = ui_background_height;
                SDL_FillRect(ui_background, &ui_background_rect, SDL_MapRGB(ui_background->format, 255, 255, 255));
                ui_background_texture = SDL_CreateTextureFromSurface(renderer, ui_background);
                
                font = TTF_OpenFont("font.ttf", 24);
                if (!font){
                    printf("TTF_OpenFont: %s\n", TTF_GetError());
                }
                ui_text = TTF_RenderText_Solid(font, ui_text_content, white);
                ui_text_texture = SDL_CreateTextureFromSurface(renderer, ui_text);
                ui_text_rect.x = ui_text_x;
                ui_text_rect.y = ui_text_y;
                ui_text_rect.w = ui_text_width;
                ui_text_rect.h = ui_text_height;
            }
        }
    }
}
Example #11
0
int NetClient::Connect( const char *hostname, int port, const char *name, const char *password )
{
	Host = hostname;
	
	if( port > 0 )
		Port = port;
	else
		Port = 7000;
	
	if( ! Initialized )
		return -1;
	
	if( Connected )
		DisconnectNice();
	
	// Clean up old data and socket.
	SDL_Delay( 1 );
	Cleanup();
	DisconnectMessage.clear();
	
	// Show the wait screen.
	char cstr[ 1024 ] = "";
	snprintf( cstr, 1024, "Connecting to %s:%i...", hostname, Port );
	Raptor::Game->Console.Print( cstr );
	Raptor::Game->ChangeState( Raptor::State::CONNECTING );
	
	// Resolve the host we are connecting to.
	IPaddress ip;
	if( SDLNet_ResolveHost( &ip, hostname, Port ) < 0 )
	{
		Raptor::Game->Console.Print( "Failed to resolve server hostname.", TextConsole::MSG_ERROR );
		Raptor::Game->ChangeState( Raptor::State::DISCONNECTED );
		return -1;
	}
	
	// Open a connection with the IP provided.
	if( !( Socket = SDLNet_TCP_Open(&ip) ) )
	{
		Raptor::Game->Console.Print( "Failed to open socket to server.", TextConsole::MSG_ERROR );
		Raptor::Game->ChangeState( Raptor::State::DISCONNECTED );
		return -1;
	}
	
	BytesSent = 0;
	BytesReceived = 0;
	
	// Start the listener thread.
	Connected = true;
	if( !( Thread = SDL_CreateThread( NetClientThread, this ) ) )
	{
		fprintf( stderr, "SDL_CreateThread: %s\n", SDLNet_GetError() );
		Connected = false;
		SDLNet_TCP_Close( Socket );
		Socket = NULL;
		Raptor::Game->ChangeState( Raptor::State::DISCONNECTED );
		return -1;
	}
	
	uint32_t ip_int = Endian::ReadBig32(&(ip.host));
	uint16_t port_int = Endian::ReadBig16(&(ip.port));
	snprintf( cstr, 1024, "Connected to: %i.%i.%i.%i:%i", (ip_int & 0xFF000000) >> 24, (ip_int & 0x00FF0000) >> 16, (ip_int & 0x0000FF00) >> 8, ip_int & 0x000000FF, port_int );
	Raptor::Game->Console.Print( cstr );
	
	// Send login information.
	Packet packet( Raptor::Packet::LOGIN );
	packet.AddString( Raptor::Game->Game );
	packet.AddString( Raptor::Game->Version );
	packet.AddString( name );
	packet.AddString( password );  // FIXME: This assumes every game requires a password!
	Send( &packet );
	
	// If we connected successfully, don't try to reconnect.
	ReconnectTime = 0;
	ReconnectAttempts = 0;
	
	return 0;
}
Example #12
0
int main(int argc, char* argv[])
{
    FILE *fp;
    int archive_flag = 0;
    int framecount = 0;
    char filename[20];
    int index = 0;
    int i1, size;
    int result, ready, timeout;
    int imageReady = 0;
    char imageBuf[MTU*10];
    char buf[MTU], *cp;
    char msg[2] = {'I', 0};
    char msg1[5] = { 'M', 0x01, 0x01, 0x01, 0};
    IPaddress ipaddress;
    TCPsocket tcpsock;
    SDLNet_SocketSet socSet;
    unsigned int flags = SDL_DOUBLEBUF|SDL_HWSURFACE;
    SDL_Surface *screen;
    SDL_Surface *image;
    unsigned int nrSocketsReady;

    // initialize SDL and SDL_net
    if((SDL_Init(SDL_INIT_VIDEO) == -1)) { 
        printf("Could not initialize SDL: %s.\n", SDL_GetError());
        return 1;
    }
    if(SDLNet_Init() == -1) {
        printf("SDLNet_Init: %s\n", SDLNet_GetError());
        return 2;
    }
    if(TTF_Init() == -1) {
        printf("TTF_Init: %s\n", TTF_GetError());
        return 3;
    }
    // initialize the screen
    screen = SDL_SetVideoMode(320, 260, 32, flags);
    SDLNet_ResolveHost(&ipaddress, IP_ADDRESS, 10001);
    tcpsock = SDLNet_TCP_Open(&ipaddress);
    if(!tcpsock) {
        printf("SDLNet_TCP_Open 1: %s\n", SDLNet_GetError());
        return 2;
    }
    socSet = SDLNet_AllocSocketSet(1);
    SDLNet_TCP_AddSocket(socSet, tcpsock);
    msg1[0] = msg1[1] = msg1[2] = msg1[3] = 0;
    
    SDL_Event event;
    int quit = 0;

    imageReady = 0;
    timeout = 0;

    // main loop
    for (; !quit;) {
        // check keyboard events
        *msg1 = 0;
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
				case SDL_MOUSEBUTTONUP:
					if(event.button.button == SDL_BUTTON_LEFT){
						printf("X: %d Y: %d\n", event.button.x, event.button.y);
					}
					break;
				case SDL_KEYDOWN:
					switch( event.key.keysym.sym ) {
						case SDLK_ESCAPE:
							quit = 1;
							break;
						case SDLK_a:
							archive_flag = 1;
							framecount = 0;
							printf(" archiving enabled - files saved in ./archives/ directory\n");
							break;
						case SDLK_RETURN:
							printf("Entering input mode...\n");
							sendCmd(tcpsock,socSet, screen);
							break;
					}
					break;
			}
        }

        index = 0;
        imageBuf[0] = 0;
        imageReady = 0;

		// send 'I' command
		result = SDLNet_TCP_Send(tcpsock, msg, 1);
		if(result < 1)
			printf("SDLNet_TCP_Send 1: %s\n", SDLNet_GetError());

		// look for frames
		while (!imageReady) {	
			if (!imageReady) {
				nrSocketsReady = SDLNet_CheckSockets(socSet, TIMEOUT);
				if (nrSocketsReady == -1) {
					printf("SDLNet_CheckSockets: %s\n", SDLNet_GetError());
					perror("SDLNet_CheckSockets");
				}
				else if (nrSocketsReady > 0) {
					if (SDLNet_CheckSockets(socSet, TIMEOUT)) {
						if (SDLNet_SocketReady(socSet)) {
							result = SDLNet_TCP_Recv(tcpsock, buf, MTU);
							memcpy(imageBuf+index, buf, result);
							index += result;
							if ((buf[result-2] == -1) && (buf[result-1] == -39))
								imageReady = 1;
						}
					}
				}
				else {
					printf("\n\rNo sockets ready.\n\r");
					break;
				}
			}
		}

		// make certain that captured frames are valid
		if (!imageReady || imageBuf[0]!='#' || imageBuf[1]!='#' || imageBuf[2]!='I') {
			imageReady = 0;
			printf("bad image, or Checksockets() timed out!\n");
			continue;
		}
		size = (unsigned int)imageBuf[6] + (unsigned int)imageBuf[7]*256 + (unsigned int)imageBuf[8]*65536;
		if (size > index-10) {
			printf("bad image size:  %d %d %d\n", size, index, framecount);
			imageReady = 0;
			continue;
		}
		imageReady = 0;
		timeout = 0;
		SDL_RWops *rwop;
		rwop = SDL_RWFromMem(&(imageBuf[10]), index-10);
		image  = IMG_LoadJPG_RW(rwop);
		cp = (char *)image->pixels;

		if (archive_flag) {
			sprintf(filename, "archives/%.4d.ppm", framecount);
			fp = fopen(filename, "w");
			fprintf(fp,"P6\n320\n240\n255\n", 15);
			fwrite(cp, 1, 230400, fp);
			fclose(fp);
		}
		framecount++;
		SDL_BlitSurface(image, NULL, screen, NULL);
		SDL_Flip(screen);
		SDL_FreeRW(rwop);
		SDL_FreeSurface(image);
	}

	TTF_Quit();
    SDLNet_TCP_Close(tcpsock);
    SDLNet_Quit();
    SDL_Quit();
    return 0;
}
Example #13
0
void sendCmd(TCPsocket tcpsock, SDLNet_SocketSet socSet, SDL_Surface *screen)
{
	int i, result;
	unsigned char cmd[30];			// Buffer to hold the input string
	unsigned char temp[31];			// temporary buffer used for printing (one extra char for the '_' -char)
	unsigned char buffer[MTU];
	SDL_Surface *text = NULL;
	SDL_Color textColor = {0,255,0,0};
	SDL_Color bgColor = {0,0,0,0};
	unsigned char len = 0;			// the length of the current command
	unsigned char done = 0, exit = 0;	// flags
	TTF_Font *font = NULL;
	SDL_Event event;
	SDL_Rect cmdPos = {16,240,320,20};
	SDL_Rect consolePos = {0,240,320,20};
	signed int nrSocketsReady;
	
	// prepare command buffers
	for (i=0;i<30;i++) {
		cmd[i] = '\0';
		temp[i] = '\0';
	}
	temp[30] = '\0';
	
	// console chars
	temp[0] = '#';
	temp[1] = '>';
	temp[2] = '_';
	
	//setup the text param's and render console chars to "screen"
	SDL_EnableUNICODE(SDL_ENABLE);
	font = TTF_OpenFont(FONT, FONT_SIZE);
	if(!font) {
		printf("TTF_OpenFont: %s\n", TTF_GetError());
	}
	text = TTF_RenderText_Shaded(font, temp, textColor, bgColor);
	if (text == NULL) {
		printf("TTF_OpenFont: %s\n", TTF_GetError());
	}
	if (SDL_BlitSurface(text,NULL, screen, &consolePos) != 0) {
		printf("TTF_OpenFont: %s\n", TTF_GetError());
	}
	SDL_UpdateRect(screen, 0, 0, 0, 0);
	SDL_FreeSurface(text);		
	
	strcpy(temp,cmd);
	
	while((!done) && (!exit)) {
		while(SDL_PollEvent(&event)) {
			//If a key was pressed
			if( event.type == SDL_KEYDOWN ) {
				
				strcpy(temp,cmd);			// reset temp
				len = 0;
				do {						// Find the length of the current command
					if (cmd[len] != '\0')
						len++;
					else
						break;
				} while(len < 29);	// save the last '\0' char
				
				if (event.key.keysym.sym == SDLK_RETURN) {
					done = 1;					// flag the command as complete, exit loop
				}
				//If backspace was pressed and the string isn't blank
				else if((event.key.keysym.sym == SDLK_BACKSPACE ) && (len > 0)) {
					cmd[len - 1] = '\0';		// Remove a character from the end
				}
				else if (event.key.keysym.sym == SDLK_ESCAPE) {
					exit = 1;					// exits loop
				}
				else if ((len < 29) && (event.key.keysym.unicode >= (unsigned short)' ') && (event.key.keysym.unicode <= (unsigned short)'}')) {
					cmd[len] = (char)event.key.keysym.unicode;		//Append the character to the command string
				}
				else if (len >= 29) {
					printf("command too long!\n\r");
				}
				
				if (strcmp(cmd,temp) != 0) {
					clrCmd(screen, CMD);
					
					memset(temp,'\0',30);
					strcpy(temp,cmd);
					len = 0;
					do {
						if (cmd[len] != '\0')
							len++;
						else
							break;
					} while(len < 29);			// save place for the '_' and '\0' char
					
					temp[len] = '_';			// add an underscore (just because it looks good)
					text = TTF_RenderText_Shaded(font, temp, textColor, bgColor);	// Render a new text surface
					SDL_BlitSurface(text,NULL, screen, &cmdPos);		// put the text onto the "screen"
					SDL_UpdateRect(screen, 0, 0, 0, 0);					// update the text area
					SDL_FreeSurface(text);								// Free the surface in memory
				}
			}
		}
	}
	
	if (!exit) {
		printf("entered command: \"%s\"\n\r",cmd);	// prints the command send to the SRV
		
		len = 0;
		do {
			if ((cmd[len] != ' ') && (cmd[len] != '\0'))
				len++;
			else
				break;
		} while(len < 30);
		
		if (len > 0) {
			// Send command to SRV-1
			result = SDLNet_TCP_Send(tcpsock, cmd, len);
			if(result < 1)
				printf("SDLNet_TCP_Send 1: %s\n", SDLNet_GetError());
			
			for (i=0;i<5;i++) {				// try to recieve an answer within 5 attempts
				nrSocketsReady = SDLNet_CheckSockets(socSet, TIMEOUT);
				if (nrSocketsReady > 0) {
					if (SDLNet_SocketReady(socSet))	{
						result = SDLNet_TCP_Recv(tcpsock, buffer, MTU);
						if (result <= 0) {
							printf("no reply, or reply reception failed\n\r");
						}
						break;
					}
				}
				else if (nrSocketsReady == -1) {
					printf("SDLNet_CheckSockets: %s\n", SDLNet_GetError());
					perror("SDLNet_CheckSockets");
				}
				else
					printf("reception attempt #%i failed\n\r",i+1);
			}
			
			if (result > 0) {
				buffer[result] = '\0';
				printf("Received reply: %s\n\r",buffer);
			}
		}
	}
	//erase command line
	clrCmd(screen, DISPLAY);

	// Clean up
	SDL_EnableUNICODE(SDL_DISABLE);
	TTF_CloseFont(font);
}
Example #14
0
static void initialize_application(void)
{
#if defined(__WIN32__) && defined(__MINGW32__)
	if (LoadLibrary("exchndl.dll")) option_debug = true;
#endif

	//	SDL_putenv(const_cast<char*>("SDL_VIDEO_ALLOW_SCREENSAVER=1"));

	// Initialize SDL
	int retval = SDL_Init(SDL_INIT_VIDEO |
						  (option_nosound ? 0 : SDL_INIT_AUDIO) |
						  (option_nojoystick ? 0 : SDL_INIT_JOYSTICK) |
						  (option_debug ? SDL_INIT_NOPARACHUTE : 0));
	if (retval < 0)
	{
		const char *sdl_err = SDL_GetError();
		if (sdl_err)
			fprintf(stderr, "Couldn't initialize SDL (%s)\n", sdl_err);
		else
			fprintf(stderr, "Couldn't initialize SDL\n");
		exit(1);
	}
#if defined(HAVE_SDL_IMAGE)
	IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG);
#endif

	// Find data directories, construct search path
	InitDefaultStringSets();

#if defined(unix) || defined(__NetBSD__) || defined(__OpenBSD__) || (defined(__APPLE__) && defined(__MACH__) && !defined(HAVE_BUNDLE_NAME))

	default_data_dir = PKGDATADIR;
	const char *home = getenv("HOME");
	if (home)
		local_data_dir = home;
	local_data_dir += ".alephone";
	log_dir = local_data_dir;

#elif defined(__APPLE__) && defined(__MACH__)
	bundle_data_dir = bundle_resource_path;
	bundle_data_dir += "DataFiles";

	data_search_path.push_back(bundle_data_dir);

#ifndef SCENARIO_IS_BUNDLED
	{
		char* buf = getcwd(0, 0);
		default_data_dir = buf;
		free(buf);
	}
#endif
	
	log_dir = app_log_directory;
	preferences_dir = app_preferences_directory;
	local_data_dir = app_support_directory;

#elif defined(__WIN32__)

	char file_name[MAX_PATH];
	GetModuleFileName(NULL, file_name, sizeof(file_name));
	char *sep = strrchr(file_name, '\\');
	*sep = '\0';

	default_data_dir = file_name;

	char login[17];
	DWORD len = 17;

	bool hasName = (GetUserName((LPSTR) login, &len) == TRUE);
	if (!hasName || strpbrk(login, "\\/:*?\"<>|") != NULL)
		strcpy(login, "Bob User");

	DirectorySpecifier legacy_data_dir = file_name;
	legacy_data_dir += "Prefs";
	legacy_data_dir += login;
	
	SHGetFolderPath(NULL,
			CSIDL_PERSONAL | CSIDL_FLAG_CREATE,
			NULL,
			0,
			file_name);
	local_data_dir = file_name;
	local_data_dir += "AlephOne";

	log_dir = local_data_dir;

#else
	default_data_dir = "";
	local_data_dir = "";
//#error Data file paths must be set for this platform.
#endif

#if defined(__WIN32__)
#define LIST_SEP ';'
#else
#define LIST_SEP ':'
#endif
	
	// in case we need to redo search path later:
	size_t dsp_insert_pos = data_search_path.size();
	size_t dsp_delete_pos = (size_t)-1;
	
	if (arg_directory != "")
	{
		default_data_dir = arg_directory;
		dsp_delete_pos = data_search_path.size();
		data_search_path.push_back(arg_directory);
	}

	const char *data_env = getenv("ALEPHONE_DATA");
	if (data_env) {
		// Read colon-separated list of directories
		string path = data_env;
		string::size_type pos;
		while ((pos = path.find(LIST_SEP)) != string::npos) {
			if (pos) {
				string element = path.substr(0, pos);
				data_search_path.push_back(element);
			}
			path.erase(0, pos + 1);
		}
		if (!path.empty())
			data_search_path.push_back(path);
	} else {
		if (arg_directory == "")
		{
			dsp_delete_pos = data_search_path.size();
			data_search_path.push_back(default_data_dir);
		}
#if defined(__WIN32__)
		data_search_path.push_back(legacy_data_dir);
#endif
		data_search_path.push_back(local_data_dir);
	}

	// Subdirectories
#if defined(__MACH__) && defined(__APPLE__)
	DirectorySpecifier legacy_preferences_dir = local_data_dir;
#elif defined(__WIN32__)
	DirectorySpecifier legacy_preferences_dir = legacy_data_dir;
	SHGetFolderPath(NULL, 
			CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE, 
			NULL,
			0,
			file_name);
	preferences_dir = file_name;
	preferences_dir += "AlephOne";
#else
	preferences_dir = local_data_dir;
#endif	
	saved_games_dir = local_data_dir + "Saved Games";
	quick_saves_dir = local_data_dir + "Quick Saves";
	image_cache_dir = local_data_dir + "Image Cache";
	recordings_dir = local_data_dir + "Recordings";
	screenshots_dir = local_data_dir + "Screenshots";
#if defined(__APPLE__) && defined(__MACH__)
    if (app_screenshots_directory)
        screenshots_dir = app_screenshots_directory;
#endif


	DirectorySpecifier local_mml_dir = local_data_dir + "MML";
	DirectorySpecifier local_themes_dir = local_data_dir + "Themes";

	// Setup resource manager
	initialize_resources();

	init_physics_wad_data();
	initialize_fonts(false);

	load_film_profile(FILM_PROFILE_DEFAULT, false);

	// Parse MML files
	LoadBaseMMLScripts();

	// Check for presence of strings
	if (!TS_IsPresent(strERRORS) || !TS_IsPresent(strFILENAMES)) {
		fprintf(stderr, "Can't find required text strings (missing MML?).\n");
		exit(1);
	}
	
	// Check for presence of files (one last chance to change data_search_path)
	if (!have_default_files()) {
		char chosen_dir[256];
		if (alert_choose_scenario(chosen_dir)) {
			// remove original argument (or fallback) from search path
			if (dsp_delete_pos < data_search_path.size())
				data_search_path.erase(data_search_path.begin() + dsp_delete_pos);
			// add selected directory where command-line argument would go
			data_search_path.insert(data_search_path.begin() + dsp_insert_pos, chosen_dir);
			
			default_data_dir = chosen_dir;
			
			// Parse MML files again, now that we have a new dir to search
			initialize_fonts(false);
			LoadBaseMMLScripts();
		}
	}

	initialize_fonts(true);
	Plugins::instance()->enumerate();			
	
#if defined(__WIN32__) || (defined(__MACH__) && defined(__APPLE__))
	preferences_dir.CreateDirectory();
	transition_preferences(legacy_preferences_dir);
#endif

	// Load preferences
	initialize_preferences();

	local_data_dir.CreateDirectory();
	saved_games_dir.CreateDirectory();
	quick_saves_dir.CreateDirectory();
	{
		std::string scen = Scenario::instance()->GetName();
		if (scen.length())
			scen.erase(std::remove_if(scen.begin(), scen.end(), char_is_not_filesafe), scen.end());
		if (!scen.length())
			scen = "Unknown";
		quick_saves_dir += scen;
		quick_saves_dir.CreateDirectory();
	}
	image_cache_dir.CreateDirectory();
	recordings_dir.CreateDirectory();
	screenshots_dir.CreateDirectory();
	local_mml_dir.CreateDirectory();
	local_themes_dir.CreateDirectory();
	
	WadImageCache::instance()->initialize_cache();

#ifndef HAVE_OPENGL
	graphics_preferences->screen_mode.acceleration = _no_acceleration;
#endif
	if (force_fullscreen)
		graphics_preferences->screen_mode.fullscreen = true;
	if (force_windowed)		// takes precedence over fullscreen because windowed is safer
		graphics_preferences->screen_mode.fullscreen = false;
	write_preferences();

	Plugins::instance()->load_mml();

//	SDL_WM_SetCaption(application_name, application_name);

// #if defined(HAVE_SDL_IMAGE) && !(defined(__APPLE__) && defined(__MACH__))
// 	SDL_WM_SetIcon(IMG_ReadXPMFromArray(const_cast<char**>(alephone_xpm)), 0);
// #endif
	atexit(shutdown_application);

#if !defined(DISABLE_NETWORKING)
	// Initialize SDL_net
	if (SDLNet_Init () < 0) {
		fprintf (stderr, "Couldn't initialize SDL_net (%s)\n", SDLNet_GetError());
		exit(1);
	}
#endif

	if (TTF_Init() < 0) {
		fprintf (stderr, "Couldn't initialize SDL_ttf (%s)\n", TTF_GetError());
		exit(1);
	}
	HTTPClient::Init();

	// Initialize everything
	mytm_initialize();
//	initialize_fonts();
	SoundManager::instance()->Initialize(*sound_preferences);
	initialize_marathon_music_handler();
	initialize_keyboard_controller();
	initialize_gamma();
	alephone::Screen::instance()->Initialize(&graphics_preferences->screen_mode);
	initialize_marathon();
	initialize_screen_drawing();
	initialize_dialogs();
	initialize_terminal_manager();
	initialize_shape_handler();
	initialize_fades();
	initialize_images_manager();
	load_environment_from_preferences();
	initialize_game_state();
}
Example #15
0
// =============================================================================
int main(int argc, char **argv){

// === INIT === 
  /* Simple parameter checking */
  if (argc < 3){
	fprintf(stderr, "Usage: %s host port\n", argv[0]);
	exit(EXIT_FAILURE);
  }
 
  if (SDLNet_Init() < 0){
	fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError());
	exit(EXIT_FAILURE);
  }
 
/* Resolve the host we are connecting to */
  if (SDLNet_ResolveHost(&ip, argv[1], atoi(argv[2])) < 0){
	fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError());
	exit(EXIT_FAILURE);
  }
 
/* Open a connection with the IP provided (listen on the host's port) */
  if (!(sd = SDLNet_TCP_Open(&ip))){
	fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError());
	exit(EXIT_FAILURE);
  }

 		tp=tbuff;
		*tp = P_NEW_PLAYER;
		tp++;
		strncpy((char *) tp, (char *) nick, 31);
		printf("tbuff[0]: 0x%X\n",tbuff[0]);
		printf("tbuff+1: %s\n", tp);

		len = tp - &tbuff[0] +32 ;
		SEND;
		bzero(tbuff, BUFF_SIZE);

	/* Send messages */
	// =============================================================================
  quit = 2;
  while (quit > 0){

		//printf("Write something:\n>");
		tp=tbuff;
		*tp = P_SPEED_UP;
		printf("tbuff: 0x%X\n",tbuff[0]);

		SEND;

		sleep(1);
		quit--;
 
  }
		tp=rbuff;
  		RECV;
		tp++;
		f= *((float *) tp);
		printf("rbuff+1: %f ", (double) f);

 		tp=tbuff;
		*tp = P_LOGOUT;

  		SEND;
 
  SDLNet_TCP_Close(sd);
  SDLNet_Quit();
 
return EXIT_SUCCESS;
}
Example #16
0
bool init() {

  char* tempchar;
  tempchar = (char*)malloc(16*sizeof(char));
  GetIP(ETHERNET_INTERFACE,tempchar);
  tempchar2 << "CONTROLLER HTTP:// " << tempchar << " : 3000";
  tempchar3 << "HELP TEXT HTTP:// " << tempchar << " : " << HELPPORT;  
  free(tempchar);

    if(SDL_Init(SDL_INIT_EVERYTHING) == -1) {
	printf("error: SDL failed to intitialize.\n");
    	return false;
    }

    // Initialize SDL_net 
    if(SDLNet_Init()==-1) {
      printf("SDLNet_Init: %s\n",SDLNet_GetError());
      return false;
    }

    // Create socketset with enough space allocated for connections
    socketSet = SDLNet_AllocSocketSet(MAX_PLAYERS+2);
    if(socketSet == NULL) {
      printf("Failed to allocate the socket set: %s\n",
	     SDLNet_GetError());
      return false;
    } else {
#ifdef PRINT_MESSAGES
      printf("Allocated socket set size: %d\n", MAX_PLAYERS+1);
#endif
    }
    
    // Setup server
    if(SDLNet_ResolveHost(&serverIP,NULL,PORT)==-1) {
      printf("SDLNet_ResolveHost: %s\n",SDLNet_GetError());
      return false;
    }

    clientSet = SDLNet_AllocSocketSet(1);
    SDLNet_ResolveHost(&servIP, serverName, PORT);
    
    // open the server socket 
    serverSocket=SDLNet_TCP_Open(&serverIP);
    if(!serverSocket) {
      printf("SDLNet_TCP_Open: %s\n",SDLNet_GetError());
      return false;
    }

#ifdef PRINT_MESSAGES
    printf("Server socket listening on %d.\n",
	   SDLNet_Read16(&serverIP.port));
#endif
    
    // Add server socket to socket set
    SDLNet_TCP_AddSocket(socketSet, serverSocket);

    // Setup help server
    if(SDLNet_ResolveHost(&serverIP,NULL,HELPPORT)==-1) {
      printf("SDLNet_ResolveHost: %s\n",SDLNet_GetError());
      return false;
    }

    // open the help socket 
    helpSocket=SDLNet_TCP_Open(&serverIP);
    if(!helpSocket) {
      printf("SDLNet_TCP_Open: %s\n",SDLNet_GetError());
      return false;
    }
    
    // Add help socket to socket set
    SDLNet_TCP_AddSocket(socketSet, helpSocket);

    reply = (char*)malloc(sizeof(char)*1600);
    sprintf(reply,"HTTP/1.1 200 OK\n"
"\n"
"Welcome to Tadpole_SDL.\n"
"A game by Dileep V. Reddy.\n"
"Network controller written in collaboration with Wes Erickson.\n"
"The project and license details can be found at:\n"
"https://github.com/dileepvr/Tadpole_SDL\n"
"https://github.com/inflamedspirit/Tadpole_Controller\n\n"
"To join the game using our Javascript controller, simply visit %s:%d.\n\n"
"To write your own custom controller, follow the protocol below:\n\n"
"Tadpole server is listening for connections on port %d.\n"
"To spawn a controllable tadpole,\n\n"
"1. Open a TCP connection to %s:%d\n\n"
"2. If a spot is not available, server sends 'X' and disconnects.\n\n"
"3. If spot is available, server sends 'N'.\n\n"
"4. Respond with desired player name.\n\n"
"5. Server sends \"RGBXXYYZZ\", where \"XXYYZZ\" are the RGB color values in hex (as a string). The Tadpole should be visible on screen.\n\n"
"6. To control Tadpole, send the following characters:\n\n"
"'1' = Up-key-pressed\n"
"'2' = Up-key-released\n"
"'3' = Right-key-pressed\n"
"'4' = Right-key-released\n"
"'5' = Down-key-pressed\n"
"'6' = Down-key-released\n"
"'7' = Left-key-pressed\n"
"'8' = Left-key-released\n\n"
"7. To kill Tadpole, send 'K'. Server replies with 'D'.\n\n"
"8. Everytime Tadpole hitpoints change, server sends \"HXX\", where \"XX\" encodes current hitpoint count.\n\n"
"9. Server sends 'D' and closes connection when Tadpole dies.\n\n"
"10. Server sends 'C' and closes connection when shutting down.\n",tempchar,JAVAPORT,PORT,tempchar,PORT);

    
    screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE);
    hiscore_layer = SDL_CreateRGBSurface(SDL_HWSURFACE, HISCORE_WIDTH, SCREEN_HEIGHT - BANNER_HEIGHT, SCREEN_BPP, 0, 0, 0, 0);
    if(screen == NULL) {
	printf("error: SDL_SetVideoMode failed.\n");
    	return false;
    }

    if( TTF_Init() == -1) {
	printf("error: TTF failed to initialize.\n");
    	return false;
    }
    
#ifdef WITH_SOUND
    if ( Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 1024 ) == -1){
	printf("error: OpenAudio failed to initialize.\n");
	return false;
    }
#endif
    SDL_WM_SetCaption("Tadpole", NULL);


    return true;

}
Example #17
0
int sdl_init (void)
{
    if (SDL_Init (SDL_INIT_VIDEO) != 0)
    {
        fprintf(stderr, "SDL_Init: %s\n", SDL_GetError());
        return 1;
    }

    win = SDL_CreateWindow ("Pisound client", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 600, 50, SDL_WINDOW_SHOWN);

    if (win == NULL)
    {
        fprintf (stderr, "Error creating window: %s\n", SDL_GetError());
        return 1;
    }

    ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (ren == NULL)
    {
        fprintf (stderr, "Error creating renderer: %s\n", SDL_GetError());
        return 1;
    }

    // Initilise networking
    if (SDLNet_Init () != 0)
    {
        fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError());
        return 1;
    }

    socket = SDLNet_UDP_Open (0);
    if (!socket)
    {
        fprintf (stderr, "Error opening socket: %s\n", SDLNet_GetError());
        return 1;
    }

    send_p = SDLNet_AllocPacket (UDP_BUFFLEN);
    if (!send_p)
    {
        fprintf (stderr, "Error allocing send_packet: %s\n", SDLNet_GetError());
        running = 0;
        return 1;
    }

    if (SDLNet_ResolveHost (&srvaddr, IP, UDP_PORT))
    {
        fprintf (stderr, "Error resolving host: %s\n", SDLNet_GetError());
        return 1;
    }

    if (TTF_Init () == -1)
    {
        fprintf (stderr, "Error initialising TTF library\n");
        return 1;
    }
    font = TTF_OpenFont("data/fonts/Alfphabet-IV.ttf",28);
    if (font == NULL)
    {
        fprintf (stderr, "Error loading font\n");
        return 1;
    }

    return 0;
}
int main(int argsn, char** args) {
	if(sizeof(onebyte)!=1) {
		fprintf(stderr, "FATAL ERROR: sizeof(onebyte)!=1.\n");
		exit(EXIT_FAILURE);
		}

	if(argsn!=1 && argsn!=3 && argsn!=2 && argsn!=4) {
		fprintf(stderr, "usage: %s [server] [screen_width screen_height]\n", args[0]);
		exit(EXIT_FAILURE);
		}

	char server_string[100];

	if(argsn>=3) {
		if(argsn==4) {
			cyberspace_screen_width=atoi(args[2]);
			cyberspace_screen_height=atoi(args[3]);
			sprintf(server_string, args[1]);
			}
		else {
			cyberspace_screen_width=atoi(args[1]);
			cyberspace_screen_height=atoi(args[2]);
			sprintf(server_string, CYBERSPACE_SERVER_NAME);
			}
		}
	else {
		cyberspace_screen_width=CYBERSPACE_GUI_WIDTH;
		cyberspace_screen_height=CYBERSPACE_GUI_HEIGHT;
		if(argsn==1) sprintf(server_string, CYBERSPACE_SERVER_NAME);
		else sprintf(server_string, args[1]);
		}

//	printf("server_string=\"%s\"\n", server_string);

	cyberspace_textures=new GLuint[CYBERSPACE_GUI_TEXTURES_MAX];
	cyberspace_textures_raw=new void*[CYBERSPACE_GUI_TEXTURES_MAX];

	FILE* rawfile;
	int l;

	for(int i=0;i<CYBERSPACE_GUI_TEXTURES_MAX;i++) {
		switch(i) {
			case CYBERSPACE_GUI_TEXTURE_TILE_32_CAN:
				l=32;
				rawfile=fopen("img/tile_32_can.raw", "rb");
				break;
			case CYBERSPACE_GUI_TEXTURE_TILE_32_RADIO:
				l=32;
				rawfile=fopen("img/tile_32_radio.raw", "rb");
				break;
			case CYBERSPACE_GUI_TEXTURE_TILE_32_CRYSTAL:
				l=32;
				rawfile=fopen("img/tile_32_crystal.raw", "rb");
				break;
			case CYBERSPACE_GUI_TEXTURE_TILE_32_START:
				l=32;
				rawfile=fopen("img/tile_32_start.raw", "rb");
				break;
			case CYBERSPACE_GUI_TEXTURE_TILE_32_END:
				l=32;
				rawfile=fopen("img/tile_32_end.raw", "rb");
				break;
			case CYBERSPACE_GUI_TEXTURE_TILE_32_FLOOR:
				l=32;
				rawfile=fopen("img/tile_32_floor.raw", "rb");
				break;
			case CYBERSPACE_GUI_TEXTURE_TILE_32_CULT_0:
				l=32;
				rawfile=fopen("img/tile_32_cult0.raw", "rb");
				break;
			case CYBERSPACE_GUI_TEXTURE_TILES_4X4_64_ICONS:
				l=256;
				rawfile=fopen("img/tiles_4x4_64_icons.raw", "rb");
				break;
/*
			case CYBERSPACE_GUI_TEXTURE_TILE_256_SELF:
				l=256;
				rawfile=fopen("img/self.raw", "rb");
				break;
*/
			default:
				l=32;
				rawfile=fopen("img/tile_32_can.raw", "rb");
				break;
			}
		cyberspace_textures_raw[i]=new onebyte[l*l*4];
		if(rawfile==NULL) {
			fprintf(stderr, "ABORT: fopen raw fails\n");
			exit(EXIT_FAILURE);
			}
		fread(cyberspace_textures_raw[i], l*l*4, 1, rawfile);
		fclose(rawfile);
		}

	for(int x=0;x<4;x++) {
		for(int y=0;y<4;y++) {
			cyberspace_clips_4x4_64_x[y*4+x][0]=0.25*x;
			cyberspace_clips_4x4_64_x[y*4+x][1]=0.25*(x+1);
			cyberspace_clips_4x4_64_y[y*4+x][0]=0.25*y;
			cyberspace_clips_4x4_64_y[y*4+x][1]=0.25*(y+1);
			}
		}

	printf("neural_connector: init SDL\n");
	if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTTHREAD)!=0) {
		fprintf(stderr, "neural_connector: FATAL ERROR: SDL_Init fails: %s\n", SDL_GetError());
		exit(EXIT_FAILURE);
		}

	if(atexit(SDL_Quit)!=0) {
		fprintf(stderr, "neural_connector: FATAL ERROR: couldn't set exit function.\n");
		exit(EXIT_FAILURE);
		}

	if(SDLNet_Init()!=0) {
		fprintf(stderr, "neural_connector: FATAL ERROR: SDLNet_Init fails: %s\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
		}

	//non serve
/*	printf("neural_connector: init SDL_Image\n");
	if(IMG_Init(IMG_INIT_PNG)!=IMG_INIT_PNG) {
		fprintf(stderr, "neural_connector: FATAL ERROR: IMG_Init fails: %s\n", IMG_GetError());
		exit(EXIT_FAILURE);
		}*/

	//using X mutlithreading
	//TODO se abilito SDL con multithread probabilmente non serve
/*	if(XInitThreads()==0) {
		fprintf(stderr, "FATAL ERROR: XInitThreads fails.\n");
		exit(EXIT_FAILURE);
		}*/

	cyberspace_login_name=new char[100];
	cyberspace_login_name[0]='\0';
	cyberspace_login_password=new char[100];
	cyberspace_login_password[0]='\0';

	cyberspace_fps=new char[20];
	cyberspace_fps[0]='\0';

	cyberspace_chat=new char*[CYBERSPACE_GUI_CHAT_HISTORY];
	for(int i=0;i<CYBERSPACE_GUI_CHAT_HISTORY;i++) {
		cyberspace_chat[i]=new char[CYBERSPACE_GUI_CHAT_LINE_WIDTH+1+25];
		cyberspace_chat[i][0]='\0';
		}
	cyberspace_chat_input=new char[CYBERSPACE_GUI_CHAT_LINE_WIDTH+1];
	cyberspace_chat_input[0]='\0';

	cyberspace_server_message=new char[1000];
	cyberspace_server_message[0]='\0';

	cyberspace_selection_message=new char[1000];
	cyberspace_selection_message[0]='\0';

	cyberspace_GUI_input_focus=CYBERSPACE_GUI_INPUT_FOCUS_NONE;


	cyberspace_personal_data.id_static=-1;

/*	pthread_mutexattr_t mutex_attr;
	pthread_mutexattr_init(&mutex_attr);
	pthread_mutex_init(&cyberspace_mutex_phase, &mutex_attr);
	pthread_mutex_init(&cyberspace_mutex_world, &mutex_attr);*/
	cyberspace_mutex_phase_sdl=SDL_CreateMutex();
	cyberspace_mutex_world_sdl=SDL_CreateMutex();

//	pthread_mutex_lock(&cyberspace_mutex_phase);
	SDL_mutexP(cyberspace_mutex_phase_sdl);
	cyberspace_phase=CYBERSPACE_PHASE_CONNECTING;
	SDL_mutexV(cyberspace_mutex_phase_sdl);
//	pthread_mutex_unlock(&cyberspace_mutex_phase);

/*	pthread_attr_t thread_detached;
	pthread_attr_init(&thread_detached);
	pthread_attr_setdetachstate(&thread_detached, PTHREAD_CREATE_DETACHED);*/

/*	if(pthread_create(&cyberspace_GUI_thread, &thread_detached, cyberspace_GUI_tf, NULL)!=0) {
		fprintf(stderr, "FATAL ERROR: GUI thread creation fails.\n");
		exit(EXIT_FAILURE);
		}*/

	cyberspace_GUI_thread_sdl=SDL_CreateThread(cyberspace_GUI_tf_sdl, NULL);
	if(cyberspace_GUI_thread_sdl==NULL) {
		fprintf(stderr, "FATAL ERROR: GUI thread creation fails: %s.\n", SDL_GetError());
		exit(EXIT_FAILURE);
		}

//	struct timespec tosleep;
//	struct timespec tosleepagain;

	printf("neural_connector: STARTED\n");

	IPaddress server_address;

	printf("neural_connector: creating local input socket...\n");
/*	if((cyberspace_input_socket_fd=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))==-1) {
		fprintf(stderr, "FATAL ERROR: local input socket creation fails.\n");
		exit(EXIT_FAILURE);
		}*/
	if(SDLNet_ResolveHost(&server_address, server_string, CYBERSPACE_FRONTDOOR_SOCKET_PORT_S2C)!=0) {
		fprintf(stderr, "FATAL ERROR: SDLNet_ResolveHost: %s.\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
		}
	if((cyberspace_input_socket=SDLNet_TCP_Open(&server_address))==NULL) {
		fprintf(stderr, "FATAL ERROR: local input socket creation fails: %s.\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
		}
	printf("neural_connector: creating local input socket DONE\n");

	int server_code;
	printf("neural_connector: receiving server code...\n");
	cyberspace_to_read=sizeof(server_code);
	if(SDLNet_TCP_Recv(cyberspace_input_socket, cyberspace_read_buffer, cyberspace_to_read)<=0) {
		fprintf(stderr, "FATAL ERROR: SDLNet_TCP_Recv: %s.\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
		}
	memcpy(&server_code, cyberspace_read_buffer, sizeof(server_code));
	printf("neural_connector: server code=%d\n", server_code);

	printf("neural_connector: creating local output socket...\n");
/*	if((cyberspace_output_socket_fd=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))==-1) {
		fprintf(stderr, "FATAL ERROR: local output socket creation fails.\n");
		exit(EXIT_FAILURE);
		}*/
	if(SDLNet_ResolveHost(&server_address, server_string, CYBERSPACE_FRONTDOOR_SOCKET_PORT_C2S)!=0) {
		fprintf(stderr, "FATAL ERROR: SDLNet_ResolveHost: %s.\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
		}
	if((cyberspace_output_socket=SDLNet_TCP_Open(&server_address))==NULL) {
		fprintf(stderr, "FATAL ERROR: local output socket creation fails: %s.\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
		}
	printf("neural_connector: creating local output socket DONE\n");

	printf("neural_connector: sending input/output coordination code...\n");
	cyberspace_to_write=sizeof(server_code);
	memcpy(cyberspace_write_buffer, &server_code, sizeof(server_code));
	if(SDLNet_TCP_Send(cyberspace_output_socket, cyberspace_write_buffer, cyberspace_to_write)<cyberspace_to_write) {
		fprintf(stderr, "FATAL ERROR: SDLNet_TCP_Send: %s.\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
		}
	printf("neural_connector: sending input/output coordination code DONE\n");

/*
	int output_remote_socket_fd;
	int input_remote_socket_fd;

	struct addrinfo sok_addr_info;
	struct addrinfo* sok_addr_res;

	memset(&sok_addr_info, 0, sizeof(sok_addr_info));
	sok_addr_info.ai_family=AF_INET;
	sok_addr_info.ai_socktype=SOCK_STREAM;
	sok_addr_info.ai_protocol=IPPROTO_TCP;

	printf("neural_connector: opening of input connection...\n");
	if(getaddrinfo(server_string, CYBERSPACE_FRONTDOOR_SOCKET_PORT_STRING_S2C, &sok_addr_info, &sok_addr_res)) {
		fprintf(stderr, "FATAL ERROR: getaddrinfo of server fails.\n");
		exit(EXIT_FAILURE);
		}

	while((input_remote_socket_fd=connect(cyberspace_input_socket_fd, sok_addr_res->ai_addr, sok_addr_res->ai_addrlen))!=0) {
		printf("neural_connector: connecting input... (%d)\n", input_remote_socket_fd);
		tosleep.tv_sec=5;
		tosleep.tv_nsec=0;
		while(nanosleep(&tosleep, &tosleepagain)!=0) {
			tosleep=tosleepagain;
			}
		}
	printf("neural_connector: opening of input connection DONE\n");

	int server_code;

	printf("neural_connector: receiving server code...\n");
	cyberspace_to_read=sizeof(server_code);
	cyberspace_read_total=0;
	while(cyberspace_read_total<cyberspace_to_read) {
		cyberspace_read_partial=recv(cyberspace_input_socket_fd, cyberspace_read_buffer+cyberspace_read_total, CYBERSPACE_USER_CONNECTION_READ_BUFFER-1-cyberspace_read_total, 0);
		if(cyberspace_read_partial==-1) {
			perror("perror: ");
			fprintf(stderr, "ERROR: (cyberspace_user_connection) recv failed.\n");
			exit(EXIT_FAILURE);
			}
		cyberspace_read_total+=cyberspace_read_partial;
		}
	printf("neural_connector: receiving server code DONE \n");

	memcpy(&server_code, cyberspace_read_buffer, sizeof(server_code));
	printf("neural_connector: server code=%d\n", server_code);

	memset(&sok_addr_info, 0, sizeof(sok_addr_info));
	sok_addr_info.ai_family=AF_INET;
	sok_addr_info.ai_socktype=SOCK_STREAM;
	sok_addr_info.ai_protocol=IPPROTO_TCP;

	printf("neural_connector: opening of output connection...\n");
	if(getaddrinfo(server_string, CYBERSPACE_FRONTDOOR_SOCKET_PORT_STRING_C2S, &sok_addr_info, &sok_addr_res)) {
//	if(getaddrinfo("127.1.1.1", CYBERSPACE_FRONTDOOR_SOCKET_PORT_STRING_C2S, &sok_addr_info, &sok_addr_res)) {
		fprintf(stderr, "FATAL ERROR: getaddrinfo of server fails.\n");
		exit(EXIT_FAILURE);
		}

	while((output_remote_socket_fd=connect(cyberspace_output_socket_fd, sok_addr_res->ai_addr, sok_addr_res->ai_addrlen))!=0) {
		printf("neural_connector: connecting output... (%d)\n", output_remote_socket_fd);
		tosleep.tv_sec=5;
		tosleep.tv_nsec=0;
		while(nanosleep(&tosleep, &tosleepagain)!=0) {
			tosleep=tosleepagain;
			}
		}
	printf("neural_connector: opening of output connection DONE\n");

	printf("neural_connector: sending input/output coordination code...\n");
	cyberspace_to_write=sizeof(server_code);
	memcpy(cyberspace_write_buffer, &server_code, sizeof(server_code));
	cyberspace_written_total=0;
	while(cyberspace_to_write>cyberspace_written_total) {
		cyberspace_written_partial=send(cyberspace_output_socket_fd, cyberspace_write_buffer+cyberspace_written_total, cyberspace_to_write-cyberspace_written_total, 0);
		if(cyberspace_written_partial==-1) {
			perror("perror: ");
			fprintf(stderr, "ERROR: (in writing) communication with remote process failed.\n");
			exit(EXIT_FAILURE);
			}
		cyberspace_written_total+=cyberspace_written_partial;
		}
	printf("neural_connector: sending input/output coordination code DONE\n");
*/

/*	if(pthread_create(&cyberspace_input_thread, &thread_detached, cyberspace_neural_connector_input_tf, NULL)!=0) {
		fprintf(stderr, "FATAL ERROR: input thread creation fails.\n");
		exit(EXIT_FAILURE);
		}*/

	cyberspace_input_thread_sdl=SDL_CreateThread(cyberspace_neural_connector_input_tf_sdl, NULL);
	if(cyberspace_input_thread_sdl==NULL) {
		fprintf(stderr, "FATAL ERROR: GUI thread creation fails: %s.\n", SDL_GetError());
		exit(EXIT_FAILURE);
		}

	int command_code;

	cyberspace_to_end=false;

	while(!cyberspace_to_end) {
		printf("invia un comando\n");
		printf("\t0\tclose connection\n");
		scanf("%d", &command_code);

		cyberspace_output_command.type=command_code;

/*			data->out_command.type=CYBERSPACE_COMMAND_SERVER_ERROR;
			data->out_command.include_data_s=true;
			data->out_command.include_data_m=false;
			data->out_command.include_data_l=false;
			char* errormessage=new char[CYBERSPACE_COMMAND_SIZE_S];
			sprintf(errormessage, "unexpected message in login");
			memcpy(data->out_command.data_s, errormessage, strlen(errormessage)+1);
			delete[] errormessage;
			cyberspace_user_connection_output(data, &(data->out_command));*/

//		cyberspace_neural_connector_output(&cyberspace_output_command);

		printf("message NOT sent\n");
		}

	SDL_WaitThread(cyberspace_GUI_thread_sdl, NULL);
	SDL_WaitThread(cyberspace_input_thread_sdl, NULL);

	printf("neural_connector: ENDING\n");
//	pthread_exit(NULL);
	exit(EXIT_SUCCESS);
	}
Example #19
0
int g_Open( char *file ) {
	char c; int i; float f;
	float screenfactor;
	unsigned long x, y;
	FILE *fp;
	char name[32];
	char valid_data[10];
	Mix_Chunk *psize;

	gameloop = 1;
	hx=xres>>1; hy=yres>>1; hz = hx;
	
	screenfactor = ((float)(xres))/320.0;
	//SDL_Rect src, dest;
	//src.x=0; dest.x=0;
	//src.y=0; dest.y=0;
	//src.w=1280*screenfactor; dest.w=0;
	//src.h=468*screenfactor; dest.h=0;
	
	// allocate memory for tables
	zbuffer = (float *) malloc(sizeof(f)*yres*xres);
	floorbuffer = (int *) malloc(sizeof(i)*yres*xres*2);
	floorbuffer_s = (int *) malloc(sizeof(i)*yres*xres*2);
	rowbuffer = (char *) malloc(sizeof(c)*yres);

	// build some tables
	map.loaded = 0;
	for( x=0; x<xres; x++ ) {
		for( y=0; y<yres; y++ ) {
			floorbuffer_s[y+x*yres]=16383;
			floorbuffer_s[y+x*yres+vidsize]=-1;
		}
	}

	// load general bitmaps
	font8_bmp = SDL_LoadBMP("images/8font.bmp");
	SDL_SetColorKey( font8_bmp, SDL_SRCCOLORKEY, SDL_MapRGB( font8_bmp->format, 255, 0, 255 ) );
	font16_bmp = SDL_LoadBMP("images/16font.bmp");
	SDL_SetColorKey( font16_bmp, SDL_SRCCOLORKEY, SDL_MapRGB( font16_bmp->format, 255, 0, 255 ) );
	r_LoadBmp("images/console.bmp", &console_bmp);
	
	// load textures
	sky2_bmp = SDL_LoadBMP("images/sky.bmp");
	sky_bmp = r_ScaleSurface(sky2_bmp, 1280*screenfactor,468*screenfactor);
	//sky_bmp = SDL_CreateRGBSurface(SDL_HWSURFACE,1280*screenfactor,468*screenfactor,32,0,0,0,0);
	//SDL_BlitSurface( SPG_Scale( sky2_bmp, screenfactor, screenfactor ), &src, sky_bmp, &dest );
	//SDL_BlitSurface( sky2_bmp, &src, sky_bmp, &dest );
	//SDL_BlitSurface( sky2_bmp, &src, sky_bmp, &dest );
	fp = fopen("images/textures.txt","r");
	for( texture_num=0; !feof(fp); texture_num++ ) {
		while( fgetc(fp) != '\n' ) if( feof(fp) ) break;
	}
	fclose(fp);
	walltex_bmp = (bitmap_t *) malloc(sizeof(bitmap_t)*texture_num);
	fp = fopen("images/textures.txt","r");
	for( x=0; !feof(fp); x++ ) {
		fscanf(fp,"%s",name); while( fgetc(fp) != '\n' ) if( feof(fp) ) break;
		r_LoadBmp(name, &walltex_bmp[x]);
	}
	fclose(fp);
	
	// load sprites
	fp = fopen("images/sprites.txt","r");
	for( sprite_num=0; !feof(fp); sprite_num++ ) {
		while( fgetc(fp) != '\n' ) if( feof(fp) ) break;
	}
	fclose(fp);
	sprite_bmp = (bitmap_t *) malloc(sizeof(bitmap_t)*sprite_num);
	fp = fopen("images/sprites.txt","r");
	for( x=0; !feof(fp); x++ ) {
		fscanf(fp,"%s",name); while( fgetc(fp) != '\n' ) if( feof(fp) ) break;
		r_LoadBmp(name, &sprite_bmp[x]);
	}
	fclose(fp);
	
	// load weapon bitmaps
	r_LoadBmp( "images/pistol1.bmp", &pistol_bmp[0] );
	r_LoadBmp( "images/pistol2.bmp", &pistol_bmp[1] );
	r_LoadBmp( "images/pistol3.bmp", &pistol_bmp[2] );
	r_LoadBmp( "images/pistol4.bmp", &pistol_bmp[3] );
	r_LoadBmp( "images/pistol5.bmp", &pistol_bmp[4] );
	r_LoadBmp( "images/shotgun1.bmp", &shotgun_bmp[0] );
	r_LoadBmp( "images/shotgun3.bmp", &shotgun_bmp[1] );
	shotgun_bmp[2] = shotgun_bmp[0];
	shotgun_bmp[3] = shotgun_bmp[0];
	shotgun_bmp[4] = shotgun_bmp[0];
	shotgun_bmp[5] = shotgun_bmp[0];
	r_LoadBmp( "images/shotgun4.bmp", &shotgun_bmp[6] );
	shotgun_bmp[7] = shotgun_bmp[6];
	r_LoadBmp( "images/shotgun5.bmp", &shotgun_bmp[8] );
	shotgun_bmp[9] = shotgun_bmp[6];
	shotgun_bmp[10] = shotgun_bmp[6];
	r_LoadBmp( "images/shotgun2.bmp", &shotgun_bmp[11] ); // swapped with shotgun[1] when needed

	// precompute some things
	sprsize = 2.45*((double)yres/240);
	texsize = 2.5*((double)yres/240);

	// load a map
	if( strstr(file,".bsm") == NULL )
		strcat(file,".bsm");
	fp = fopen(file, "rb");
	if( fp == NULL ) {
		printf( "ERROR: Could not load map file: %s\n\n", file );
		g_Close();
		exit(15);
	}
	
	// validate the file
	fread(valid_data, sizeof(char), strlen("BSDLMAP"), fp);
	if( strncmp(valid_data,"BSDLMAP",7) || fgetc(fp) != MAPVERSION ) {
		printf( "ERROR: Not a valid map file: %s\n\n", file );
		fclose(fp);
		g_Close();
		exit(46);
	}
	else
		map.loaded = 1; // lets the engine know that there's junk to be freed
	
	// header
	fread(map.name, sizeof(char), 32, fp);   // map name
	fread(map.author, sizeof(char), 32, fp); // map author
	fread(&map.width, sizeof(int), 1, fp);    // map width
	fread(&map.height, sizeof(int), 1, fp);   // map height
	
	// allocate data
	map.floors = (int *) malloc(sizeof(int)*map.width*map.height);
	map.floors_tex = (int *) malloc(sizeof(int)*map.width*map.height);
	map.floors_tex2 = (int *) malloc(sizeof(int)*map.width*map.height);
	map.ceilings = (int *) malloc(sizeof(int)*map.width*map.height);
	map.ceilings_tex = (int *) malloc(sizeof(int)*map.width*map.height);
	map.ceilings_tex2 = (int *) malloc(sizeof(int)*map.width*map.height);
	
	// map data
	fread(map.floors, sizeof(int), map.width*map.height, fp);        // floor height
	fread(map.floors_tex, sizeof(int), map.width*map.height, fp);    // lower wall texture
	fread(map.floors_tex2, sizeof(int), map.width*map.height, fp);   // floor texture
	fread(map.ceilings, sizeof(int), map.width*map.height, fp);      // ceiling height
	fread(map.ceilings_tex, sizeof(int), map.width*map.height, fp);  // upper wall texture
	fread(map.ceilings_tex2, sizeof(int), map.width*map.height, fp); // ceiling texture
	
	// close the file
	fclose(fp);
	
	// spawn the player
	if( !server ) {
		e_CreateEntity();
		player = lastentity;
		player->behavior = &e_ActPlayer;
		
		player->sizex = .5;
		player->sizey = .5;
		player->sizez = 52;
		
		player->x=2.5;
		player->y=2.5;
		player->z=0;
		player->ang=0;
	}
	vang=0;
	bob1 = 0; bob2 = 0; bob3 = 1;
	weap_mag[2]=2;
	
	// set camera
	camx=8;
	camy=2.5;
	camz=0;
	camang=0;

	// initiate SDL
	if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER ) == -1 ) {
		printf("ERROR: Could not initialize SDL. Aborting...\n\n");
		g_Close();
		exit(4);
	}
	//SDL_WM_GrabInput(SDL_GRAB_ON);
	
	// open audio
	if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers)) {
		printf("Unable to open audio!\n");
		exit(1);
	}

	// create a screen surface
	screen = SDL_CreateRGBSurface(SDL_HWSURFACE,xres,yres,32,0,0,0,0);
	if( !windowed )
		screen2 = SDL_SetVideoMode( xres, yres, 32, SDL_HWSURFACE | SDL_FULLSCREEN );
	else
		screen2 = SDL_SetVideoMode( xres, yres, 32, SDL_HWSURFACE );
	if( screen == NULL || screen2 == NULL ) {
		printf("ERROR: Could not create video surface. Aborting...\n\n");
		g_Close();
		exit(5);
	}
	SDL_WM_SetCaption( "Bubbenstein/SDL\n\n", 0 );
	SDL_ShowCursor(SDL_DISABLE);
	
	// reset the clock
	ot=SDL_GetTicks();
	i_GetFrameRate();
	
	// load sound effects
	fp = fopen("sound/sounds.txt","r");
	for( sound_num=0; !feof(fp); sound_num++ ) {
		while( fgetc(fp) != '\n' ) if( feof(fp) ) break;
	}
	fclose(fp);
	sounds = (Mix_Chunk **) malloc(sizeof(psize)*sound_num);
	fp = fopen("sound/sounds.txt","r");
	for( x=0; !feof(fp); x++ ) {
		fscanf(fp,"%s",name); while( fgetc(fp) != '\n' ) if( feof(fp) ) break;
		sounds[x] = Mix_LoadWAV(name);
	}
	fclose(fp);
	
	// load music
	music = Mix_LoadMUS("music/dead.ogg");
	Mix_VolumeMusic(64);
	//Mix_PlayMusic(music, -1);
	musicplaying=0;
	
	// multiplayer
	if (SDLNet_Init() < 0) {
		g_Close();
		printf("ERROR: SDLNet_Init: %s\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
	}

	// starting a server
	if( server ) {
		// listen on the host's port
		if( !(sd = SDLNet_UDP_Open(PORT)) ) {
			g_Close();
			printf("ERROR: SDLNet_UDP_Open: %s\n", SDLNet_GetError());
			exit(EXIT_FAILURE);
		}
		
		// Allocate memory for the packet
		if( !(packet = SDLNet_AllocPacket(512)) ) {
			printf("ERROR: SDLNet_AllocPacket: %s\n", SDLNet_GetError());
			exit(EXIT_FAILURE);
		}
	}
	
	// joining a server
	else if( address != NULL ) {
		if( !(sd = SDLNet_UDP_Open(0)) ) {
			g_Close();
			printf("ERROR: SDLNet_UDP_Open: %s\n", SDLNet_GetError());
			exit(EXIT_FAILURE);
		}
		
		if( SDLNet_ResolveHost(&ip, address, PORT) < 0 ) {
			printf("ERROR: SDLNet_ResolveHost: %s\n", SDLNet_GetError());
			exit(EXIT_FAILURE);
		}
		
		// Allocate memory for the packet
		if( !(packet = SDLNet_AllocPacket(512)) ) {
			printf("ERROR: SDLNet_AllocPacket: %s\n", SDLNet_GetError());
			exit(EXIT_FAILURE);
		}
	}
	
	// report a success!
	if( address == NULL )
		i_Message( "Map loaded: %s", file );
	else
		i_Message( "Map loaded: %s\nConnected to %s", file, address );
	return(0);
}
Example #20
0
char *rocsmq_error() {
	return SDLNet_GetError();
}
Example #21
0
void Rekd2D::Core::Game::Run(char* title, unsigned int width, unsigned int height, unsigned int windowWidth, unsigned int windowHeight)
{
	SDL_Init(SDL_INIT_EVERYTHING);
	InitGL(2, 1);
	m_Window = new Window(title, width, height, windowWidth, windowHeight);
	int err = glewInit();
	if (err != 0) std::cout << "GLEW ERROR " << err << ": " << glewGetErrorString(err) << std::endl;
	Init();
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	err = SDLNet_Init();
	if (err != 0) std::cout << "SDLNet ERROR " << err << ": " << SDLNet_GetError() << std::endl;
	err = IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF);
	if (!err) std::cout << "IMG ERROR " << err << ": " << IMG_GetError() << std::endl;
	m_Renderer = new Renderer(m_Window);
	m_Window->GenerateFramebuffer();
	m_PostProcess = new PredefinedShader(
		"void main() { gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; gl_TexCoord[0] = gl_MultiTexCoord0; }",
		"uniform sampler2D sampler; void main() { gl_FragColor = texture2D(sampler, gl_TexCoord[0].st); }"
		);
	SDL_StartTextInput();
	Load();
	Event e;
	m_Window->Show();
	unsigned int last = 0, delta = 0;
	unsigned int now;
	MouseState s;
	KeyboardState ks;
	while (m_Window->Update())
	{
		m_Window->BindFramebuffer();
		now = SDL_GetTicks();
		if (now > last)
		{
			delta = now - last;
			last = now;
		}
		while (m_Window->PollEvent(&e))
		{
			s = Mouse::GetState();
			ks = Keyboard::GetState();
			if (e.Type == Enum::EventType::MouseMove)
			{
				s.X = (int)((e.MouseMove.DestinationX + e.MouseMove.RelativeX) / (float)m_Window->GetWidth() * width);
				s.Y = (int)((e.MouseMove.DestinationY + e.MouseMove.RelativeY) / (float)m_Window->GetHeight() * height);
				s.RelX = e.MouseMove.RelativeX;
				s.RelY = e.MouseMove.RelativeY;

				Mouse::SetState(s);
			}
			else if (e.Type == Enum::EventType::MouseClick)
			{
				s.X = (int)(e.MouseButton.X / (float)m_Window->GetWidth() * width);
				s.Y = (int)(e.MouseButton.Y / (float)m_Window->GetHeight() * height);
				if (e.MouseButton.Button < 4)
					s.MouseButtons[e.MouseButton.Button] = true;
				Mouse::SetState(s);
			}
			else if (e.Type == Enum::EventType::MouseRelease)
			{
				s.X = (int)(e.MouseButton.X / (float)m_Window->GetWidth() * width);
				s.Y = (int)(e.MouseButton.Y / (float)m_Window->GetHeight() * height);
				if (e.MouseButton.Button < 4)
					s.MouseButtons[e.MouseButton.Button] = false;
				Mouse::SetState(s);
			}
			else if (e.Type == Enum::EventType::KeyDown)
			{
				ks.Keys[e.Keyboard.KeyCode] = true;
				ks.Mods[e.Keyboard.KeyCode] = e.Keyboard.Modifiers;
				Keyboard::SetState(ks);
			}
			else if (e.Type == Enum::EventType::KeyUp)
			{
				ks.Keys[e.Keyboard.KeyCode] = false;
				ks.Mods[e.Keyboard.KeyCode] = 0;
				Keyboard::SetState(ks);
			}
			else if (e.Type == Enum::EventType::Text)
			{
				KeyDown(e.Text.Append, e.Text.Text, e.Text.Cursor, e.Text.SelectionLength);
			}
		}
		m_Renderer->Clear(Color(43, 78, 124));
		Update(delta);
		Render(delta);

		m_Window->UnbindFramebuffer();
		m_Renderer->Clear(Color(43, 78, 124));
		glLoadIdentity();
		m_PostProcess->Bind();
		m_Window->BindScreentex();
		glBegin(GL_QUADS);
		glTexCoord2f(0, 1);
		glVertex2f(0, 0);
		glTexCoord2f(1, 1);
		glVertex2f(width, 0);
		glTexCoord2f(1, 0);
		glVertex2f(width, height);
		glTexCoord2f(0, 0);
		glVertex2f(0, height);
		glEnd();
	}
	Unload();
	IMG_Quit();
	SDLNet_Quit();
	m_Renderer->Dispose();
	m_Window->Dispose();
	delete m_Window;
	delete m_Renderer;
	SDL_Quit();
}
Example #22
0
void Network::receive()
{
    SDLNet_SocketSet set;

    if (!(set = SDLNet_AllocSocketSet(1)))
    {
        setError("Error in SDLNet_AllocSocketSet(): " +
            std::string(SDLNet_GetError()));
        return;
    }

    if (SDLNet_TCP_AddSocket(set, mSocket) == -1)
    {
        setError("Error in SDLNet_AddSocket(): " +
            std::string(SDLNet_GetError()));
    }

    while (mState == CONNECTED)
    {
        // TODO Try to get this to block all the time while still being able
        // to escape the loop
        int numReady = SDLNet_CheckSockets(set, (static_cast<uint32_t>(500)));
        int ret;
        switch (numReady)
        {
            case -1:
                logger->log1("Error: SDLNet_CheckSockets");
                // FALLTHROUGH
            case 0:
                break;

            case 1:
                // Receive data from the socket
                SDL_mutexP(mMutex);
                ret = SDLNet_TCP_Recv(mSocket, mInBuffer + mInSize,
                                      BUFFER_SIZE - mInSize);

                if (!ret)
                {
                    // We got disconnected
                    mState = IDLE;
                    logger->log1("Disconnected.");
                }
                else if (ret < 0)
                {
                    setError(_("Connection to server terminated. ") +
                             std::string(SDLNet_GetError()));
                }
                else
                {
//                    DEBUGLOG("Receive " + toString(ret) + " bytes");
                    mInSize += ret;
                    if (mToSkip)
                    {
                        if (mInSize >= mToSkip)
                        {
                            mInSize -= mToSkip;
                            memmove(mInBuffer, mInBuffer + mToSkip, mInSize);
                            mToSkip = 0;
                        }
                        else
                        {
                            mToSkip -= mInSize;
                            mInSize = 0;
                        }
                    }
                }
                SDL_mutexV(mMutex);
                break;

            default:
                // more than one socket is ready..
                // this should not happen since we only listen once socket.
                std::stringstream errorStream;
                errorStream << "Error in SDLNet_TCP_Recv(), " << numReady
                            << " sockets are ready: " << SDLNet_GetError();
                setError(errorStream.str());
                break;
        }
    }

    if (SDLNet_TCP_DelSocket(set, mSocket) == -1)
        logger->log("Error in SDLNet_DelSocket(): %s", SDLNet_GetError());

    SDLNet_FreeSocketSet(set);
}
Example #23
0
int main( int argc, char * argv[] ) {
	
	IDCounter = 0;
	unsigned char consoleWidth = 60;
	for (Uint8 k = 0; k < 10; k++) {
		const char * newName = GenerateName();
		if ( strlen (newName) > consoleWidth ) {
			consoleWidth = 80;
			printf("\n");
		}
		consoleWidth -= strlen (newName);
		printf( "%s ", newName );
	}
	printf( "\n" );

	printf( "Initializing SDL system... " );
			if(SDL_Init(SDL_INIT_EVERYTHING) == -1)	{printf("\nSDL_Init: %s\n", SDL_GetError());exit(1);	}
			if(SDLNet_Init() == -1 )				{printf("\nSDLNet_Init: %s\n", SDLNet_GetError());exit(2);}	
	printf( "ok.\n" );
	
	printf( "Starting server...\n" );
			//
			//
			if( SDLNet_ResolveHost(&ip, NULL, 3879) < 0 ) {
				printf( "\nSDLNet_ResolveHost: %s\n", SDLNet_GetError());
				exit(1);
			} else {
				//ip.host = convFromIP(127,0,0,1);
				ip.port = 3879;
				printf( "Resolved address: %s\n", getStringAddress(ip));
			}
			socket = SDLNet_TCP_Open( &ip );
			if(!socket ) {
				printf( "\nSDLNet_TCP_Open: %s\n", SDLNet_GetError());
				exit(2);
			}

	printf( "ok.\n");
	
	SDLNet_TCP_AddSocket( socketSet, socket );

	printf("Waiting for clients...\n");

	acceptClientThread = SDL_CreateThread(clientNetLoop, NULL);
	
	updateLoopThread = SDL_CreateThread(updateLoop, NULL);

	char instr = 0;
	for(;;) {
		scanf("%c", &instr);
		if (instr == 'q')
			break;
		if (instr == 'a') {
			send(&lastSocket, 'm', "yopt", 4);
		}
		if (instr == 'b') {
			char * broadcastMsg = (char*)malloc(255);
			broadcastMsg[0] = 1;
			broadcastMsg[1] = 0;
			scanf("%[' 'A-z'\'''!'-'+']s", broadcastMsg);
			broadcast('m', broadcastMsg, strlen(broadcastMsg));
		}
		if (instr == 'w') {
			printf("startPos: %i; recvSize: %i\n", clients[0]->startPos, clients[0]->recvSize);
			for (unsigned char i = 0; i < clients[i]->recvSize; i++) {
				if (	clients[0]->msg[i] != '\n' 
					&&	clients[0]->msg[i] != 10)
					printf("%3i\'%c\'; ", (unsigned char)clients[0]->msg[i], (unsigned char)clients[0]->msg[i]);
				else
					printf("%3i\' \'; ", (unsigned char)clients[0]->msg[i]);
			}
			printf("\n");
		}
		instr = 0;
	}
	terminated = true;
	printf("Terminated.\n");
	int status = 0;
	printf("Wait for accepting thread end. ");
	SDL_WaitThread(acceptClientThread,&status);
	printf("Ended.\nClosing socket. ");
	SDLNet_TCP_Close(socket);
	printf("Closed.\n");
	SDL_Quit();
	return 0x127;
}
Example #24
0
int
main(int argc, char *argv[])
{
   SDL_Window  *window;
   CLC_CONFIG  config;
   Uint8       *kbdstate;
   SDL_Event   e;
   PLAYER      *me;
   PLAYER      *player;
   Uint32      time;
   IPaddress   srv_ip;
   TCPsocket   srv_sock;
   Uint16      magic;
   int         i;
   SDLNet_SocketSet srv_sset;
   char myname[PNAME_SIZE];
   unsigned char myno;

   if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_EVENTS) == -1)
   {
      fprintf(stderr, "SDL_Init: %s\n", SDL_GetError());
      exit(EXIT_FAILURE);
   }

   if (SDLNet_Init() == -1)
   {
      fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError());
      exit(EXIT_FAILURE);
   }

   parsecfg(&config);

   /*
    * Get player name.
    */
   printf("Wow such name: ");
   fgets(myname, PNAME_SIZE, stdin);

   for (i = 0; i < PNAME_SIZE; i++)
   {
      if (myname[i] == '\n')
      {
         myname[i] = '\0';
         break;
      }
   }


   /*
    * Connect to server!
    */
   if (SDLNet_ResolveHost(&srv_ip, config.defaultsrv,
            atoi(config.defaultport)))
   {
      fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError());
      exit(EXIT_FAILURE);
   }


   /*
    * Bind socket!
    */
   if (!(srv_sock = SDLNet_TCP_Open(&srv_ip)))
   {
      fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError());
      exit(EXIT_FAILURE);
   }


   /*
    * Add (a single) server socket to srv_sset for cheap hack for checking
    * the server socket's state.
    */
   srv_sset = SDLNet_AllocSocketSet(1);

   if (!srv_sset)
   {
      printf("SDLNet_AllocSocketSet: %s\n", SDLNet_GetError());
      exit(EXIT_FAILURE);
   }

   SDLNet_TCP_AddSocket(srv_sset, srv_sock);


   /*
    * Get maze, add connecting players to buffer and wait until the game
    * begins.
    */

   getmaze(srv_sock);

   window = SDL_CreateWindow(
         "MAZE OF TORMENT",
         SDL_WINDOWPOS_UNDEFINED,
         SDL_WINDOWPOS_UNDEFINED,
         config.win_width,
         config.win_height,
         config.win_flags
   );

   SDL_GetWindowSize(window, &config.win_width, &config.win_height);

   if (window == NULL)
   {
      fprintf(stderr, "Could not create window: %s\n",
            SDL_GetError());
      exit(EXIT_FAILURE);
   }

   renderer = SDL_CreateRenderer(window, -1, config.renderflags);

   hsprite  = loadPic("img/predator.gif");
   psprite  = loadPic("img/prey.gif");
   black    = loadPic("img/black.gif");

   /*
    * Initialize maze, and send player name.
    */
   MAZE.X = (config.win_width - MAZE.w * 16) / 2;
   MAZE.Y = (config.win_height - MAZE.h * 16) / 2;

   SDLNet_TCP_Send(srv_sock, myname, PNAME_SIZE);


   /*
    * Initialize maze and get the LOCAL player, then the REMOTE players.
    */

   SDLNet_TCP_Recv(srv_sock, &myno, 1);
   player = calloc(1, sizeof(PLAYER));

   if (!((magic = getshort(srv_sock)) == ADD_PLAYER))
   {
      printf("server not sending players\n!");
      exit(EXIT_FAILURE);
   }

   unsigned char hunter = addp(player, srv_sock);

   choose_hunter(player, hunter);
   me = choose_player(player, myno);

   SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255);
   draw_maze(MAZE.X, MAZE.Y);

   PLAYER *temp;

   for (temp = player->next; temp != NULL; temp = temp->next)
   {
      printf("drew player %d\n", temp->playerno);
      drawPlayer(temp);
   }
   
   printf("starting game!!\n");
   /*
    * Game loop!
    */
   
   for (;;)
   {
      time = SDL_GetTicks();

      /*
       * Poll the  network in each frame. Because.
       */

      int result, numready = SDLNet_CheckSockets(srv_sset, 0);

      if (numready == -1)
      {
         printf("SDLNet_CheckSockets: %s\n", SDLNet_GetError());
         perror("SDLNet_CheckSockets");
      }
      else if (numready)
      {
         unsigned char packet;
         unsigned char pnum, movx, movy;

         printf("srv socket is ready!!\n");

         if ((result = SDLNet_TCP_Recv(srv_sock, &packet, 2)) == 2)
         {
            switch (SDLNet_Read16(&packet))
            {
               case PLAYER_MOV:
                  puts("PLAYER_MOV");
                  pnum = getshort(srv_sock);
                  movx = getshort(srv_sock);
                  movy = getshort(srv_sock);

                  printf("player %d moved to (%d,%d)\n",
                              pnum, movx, movy);
                  movePlayer(choose_player(player,pnum), movx, movy);
                  break;

               case PLAYER_WIN:
                  puts("PLAYER_WIN");
                  break;

               case PLAYER_DC:
                  puts("PLAYER_DC");
                  pnum = getshort(srv_sock);
                  printf("Player %d disconnected!!\n", pnum);
                  removep(choose_player(player,pnum));
                  break;

               case PLAYER_DIE:
                  puts("PLAYER_DIE");
                  pnum = getshort(srv_sock);

                  if (pnum == myno)
                  {
                     puts("YOU ARE DEAD\nGAME OVER");
                     goto exit;
                  }
                  printf("Player %d deaded!!!!!\n", pnum);
                  removep(choose_player(player, pnum));
                  break;

            }
         }
         else if (result <= 0)
         {
            fprintf(stderr, "SDLNet_TCP_Recv: %s\n", SDLNet_GetError());
            fprintf(stderr, "Lost connection to the server?\n");
            break;
         }
      }

      /*
       * Poll for keys
       */
      if (SDL_PollEvent(&e))
      {
         if (e.type == SDL_QUIT)
         {
            break;
         }

         kbdstate = (Uint8 *) SDL_GetKeyboardState(NULL);

         if (kbdstate[SDL_SCANCODE_Q])
         {
            break;
         }

         local_player_update(srv_sock, me, player, SDL_GetKeyboardState(NULL));
      }

      SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255);
      SDL_RenderPresent(renderer);

      if (20 > (SDL_GetTicks() - time))
      {
         SDL_Delay(20 - (SDL_GetTicks() - time));
      }
   }

exit:
   SDL_DestroyTexture(psprite.texture);
   SDL_DestroyTexture(hsprite.texture);
   SDL_DestroyTexture(black.texture);
   free(player);
   free(MAZE.data);

   SDL_DestroyWindow(window);

   SDLNet_Quit();
   SDL_Quit();

   return 0;
}
Example #25
0
int main(int argc, char *argv[])
{
	if(argc != 4)
	{
		printf("Please run bot as such:\nDnDRollBot Server IP Nick\n\n");
		return(1);
	}

	SDLNet_SocketSet set;
	IPaddress ip;
	TCPsocket TCPsock;
	char *inbuffer = new char[1024], *buffer = new char[1024], *words[256] = {0}, *channels[16] = {0};
	char temp = '\0', *ptmp = 0;
	int inbufferpos = 0, x = 0, wordc = 0, chanc = 0, nd = 0, vd = 0;
	bool Done = false, LineReady = false, DoneParsing = false;

	srand((unsigned int)time(NULL));

	if(SDL_Init(0) == -1)
	{
		printf("SDL_Init: %s\n", SDL_GetError());
		CLEANUP();
		return(2);
	}

	if(SDLNet_Init() == -1)
	{
		printf("SDLNet_Init: %s\n", SDLNet_GetError());
		CLEANUP();
		return(3);
	}

	set = SDLNet_AllocSocketSet(1);
	if(!set)
	{
		printf("SDLNet_AllocSocketSet: %s\n", SDLNet_GetError());
		CLEANUP();
		return(4);
	}
	
	printf("SDL and SDL_net initiated successfully, resolving server...\n");

	if(SDLNet_ResolveHost(&ip, argv[1], atoi(argv[2])) == -1)
	{
		printf("SDLNet_ResolveHost: %s\n", SDLNet_GetError());
		CLEANUP();
		return(5);
	}

	printf("Host resolved, attempting to connect...\n");

	TCPsock = SDLNet_TCP_Open(&ip);
	if(!TCPsock)
	{
		printf("SDLNet_TCP_Open: %s\n", SDLNet_GetError());
		CLEANUP();
		return(6);
	}

	printf("Connected to host, handshaking...\n");

	sprintf(buffer, "NICK %s\n", argv[3]);
	SDLNet_TCP_Send(TCPsock, buffer, strlen(buffer));

	sprintf(buffer, "USER DnD 0 DnD :DnDRollBot\n");
	SDLNet_TCP_Send(TCPsock, buffer, strlen(buffer));

	while(!Done)
	{
		while(!LineReady)
		{
			if(SDLNet_TCP_Recv(TCPsock, &temp, 1) <= 0)
			{
				printf("SDLNet_TCP_Recv: %s\n", SDLNet_GetError());
				SDLNet_TCP_Close(TCPsock);
				CLEANUP();
				return(0);
			}

			inbuffer[inbufferpos] = temp;

			if(inbuffer[inbufferpos] == '\n')
			{
				LineReady = true;
				inbuffer[++inbufferpos] = '\0';
			}
			else
			{
				inbufferpos++;
			}

			if(inbufferpos >= 1020)
			{
				inbuffer[inbufferpos] = '\n';
				inbuffer[++inbufferpos] = '\0';
				LineReady = true;
			}
		}

		TrimBlanks(inbuffer);
		wordc = 0;

		printf("%s", inbuffer);

		//thanks again Hero, this is damn clever
		words[wordc++] = inbuffer;
		while(inbuffer[x] != '\0')
		{
			if(inbuffer[x] == ' ')
			{
				inbuffer[x] = '\0';
				words[wordc++] = &inbuffer[++x];
				continue;
			}
			x++;
		}
		
		//Do some fun parsing
		if(!strcasecmp(words[0], "PING"))
		{
			sprintf(buffer, "PONG %s", words[1]);
			SDLNet_TCP_Send(TCPsock, buffer, strlen(buffer));
		}

		if(!strcasecmp(words[1], "PRIVMSG"))
		{
			if(!strcasecmp(words[3] + 1, "!JOIN"))
			{
				ptmp = GrabAfter(words[4], wordc - 4);
				sprintf(buffer, "JOIN %s\n", ptmp);

				delete [] ptmp;
				ptmp = 0;				

				SDLNet_TCP_Send(TCPsock, buffer, strlen(buffer));
			}

			if(!strcasecmp(words[3] + 1, "!PART"))
			{
				ptmp = GrabAfter(words[4], wordc - 4);
				sprintf(buffer, "PART %s :%s\n", words[4], ptmp);

				delete [] ptmp;
				ptmp = 0;

				SDLNet_TCP_Send(TCPsock, buffer, strlen(buffer));
			}

			if(!strcasecmp(words[3] + 1, "!QUIT"))
			{
				ptmp = GrabAfter(words[4], wordc - 4);
				sprintf(buffer, "QUIT :%s\n", ptmp);

				delete [] ptmp;
				ptmp = 0;

				SDLNet_TCP_Send(TCPsock, buffer, strlen(buffer));
				Done = true;
			}

			if(!strcasecmp(words[3] + 1, "\001ACTION") && !strcasecmp(words[4], "slaps") && !strcasecmp(words[5], argv[3]))
			{
				strcpy(buffer, "QUIT :Ouch!\n");

				SDLNet_TCP_Send(TCPsock, buffer, strlen(buffer));
				Done = true;
			}

			if(!strcasecmp(words[3] + 1, "!ROLL"))
			{
				ptmp = strchr(words[4], 'd');
				if(!ptmp || !atoi(words[4]))
				{
					sprintf(buffer, "PRIVMSG %s :#d# is proper format!\n", words[2]);
					SDLNet_TCP_Send(TCPsock, buffer, strlen(buffer));
					
					for(x = 0; x <= wordc; x++) 
					{
						words[x] = 0;
					}

					LineReady = DoneParsing = false;
					wordc = x = inbufferpos = 0;
					continue;
				}

				*ptmp = '\0';
				ptmp++;

				nd = atoi(words[4]);
				vd = atoi(ptmp);

				if(nd == 0 || vd == 0)
				{
					sprintf(buffer, "PRIVMSG %s :#d# is proper format!\n", words[2]);
					SDLNet_TCP_Send(TCPsock, buffer, strlen(buffer));
					
					for(x = 0; x <= wordc; x++) 
					{
						words[x] = 0;
					}

					LineReady = DoneParsing = false;
					wordc = x = inbufferpos = 0;
					continue;
				}

				ptmp--;
				*ptmp = 'd';
				ptmp = 0;
	
				sprintf(buffer, "PRIVMSG %s :Rolled a %d!\n", words[2], Roll(nd, vd));
				SDLNet_TCP_Send(TCPsock, buffer, strlen(buffer));
			}
		}

		for(x = 0; x <= wordc; x++) 
		{
			words[x] = 0;
		}

		LineReady = DoneParsing = false;
		wordc = x = inbufferpos = 0;
	}

	sprintf(buffer, "QUIT\n");
	SDLNet_TCP_Send(TCPsock, buffer, strlen(buffer));
	
	SDLNet_TCP_Close(TCPsock);
	CLEANUP();

	return(0);
}