<commit_before>/*
   Copyright (c) 2010, The Mineserver Project
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
 * Neither the name of the The Mineserver Project nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdlib.h>
#ifdef WIN32
  #include <conio.h>
  #include <winsock2.h>
  #include <process.h>
#else
  #include <sys/socket.h>
  #include <netinet/in.h>
  #include <arpa/inet.h>
  #include <string.h>
  #include <netdb.h>
  #include <unistd.h>
  #include <sys/times.h>
#endif
#include <sys/types.h>
#include <fcntl.h>
#include <cassert>
#include <deque>
#include <map>
#include <iostream>
#include <fstream>
#include <event.h>
#include <ctime>
#include <vector>
#include <zlib.h>
#include <signal.h>

#include "constants.h"
#include "mineserver.h"
#include "logger.h"
#include "sockets.h"
#include "tools.h"
#include "map.h"
#include "user.h"
#include "chat.h"
#include "worldgen/mapgen.h"
#include "config.h"
#include "nbt.h"
#include "packets.h"
#include "physics.h"
#include "plugin.h"
#include "furnaceManager.h"
#include "screen.h"

#ifdef WIN32
static bool quit = false;
#endif

int setnonblock(int fd)
{
  #ifdef WIN32
  u_long iMode = 1;
  ioctlsocket(fd, FIONBIO, &iMode);
  #else
  int flags;

  flags  = fcntl(fd, F_GETFL);
  flags |= O_NONBLOCK;
  fcntl(fd, F_SETFL, flags);
  #endif

  return 1;
}

//Handle signals
void sighandler(int sig_num)
{
  Mineserver::get().stop();
}

int main(int argc, char *argv[])
{
  signal(SIGTERM, sighandler);
  signal(SIGINT, sighandler);

  srand(time(NULL));

  return Mineserver::get().run(argc, argv);
}

Mineserver::Mineserver()
{
}

event_base *Mineserver::getEventBase()
{
  return m_eventBase;
}

void Mineserver::updatePlayerList()
{
	// Update the player window
	Screen::get()->updatePlayerList(users());
}
int Mineserver::run(int argc, char *argv[])
{
  uint32 starttime = (uint32)time(0);
  uint32 tick      = (uint32)time(0);

	// Init our Screen
	Screen::get()->init(VERSION);
	Screen::get()->log("Welcome to Mineserver v" + VERSION);
	updatePlayerList();

  initConstants();

  std::string file_config;
  file_config.assign(CONFIG_FILE);
  std::string file_commands;
  file_commands.assign(COMMANDS_FILE);

  if (argc > 1)
    file_config.assign(argv[1]);

  // Initialize conf
  Conf::get()->load(file_config);
  Conf::get()->load(file_commands, COMMANDS_NAME_PREFIX);

  // Write PID to file
  std::ofstream pid_out((Conf::get()->sValue("pid_file")).c_str());
  if (!pid_out.fail())
#ifdef WIN32
     pid_out << _getpid();
#else
     pid_out << getpid();
#endif
  pid_out.close();

  // Load admin, banned and whitelisted users
  Conf::get()->loadRoles();
  Conf::get()->loadBanned();
  Conf::get()->loadWhitelist();
  // Load MOTD
  Chat::get()->checkMotd(Conf::get()->sValue("motd_file"));

  // Set physics enable state according to config
  Physics::get()->enabled = (Conf::get()->bValue("liquid_physics"));

  // Initialize map
  Map::get()->init();

  if (Conf::get()->bValue("map_generate_spawn"))
  {
    Screen::get()->log("Generating spawn area...");
    int size=Conf::get()->iValue("map_generate_spawn_size");
    bool show_progress = Conf::get()->bValue("map_generate_spawn_show_progress");
    #ifdef WIN32
      DWORD t_begin,t_end;
    #else
      clock_t t_begin,t_end;
    #endif

    for (int x=-size;x<=size;x++)
    {
    #ifdef WIN32
      if(show_progress)
        t_begin = timeGetTime();
    #else
      if(show_progress)
        t_begin = clock();
    #endif
      for (int z=-size;z<=size;z++)
      {
        Map::get()->loadMap(x, z);
      }
      if(show_progress)
      {
        #ifdef WIN32
          t_end = timeGetTime ();
          Screen::get()->log("" << ((x+size+1)*(size*2+1)) << "/" << (size*2+1)*(size*2+1) << " done. " << (t_end-t_begin)/(size*2+1) << "ms per chunk" << "");
        #else
          t_end = clock();
          Screen::get()->log(dtos((x+size+1)*(size*2+1)) + "/" + dtos((size*2+1)*(size*2+1)) + " done. " + dtos(((t_end-t_begin)/(CLOCKS_PER_SEC/1000))/(size*2+1)) + "ms per chunk");
        #endif

      }
    }
#ifdef _DEBUG
    Screen::get()->log("Spawn area ready!");
#endif
  }

  // Initialize packethandler
  PacketHandler::get()->init();

  // Load ip from config
  std::string ip = Conf::get()->sValue("ip");

  // Load port from config
  int port = Conf::get()->iValue("port");

  // Initialize plugins
  Plugin::get()->init();

#ifdef WIN32
  WSADATA wsaData;
  int iResult;
  // Initialize Winsock
  iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
  if(iResult != 0)
  {
    printf("WSAStartup failed with error: %d\n", iResult);
		Screen::get()->end();
    return EXIT_FAILURE;
  }
#endif

  struct sockaddr_in addresslisten;
  int reuse             = 1;

  m_eventBase = (event_base *)event_init();
#ifdef WIN32
  m_socketlisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
#else
  m_socketlisten = socket(AF_INET, SOCK_STREAM, 0);
#endif

  if(m_socketlisten < 0)
  {
    Screen::get()->log(LOG_ERROR, "Failed to create listen socket");
		Screen::get()->end();
    return 1;
  }

  memset(&addresslisten, 0, sizeof(addresslisten));

  addresslisten.sin_family      = AF_INET;
  addresslisten.sin_addr.s_addr = inet_addr(ip.c_str());
  addresslisten.sin_port        = htons(port);

  setsockopt(m_socketlisten, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse));

  //Bind to port
  if(bind(m_socketlisten, (struct sockaddr *)&addresslisten, sizeof(addresslisten)) < 0)
  {
    Screen::get()->log(LOG_ERROR, "Failed to bind");
    return 1;
  }

  if(listen(m_socketlisten, 5) < 0)
  {
    Screen::get()->log(LOG_ERROR, "Failed to listen to socket");
		Screen::get()->end();
    return 1;
  }

  setnonblock(m_socketlisten);
  event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL);
  event_add(&m_listenEvent, NULL);

 /* std::cout <<
  "   _____  .__  "<<
  std::endl<<
  "  /     \\ |__| ____   ____   ______ ______________  __ ___________ "<<
  std::endl<<
  " /  \\ /  \\|  |/    \\_/ __ \\ /  ___// __ \\_  __ \\  \\/ // __ \\_  __ \\"<<
  std::endl<<
  "/    Y    \\  |   |  \\  ___/ \\___ \\\\  ___/|  | \\/\\   /\\  ___/|  | \\/"<<
  std::endl<<
  "\\____|__  /__|___|  /\\___  >____  >\\___  >__|    \\_/  \\___  >__|   "<<
  std::endl<<
  "        \\/        \\/     \\/     \\/     \\/                 \\/       "<<
  std::endl<<
  "Version " << VERSION <<" by The Mineserver Project"<<
  std::endl << std::endl;
*/
  if(ip == "0.0.0.0")
  {
    // Print all local IPs
    char name[255];
    gethostname ( name, sizeof(name));
    struct hostent *hostinfo = gethostbyname(name);
    Screen::get()->log("Listening on: ");
    int ipIndex = 0;
    while(hostinfo->h_addr_list[ipIndex]) {
        std::string ip(inet_ntoa(*(struct in_addr *)hostinfo->h_addr_list[ipIndex++]));
        Screen::get()->log(" " + ip + ":" + dtos(port));
    }
  }
  else
  {
		std::string myip(ip);
    Screen::get()->log("Listening on " + myip + ":" + dtos(port));
  }
  //std::cout << std::endl;

  timeval loopTime;
  loopTime.tv_sec  = 0;
  loopTime.tv_usec = 200000; //200ms

  m_running=true;
  event_base_loopexit(m_eventBase, &loopTime);

  User *serverUser = new User(-1, -1);
  serverUser->changeNick("[Server]");

  while(m_running && event_base_loop(m_eventBase, 0) == 0)
  {

    // Check for key input from server console (get's triggered when console hits return)
    if (kbhit() != 0)
    {
      // Loop thru all chars up until CRLF
      std::string consoleCommand;
      char c;
      do
      {
        c = fgetc (stdin);
        consoleCommand.push_back(c);
      } while (c != '\n');

      // Now handle this command as normal
      if (consoleCommand[0] == '/' || consoleCommand[0] == '&' || consoleCommand[0] == '%')
      {
        Chat::get()->handleMsg(serverUser, consoleCommand);
        Screen::get()->log("Command sent");
      }
    }

    if(time(0)-starttime > 10)
    {
      starttime = (uint32)time(0);
      //Screen::get()->log("Currently " + User::all().size() + " users in!");

      //If users, ping them
      if(User::all().size() > 0)
      {
        //0x00 package
        uint8 data = 0;
        User::all()[0]->sendAll(&data, 1);

        //Send server time
        Packet pkt;
        pkt << (sint8)PACKET_TIME_UPDATE << (sint64)Map::get()->mapTime;
        User::all()[0]->sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen());
      }

      //Try to load release time from config
      int map_release_time = Conf::get()->iValue("map_release_time");

      //Release chunks not used in <map_release_time> seconds
      std::vector<uint32> toRelease;
      for(std::map<uint32, int>::const_iterator it = Map::get()->mapLastused.begin();
          it != Map::get()->mapLastused.end();
          ++it)
      {
        if(Map::get()->mapLastused[it->first] <= time(0)-map_release_time)
          toRelease.push_back(it->first);
      }

      int x_temp, z_temp;
      for(unsigned i = 0; i < toRelease.size(); i++)
      {
        Map::get()->idToPos(toRelease[i], &x_temp, &z_temp);
        Map::get()->releaseMap(x_temp, z_temp);
      }
    }

    //Every second
    if(time(0)-tick > 0)
    {
      tick = (uint32)time(0);
      //Loop users
      for(unsigned int i = 0; i < User::all().size(); i++)
      {
        User::all()[i]->pushMap();
        User::all()[i]->popMap();

        //Minecart hacks!!
        if(User::all()[i]->attachedTo)
        {
          Packet pkt;
          pkt << PACKET_ENTITY_VELOCITY << (sint32)User::all()[i]->attachedTo <<  (sint16)10000       << (sint16)0 << (sint16)0;
          //pkt << PACKET_ENTITY_RELATIVE_MOVE << (sint32)User::all()[i]->attachedTo <<  (sint8)100       << (sint8)0 << (sint8)0;
          User::all()[i]->sendAll((uint8 *)pkt.getWrite(), pkt.getWriteLen());
        }
      }
      Map::get()->mapTime+=20;
      if(Map::get()->mapTime>=24000) Map::get()->mapTime=0;

      Map::get()->checkGenTrees();

      // Check for Furnace activity
      FurnaceManager::get()->update();

    }

    //Physics simulation every 200ms
    Physics::get()->update();

    //Underwater check / drowning
    for( unsigned int i = 0; i < User::all().size(); i++ )
      User::all()[i]->isUnderwater();

    event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL);
    event_add(&m_listenEvent, NULL);

    event_base_loopexit(m_eventBase, &loopTime);
  }

