44 lines
2.1 KiB
C++
44 lines
2.1 KiB
C++
#pragma once
|
|
#include "lan_pairing.h"
|
|
#include <set>
|
|
namespace ks::lan
|
|
{
|
|
inline Json edgeCell(int edge)
|
|
{
|
|
switch(edge){case 0:return Json::array({-1,0});case 1:return Json::array({1,0});case 2:return Json::array({0,-1});default:return Json::array({0,1});}
|
|
}
|
|
inline int cellEdge(const Json &cell)
|
|
{
|
|
for(int edge=0;edge<4;++edge)if(cell==edgeCell(edge))return edge;
|
|
return -1;
|
|
}
|
|
inline void validateCell(const Json &positions,const std::string &peer,int x,int y)
|
|
{
|
|
if(x < -8||x > 8||y < -8||y > 8)throw std::runtime_error("Keep computers within the layout grid.");
|
|
if(!x&&!y)throw std::runtime_error("This cell belongs to this computer.");
|
|
for(auto &[id,cell]:positions.items())if(id!=peer&&cell==Json::array({x,y}))throw std::runtime_error("Another computer already occupies this cell.");
|
|
}
|
|
inline void fillPositions(Json &positions,const Json &trusted,const std::string &active,int edge)
|
|
{
|
|
if(!positions.is_object())throw std::runtime_error("Invalid computer layout.");
|
|
for(auto it=positions.begin();it!=positions.end();)if(!trusted.contains(it.key()))it=positions.erase(it);else ++it;
|
|
for(auto &[peer,cell]:positions.items()){
|
|
if(!cell.is_array()||cell.size()!=2||!cell[0].is_number_integer()||!cell[1].is_number_integer())throw std::runtime_error("Invalid computer position.");
|
|
validateCell(positions,peer,cell[0].get<int>(),cell[1].get<int>());
|
|
}
|
|
if(trusted.contains(active)&&!positions.contains(active)){
|
|
auto cell=edgeCell(edge);bool free=true;for(auto &[peer,other]:positions.items())if(other==cell)free=false;
|
|
if(free)positions[active]=cell;
|
|
}
|
|
for(auto &[peer,value]:trusted.items())if(!positions.contains(peer)){
|
|
bool placed=false;
|
|
for(int radius=1;radius<=8&&!placed;++radius)for(int y=-radius;y<=radius&&!placed;++y)for(int x=-radius;x<=radius&&!placed;++x){
|
|
if(std::abs(x)+std::abs(y)!=radius)continue;
|
|
bool free=true;for(auto &[id,cell]:positions.items())if(cell==Json::array({x,y}))free=false;
|
|
if(free){positions[peer]=Json::array({x,y});placed=true;}
|
|
}
|
|
if(!placed)throw std::runtime_error("Computer layout is full.");
|
|
}
|
|
}
|
|
}
|