]> git.tdb.fi Git - netvis.git/blob - source/host.cpp
be24f05360d05060455228e66b6492dbb2160397
[netvis.git] / source / host.cpp
1 #include <cmath>
2 #include <netinet/in.h>
3 #include <arpa/inet.h>
4 #include <msp/gl/immediate.h>
5 #include <msp/gl/matrix.h>
6 #include <msp/gl/texture.h>
7 #include <msp/gl/transform.h>
8 #include <msp/time/units.h>
9 #include "host.h"
10 #include "netvis.h"
11
12 using namespace std;
13 using namespace Msp;
14
15 Host::Host(NetVis &nv, unsigned a):
16         netvis(nv),
17         addr(a)
18 {
19         in_addr ina;
20         ina.s_addr=htonl(addr);
21         name=inet_ntoa(ina);
22 }
23
24 void Host::set_position(const Vector2 &p)
25 {
26         pos=p;
27 }
28
29 void Host::add_connection(Connection &)
30 {
31 }
32
33 Connection *Host::get_connection(Host &)
34 {
35         return 0;
36 }
37
38 void Host::tick(const Msp::Time::TimeDelta &td)
39 {
40         float dt=td/Msp::Time::sec;
41
42         const map<unsigned, Host *> &hosts=netvis.get_hosts();
43         float fx=-pos.x*0.1;
44         float fy=-pos.y*0.1;
45         for(map<unsigned, Host *>::const_iterator i=hosts.begin(); i!=hosts.end(); ++i)
46         {
47                 if(i->second!=this)
48                 {
49                         const Vector2 &other_pos=i->second->get_position();
50                         float dx=other_pos.x-pos.x;
51                         float dy=other_pos.y-pos.y;
52                         float d2=dx*dx+dy*dy;
53                         float d=sqrt(d2);
54
55                         unsigned other_addr=i->second->get_address();
56                         unsigned matching_bits=0;
57                         for(unsigned j=32; (j-- && !((addr^other_addr)>>j));)
58                                 ++matching_bits;
59
60                         float nearness=24-min(matching_bits, 24U);
61                         float f=10000.0*(1.0/(60+nearness*15)-1.0/d);
62
63                         fx+=dx/d*f;
64                         fy+=dy/d*f;
65                 }
66         }
67
68         if(fx<-4 || fx>4)
69                 pos.x+=fx*dt;
70         if(fy<-4 || fy>4)
71                 pos.y+=fy*dt;
72 }
73
74 void Host::render() const
75 {
76         GL::push_matrix();
77         GL::translate(static_cast<int>(pos.x), static_cast<int>(pos.y), 0);
78
79         GL::Immediate imm((GL::COLOR4_UBYTE, GL::VERTEX2));
80         imm.begin(GL::QUADS);
81         imm.color(1.0f, 1.0f, 1.0f, 1.0f);
82         imm.vertex(-5, -5);
83         imm.vertex(5, -5);
84         imm.vertex(5, 5);
85         imm.vertex(-5, 5);
86         imm.end();
87
88         const GL::Font &font=netvis.get_font();
89         GL::translate(-static_cast<int>(font.get_string_width(name)*5), 6, 0);
90         GL::scale_uniform(10);
91         font.draw_string(name);
92         GL::Texture::unbind();
93
94         GL::pop_matrix();
95 }