#ifdef WIN32
  closesocket(m_socketlisten);
#else
  close(m_socketlisten);
#endif

  // Remove the PID file
#ifdef WIN32
  _unlink((Conf::get()->sValue("pid_file")).c_str());
#else
  unlink((Conf::get()->sValue("pid_file")).c_str());
#endif

  /* Free memory */
  PacketHandler::get()->free();
  Map::get()->free();
  Physics::get()->free();
  FurnaceManager::get()->free();
  Chat::get()->free();
  Conf::get()->free();
  Plugin::get()->free();
  Logger::get()->free();
  MapGen::get()->free();

	// End our NCurses session
	Screen::get()->end();

  return EXIT_SUCCESS;
}

bool Mineserver::stop()
{
  m_running=false;

  return true;
}

<commit_msg>Fixed a WIN32 call...<commit_after>/*
   Copyright (c) 2010, The Mineserver Project
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
 * Neither the name of the The Mineserver Project nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdlib.h>
#ifdef WIN32
  #include <conio.h>
  #include <winsock2.h>
  #include <process.h>
#else
  #include <sys/socket.h>
  #include <netinet/in.h>
  #include <arpa/inet.h>
  #include <string.h>
  #include <netdb.h>
  #include <unistd.h>
  #include <sys/times.h>
#endif
#include <sys/types.h>
#include <fcntl.h>
#include <cassert>
#include <deque>
#include <map>
#include <iostream>
#include <fstream>
#include <event.h>
#include <ctime>
#include <vector>
#include <zlib.h>
#include <signal.h>

#include "constants.h"
#include "mineserver.h"
#include "logger.h"
#include "sockets.h"
#include "tools.h"
#include "map.h"
#include "user.h"
#include "chat.h"
#include "worldgen/mapgen.h"
#include "config.h"
#include "nbt.h"
#include "packets.h"
#include "physics.h"
#include "plugin.h"
#include "furnaceManager.h"
#include "screen.h"

#ifdef WIN32
static bool quit = false;
#endif

int setnonblock(int fd)
{
  #ifdef WIN32
  u_long iMode = 1;
  ioctlsocket(fd, FIONBIO, &iMode);
  #else
  int flags;

  flags  = fcntl(fd, F_GETFL);
  flags |= O_NONBLOCK;
  fcntl(fd, F_SETFL, flags);
  #endif

  return 1;
}

//Handle signals
void sighandler(int sig_num)
{
  Mineserver::get().stop();
}

int main(int argc, char *argv[])
{
  signal(SIGTERM, sighandler);
  signal(SIGINT, sighandler);

  srand(time(NULL));

  return Mineserver::get().run(argc, argv);
}

Mineserver::Mineserver()
{
}

event_base *Mineserver::getEventBase()
{
  return m_eventBase;
}

void Mineserver::updatePlayerList()
{
	// Update the player window
	Screen::get()->updatePlayerList(users());
}
int Mineserver::run(int argc, char *argv[])
{
  uint32 starttime = (uint32)time(0);
  uint32 tick      = (uint32)time(0);

	// Init our Screen
	Screen::get()->init(VERSION);
	Screen::get()->log("Welcome to Mineserver v" + VERSION);
	updatePlayerList();

  initConstants();

  std::string file_config;
  file_config.assign(CONFIG_FILE);
  std::string file_commands;
  file_commands.assign(COMMANDS_FILE);

  if (argc > 1)
    file_config.assign(argv[1]);

  // Initialize conf
  Conf::get()->load(file_config);
  Conf::get()->load(file_commands, COMMANDS_NAME_PREFIX);

  // Write PID to file
  std::ofstream pid_out((Conf::get()->sValue("pid_file")).c_str());
  if (!pid_out.fail())
#ifdef WIN32
     pid_out << _getpid();
#else
     pid_out << getpid();
#endif
  pid_out.close();

  // Load admin, banned and whitelisted users
  Conf::get()->loadRoles();
  Conf::get()->loadBanned();
  Conf::get()->loadWhitelist();
  // Load MOTD
  Chat::get()->checkMotd(Conf::get()->sValue("motd_file"));

  // Set physics enable state according to config
  Physics::get()->enabled = (Conf::get()->bValue("liquid_physics"));

  // Initialize map
  Map::get()->init();

  if (Conf::get()->bValue("map_generate_spawn"))
  {
    Screen::get()->log("Generating spawn area...");
    int size=Conf::get()->iValue("map_generate_spawn_size");
    bool show_progress = Conf::get()->bValue("map_generate_spawn_show_progress");
    #ifdef WIN32
      DWORD t_begin,t_end;
    #else
      clock_t t_begin,t_end;
    #endif

    for (int x=-size;x<=size;x++)
    {
    #ifdef WIN32
      if(show_progress)
        t_begin = timeGetTime();
    #else
      if(show_progress)
        t_begin = clock();
    #endif
      for (int z=-size;z<=size;z++)
      {
        Map::get()->loadMap(x, z);
      }
      if(show_progress)
      {
        #ifdef WIN32
          t_end = timeGetTime ();
          Screen::get()->log(dtos((x+size+1)*(size*2+1)) + "/" + dtos((size*2+1)*(size*2+1)) + " done. " + dtos((t_end-t_begin)/(size*2+1)) + "ms per chunk");
        #else
          t_end = clock();
          Screen::get()->log(dtos((x+size+1)*(size*2+1)) + "/" + dtos((size*2+1)*(size*2+1)) + " done. " + dtos(((t_end-t_begin)/(CLOCKS_PER_SEC/1000))/(size*2+1)) + "ms per chunk");
        #endif

      }
    }
#ifdef _DEBUG
    Screen::get()->log("Spawn area ready!");
#endif
  }

  // Initialize packethandler
  PacketHandler::get()->init();

  // Load ip from config
  std::string ip = Conf::get()->sValue("ip");

  // Load port from config
  int port = Conf::get()->iValue("port");

  // Initialize plugins
  Plugin::get()->init();

#ifdef WIN32
  WSADATA wsaData;
  int iResult;
  // Initialize Winsock
  iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
  if(iResult != 0)
  {
    printf("WSAStartup failed with error: %d\n", iResult);
		Screen::get()->end();
    return EXIT_FAILURE;
  }
#endif

  struct sockaddr_in addresslisten;
  int reuse             = 1;

  m_eventBase = (event_base *)event_init();
#ifdef WIN32
  m_socketlisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
#else
  m_socketlisten = socket(AF_INET, SOCK_STREAM, 0);
#endif

  if(m_socketlisten < 0)
  {
    Screen::get()->log(LOG_ERROR, "Failed to create listen socket");
		Screen::get()->end();
    return 1;
  }

  memset(&addresslisten, 0, sizeof(addresslisten));

  addresslisten.sin_family      = AF_INET;
  addresslisten.sin_addr.s_addr = inet_addr(ip.c_str());
  addresslisten.sin_port        = htons(port);

  setsockopt(m_socketlisten, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse));

  //Bind to port
  if(bind(m_socketlisten, (struct sockaddr *)&addresslisten, sizeof(addresslisten)) < 0)
  {
    Screen::get()->log(LOG_ERROR, "Failed to bind");
    return 1;
  }

  if(listen(m_socketlisten, 5) < 0)
  {
    Screen::get()->log(LOG_ERROR, "Failed to listen to socket");
		Screen::get()->end();
    return 1;
  }

  setnonblock(m_socketlisten);
  event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL);
  event_add(&m_listenEvent, NULL);

 /* std::cout <<
  "   _____  .__  "<<
  std::endl<<
  "  /     \\ |__| ____   ____   ______ ______________  __ ___________ "<<
  std::endl<<
  " /  \\ /  \\|  |/    \\_/ __ \\ /  ___// __ \\_  __ \\  \\/ // __ \\_  __ \\"<<
  std::endl<<
  "/    Y    \\  |   |  \\  ___/ \\___ \\\\  ___/|  | \\/\\   /\\  ___/|  | \\/"<<
  std::endl<<
  "\\____|__  /__|___|  /\\___  >____  >\\___  >__|    \\_/  \\___  >__|   "<<
  std::endl<<
  "        \\/        \\/     \\/     \\/     \\/                 \\/       "<<
  std::endl<<
  "Version " << VERSION <<" by The Mineserver Project"<<
  std::endl << std::endl;
*/
  if(ip == "0.0.0.0")
  {
    // Print all local IPs
    char name[255];
    gethostname ( name, sizeof(name));
    struct hostent *hostinfo = gethostbyname(name);
    Screen::get()->log("Listening on: ");
    int ipIndex = 0;
    while(hostinfo->h_addr_list[ipIndex]) {
        std::string ip(inet_ntoa(*(struct in_addr *)hostinfo->h_addr_list[ipIndex++]));
        Screen::get()->log(" " + ip + ":" + dtos(port));
    }
  }
  else
  {
		std::string myip(ip);
    Screen::get()->log("Listening on " + myip + ":" + dtos(port));
  }
  //std::cout << std::endl;

  timeval loopTime;
  loopTime.tv_sec  = 0;
  loopTime.tv_usec = 200000; //200ms

  m_running=true;
  event_base_loopexit(m_eventBase, &loopTime);

  User *serverUser = new User(-1, -1);
  serverUser->changeNick("[Server]");

  while(m_running && event_base_loop(m_eventBase, 0) == 0)
  {

    // Check for key input from server console (get's triggered when console hits return)
    if (kbhit() != 0)
    {
      // Loop thru all chars up until CRLF
      std::string consoleCommand;
      char c;
      do
      {
        c = fgetc (stdin);
        consoleCommand.push_back(c);
      } while (c != '\n');

      // Now handle this command as normal
      if (consoleCommand[0] == '/' || consoleCommand[0] == '&' || consoleCommand[0] == '%')
      {
        Chat::get()->handleMsg(serverUser, consoleCommand);
        Screen::get()->log("Command sent");
      }
    }

    if(time(0)-starttime > 10)
    {
      starttime = (uint32)time(0);
      //Screen::get()->log("Currently " + User::all().size() + " users in!");

      //If users, ping them
      if(User::all().size() > 0)
      {
        //0x00 package
        uint8 data = 0;
        User::all()[0]->sendAll(&data, 1);

        //Send server time
        Packet pkt;
        pkt << (sint8)PACKET_TIME_UPDATE << (sint64)Map::get()->mapTime;
        User::all()[0]->sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen());
      }

      //Try to load release time from config
      int map_release_time = Conf::get()->iValue("map_release_time");

      //Release chunks not used in <map_release_time> seconds
      std::vector<uint32> toRelease;
      for(std::map<uint32, int>::const_iterator it = Map::get()->mapLastused.begin();
          it != Map::get()->mapLastused.end();
          ++it)
      {
        if(Map::get()->mapLastused[it->first] <= time(0)-map_release_time)
          toRelease.push_back(it->first);
      }

      int x_temp, z_temp;
      for(unsigned i = 0; i < toRelease.size(); i++)
      {
        Map::get()->idToPos(toRelease[i], &x_temp, &z_temp);
        Map::get()->releaseMap(x_temp, z_temp);
      }
    }

    //Every second
    if(time(0)-tick > 0)
    {
      tick = (uint32)time(0);
      //Loop users
      for(unsigned int i = 0; i < User::all().size(); i++)
      {
        User::all()[i]->pushMap();
        User::all()[i]->popMap();

        //Minecart hacks!!
        if(User::all()[i]->attachedTo)
        {
          Packet pkt;
          pkt << PACKET_ENTITY_VELOCITY << (sint32)User::all()[i]->attachedTo <<  (sint16)10000       << (sint16)0 << (sint16)0;
          //pkt << PACKET_ENTITY_RELATIVE_MOVE << (sint32)User::all()[i]->attachedTo <<  (sint8)100       << (sint8)0 << (sint8)0;
          User::all()[i]->sendAll((uint8 *)pkt.getWrite(), pkt.getWriteLen());
        }
      }
      Map::get()->mapTime+=20;
      if(Map::get()->mapTime>=24000) Map::get()->mapTime=0;

      Map::get()->checkGenTrees();

      // Check for Furnace activity
      FurnaceManager::get()->update();

    }

    //Physics simulation every 200ms
    Physics::get()->update();

    //Underwater check / drowning
    for( unsigned int i = 0; i < User::all().size(); i++ )
      User::all()[i]->isUnderwater();

    event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL);
    event_add(&m_listenEvent, NULL);

    event_base_loopexit(m_eventBase, &loopTime);
  }

