blue_noise.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2020 Alec Jacobson <[email protected]>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "blue_noise.h"
  9. #include "doublearea.h"
  10. #include "random_points_on_mesh.h"
  11. #include "slice.h"
  12. #include "sortrows.h"
  13. #include "PI.h"
  14. #include "get_seconds.h"
  15. #include <unordered_map>
  16. #include <algorithm>
  17. #include <vector>
  18. #include <random>
  19. namespace igl
  20. {
  21. // It is very important that we use 64bit keys to avoid out of bounds (easy to
  22. // get to happen with dense samplings (e.g., r = 0.0005*bbd)
  23. typedef int64_t BlueNoiseKeyType;
  24. }
  25. // Helper functions
  26. namespace igl
  27. {
  28. // Should probably find and replace with less generic name
  29. //
  30. // Map 3D subscripts (x,y,z) to unique index (return value)
  31. //
  32. // Inputs:
  33. // w side length of w×w×w integer cube lattice
  34. // x subscript along x direction
  35. // y subscript along y direction
  36. // z subscript along z direction
  37. // Returns index value
  38. //
  39. inline BlueNoiseKeyType blue_noise_key(
  40. const BlueNoiseKeyType w, // pass by copy --> int64_t so that multiplication is OK
  41. const BlueNoiseKeyType x, // pass by copy --> int64_t so that multiplication is OK
  42. const BlueNoiseKeyType y, // pass by copy --> int64_t so that multiplication is OK
  43. const BlueNoiseKeyType z) // pass by copy --> int64_t so that multiplication is OK
  44. {
  45. return x+w*(y+w*z);
  46. }
  47. // Determine if a query candidate at position X.row(i) is too close to already
  48. // selected sites (stored in S).
  49. //
  50. // Inputs:
  51. // X #X by 3 list of raw candidate positions
  52. // Xs #Xs by 3 list of corresponding integer cell subscripts
  53. // i index of candidate in question
  54. // S map from cell index to index into X of selected candidate (or -1 if
  55. // cell is currently empty)
  56. // rr Poisson disk radius squared
  57. // w side length of w×w×w integer cube lattice (into which Xs subscripts)
  58. template <
  59. typename DerivedX,
  60. typename DerivedXs>
  61. inline bool blue_noise_far_enough(
  62. const Eigen::MatrixBase<DerivedX> & X,
  63. const Eigen::MatrixBase<DerivedXs> & Xs,
  64. const std::unordered_map<BlueNoiseKeyType,int> & S,
  65. const double & rr,
  66. const int & w,
  67. const int i)
  68. {
  69. const int xi = Xs(i,0);
  70. const int yi = Xs(i,1);
  71. const int zi = Xs(i,2);
  72. int g = 2; // ceil(r/s)
  73. for(int x = std::max(xi-g,0);x<=std::min(xi+g,w-1);x++)
  74. for(int y = std::max(yi-g,0);y<=std::min(yi+g,w-1);y++)
  75. for(int z = std::max(zi-g,0);z<=std::min(zi+g,w-1);z++)
  76. {
  77. if(x!=xi || y!=yi || z!=zi)
  78. {
  79. const BlueNoiseKeyType nk = blue_noise_key(w,x,y,z);
  80. // have already selected from this cell
  81. const auto Siter = S.find(nk);
  82. if(Siter !=S.end() && Siter->second >= 0)
  83. {
  84. const int ni = Siter->second;
  85. // too close
  86. if( (X.row(i)-X.row(ni)).squaredNorm() < rr)
  87. {
  88. return false;
  89. }
  90. }
  91. }
  92. }
  93. return true;
  94. }
  95. // Try to activate a candidate in a given cell
  96. //
  97. // Inputs:
  98. // X #X by 3 list of raw candidate positions
  99. // Xs #Xs by 3 list of corresponding integer cell subscripts
  100. // rr Poisson disk radius squared
  101. // w side length of w×w×w integer cube lattice (into which Xs subscripts)
  102. // nk index of cell in which we'd like to activate a candidate
  103. // M map from cell index to list of candidates
  104. // S map from cell index to index into X of selected candidate (or -1 if
  105. // cell is currently empty)
  106. // active list of indices into X of active candidates
  107. // Outputs:
  108. // M visited candidates deemed too close to already selected points are
  109. // removed
  110. // S updated to reflect activated point (if successful)
  111. // active updated to reflect activated point (if successful)
  112. // Returns true iff activation was successful
  113. template <
  114. typename DerivedX,
  115. typename DerivedXs>
  116. inline bool activate(
  117. const Eigen::MatrixBase<DerivedX> & X,
  118. const Eigen::MatrixBase<DerivedXs> & Xs,
  119. const double & rr,
  120. const int & i,
  121. const int & w,
  122. const BlueNoiseKeyType & nk,
  123. std::unordered_map<BlueNoiseKeyType,std::vector<int> > & M,
  124. std::unordered_map<BlueNoiseKeyType,int> & S,
  125. std::vector<int> & active)
  126. {
  127. assert(M.count(nk));
  128. auto & Mvec = M.find(nk)->second;
  129. auto miter = Mvec.begin();
  130. while(miter != Mvec.end())
  131. {
  132. const int mi = *miter;
  133. // mi is our candidate sample. Is it far enough from all existing
  134. // samples?
  135. if(i>=0 && (X.row(i)-X.row(mi)).squaredNorm() > 4.*rr)
  136. {
  137. // too far skip (reject)
  138. miter++;
  139. } else if(blue_noise_far_enough(X,Xs,S,rr,w,mi))
  140. {
  141. active.push_back(mi);
  142. S.find(nk)->second = mi;
  143. //printf(" found %d\n",mi);
  144. return true;
  145. }else
  146. {
  147. // remove forever (instead of incrementing we swap and eat from the
  148. // back)
  149. //std::swap(*miter,Mvec.back());
  150. *miter = Mvec.back();
  151. bool was_last = (std::next(miter) == Mvec.end());
  152. Mvec.pop_back();
  153. if (was_last) {
  154. // popping from the vector can invalidate the iterator, if it was
  155. // pointing to the last element that was popped. Alternatively,
  156. // one could use indices directly...
  157. miter = Mvec.end();
  158. }
  159. }
  160. }
  161. return false;
  162. }
  163. template <
  164. typename DerivedX,
  165. typename DerivedXs,
  166. typename URBG>
  167. inline bool step(
  168. const Eigen::MatrixBase<DerivedX> & X,
  169. const Eigen::MatrixBase<DerivedXs> & Xs,
  170. const double & rr,
  171. const int & w,
  172. URBG && urbg,
  173. std::unordered_map<BlueNoiseKeyType,std::vector<int> > & M,
  174. std::unordered_map<BlueNoiseKeyType,int> & S,
  175. std::vector<int> & active,
  176. std::vector<int> & collected
  177. )
  178. {
  179. //considered.clear();
  180. if(active.size() == 0) return false;
  181. // random entry
  182. std::uniform_int_distribution<> dis(0, active.size()-1);
  183. const int e = dis(urbg);
  184. const int i = active[e];
  185. //printf("%d\n",i);
  186. const int xi = Xs(i,0);
  187. const int yi = Xs(i,1);
  188. const int zi = Xs(i,2);
  189. //printf("%d %d %d - %g %g %g\n",xi,yi,zi,X(i,0),X(i,1),X(i,2));
  190. // cell indices of neighbors
  191. int g = 4;
  192. std::vector<BlueNoiseKeyType> N;N.reserve((1+g*1)^3-1);
  193. for(int x = std::max(xi-g,0);x<=std::min(xi+g,w-1);x++)
  194. for(int y = std::max(yi-g,0);y<=std::min(yi+g,w-1);y++)
  195. for(int z = std::max(zi-g,0);z<=std::min(zi+g,w-1);z++)
  196. {
  197. if(x!=xi || y!=yi || z!=zi)
  198. {
  199. //printf(" %d %d %d\n",x,y,z);
  200. const BlueNoiseKeyType nk = blue_noise_key(w,x,y,z);
  201. // haven't yet selected from this cell?
  202. const auto Siter = S.find(nk);
  203. if(Siter !=S.end() && Siter->second < 0)
  204. {
  205. assert(M.find(nk) != M.end());
  206. N.emplace_back(nk);
  207. }
  208. }
  209. }
  210. //printf(" --------\n");
  211. // randomize order: this might be a little paranoid...
  212. std::shuffle(std::begin(N), std::end(N), urbg);
  213. bool found = false;
  214. for(const BlueNoiseKeyType & nk : N)
  215. {
  216. assert(M.find(nk) != M.end());
  217. if(activate(X,Xs,rr,i,w,nk,M,S,active))
  218. {
  219. found = true;
  220. break;
  221. }
  222. }
  223. if(!found)
  224. {
  225. // remove i from active list
  226. // https://stackoverflow.com/a/60765833/148668
  227. collected.push_back(i);
  228. //printf(" before: "); for(const int j : active) { printf("%d ",j); } printf("\n");
  229. std::swap(active[e], active.back());
  230. //printf(" after : "); for(const int j : active) { printf("%d ",j); } printf("\n");
  231. active.pop_back();
  232. //printf(" removed %d\n",i);
  233. }
  234. //printf(" active: "); for(const int j : active) { printf("%d ",j); } printf("\n");
  235. return true;
  236. }
  237. }
  238. template <
  239. typename DerivedV,
  240. typename DerivedF,
  241. typename DerivedB,
  242. typename DerivedFI,
  243. typename DerivedP,
  244. typename URBG>
  245. IGL_INLINE void igl::blue_noise(
  246. const Eigen::MatrixBase<DerivedV> & V,
  247. const Eigen::MatrixBase<DerivedF> & F,
  248. const typename DerivedV::Scalar r,
  249. Eigen::PlainObjectBase<DerivedB> & B,
  250. Eigen::PlainObjectBase<DerivedFI> & FI,
  251. Eigen::PlainObjectBase<DerivedP> & P,
  252. URBG && urbg)
  253. {
  254. typedef typename DerivedV::Scalar Scalar;
  255. // float+RowMajor is faster...
  256. typedef Eigen::Matrix<Scalar,Eigen::Dynamic,3,Eigen::RowMajor> MatrixX3S;
  257. assert(V.cols() == 3 && "Only 3D embeddings allowed");
  258. // minimum radius
  259. const Scalar min_r = r;
  260. // cell size based on 3D distance
  261. // It works reasonably well (but is probably biased to use s=2*r/√3 here and
  262. // g=1 in the outer loop below.
  263. //
  264. // One thing to try would be to store a list in S (rather than a single point)
  265. // or equivalently a mask over M and just use M as a generic spatial hash
  266. // (with arbitrary size) and then tune its size (being careful to make g a
  267. // function of r and s; and removing the `if S=-1 checks`)
  268. const Scalar s = r/sqrt(3.0);
  269. const double area =
  270. [&](){Eigen::VectorXd A;igl::doublearea(V,F,A);return A.array().sum()/2;}();
  271. // Circle packing in the plane has igl::PI*sqrt(3)/6 efficiency
  272. const double expected_number_of_points =
  273. area * (igl::PI * sqrt(3.0) / 6.0) / (igl::PI * min_r * min_r / 4.0);
  274. // Make a uniform random sampling with 30*expected_number_of_points.
  275. const int nx = 30.0*expected_number_of_points;
  276. MatrixX3S X,XB;
  277. Eigen::VectorXi XFI;
  278. igl::random_points_on_mesh(nx,V,F,XB,XFI,X,urbg);
  279. // Rescale so that s = 1
  280. Eigen::Matrix<int,Eigen::Dynamic,3,Eigen::RowMajor> Xs =
  281. ((X.rowwise()-X.colwise().minCoeff())/s).template cast<int>();
  282. const int w = Xs.maxCoeff()+1;
  283. {
  284. Eigen::VectorXi I;
  285. igl::sortrows(decltype(Xs)(Xs),true,Xs,I);
  286. igl::slice(decltype(X)(X),I,1,X);
  287. // These two could be spun off in their own thread.
  288. igl::slice(decltype(XB)(XB),I,1,XB);
  289. igl::slice(decltype(XFI)(XFI),I,1,XFI);
  290. }
  291. // Initialization
  292. std::unordered_map<BlueNoiseKeyType,std::vector<int> > M;
  293. std::unordered_map<BlueNoiseKeyType, int > S;
  294. // attempted to seed
  295. std::unordered_map<BlueNoiseKeyType, int > A;
  296. // Q: Too many?
  297. // A: Seems to help though.
  298. M.reserve(Xs.rows());
  299. S.reserve(Xs.rows());
  300. for(int i = 0;i<Xs.rows();i++)
  301. {
  302. BlueNoiseKeyType k = blue_noise_key(w,Xs(i,0),Xs(i,1),Xs(i,2));
  303. const auto Miter = M.find(k);
  304. if(Miter == M.end())
  305. {
  306. M.insert({k,{i}});
  307. }else
  308. {
  309. Miter->second.push_back(i);
  310. }
  311. S.emplace(k,-1);
  312. A.emplace(k,false);
  313. }
  314. std::vector<int> active;
  315. // precompute r²
  316. // Q: is this necessary?
  317. const double rr = r*r;
  318. std::vector<int> collected;
  319. collected.reserve(2.0*expected_number_of_points);
  320. auto Mouter = M.begin();
  321. // Just take the first point as the initial seed
  322. const auto initialize = [&]()->bool
  323. {
  324. while(true)
  325. {
  326. if(Mouter == M.end())
  327. {
  328. return false;
  329. }
  330. const BlueNoiseKeyType k = Mouter->first;
  331. // Haven't placed in this cell yet
  332. if(S[k]<0)
  333. {
  334. if(activate(X,Xs,rr,-1,w,k,M,S,active)) return true;
  335. }
  336. Mouter++;
  337. }
  338. assert(false && "should not be reachable.");
  339. };
  340. // important if mesh contains many connected components
  341. while(initialize())
  342. {
  343. while(active.size()>0)
  344. {
  345. step(X,Xs,rr,w,urbg,M,S,active,collected);
  346. }
  347. }
  348. {
  349. const int n = collected.size();
  350. P.resize(n,3);
  351. B.resize(n,3);
  352. FI.resize(n);
  353. for(int i = 0;i<n;i++)
  354. {
  355. const int c = collected[i];
  356. P.row(i) = X.row(c).template cast<typename DerivedP::Scalar>();
  357. B.row(i) = XB.row(c).template cast<typename DerivedB::Scalar>();
  358. FI(i) = XFI(c);
  359. }
  360. }
  361. }
  362. #ifdef IGL_STATIC_LIBRARY
  363. // Explicit template instantiation
  364. template void igl::blue_noise<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, std::mt19937_64 >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::Matrix<double, -1, -1, 0, -1, -1>::Scalar, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, std::mt19937_64&&);
  365. template void igl::blue_noise<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, std::mt19937 >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::Matrix<double, -1, -1, 0, -1, -1>::Scalar, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, std::mt19937&&);
  366. #endif