Wednesday, March 6, 2013

The Little Death

Philosophy time. This is something that's been worrying me for a few weeks now... and I don't know if I should even be worried about it or happy about it.

It all started through a bunch of discussions we had at work, talking about whether if you magically created an atomically identical clone of yourself, and destroyed your original body at the same time (as happens in most realistic ideas of teleportation), would that clone really be you? Sure, the clone would feel that it was you, but would you (whatever that means) still experience living on as the clone? The usual response was that no, because that clone had no continuity of experience with you. It wasn't the same person because at some point, it had not had the experience of being you. But you had that experience, and so you were the same person.

The thing is, every single discussion I've ever heard on this topic hinges on the fact that I am me because I've always been me, and I have a continuous unbroken chain of continuity between the first me that I remember and me now.

I don't think that's the case. I think we're taking for granted something that we have assumed but never really shown; that just because usually, moment to moment, our experience of this world is continuous, that we have some magical property of continuity of experience. And that we, being people, are somehow special because of it.

When you go under general anaesthetic, it's not dark or fuzzy. It's not black. It's nothing. You don't exist and then as you come out from under it, *bam*. Suddenly you are awake and sensing and perceiving and it feels like it never left off... but it did. There's a gap in there, hours long, where you were a not-person. "You" didn't exist.

Every time you are truly, properly unconscious, you die. When your body recovers and starts processing information again, you are reborn. Is it really you? It's the same types of atoms in the same configuration, but then again so is the teleported clone in the first example. You can never cross the same river twice. In the same way, maybe we die and are reborn every once in a while... or every day, or every instant.

Something to think about.

Friday, July 27, 2012

3D Vision Is Broken With Multiple Monitors

More accurately, "My Asus VG278H won't enable the IR emitter and synch with the 3D Vision 2 glasses that came with it, unless it's the only monitor attached to my computer, or the 3D application in question is running in a windowed mode." Diablo 3 works fine in 3D (but I run in Fullscreen Windowed), but none of the other games I have (all via Steam) work. They appear to be rendering both views but my monitor refuses to activate the IR emitter and synch up with the shutter glasses. Disconnecting my second monitor, for some reason, makes the IR emitter work. Hurrah.

Monday, August 1, 2011

Constructing a Diminutive Velocipede

This is something I've wanted to do for a while, and a week ago I bit the bullet and did it.

Required bits:
  • A 26" mountain bike

  • A 10" - 12" scooter or child's bike

Required utensils:
  • Hacksaw

  • Angle grinder

  • Some form of welder

Begin by cutting the front off the bike with the hacksaw, at the red lines shown below. Also, cut the handle bars shorter (I cut just inside the stock handgrips) and remove the stem that holds the handle bars in place. We'll weld the handle bars on directly for a more scale appearance.

Once you've done this, use the angle grinder to shape the stub of the stem so that it fits neatly with the shortened handle bars. Clamp the bars in the right position, tack weld them in place, and when you're happy with the alignment, weld them on. Remember to always clean any paint, rust etc. off the metal surfaces before welding.

Cut the seat post to length (I made mine around 100mm long), once again shape it with the angle grinder so that it fits neatly on the top of the down tube, and weld it in place. This geometry isn't very strong, so cut a short length of pipe (I got mine from one of the seat stays) and use it as a brace to support the seat post. You can see the seat post support propped in place ready to weld.

In order to get a better shape to the frame, I simply cut a wedge out of the down-tube (leaving it attached by a strip across the top) and re-welded it in place. In this picture you can also seat the seat post support properly welded in place.

Next, I needed a rear wheel. At the recycling station near work, I found a kids' 10" scooter which fit the bill.

It was a simple job to neaten up the cut end of the frame, cut off the scooter's front fork, and weld it in place at the rear. I'm still very new to welding, and the wall of the tube on the right is maybe 2mm thick, so I had a hard time making them stick without blowing a hole in the tubing.

You should now have something ridable, but the colour scheme leaves somewhat to be desired.

As this was to be prop for The Great Steampunk Affaire, bare brushed metal was fully appropriate. However, I plan to paint the frame black to prevent corrosion.


I'd initially planned for electric propulsion, but it ended up being quite practical to merely kick it along until I got up to speed, and then coast for a while. It was certainly a lot of fun on the night. :D

Friday, March 25, 2011

Pascal's Wager

I'm sure we've all heard of Pascal's Wager in some form. The general logic runs that "if there is no God, then what I believe holds no consequence, but if there IS a God, then believing in Him is a significant net benefit." This makes a lot of sense... in fact Blaise Pascal himself trusted it to get him out of any awkward situations in which, after he died, he discovered that there in fact WAS a God.