#ifdef WIN32
  closesocket(m_socketlisten);
#else
  close(m_socketlisten);
#endif

  // Remove the PID file
#ifdef WIN32
  _unlink((Conf::get()->sValue("pid_file")).c_str());
#else
  unlink((Conf::get()->sValue("pid_file")).c_str());
#endif

  /* Free memory */
  PacketHandler::get()->free();
  Map::get()->free();
  Physics::get()->free();
  FurnaceManager::get()->free();
  Chat::get()->free();
  Conf::get()->free();
  Plugin::get()->free();
  Logger::get()->free();
  MapGen::get()->free();

	// End our NCurses session
	Screen::get()->end();

  return EXIT_SUCCESS;
}

bool Mineserver::stop()
{
  m_running=false;

  return true;
}

<|endoftext|>


<commit_before><commit_msg>Minor.<commit_after><|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkRotationalExtrusionFilter.cc
  Language:  C++
  Date:      09 Oct 1995
  Version:   1.13

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include "vtkRotationalExtrusionFilter.hh"
#include "vtkMath.hh"
#include "vtkIdList.hh"

// Description:
// Create object with capping on, angle of 360 degrees, resolution = 12, and
// no translation along z-axis.
// vector (0,0,1), and point (0,0,0).
vtkRotationalExtrusionFilter::vtkRotationalExtrusionFilter()
{
  this->Capping = 1;
  this->Angle = 360.0;
  this->DeltaRadius = 0.0;
  this->Translation = 0.0;
  this->Resolution = 12; // 30 degree increments
}

