summaryrefslogtreecommitdiff
path: root/game/network/network.cpp
blob: 775d420d0fc04dde04760ee2d218f8569b1923d6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "network.h"
#include "routeWalker.h"
#include <array>
#include <cache.h>
#include <filesystem>
#include <game/network/link.h>
#include <gfx/models/texture.h>
#include <glm/gtx/intersect.hpp>
#include <initializer_list>
#include <ray.hpp>
#include <stdexcept>
#include <utility>

Network::Network(const std::string & tn) : texture {Texture::cachedTexture.get(tn)} { }

NodePtr
Network::nodeAt(glm::vec3 pos)
{
	return *nodes.insert(std::make_shared<Node>(pos)).first;
}

std::pair<NodePtr, bool>
Network::newNodeAt(glm::vec3 pos)
{
	const auto i = nodes.insert(std::make_shared<Node>(pos));
	return {*i.first, i.second};
}

NodePtr
Network::findNodeAt(glm::vec3 pos) const
{
	if (const auto n = nodes.find(std::make_shared<Node>(pos)); n != nodes.end()) {
		return *n;
	}
	return {};
}

Network::IntersectRayResult
Network::intersectRay(const Ray & ray) const
{
	// Click within 2m of a node
	if (const auto node = std::find_if(nodes.begin(), nodes.end(),
				[&ray](const NodePtr & node) {
					glm::vec3 ipos, inorm;
					return glm::intersectRaySphere(ray.start, ray.direction, node->pos, 2.F, ipos, inorm);
				});
			node != nodes.end()) {
		return *node;
	}
	return intersectRayLinks(ray);
}

void
Network::joinLinks(const LinkPtr & l, const LinkPtr & ol)
{
	if (l != ol) {
		for (const auto oe : {0U, 1U}) {
			for (const auto te : {0U, 1U}) {
				if (l->ends[te].node == ol->ends[oe].node) {
					l->ends[te].nexts.emplace_back(ol, oe);
					ol->ends[oe].nexts.emplace_back(l, te);
				}
			}
		}
	}
}

Link::Nexts
Network::routeFromTo(const Link::End & start, glm::vec3 dest) const
{
	auto destNode {findNodeAt(dest)};
	if (!destNode) {
		throw std::out_of_range("Node does not exist in network");
	}
	return routeFromTo(start, destNode);
}

Link::Nexts
Network::routeFromTo(const Link::End & end, const NodePtr & dest) const
{
	return RouteWalker().findRouteTo(end, dest);
}