What's kind of scary is when you reverse the logic. "If there is, in fact, a God, despite the utter lack of any rational evidence of Him - then I'm screwed, because I chose to take the path which I was created to take. If there is no God, then religion, that structure which we humans have created around the presumed existance of an irrational, pathological creator, has caused more harm than we know how to repair."

Monday, November 15, 2010

Creating a std::iostream socket class (Part 3)

So far we've covered implementation of a custom stream buffer that can be used with standard library functions. Now all that's left to go is the actual socket code itself! For more information on modern socket programming, I highly recommend Beej's Guide to Network Programming. It's simple, easy to read, and covers what you need to know as you need to know it. It's also the reference I used while implementing my socket code. :)

Connecting to a server is done in three steps: Resolve the address, create a socket, and connect the socket to the address. Resolving the address looks like this:
  addrinfo hints, *info, *cur;
  memset(&hints, 0, sizeof(hints));
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  int ret = getaddrinfo(host.c_str(), port.c_str(), &hints, &info);
  if (ret != 0) handle_error();


Once we've resolved the address, we create a socket. Since getaddrinfo() returns a linked list of address results, we need to find one that has an address type we can connect to. This way, it will automatically use IPv6 if that's all that's available. Once we have a connected socket we can free the returned address info.
  for (cur = info; cur != NULL && m_data->socket == -1; cur = cur->ai_next) {
    m_data->socket = socket(cur->ai_family,
      cur->ai_socktype, cur->ai_protocol);
    if (m_data->socket != -1) {
      // we can bind via this protocol, can we connect?
      if (::connect(m_data->socket, cur->ai_addr, cur->ai_addrlen) == -1) {
        ::close(m_data->socket);
        m_data->socket = -1;
      } else {
        m_data->remotehost = host + ":" + port;
      }
    }
  }
  freeaddrinfo(info);


To read from the socket, use either read() (which works with all file descriptors) or recv() which also takes socket-specific flags. Note that by default, either will block if there's nothing to be read yet.
  int num = recv(m_data->socket, m_data->buffer, BUFSIZE, 0);
  if (num <= 0) handle_socket_closed();


To check whether there's anything to read on a socket, use the select() function:
  timeval waittime = { 0, 0 };
  fd_set readset;
  FD_ZERO(&readset);
  FD_SET(m_data->socket, &readset);
  select(m_data->socket+1, &readset, NULL, NULL, &waittime);
  if (FD_ISSET(m_data->socket, &readset)) read_socket_data();


If you want to listen for incoming network connections the setup is slightly different. We use a 'listener socket' which listens on a given port, and then when a connection attempt is made, a call to accept() will return another socket which is connected to the remote client.

To listen:
  // bind to the requested port
  addrinfo hints, *info, *cur;
  memset(&hints, 0, sizeof(hints));
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = AI_PASSIVE;
  int r;
  if ((r = getaddrinfo(NULL, port.c_str(), &hints, &info)) != 0) return false;

  // try to get a socket to bind to the port
  for (cur = info; cur != NULL && m_data->socket == -1; cur = cur->ai_next) {
    m_data->socket = socket(cur->ai_family,
      cur->ai_socktype, cur->ai_protocol);
    if (m_data->socket != -1) {
      // insert lame joke about rings here
      if (bind(m_data->socket, cur->ai_addr, cur->ai_addrlen) == -1)
        close();
    }
    }
  freeaddrinfo(info);

  // if we have a socket, listen on it
  listen(m_data->socket, m_data->backlog);

  // accept the incoming connection
  sockaddr_storage addr;
  socklen_t addrlen = sizeof(addr);
  sock.m_data->socket = ::accept(m_data->socket, (sockaddr *)&addr, &addrlen);
  if (sock.m_data->socket == -1) return false; // fail :(


So there you go; almost everything you need to know to write socket code. And if you just want something that works, here's the full source of tcpstream.cpp and tcpstream.h. I've released it under attribution license, so feel free to use it in whatever projects you want, commercial or otherwise.

Saturday, November 13, 2010

You can't reuse ports within 60 seconds

As the title says, just a little gotchya I ran into. After having an open socket on a port, you can't bind another socket to that port for some specified timeout time afterwards. My test program for my tcpstream class worked fine, but if I tried to re-run it, I couldn't re-bind to the port I was using until a short while had passed. After an hour or so of trying to figure out why my socket wasn't closing, I finally found that it was actually Working As Intended(TM). It's fully explained in this post:

The short answer is:
"No, you may not re-use the port for the first 60 seconds
after a bound socket is closed (explicitly or because
the program exited)".