void vtkRotationalExtrusionFilter::Execute()
{
  int numPts, numCells;
  vtkPolyData *input=(vtkPolyData *)this->Input;
  vtkPointData *pd=input->GetPointData();
  vtkPolyData mesh;
  vtkPoints *inPts;
  vtkCellArray *inVerts, *inLines, *inPolys, *inStrips;
  int npts, *pts, numEdges, cellId, dim;
  int ptId, ncells;
  float *x, newX[3], radius, angleIncr, radIncr, transIncr;
  vtkFloatPoints *newPts;
  vtkCellArray *newLines=NULL, *newPolys=NULL, *newStrips=NULL;
  vtkCell *cell, *edge;
  vtkIdList cellIds(VTK_CELL_SIZE), *cellPts;
  vtkMath math;
  int i, j, k, p1, p2;
  vtkPolyData *output=(vtkPolyData *)this->Output;
  vtkPointData *outPD=output->GetPointData();
//
// Initialize / check input
//
  vtkDebugMacro(<<"Rotationally extruding data");

  numPts = input->GetNumberOfPoints();
  numCells = input->GetNumberOfCells();
  if (numPts < 1 || numCells < 1)
    {
    vtkErrorMacro(<<"No data to extrude!");
    return;
    }
//
// Build cell data structure.
//
  inPts = input->GetPoints();
  inVerts = input->GetVerts();
  inLines = input->GetLines();
  inPolys = input->GetPolys();
  inStrips = input->GetStrips();
  mesh.SetPoints(inPts);
  mesh.SetVerts(inVerts);
  mesh.SetLines(inLines);
  mesh.SetPolys(inPolys);
  mesh.SetStrips(inStrips);
  if ( inPolys || inStrips ) mesh.BuildLinks();
//
// Allocate memory for output. We don't copy normals because surface geometry
// is modified.
//
  outPD->CopyNormalsOff();
  outPD->CopyAllocate(pd,(this->Resolution+1)*numPts);
  newPts = new vtkFloatPoints((this->Resolution+1)*numPts);
  if ( (ncells=inVerts->GetNumberOfCells()) > 0 )
    {
    newLines = new vtkCellArray;
    newLines->Allocate(newLines->EstimateSize(ncells,this->Resolution+1));
    }
  // arbitrary initial allocation size
  ncells = inLines->GetNumberOfCells() + inPolys->GetNumberOfCells()/10 +
           inStrips->GetNumberOfCells()/10;
  ncells = (ncells < 100 ? 100 : ncells);
  newStrips = new vtkCellArray;
  newStrips->Allocate(newStrips->EstimateSize(ncells,2*(this->Resolution+1)));

  // copy points
  for (ptId=0; ptId < numPts; ptId++) //base level
    {
    newPts->SetPoint(ptId,inPts->GetPoint(ptId));
    outPD->CopyData(pd,ptId,ptId);
    }

  radIncr = this->DeltaRadius / this->Resolution;
  transIncr = this->Translation / this->Resolution;
  angleIncr = this->Angle / this->Resolution;
  for ( i = 1; i <= this->Resolution; i++ )
    {
    for (ptId=0; ptId < numPts; ptId++)
      {
      x = inPts->GetPoint(ptId);
      radius = sqrt(x[0]*x[0] + x[1]*x[1]) + i * radIncr;
      newX[0] = radius * cos (i*angleIncr*math.DegreesToRadians());
      newX[1] = radius * sin (i*angleIncr*math.DegreesToRadians());
      newX[2] = x[2] + i * transIncr;

      newPts->SetPoint(ptId+i*numPts,newX);
      outPD->CopyData(pd,ptId,ptId+i*numPts);
      }
    }
//
// If capping is on, copy 2D cells to output (plus create cap)
//
  if ( this->Capping && (this->Angle != 360.0 || this->DeltaRadius != 0.0 ||
  this->Translation != 0.0) )
    {
    if ( inPolys->GetNumberOfCells() > 0 )
      {
      newPolys = new vtkCellArray(inPolys->GetSize());
      for ( inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); )
        {
        newPolys->InsertNextCell(npts,pts);
        newPolys->InsertNextCell(npts);
	// note that we need to reverse the vertex order on the far cap
        for (i=0; i < npts; i++)
          newPolys->InsertCellPoint(pts[i] + this->Resolution*numPts);
        }
      }

    if ( inStrips->GetNumberOfCells() > 0 )
      {
      for ( inStrips->InitTraversal(); inStrips->GetNextCell(npts,pts); )
        {
        newStrips->InsertNextCell(npts,pts);
        newStrips->InsertNextCell(npts);
        for (i=0; i < npts; i++)
          newStrips->InsertCellPoint(pts[i] + this->Resolution*numPts);
        }
      }
    }
//
// Loop over all polygons and triangle strips searching for boundary edges.
// If boundary edge found, extrude triangle strip.
//
  for ( cellId=0; cellId < numCells; cellId++)
    {
    cell = mesh.GetCell(cellId);
    cellPts = cell->GetPointIds();

    if ( (dim=cell->GetCellDimension()) == 0 ) //create lines from points
      {
      for (i=0; i<cellPts->GetNumberOfIds(); i++)
        {
        ptId = cellPts->GetId(i);
        newLines->InsertNextCell(this->Resolution+1);

        for ( j=0; j<=this->Resolution; j++ )
          newLines->InsertCellPoint(ptId + j*numPts);
        }
      }

    else if ( dim == 1 ) // create strips from lines
      {
      for (i=0; i < (cellPts->GetNumberOfIds()-1); i++)
        {
        p1 = cellPts->GetId(i);
        p2 = cellPts->GetId(i+1);
        newStrips->InsertNextCell(2*(this->Resolution+1));
        for ( j=0; j<=this->Resolution; j++)
          {
          newStrips->InsertCellPoint(p2 + j*numPts);
          newStrips->InsertCellPoint(p1 + j*numPts);
          }
        }
      }

    else if ( dim == 2 ) // create strips from boundary edges
      {
      numEdges = cell->GetNumberOfEdges();
      for (i=0; i<numEdges; i++)
        {
        edge = cell->GetEdge(i);
        for (j=0; j<(edge->GetNumberOfPoints()-1); j++)
          {
          p1 = edge->PointIds.GetId(j);
          p2 = edge->PointIds.GetId(j+1);
          mesh.GetCellEdgeNeighbors(cellId, p1, p2, cellIds);

          if ( cellIds.GetNumberOfIds() < 1 ) //generate strip
            {
            newStrips->InsertNextCell(2*(this->Resolution+1));
            for (k=0; k<=this->Resolution; k++)
              {
              newStrips->InsertCellPoint(p2 + k*numPts);
              newStrips->InsertCellPoint(p1 + k*numPts);
              }
            } //if boundary edge
          } //for each sub-edge
        } //for each edge
      } //for each polygon or triangle strip
    } //for each cell
//
// Update ourselves and release memory
//
  output->SetPoints(newPts);
  newPts->Delete();

  if ( newLines )
    {
    output->SetLines(newLines);
    newLines->Delete();
    }

  if ( newPolys )
    {
    output->SetPolys(newPolys);
    newPolys->Delete();
    }

  output->SetStrips(newStrips);
  newStrips->Delete();

  output->Squeeze();
}

void vtkRotationalExtrusionFilter::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkPolyToPolyFilter::PrintSelf(os,indent);

  os << indent << "Resolution: " << this->Resolution << "\n";
  os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n");
  os << indent << "Angle: " << this->Angle << "\n";
  os << indent << "Translation: " << this->Translation << "\n";
  os << indent << "Delta Radius: " << this->DeltaRadius << "\n";
}

<commit_msg>ERR: Fixed x-y plane bug.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkRotationalExtrusionFilter.cc
  Language:  C++
  Date:      09 Oct 1995
  Version:   1.13

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include "vtkRotationalExtrusionFilter.hh"
#include "vtkMath.hh"
#include "vtkIdList.hh"

// Description:
// Create object with capping on, angle of 360 degrees, resolution = 12, and
// no translation along z-axis.
// vector (0,0,1), and point (0,0,0).
vtkRotationalExtrusionFilter::vtkRotationalExtrusionFilter()
{
  this->Capping = 1;
  this->Angle = 360.0;
  this->DeltaRadius = 0.0;
  this->Translation = 0.0;
  this->Resolution = 12; // 30 degree increments
}

void vtkRotationalExtrusionFilter::Execute()
{
  int numPts, numCells;
  vtkPolyData *input=(vtkPolyData *)this->Input;
  vtkPointData *pd=input->GetPointData();
  vtkPolyData mesh;
  vtkPoints *inPts;
  vtkCellArray *inVerts, *inLines, *inPolys, *inStrips;
  int npts, *pts, numEdges, cellId, dim;
  int ptId, ncells;
  float *x, newX[3], radius, angleIncr, radIncr, transIncr;
  float psi, theta;
  vtkFloatPoints *newPts;
  vtkCellArray *newLines=NULL, *newPolys=NULL, *newStrips=NULL;
  vtkCell *cell, *edge;
  vtkIdList cellIds(VTK_CELL_SIZE), *cellPts;
  vtkMath math;
  int i, j, k, p1, p2;
  vtkPolyData *output=(vtkPolyData *)this->Output;
  vtkPointData *outPD=output->GetPointData();
//
// Initialize / check input
//
  vtkDebugMacro(<<"Rotationally extruding data");

  numPts = input->GetNumberOfPoints();
  numCells = input->GetNumberOfCells();
  if (numPts < 1 || numCells < 1)
    {
    vtkErrorMacro(<<"No data to extrude!");
    return;
    }
//
// Build cell data structure.
//
  inPts = input->GetPoints();
  inVerts = input->GetVerts();
  inLines = input->GetLines();
  inPolys = input->GetPolys();
  inStrips = input->GetStrips();
  mesh.SetPoints(inPts);
  mesh.SetVerts(inVerts);
  mesh.SetLines(inLines);
  mesh.SetPolys(inPolys);
  mesh.SetStrips(inStrips);
  if ( inPolys || inStrips ) mesh.BuildLinks();
//
// Allocate memory for output. We don't copy normals because surface geometry
// is modified.
//
  outPD->CopyNormalsOff();
  outPD->CopyAllocate(pd,(this->Resolution+1)*numPts);
  newPts = new vtkFloatPoints((this->Resolution+1)*numPts);
  if ( (ncells=inVerts->GetNumberOfCells()) > 0 )
    {
    newLines = new vtkCellArray;
    newLines->Allocate(newLines->EstimateSize(ncells,this->Resolution+1));
    }
  // arbitrary initial allocation size
  ncells = inLines->GetNumberOfCells() + inPolys->GetNumberOfCells()/10 +
           inStrips->GetNumberOfCells()/10;
  ncells = (ncells < 100 ? 100 : ncells);
  newStrips = new vtkCellArray;
  newStrips->Allocate(newStrips->EstimateSize(ncells,2*(this->Resolution+1)));

  // copy points
  for (ptId=0; ptId < numPts; ptId++) //base level
    {
    newPts->SetPoint(ptId,inPts->GetPoint(ptId));
    outPD->CopyData(pd,ptId,ptId);
    }

  // loop assumes rotation around z-axis
  radIncr = this->DeltaRadius / this->Resolution;
  transIncr = this->Translation / this->Resolution;
  angleIncr = this->Angle / this->Resolution * math.DegreesToRadians();
  for ( i = 1; i <= this->Resolution; i++ )
    {
    for (ptId=0; ptId < numPts; ptId++)
      {
      x = inPts->GetPoint(ptId);
      //convert to cylindrical
      radius = sqrt(x[0]*x[0] + x[1]*x[1]);
      theta = acos((double)x[0]/radius);
      if ( (psi=asin((double)x[1]/radius)) < 0.0 )
        {
        if ( theta > 0.0 ) theta = 2.0*math.Pi() + psi;
        else theta = math.Pi() - psi;
        }

      //increment angle
      radius += i*radIncr;
      newX[0] = radius * cos (i*angleIncr + theta);
      newX[1] = radius * sin (i*angleIncr + theta);
      newX[2] = x[2] + i * transIncr;

      newPts->SetPoint(ptId+i*numPts,newX);
      outPD->CopyData(pd,ptId,ptId+i*numPts);
      }
    }
//
// If capping is on, copy 2D cells to output (plus create cap)
//
  if ( this->Capping && (this->Angle != 360.0 || this->DeltaRadius != 0.0 ||
  this->Translation != 0.0) )
    {
    if ( inPolys->GetNumberOfCells() > 0 )
      {
      newPolys = new vtkCellArray(inPolys->GetSize());
      for ( inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); )
        {
        newPolys->InsertNextCell(npts,pts);
        newPolys->InsertNextCell(npts);
	// note that we need to reverse the vertex order on the far cap
        for (i=0; i < npts; i++)
          newPolys->InsertCellPoint(pts[i] + this->Resolution*numPts);
        }
      }

    if ( inStrips->GetNumberOfCells() > 0 )
      {
      for ( inStrips->InitTraversal(); inStrips->GetNextCell(npts,pts); )
        {
        newStrips->InsertNextCell(npts,pts);
        newStrips->InsertNextCell(npts);
        for (i=0; i < npts; i++)
          newStrips->InsertCellPoint(pts[i] + this->Resolution*numPts);
        }
      }
    }
//
// Loop over all polygons and triangle strips searching for boundary edges.
// If boundary edge found, extrude triangle strip.
//
  for ( cellId=0; cellId < numCells; cellId++)
    {
    cell = mesh.GetCell(cellId);
    cellPts = cell->GetPointIds();

    if ( (dim=cell->GetCellDimension()) == 0 ) //create lines from points
      {
      for (i=0; i<cellPts->GetNumberOfIds(); i++)
        {
        ptId = cellPts->GetId(i);
        newLines->InsertNextCell(this->Resolution+1);

        for ( j=0; j<=this->Resolution; j++ )
          newLines->InsertCellPoint(ptId + j*numPts);
        }
      }

    else if ( dim == 1 ) // create strips from lines
      {
      for (i=0; i < (cellPts->GetNumberOfIds()-1); i++)
        {
        p1 = cellPts->GetId(i);
        p2 = cellPts->GetId(i+1);
        newStrips->InsertNextCell(2*(this->Resolution+1));
        for ( j=0; j<=this->Resolution; j++)
          {
          newStrips->InsertCellPoint(p2 + j*numPts);
          newStrips->InsertCellPoint(p1 + j*numPts);
          }
        }
      }

    else if ( dim == 2 ) // create strips from boundary edges
      {
      numEdges = cell->GetNumberOfEdges();
      for (i=0; i<numEdges; i++)
        {
        edge = cell->GetEdge(i);
        for (j=0; j<(edge->GetNumberOfPoints()-1); j++)
          {
          p1 = edge->PointIds.GetId(j);
          p2 = edge->PointIds.GetId(j+1);
          mesh.GetCellEdgeNeighbors(cellId, p1, p2, cellIds);

          if ( cellIds.GetNumberOfIds() < 1 ) //generate strip
            {
            newStrips->InsertNextCell(2*(this->Resolution+1));
            for (k=0; k<=this->Resolution; k++)
              {
              newStrips->InsertCellPoint(p2 + k*numPts);
              newStrips->InsertCellPoint(p1 + k*numPts);
              }
            } //if boundary edge
          } //for each sub-edge
        } //for each edge
      } //for each polygon or triangle strip
    } //for each cell
//
// Update ourselves and release memory
//
  output->SetPoints(newPts);
  newPts->Delete();

  if ( newLines )
    {
    output->SetLines(newLines);
    newLines->Delete();
    }

  if ( newPolys )
    {
    output->SetPolys(newPolys);
    newPolys->Delete();
    }

  output->SetStrips(newStrips);
  newStrips->Delete();

  output->Squeeze();
}

void vtkRotationalExtrusionFilter::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkPolyToPolyFilter::PrintSelf(os,indent);

  os << indent << "Resolution: " << this->Resolution << "\n";
  os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n");
  os << indent << "Angle: " << this->Angle << "\n";
  os << indent << "Translation: " << this->Translation << "\n";
  os << indent << "Delta Radius: " << this->DeltaRadius << "\n";
}

<|endoftext|>


<commit_before>//! \file
/*
**  Copyright (C) - Triton
**
**  This program is under the terms of the BSD License.
*/

#include <triton/api.hpp>
#include <triton/callbacks.hpp>
#include <triton/exceptions.hpp>

namespace triton {
  namespace callbacks {

    Callbacks::Callbacks(triton::API& api) : api(api) {
      this->isDefined = false;
    }

    void Callbacks::addCallback(triton::callbacks::getConcreteMemoryValueCallback cb) {
      this->getConcreteMemoryValueCallbacks.push_back(cb);
      this->isDefined = true;
    }

    void Callbacks::addCallback(triton::callbacks::getConcreteRegisterValueCallback cb) {
      this->getConcreteRegisterValueCallbacks.push_back(cb);
      this->isDefined = true;
    }

    void Callbacks::addCallback(triton::callbacks::symbolicSimplificationCallback cb) {
      this->symbolicSimplificationCallbacks.push_back(cb);
      this->isDefined = true;
    }

    void Callbacks::removeAllCallbacks(void) {
      this->getConcreteMemoryValueCallbacks.clear();
      this->getConcreteRegisterValueCallbacks.clear();
      this->symbolicSimplificationCallbacks.clear();
    }

    void Callbacks::removeCallback(triton::callbacks::getConcreteMemoryValueCallback cb) {
      this->getConcreteMemoryValueCallbacks.remove(cb);
      if (this->countCallbacks() == 0)
        this->isDefined = false;
    }

    void Callbacks::removeCallback(triton::callbacks::getConcreteRegisterValueCallback cb) {
      this->getConcreteRegisterValueCallbacks.remove(cb);
      if (this->countCallbacks() == 0)
        this->isDefined = false;
    }

    void Callbacks::removeCallback(triton::callbacks::symbolicSimplificationCallback cb) {
      this->symbolicSimplificationCallbacks.remove(cb);
      if (this->countCallbacks() == 0)
        this->isDefined = false;
    }

    triton::ast::AbstractNode* Callbacks::processCallbacks(triton::callbacks::callback_e kind, triton::ast::AbstractNode* node) const {
      // FIXME : Most of callback node are ignored. May be we should return a list of nodes?
      switch (kind) {
        case triton::callbacks::SYMBOLIC_SIMPLIFICATION: {
          for (auto& function: this->symbolicSimplificationCallbacks) {
            node = function(api, node);
            if (node == nullptr)
              throw triton::exceptions::Callbacks("Callbacks::processCallbacks(SYMBOLIC_SIMPLIFICATION): You cannot return a nullptr node.");
          }
          break;
        }
        default:
          throw triton::exceptions::Callbacks("Callbacks::processCallbacks(): Invalid kind of callback for this C++ polymorphism.");
      };

      return node;
    }

    void Callbacks::processCallbacks(triton::callbacks::callback_e kind, const triton::arch::MemoryAccess& mem) const {
      switch (kind) {
        case triton::callbacks::GET_CONCRETE_MEMORY_VALUE: {
           for (auto& function: this->getConcreteMemoryValueCallbacks) {
             // FIXME Const_cast is certainly bad
             function(api, const_cast<triton::arch::MemoryAccess&>(mem));
           }
          break;
        }

        default:
          throw triton::exceptions::Callbacks("Callbacks::processCallbacks(): Invalid kind of callback for this C++ polymorphism.");
      };
    }