Friday, November 12, 2010

Creating a std::iostream socket class (Part 2)

Last time I outlined how the tcpstream class should work. Having written socket code before, the biggest unknown was "how does I makes a stream of my owns"? The answer is "you implement a custom std::streambuf object." Once you have a stream buffer reading from your source, you simply create a std::iostream object and set it to use that stream buffer, et voila!

The standard documentation for streambuf is rather terse and more than a little ambiguous, but happily, C++ Annotations Version 6.2.3 chapter 20 begins by detailing the implementation of a custom std::streambuf object.

In short, all that's required to create your own stream buffer is to implement some or all of the following methods:

// implement for std::streambuf read functionality
virtual int underflow();

// implement for std::streambuf write functionality
virtual int overflow(int c = EOF);

// optional but may improve performance
virtual std::streamsize xsgetn(char_type *s, std::streamsize n);
virtual std::streamsize xsputn(char_type *s, std::streamsize n);


The first of these, underflow(), is called when the owner of the stream buffer runs out of data while reading. The general form that this method should take is:

int underflow() {
  int bytes_read = fillbuffer(m_pBuffer, MAX_BUFFER_SIZE);
  setg(m_pBuffer, m_pBuffer, m_pBuffer + bytes_read);
}


The setg() call sets the object's stream buffer. The arguments are, in order:
  • A pointer to the first byte of the buffer.

  • A pointer to the current byte in the buffer (which will usually be the first byte of the buffer, if you read a whole buffer at a time).

  • A pointer to the byte after the end of the buffer.
For tcpstream, I added a helper method, fillbuffer(), which checks the socket for new data and is called at the beginning of all data-related methods. Since I didn't want to limit my stream to a predetermined fixed line length, I needed to buffer an arbitrary amount of data, and for this I settled on storing a linked list of data chunks. Each chunk represents a single read operation on the socket, and can store up to BUFFER_SIZE bytes.

struct datachunk {
  int bytes;
  uint8_t *data;
  datachunk *next; // pointer to next datachunk
  datachunk(int size) : bytes(size),
     data(new uint8_t[size]), next(NULL) { }
  ~datachunk() { delete[] data; }
};


With this linked list, the logic became pretty simple: If there's a new data chunk queued up, delete the current chunk and start using the new chunk's data. If there isn't then we've temporarily run out of data and we return EOF.

// implementation of underflow() for std::streambuf
int tcpbuf::underflow() {
  fillbuffer();

  // bail if we don't have another buffer to swap to yet
  if (m_data->inbox == NULL || m_data->inbox->next == NULL)
    return EOF;

  // we've used up the buffer at the front of the inbox, free it
  datachunk *old = m_data->inbox;
  m_data->inbox = old->next;
  delete old;

  // and set the new buffer up for the stream to read from
  char_type *newdata = (char_type *)m_data->inbox->data;
  setg(newdata, newdata, newdata + m_data->inbox->bytes);
  return *newdata;
}


Note: In order to keep the interface completely platform-independent without resorting to factory methods and the like, the class stores its data in a wrapper struct m_data. For this method it's enough to know that m_data->inbox is a pointer to the head of the list of datachunks.

The second of the mandatory methods, overflow(), is called in the inverse condition, when data is written to the stream. It just needs to make sure the byte it's given gets to where it needs to be. Unless you're buffering the data to write later (not a good plan for a socket class that's intended to be used somewhat interactively!) then it's usually a simple matter:

// implementation of overflow() for std::streambuf
int tcpbuf::overflow(int c) {
  if (m_data->socket == -1) return -1;
  return write(m_data->socket, &c, sizeof(c));
}


In this case, I didn't want to write my bytes to the socket individually every time, so I added an implementation for the optional xsputn() method, which simply writes n bytes instead of a single byte:

// implementation of xsputn() for std::streambuf
std::streamsize tcpbuf::xsputn(const char *s, std::streamsize n) {
  if (m_data->socket == -1) return -1;
  return write(m_data->socket, s, n);
}


So there you go. That's all you have to do to implement a std::streambuf. Of course, I haven't covered any of the socket code here. That's for next time.

One last thing; it's a drag to create a stream buffer, connect that to your network, and then create a new std::iostream to use that streambuffer, every time you want to connect a socket. There's a simple way around this though:

// tcpstream - a tcpbuf-based iostream, for convenience
class tcpstream : public std::iostream, public tcpbuf {
public:
  tcpstream() : std::iostream(this) { }
};


So now all of the socket-related methods in tcpbuf are available on a tcpstream, and you can also use the stream for your overloaded IO operators.