    void Callbacks::processCallbacks(triton::callbacks::callback_e kind, const triton::arch::Register& reg) const {
      switch (kind) {
        case triton::callbacks::GET_CONCRETE_REGISTER_VALUE: {
           for (auto& function: this->getConcreteRegisterValueCallbacks) {
             // FIXME Const_cast is certainly bad
             function(api, const_cast<triton::arch::Register&>(reg));
           }
          break;
        }

        default:
          throw triton::exceptions::Callbacks("Callbacks::processCallbacks(): Invalid kind of callback for this C++ polymorphism.");
      };
    }

    triton::usize Callbacks::countCallbacks(void) const {
      triton::usize count = 0;

      count += this->getConcreteMemoryValueCallbacks.size();
      count += this->getConcreteRegisterValueCallbacks.size();
      count += this->symbolicSimplificationCallbacks.size();

      return count;
    }

  }; /* callbacks namespace */
}; /* triton namespace */
<commit_msg>Remove fixme<commit_after>//! \file
/*
**  Copyright (C) - Triton
**
**  This program is under the terms of the BSD License.
*/

#include <triton/api.hpp>
#include <triton/callbacks.hpp>
#include <triton/exceptions.hpp>

namespace triton {
  namespace callbacks {

    Callbacks::Callbacks(triton::API& api) : api(api) {
      this->isDefined = false;
    }

    void Callbacks::addCallback(triton::callbacks::getConcreteMemoryValueCallback cb) {
      this->getConcreteMemoryValueCallbacks.push_back(cb);
      this->isDefined = true;
    }

    void Callbacks::addCallback(triton::callbacks::getConcreteRegisterValueCallback cb) {
      this->getConcreteRegisterValueCallbacks.push_back(cb);
      this->isDefined = true;
    }

    void Callbacks::addCallback(triton::callbacks::symbolicSimplificationCallback cb) {
      this->symbolicSimplificationCallbacks.push_back(cb);
      this->isDefined = true;
    }

    void Callbacks::removeAllCallbacks(void) {
      this->getConcreteMemoryValueCallbacks.clear();
      this->getConcreteRegisterValueCallbacks.clear();
      this->symbolicSimplificationCallbacks.clear();
    }

    void Callbacks::removeCallback(triton::callbacks::getConcreteMemoryValueCallback cb) {
      this->getConcreteMemoryValueCallbacks.remove(cb);
      if (this->countCallbacks() == 0)
        this->isDefined = false;
    }

    void Callbacks::removeCallback(triton::callbacks::getConcreteRegisterValueCallback cb) {
      this->getConcreteRegisterValueCallbacks.remove(cb);
      if (this->countCallbacks() == 0)
        this->isDefined = false;
    }

    void Callbacks::removeCallback(triton::callbacks::symbolicSimplificationCallback cb) {
      this->symbolicSimplificationCallbacks.remove(cb);
      if (this->countCallbacks() == 0)
        this->isDefined = false;
    }

    triton::ast::AbstractNode* Callbacks::processCallbacks(triton::callbacks::callback_e kind, triton::ast::AbstractNode* node) const {
      // FIXME : Most of callback node are ignored. May be we should return a list of nodes?
      switch (kind) {
        case triton::callbacks::SYMBOLIC_SIMPLIFICATION: {
          for (auto& function: this->symbolicSimplificationCallbacks) {
            node = function(api, node);
            if (node == nullptr)
              throw triton::exceptions::Callbacks("Callbacks::processCallbacks(SYMBOLIC_SIMPLIFICATION): You cannot return a nullptr node.");
          }
          break;
        }
        default:
          throw triton::exceptions::Callbacks("Callbacks::processCallbacks(): Invalid kind of callback for this C++ polymorphism.");
      };

      return node;
    }

    void Callbacks::processCallbacks(triton::callbacks::callback_e kind, const triton::arch::MemoryAccess& mem) const {
      switch (kind) {
        case triton::callbacks::GET_CONCRETE_MEMORY_VALUE: {
           for (auto& function: this->getConcreteMemoryValueCallbacks) {
             function(api, mem);
           }
          break;
        }

        default:
          throw triton::exceptions::Callbacks("Callbacks::processCallbacks(): Invalid kind of callback for this C++ polymorphism.");
      };
    }

    void Callbacks::processCallbacks(triton::callbacks::callback_e kind, const triton::arch::Register& reg) const {
      switch (kind) {
        case triton::callbacks::GET_CONCRETE_REGISTER_VALUE: {
           for (auto& function: this->getConcreteRegisterValueCallbacks) {
             function(api, reg);
           }
          break;
        }

        default:
          throw triton::exceptions::Callbacks("Callbacks::processCallbacks(): Invalid kind of callback for this C++ polymorphism.");
      };
    }

    triton::usize Callbacks::countCallbacks(void) const {
      triton::usize count = 0;

      count += this->getConcreteMemoryValueCallbacks.size();
      count += this->getConcreteRegisterValueCallbacks.size();
      count += this->symbolicSimplificationCallbacks.size();

      return count;
    }

  }; /* callbacks namespace */
}; /* triton namespace */
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#include <vcl/window.hxx>

#include "hintids.hxx"
#include "viewsh.hxx"
#include "virtoutp.hxx"
#include "viewopt.hxx"
#include "rootfrm.hxx"
// OD 12.11.2002 #96272# - include declaration for <SetMappingForVirtDev>
#include "setmapvirtdev.hxx"

#ifdef DBG_UTIL

/*************************************************************************
 *                          class DbgRect
 *************************************************************************/

class DbgRect
{
        OutputDevice *pOut;
public:
        DbgRect( OutputDevice *pOut, const Rectangle &rRect,
                 const ColorData eColor = COL_LIGHTBLUE );
};

inline DbgRect::DbgRect( OutputDevice *pOutDev, const Rectangle &rRect,
                         const ColorData eColor )
   :pOut( pOutDev )
{
    if( pOut )
    {
        pOut->Push( PUSH_FILLCOLOR|PUSH_LINECOLOR );
        pOut->SetLineColor( eColor );
        pOut->SetFillColor();
        pOut->DrawRect( rRect );
        pOut->Pop();
    }
}

#endif

/* class SwLayVout verwaltet das virtuelle Outputdevice
 * Es gibt von dieser Klasse einen statischen Member am RootFrm,
 * dieser wird in _FrmInit angelegt und in _FrmFinit zerstoert.
 * */

BOOL SwRootFrm::FlushVout()
{
    if( SwRootFrm::pVout->IsFlushable() )
    {
        SwRootFrm::pVout->_Flush();
        return TRUE;
    }
    return FALSE;
}

BOOL SwRootFrm::HasSameRect( const SwRect& rRect )
{
    if( SwRootFrm::pVout->IsFlushable() )
        return ( rRect == SwRootFrm::pVout->GetOrgRect() );
    return FALSE;
}

/** method to set mapping/pixel offset for virtual output device

    OD 12.11.2002 #96272# - method implements two solutions for the mapping of
    the virtual output device:
    The old solution set the origin of the mapping mode, which will be used in
    the virtual output device. This causes several paint errors, because of the
    different roundings in the virtual output device and the original output device.
    The new solution avoids the rounding differences between virtual and original
    output device by setting a pixel offset at the virtual output device.
    A define controls, which solution is used, in order to switch in escalation
    back to old solution.

    @author OD

    @param _pOrgOutDev
    input parameter - constant instance of the original output device, for which
    the virtual output device is created.

    @param _pVirDev
    input/output parameter - instance of the virtual output device.

    @param _pMapMode
    input/output parameter - instance of the mapping mode, which will be set
    at the virtual output device.

    @param _rNewOrigin
    input parameter - constant instance of the origin, which will be used in
    the virtual output device
*/
// define to control, if old or new solution for setting the mapping for
// an virtual output device is used.
void SetMappingForVirtDev(  const Point&    _rNewOrigin,
                            MapMode*        ,
                            const OutputDevice* _pOrgOutDev,
                            VirtualDevice*  _pVirDev )
{
        // new solution: set pixel offset at virtual output device
        Point aPixelOffset = _pOrgOutDev->LogicToPixel( _rNewOrigin );
        _pVirDev->SetPixelOffset( Size( -aPixelOffset.X(), -aPixelOffset.Y() ) );
}

/*************************************************************************
 *                          SwVOut::DoesFit()
 *************************************************************************/

// rSize muss in Pixel-Koordinaten vorliegen!
BOOL SwLayVout::DoesFit( const Size &rNew )
{
    if( rNew.Height() > VIRTUALHEIGHT )
        return FALSE;
    if( rNew.Width() <= 0 || rNew.Height() <= 0 )
        return FALSE;
    if( rNew.Width() <= aSize.Width() )
        return TRUE;
    if( !pVirDev )
    {
        pVirDev = new VirtualDevice();
        pVirDev->SetLineColor();
        if( pOut )
        {
            if( pVirDev->GetFillColor() != pOut->GetFillColor() )
                pVirDev->SetFillColor( pOut->GetFillColor() );
        }
    }

    if( rNew.Width() > aSize.Width() )
    {
        aSize.Width() = rNew.Width();
        if( !pVirDev->SetOutputSizePixel( aSize ) )
        {
            delete pVirDev;
            pVirDev = NULL;
            aSize.Width() = 0;
            return FALSE;
        }
    }
    return TRUE;
}

/*************************************************************************
 *                         SwLayVout::Enter
 *************************************************************************/
/// OD 27.09.2002 #103636# - change 2nd parameter <rRect> - no longer <const>
///     in order to return value of class member variable <aRect>, if virtual
///     output is used.
///     <aRect> contains the rectangle that represents the area the virtual
///     output device is used for and that is flushed at the end.
void SwLayVout::Enter(  ViewShell *pShell, SwRect &rRect, BOOL bOn )
{
    Flush();

#ifdef DBG_UTIL
        if( pShell->GetViewOptions()->IsTest3() )
        {
            ++nCount;
            return;
        }
#endif

    bOn = bOn && !nCount && rRect.HasArea() && pShell->GetWin();
    ++nCount;
    if( bOn )
    {
        pSh = pShell;
        pOut = NULL;
        OutputDevice *pO = pSh->GetOut();
// Auf dem Drucker oder einem virt. Outputdevice wird nicht getrickst...
        if( OUTDEV_WINDOW != pO->GetOutDevType() )
            return;

        pOut = pO;
        Size aPixSz( pOut->PixelToLogic( Size( 1,1 )) );
        SwRect aTmp( rRect );
        aTmp.SSize().Width() += aPixSz.Width()/2 + 1;
        aTmp.SSize().Height()+= aPixSz.Height()/2 + 1;
        Rectangle aTmpRect( pO->LogicToPixel( aTmp.SVRect() ) );

        ASSERT( !pSh->GetWin()->IsReallyVisible() ||
                aTmpRect.GetWidth() <= pSh->GetWin()->GetOutputSizePixel().Width() + 2,
                "Paintwidth bigger than visarea?" );
        // Passt das Rechteck in unseren Buffer ?
        if( !DoesFit( aTmpRect.GetSize() ) )
        {
            pOut = NULL;
            return;
        }

        aRect = SwRect( pO->PixelToLogic( aTmpRect ) );

        SetOutDev( pSh, pVirDev );

        if( pVirDev->GetFillColor() != pOut->GetFillColor() )
            pVirDev->SetFillColor( pOut->GetFillColor() );

        MapMode aMapMode( pOut->GetMapMode() );
        // OD 12.11.2002 #96272# - use method to set mapping
        //aMapMode.SetOrigin( Point(0,0) - aRect.Pos() );
        ::SetMappingForVirtDev( aRect.Pos(), &aMapMode, pOut, pVirDev );

        if( aMapMode != pVirDev->GetMapMode() )
            pVirDev->SetMapMode( aMapMode );

        /// OD 27.09.2002 #103636# - set value of parameter <rRect>
        rRect = aRect;
    }
}

/*************************************************************************
 *                         SwLayVout::Flush()
 *************************************************************************/

void SwLayVout::_Flush()
{
    ASSERT( pVirDev, "SwLayVout::DrawOut: nothing left Toulouse" );
    Rectangle aTmp( aRect.SVRect() );
    pOut->DrawOutDev( aRect.Pos(), aRect.SSize(),
                      aRect.Pos(), aRect.SSize(), *pVirDev );
    SetOutDev( pSh, pOut );
    pOut = NULL;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Fix compilation error caused by DBG_UTIL vs. OSL_DEBUG_LEVEL mixup<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#include <vcl/window.hxx>

#include "hintids.hxx"
#include "viewsh.hxx"
#include "virtoutp.hxx"
#include "viewopt.hxx"
#include "rootfrm.hxx"
// OD 12.11.2002 #96272# - include declaration for <SetMappingForVirtDev>
#include "setmapvirtdev.hxx"

#ifdef DBG_UTIL

/*************************************************************************
 *                          class DbgRect
 *************************************************************************/

class DbgRect
{
        OutputDevice *pOut;
public:
        DbgRect( OutputDevice *pOut, const Rectangle &rRect,
                 const ColorData eColor = COL_LIGHTBLUE );
};

inline DbgRect::DbgRect( OutputDevice *pOutDev, const Rectangle &rRect,
                         const ColorData eColor )
   :pOut( pOutDev )
{
    if( pOut )
    {
        pOut->Push( PUSH_FILLCOLOR|PUSH_LINECOLOR );
        pOut->SetLineColor( eColor );
        pOut->SetFillColor();
        pOut->DrawRect( rRect );
        pOut->Pop();
    }
}

#endif

/* class SwLayVout verwaltet das virtuelle Outputdevice
 * Es gibt von dieser Klasse einen statischen Member am RootFrm,
 * dieser wird in _FrmInit angelegt und in _FrmFinit zerstoert.
 * */

BOOL SwRootFrm::FlushVout()
{
    if( SwRootFrm::pVout->IsFlushable() )
    {
        SwRootFrm::pVout->_Flush();
        return TRUE;
    }
    return FALSE;
}

BOOL SwRootFrm::HasSameRect( const SwRect& rRect )
{
    if( SwRootFrm::pVout->IsFlushable() )
        return ( rRect == SwRootFrm::pVout->GetOrgRect() );
    return FALSE;
}

/** method to set mapping/pixel offset for virtual output device

    OD 12.11.2002 #96272# - method implements two solutions for the mapping of
    the virtual output device:
    The old solution set the origin of the mapping mode, which will be used in
    the virtual output device. This causes several paint errors, because of the
    different roundings in the virtual output device and the original output device.
    The new solution avoids the rounding differences between virtual and original
    output device by setting a pixel offset at the virtual output device.
    A define controls, which solution is used, in order to switch in escalation
    back to old solution.

    @author OD

    @param _pOrgOutDev
    input parameter - constant instance of the original output device, for which
    the virtual output device is created.

    @param _pVirDev
    input/output parameter - instance of the virtual output device.

    @param _pMapMode
    input/output parameter - instance of the mapping mode, which will be set
    at the virtual output device.

    @param _rNewOrigin
    input parameter - constant instance of the origin, which will be used in
    the virtual output device
*/
// define to control, if old or new solution for setting the mapping for
// an virtual output device is used.
void SetMappingForVirtDev(  const Point&    _rNewOrigin,
                            MapMode*        ,
                            const OutputDevice* _pOrgOutDev,
                            VirtualDevice*  _pVirDev )
{
        // new solution: set pixel offset at virtual output device
        Point aPixelOffset = _pOrgOutDev->LogicToPixel( _rNewOrigin );
        _pVirDev->SetPixelOffset( Size( -aPixelOffset.X(), -aPixelOffset.Y() ) );
}

/*************************************************************************
 *                          SwVOut::DoesFit()
 *************************************************************************/

// rSize muss in Pixel-Koordinaten vorliegen!
BOOL SwLayVout::DoesFit( const Size &rNew )
{
    if( rNew.Height() > VIRTUALHEIGHT )
        return FALSE;
    if( rNew.Width() <= 0 || rNew.Height() <= 0 )
        return FALSE;
    if( rNew.Width() <= aSize.Width() )
        return TRUE;
    if( !pVirDev )
    {
        pVirDev = new VirtualDevice();
        pVirDev->SetLineColor();
        if( pOut )
        {
            if( pVirDev->GetFillColor() != pOut->GetFillColor() )
                pVirDev->SetFillColor( pOut->GetFillColor() );
        }
    }

    if( rNew.Width() > aSize.Width() )
    {
        aSize.Width() = rNew.Width();
        if( !pVirDev->SetOutputSizePixel( aSize ) )
        {
            delete pVirDev;
            pVirDev = NULL;
            aSize.Width() = 0;
            return FALSE;
        }
    }
    return TRUE;
}

/*************************************************************************
 *                         SwLayVout::Enter
 *************************************************************************/
/// OD 27.09.2002 #103636# - change 2nd parameter <rRect> - no longer <const>
///     in order to return value of class member variable <aRect>, if virtual
///     output is used.
///     <aRect> contains the rectangle that represents the area the virtual
///     output device is used for and that is flushed at the end.
void SwLayVout::Enter(  ViewShell *pShell, SwRect &rRect, BOOL bOn )
{
    Flush();

#if OSL_DEBUG_LEVEL > 1
        if( pShell->GetViewOptions()->IsTest3() )
        {
            ++nCount;
            return;
        }
#endif

    bOn = bOn && !nCount && rRect.HasArea() && pShell->GetWin();
    ++nCount;
    if( bOn )
    {
        pSh = pShell;
        pOut = NULL;
        OutputDevice *pO = pSh->GetOut();
// Auf dem Drucker oder einem virt. Outputdevice wird nicht getrickst...
        if( OUTDEV_WINDOW != pO->GetOutDevType() )
            return;

        pOut = pO;
        Size aPixSz( pOut->PixelToLogic( Size( 1,1 )) );
        SwRect aTmp( rRect );
        aTmp.SSize().Width() += aPixSz.Width()/2 + 1;
        aTmp.SSize().Height()+= aPixSz.Height()/2 + 1;
        Rectangle aTmpRect( pO->LogicToPixel( aTmp.SVRect() ) );

        ASSERT( !pSh->GetWin()->IsReallyVisible() ||
                aTmpRect.GetWidth() <= pSh->GetWin()->GetOutputSizePixel().Width() + 2,
                "Paintwidth bigger than visarea?" );
        // Passt das Rechteck in unseren Buffer ?
        if( !DoesFit( aTmpRect.GetSize() ) )
        {
            pOut = NULL;
            return;
        }

        aRect = SwRect( pO->PixelToLogic( aTmpRect ) );

        SetOutDev( pSh, pVirDev );

        if( pVirDev->GetFillColor() != pOut->GetFillColor() )
            pVirDev->SetFillColor( pOut->GetFillColor() );

        MapMode aMapMode( pOut->GetMapMode() );
        // OD 12.11.2002 #96272# - use method to set mapping
        //aMapMode.SetOrigin( Point(0,0) - aRect.Pos() );
        ::SetMappingForVirtDev( aRect.Pos(), &aMapMode, pOut, pVirDev );

        if( aMapMode != pVirDev->GetMapMode() )
            pVirDev->SetMapMode( aMapMode );

        /// OD 27.09.2002 #103636# - set value of parameter <rRect>
        rRect = aRect;
    }
}

/*************************************************************************
 *                         SwLayVout::Flush()
 *************************************************************************/

void SwLayVout::_Flush()
{
    ASSERT( pVirDev, "SwLayVout::DrawOut: nothing left Toulouse" );
    Rectangle aTmp( aRect.SVRect() );
    pOut->DrawOutDev( aRect.Pos(), aRect.SSize(),
                      aRect.Pos(), aRect.SSize(), *pVirDev );
    SetOutDev( pSh, pOut );
    pOut = NULL;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: wrt_fn.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 09:56:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#ifndef _SFXITEMITER_HXX //autogen
#include <svtools/itemiter.hxx>
#endif
#ifndef _SFX_WHITER_HXX //autogen
#include <svtools/whiter.hxx>
#endif

#include "shellio.hxx"
#include "wrt_fn.hxx"
#include "pam.hxx"
#include "node.hxx"
#include "format.hxx"

Writer& Out( const SwAttrFnTab pTab, const SfxPoolItem& rHt, Writer & rWrt )
{
    USHORT nId = rHt.Which();
    ASSERT(  nId < POOLATTR_END && nId >= POOLATTR_BEGIN, "SwAttrFnTab::Out()" );
    FnAttrOut pOut;
    if( 0 != ( pOut = pTab[ nId - RES_CHRATR_BEGIN] ))
        (*pOut)( rWrt, rHt );
    return rWrt;

}

Writer& Out_SfxItemSet( const SwAttrFnTab pTab, Writer& rWrt,
                        const SfxItemSet& rSet, BOOL bDeep,
                        BOOL bTstForDefault )
{
    // erst die eigenen Attribute ausgeben
    const SfxItemPool& rPool = *rSet.GetPool();
    const SfxItemSet* pSet = &rSet;
    if( !pSet->Count() )        // Optimierung - leere Sets
    {
        if( !bDeep )
            return rWrt;
        while( 0 != ( pSet = pSet->GetParent() ) && !pSet->Count() )
            ;
        if( !pSet )
            return rWrt;
    }
    const SfxPoolItem* pItem;
    FnAttrOut pOut;
    if( !bDeep || !pSet->GetParent() )
    {
        ASSERT( rSet.Count(), "Wurde doch schon behandelt oder?" );
        SfxItemIter aIter( *pSet );
        pItem = aIter.GetCurItem();
        do {
            if( 0 != ( pOut = pTab[ pItem->Which() - RES_CHRATR_BEGIN] ))
                    (*pOut)( rWrt, *pItem );
        } while( !aIter.IsAtEnd() && 0 != ( pItem = aIter.NextItem() ) );
    }
    else
    {
        SfxWhichIter aIter( *pSet );
        USHORT nWhich = aIter.FirstWhich();
        while( nWhich )
        {
            if( SFX_ITEM_SET == pSet->GetItemState( nWhich, bDeep, &pItem ) &&
                ( !bTstForDefault || (
                    *pItem != rPool.GetDefaultItem( nWhich )
                    || ( pSet->GetParent() &&
                        *pItem != pSet->GetParent()->Get( nWhich ))
                )) && 0 != ( pOut = pTab[ nWhich - RES_CHRATR_BEGIN] ))
                    (*pOut)( rWrt, *pItem );
            nWhich = aIter.NextWhich();
        }
    }
    return rWrt;
}

Writer& Out( const SwNodeFnTab pTab, SwNode& rNode, Writer & rWrt )
{
    // es muss ein CntntNode sein !!
    SwCntntNode * pCNd = rNode.GetCntntNode();
    if( !pCNd )
        return rWrt;

    USHORT nId = RES_TXTNODE;
    switch (pCNd->GetNodeType())
    {
        case ND_TEXTNODE:
            nId = RES_TXTNODE;
             break;
        case ND_GRFNODE:
            nId = RES_GRFNODE;
            break;
        case ND_OLENODE:
            nId = RES_OLENODE;
            break;
        default:
            ASSERT(false, "was fuer ein Node ist es denn nun?");
            break;
    }
    FnNodeOut pOut;
    if( 0 != ( pOut = pTab[ nId - RES_NODE_BEGIN ] ))
        (*pOut)( rWrt, *pCNd );
    return rWrt;
}

<commit_msg>INTEGRATION: CWS changefileheader (1.7.242); FILE MERGED 2008/04/01 15:57:50 thb 1.7.242.2: #i85898# Stripping all external header guards 2008/03/31 16:55:47 rt 1.7.242.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: wrt_fn.cxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <svtools/itemiter.hxx>
#include <svtools/whiter.hxx>

#include "shellio.hxx"
#include "wrt_fn.hxx"
#include "pam.hxx"
#include "node.hxx"
#include "format.hxx"

Writer& Out( const SwAttrFnTab pTab, const SfxPoolItem& rHt, Writer & rWrt )
{
    USHORT nId = rHt.Which();
    ASSERT(  nId < POOLATTR_END && nId >= POOLATTR_BEGIN, "SwAttrFnTab::Out()" );
    FnAttrOut pOut;
    if( 0 != ( pOut = pTab[ nId - RES_CHRATR_BEGIN] ))
        (*pOut)( rWrt, rHt );
    return rWrt;

}

Writer& Out_SfxItemSet( const SwAttrFnTab pTab, Writer& rWrt,
                        const SfxItemSet& rSet, BOOL bDeep,
                        BOOL bTstForDefault )
{
    // erst die eigenen Attribute ausgeben
    const SfxItemPool& rPool = *rSet.GetPool();
    const SfxItemSet* pSet = &rSet;
    if( !pSet->Count() )        // Optimierung - leere Sets
    {
        if( !bDeep )
            return rWrt;
        while( 0 != ( pSet = pSet->GetParent() ) && !pSet->Count() )
            ;
        if( !pSet )
            return rWrt;
    }
    const SfxPoolItem* pItem;
    FnAttrOut pOut;
    if( !bDeep || !pSet->GetParent() )
    {
        ASSERT( rSet.Count(), "Wurde doch schon behandelt oder?" );
        SfxItemIter aIter( *pSet );
        pItem = aIter.GetCurItem();
        do {
            if( 0 != ( pOut = pTab[ pItem->Which() - RES_CHRATR_BEGIN] ))
                    (*pOut)( rWrt, *pItem );
        } while( !aIter.IsAtEnd() && 0 != ( pItem = aIter.NextItem() ) );
    }
    else
    {
        SfxWhichIter aIter( *pSet );
        USHORT nWhich = aIter.FirstWhich();
        while( nWhich )
        {
            if( SFX_ITEM_SET == pSet->GetItemState( nWhich, bDeep, &pItem ) &&
                ( !bTstForDefault || (
                    *pItem != rPool.GetDefaultItem( nWhich )
                    || ( pSet->GetParent() &&
                        *pItem != pSet->GetParent()->Get( nWhich ))
                )) && 0 != ( pOut = pTab[ nWhich - RES_CHRATR_BEGIN] ))
                    (*pOut)( rWrt, *pItem );
            nWhich = aIter.NextWhich();
        }
    }
    return rWrt;
}

Writer& Out( const SwNodeFnTab pTab, SwNode& rNode, Writer & rWrt )
{
    // es muss ein CntntNode sein !!
    SwCntntNode * pCNd = rNode.GetCntntNode();
    if( !pCNd )
        return rWrt;

    USHORT nId = RES_TXTNODE;
    switch (pCNd->GetNodeType())
    {
        case ND_TEXTNODE:
            nId = RES_TXTNODE;
             break;
        case ND_GRFNODE:
            nId = RES_GRFNODE;
            break;
        case ND_OLENODE:
            nId = RES_OLENODE;
            break;
        default:
            ASSERT(false, "was fuer ein Node ist es denn nun?");
            break;
    }
    FnNodeOut pOut;
    if( 0 != ( pOut = pTab[ nId - RES_NODE_BEGIN ] ))
        (*pOut)( rWrt, *pCNd );
    return rWrt;
}

<|endoftext|>


<commit_before><commit_msg>Again fixed the lockup problem on exit under Windows 2000.<commit_after><|endoftext|>