mapblock_mesh.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "mapblock_mesh.h"
  17. #include "client.h"
  18. #include "mapblock.h"
  19. #include "map.h"
  20. #include "profiler.h"
  21. #include "shader.h"
  22. #include "mesh.h"
  23. #include "minimap.h"
  24. #include "content_mapblock.h"
  25. #include "util/directiontables.h"
  26. #include "client/meshgen/collector.h"
  27. #include "client/renderingengine.h"
  28. #include <array>
  29. /*
  30. MeshMakeData
  31. */
  32. MeshMakeData::MeshMakeData(Client *client, bool use_shaders,
  33. bool use_tangent_vertices):
  34. m_client(client),
  35. m_use_shaders(use_shaders),
  36. m_use_tangent_vertices(use_tangent_vertices)
  37. {}
  38. void MeshMakeData::fillBlockDataBegin(const v3s16 &blockpos)
  39. {
  40. m_blockpos = blockpos;
  41. v3s16 blockpos_nodes = m_blockpos*MAP_BLOCKSIZE;
  42. m_vmanip.clear();
  43. VoxelArea voxel_area(blockpos_nodes - v3s16(1,1,1) * MAP_BLOCKSIZE,
  44. blockpos_nodes + v3s16(1,1,1) * MAP_BLOCKSIZE*2-v3s16(1,1,1));
  45. m_vmanip.addArea(voxel_area);
  46. }
  47. void MeshMakeData::fillBlockData(const v3s16 &block_offset, MapNode *data)
  48. {
  49. v3s16 data_size(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);
  50. VoxelArea data_area(v3s16(0,0,0), data_size - v3s16(1,1,1));
  51. v3s16 bp = m_blockpos + block_offset;
  52. v3s16 blockpos_nodes = bp * MAP_BLOCKSIZE;
  53. m_vmanip.copyFrom(data, data_area, v3s16(0,0,0), blockpos_nodes, data_size);
  54. }
  55. void MeshMakeData::fill(MapBlock *block)
  56. {
  57. fillBlockDataBegin(block->getPos());
  58. fillBlockData(v3s16(0,0,0), block->getData());
  59. // Get map for reading neighbor blocks
  60. Map *map = block->getParent();
  61. for (const v3s16 &dir : g_26dirs) {
  62. v3s16 bp = m_blockpos + dir;
  63. MapBlock *b = map->getBlockNoCreateNoEx(bp);
  64. if(b)
  65. fillBlockData(dir, b->getData());
  66. }
  67. }
  68. void MeshMakeData::fillSingleNode(MapNode *node)
  69. {
  70. m_blockpos = v3s16(0,0,0);
  71. v3s16 blockpos_nodes = v3s16(0,0,0);
  72. VoxelArea area(blockpos_nodes-v3s16(1,1,1)*MAP_BLOCKSIZE,
  73. blockpos_nodes+v3s16(1,1,1)*MAP_BLOCKSIZE*2-v3s16(1,1,1));
  74. s32 volume = area.getVolume();
  75. s32 our_node_index = area.index(1,1,1);
  76. // Allocate this block + neighbors
  77. m_vmanip.clear();
  78. m_vmanip.addArea(area);
  79. // Fill in data
  80. MapNode *data = new MapNode[volume];
  81. for(s32 i = 0; i < volume; i++)
  82. {
  83. if (i == our_node_index)
  84. data[i] = *node;
  85. else
  86. data[i] = MapNode(CONTENT_AIR, LIGHT_MAX, 0);
  87. }
  88. m_vmanip.copyFrom(data, area, area.MinEdge, area.MinEdge, area.getExtent());
  89. delete[] data;
  90. }
  91. void MeshMakeData::setCrack(int crack_level, v3s16 crack_pos)
  92. {
  93. if (crack_level >= 0)
  94. m_crack_pos_relative = crack_pos - m_blockpos*MAP_BLOCKSIZE;
  95. }
  96. void MeshMakeData::setSmoothLighting(bool smooth_lighting)
  97. {
  98. m_smooth_lighting = smooth_lighting;
  99. }
  100. /*
  101. Light and vertex color functions
  102. */
  103. /*
  104. Calculate non-smooth lighting at interior of node.
  105. Single light bank.
  106. */
  107. static u8 getInteriorLight(enum LightBank bank, MapNode n, s32 increment,
  108. const NodeDefManager *ndef)
  109. {
  110. u8 light = n.getLight(bank, ndef);
  111. if (light > 0)
  112. light = rangelim(light + increment, 0, LIGHT_SUN);
  113. return decode_light(light);
  114. }
  115. /*
  116. Calculate non-smooth lighting at interior of node.
  117. Both light banks.
  118. */
  119. u16 getInteriorLight(MapNode n, s32 increment, const NodeDefManager *ndef)
  120. {
  121. u16 day = getInteriorLight(LIGHTBANK_DAY, n, increment, ndef);
  122. u16 night = getInteriorLight(LIGHTBANK_NIGHT, n, increment, ndef);
  123. return day | (night << 8);
  124. }
  125. /*
  126. Calculate non-smooth lighting at face of node.
  127. Single light bank.
  128. */
  129. static u8 getFaceLight(enum LightBank bank, MapNode n, MapNode n2,
  130. v3s16 face_dir, const NodeDefManager *ndef)
  131. {
  132. u8 light;
  133. u8 l1 = n.getLight(bank, ndef);
  134. u8 l2 = n2.getLight(bank, ndef);
  135. if(l1 > l2)
  136. light = l1;
  137. else
  138. light = l2;
  139. // Boost light level for light sources
  140. u8 light_source = MYMAX(ndef->get(n).light_source,
  141. ndef->get(n2).light_source);
  142. if(light_source > light)
  143. light = light_source;
  144. return decode_light(light);
  145. }
  146. /*
  147. Calculate non-smooth lighting at face of node.
  148. Both light banks.
  149. */
  150. u16 getFaceLight(MapNode n, MapNode n2, const v3s16 &face_dir,
  151. const NodeDefManager *ndef)
  152. {
  153. u16 day = getFaceLight(LIGHTBANK_DAY, n, n2, face_dir, ndef);
  154. u16 night = getFaceLight(LIGHTBANK_NIGHT, n, n2, face_dir, ndef);
  155. return day | (night << 8);
  156. }
  157. /*
  158. Calculate smooth lighting at the XYZ- corner of p.
  159. Both light banks
  160. */
  161. static u16 getSmoothLightCombined(const v3s16 &p,
  162. const std::array<v3s16,8> &dirs, MeshMakeData *data)
  163. {
  164. const NodeDefManager *ndef = data->m_client->ndef();
  165. u16 ambient_occlusion = 0;
  166. u16 light_count = 0;
  167. u8 light_source_max = 0;
  168. u16 light_day = 0;
  169. u16 light_night = 0;
  170. bool direct_sunlight = false;
  171. auto add_node = [&] (u8 i, bool obstructed = false) -> bool {
  172. if (obstructed) {
  173. ambient_occlusion++;
  174. return false;
  175. }
  176. MapNode n = data->m_vmanip.getNodeNoExNoEmerge(p + dirs[i]);
  177. if (n.getContent() == CONTENT_IGNORE)
  178. return true;
  179. const ContentFeatures &f = ndef->get(n);
  180. if (f.light_source > light_source_max)
  181. light_source_max = f.light_source;
  182. // Check f.solidness because fast-style leaves look better this way
  183. if (f.param_type == CPT_LIGHT && f.solidness != 2) {
  184. u8 light_level_day = n.getLightNoChecks(LIGHTBANK_DAY, &f);
  185. u8 light_level_night = n.getLightNoChecks(LIGHTBANK_NIGHT, &f);
  186. if (light_level_day == LIGHT_SUN)
  187. direct_sunlight = true;
  188. light_day += decode_light(light_level_day);
  189. light_night += decode_light(light_level_night);
  190. light_count++;
  191. } else {
  192. ambient_occlusion++;
  193. }
  194. return f.light_propagates;
  195. };
  196. bool obstructed[4] = { true, true, true, true };
  197. add_node(0);
  198. bool opaque1 = !add_node(1);
  199. bool opaque2 = !add_node(2);
  200. bool opaque3 = !add_node(3);
  201. obstructed[0] = opaque1 && opaque2;
  202. obstructed[1] = opaque1 && opaque3;
  203. obstructed[2] = opaque2 && opaque3;
  204. for (u8 k = 0; k < 3; ++k)
  205. if (add_node(k + 4, obstructed[k]))
  206. obstructed[3] = false;
  207. if (add_node(7, obstructed[3])) { // wrap light around nodes
  208. ambient_occlusion -= 3;
  209. for (u8 k = 0; k < 3; ++k)
  210. add_node(k + 4, !obstructed[k]);
  211. }
  212. if (light_count == 0) {
  213. light_day = light_night = 0;
  214. } else {
  215. light_day /= light_count;
  216. light_night /= light_count;
  217. }
  218. // boost direct sunlight, if any
  219. if (direct_sunlight)
  220. light_day = 0xFF;
  221. // Boost brightness around light sources
  222. bool skip_ambient_occlusion_day = false;
  223. if (decode_light(light_source_max) >= light_day) {
  224. light_day = decode_light(light_source_max);
  225. skip_ambient_occlusion_day = true;
  226. }
  227. bool skip_ambient_occlusion_night = false;
  228. if(decode_light(light_source_max) >= light_night) {
  229. light_night = decode_light(light_source_max);
  230. skip_ambient_occlusion_night = true;
  231. }
  232. if (ambient_occlusion > 4) {
  233. static thread_local const float ao_gamma = rangelim(
  234. g_settings->getFloat("ambient_occlusion_gamma"), 0.25, 4.0);
  235. // Table of gamma space multiply factors.
  236. static thread_local const float light_amount[3] = {
  237. powf(0.75, 1.0 / ao_gamma),
  238. powf(0.5, 1.0 / ao_gamma),
  239. powf(0.25, 1.0 / ao_gamma)
  240. };
  241. //calculate table index for gamma space multiplier
  242. ambient_occlusion -= 5;
  243. if (!skip_ambient_occlusion_day)
  244. light_day = rangelim(core::round32(
  245. light_day * light_amount[ambient_occlusion]), 0, 255);
  246. if (!skip_ambient_occlusion_night)
  247. light_night = rangelim(core::round32(
  248. light_night * light_amount[ambient_occlusion]), 0, 255);
  249. }
  250. return light_day | (light_night << 8);
  251. }
  252. /*
  253. Calculate smooth lighting at the given corner of p.
  254. Both light banks.
  255. Node at p is solid, and thus the lighting is face-dependent.
  256. */
  257. u16 getSmoothLightSolid(const v3s16 &p, const v3s16 &face_dir, const v3s16 &corner, MeshMakeData *data)
  258. {
  259. return getSmoothLightTransparent(p + face_dir, corner - 2 * face_dir, data);
  260. }
  261. /*
  262. Calculate smooth lighting at the given corner of p.
  263. Both light banks.
  264. Node at p is not solid, and the lighting is not face-dependent.
  265. */
  266. u16 getSmoothLightTransparent(const v3s16 &p, const v3s16 &corner, MeshMakeData *data)
  267. {
  268. const std::array<v3s16,8> dirs = {{
  269. // Always shine light
  270. v3s16(0,0,0),
  271. v3s16(corner.X,0,0),
  272. v3s16(0,corner.Y,0),
  273. v3s16(0,0,corner.Z),
  274. // Can be obstructed
  275. v3s16(corner.X,corner.Y,0),
  276. v3s16(corner.X,0,corner.Z),
  277. v3s16(0,corner.Y,corner.Z),
  278. v3s16(corner.X,corner.Y,corner.Z)
  279. }};
  280. return getSmoothLightCombined(p, dirs, data);
  281. }
  282. void get_sunlight_color(video::SColorf *sunlight, u32 daynight_ratio){
  283. f32 rg = daynight_ratio / 1000.0f - 0.04f;
  284. f32 b = (0.98f * daynight_ratio) / 1000.0f + 0.078f;
  285. sunlight->r = rg;
  286. sunlight->g = rg;
  287. sunlight->b = b;
  288. }
  289. void final_color_blend(video::SColor *result,
  290. u16 light, u32 daynight_ratio)
  291. {
  292. video::SColorf dayLight;
  293. get_sunlight_color(&dayLight, daynight_ratio);
  294. final_color_blend(result,
  295. encode_light(light, 0), dayLight);
  296. }
  297. void final_color_blend(video::SColor *result,
  298. const video::SColor &data, const video::SColorf &dayLight)
  299. {
  300. static const video::SColorf artificialColor(1.04f, 1.04f, 1.04f);
  301. video::SColorf c(data);
  302. f32 n = 1 - c.a;
  303. f32 r = c.r * (c.a * dayLight.r + n * artificialColor.r) * 2.0f;
  304. f32 g = c.g * (c.a * dayLight.g + n * artificialColor.g) * 2.0f;
  305. f32 b = c.b * (c.a * dayLight.b + n * artificialColor.b) * 2.0f;
  306. // Emphase blue a bit in darker places
  307. // Each entry of this array represents a range of 8 blue levels
  308. static const u8 emphase_blue_when_dark[32] = {
  309. 1, 4, 6, 6, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0,
  310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  311. };
  312. b += emphase_blue_when_dark[irr::core::clamp((s32) ((r + g + b) / 3 * 255),
  313. 0, 255) / 8] / 255.0f;
  314. result->setRed(core::clamp((s32) (r * 255.0f), 0, 255));
  315. result->setGreen(core::clamp((s32) (g * 255.0f), 0, 255));
  316. result->setBlue(core::clamp((s32) (b * 255.0f), 0, 255));
  317. }
  318. /*
  319. Mesh generation helpers
  320. */
  321. // This table is moved outside getNodeVertexDirs to avoid the compiler using
  322. // a mutex to initialize this table at runtime right in the hot path.
  323. // For details search the internet for "cxa_guard_acquire".
  324. static const v3s16 vertex_dirs_table[] = {
  325. // ( 1, 0, 0)
  326. v3s16( 1,-1, 1), v3s16( 1,-1,-1),
  327. v3s16( 1, 1,-1), v3s16( 1, 1, 1),
  328. // ( 0, 1, 0)
  329. v3s16( 1, 1,-1), v3s16(-1, 1,-1),
  330. v3s16(-1, 1, 1), v3s16( 1, 1, 1),
  331. // ( 0, 0, 1)
  332. v3s16(-1,-1, 1), v3s16( 1,-1, 1),
  333. v3s16( 1, 1, 1), v3s16(-1, 1, 1),
  334. // invalid
  335. v3s16(), v3s16(), v3s16(), v3s16(),
  336. // ( 0, 0,-1)
  337. v3s16( 1,-1,-1), v3s16(-1,-1,-1),
  338. v3s16(-1, 1,-1), v3s16( 1, 1,-1),
  339. // ( 0,-1, 0)
  340. v3s16( 1,-1, 1), v3s16(-1,-1, 1),
  341. v3s16(-1,-1,-1), v3s16( 1,-1,-1),
  342. // (-1, 0, 0)
  343. v3s16(-1,-1,-1), v3s16(-1,-1, 1),
  344. v3s16(-1, 1, 1), v3s16(-1, 1,-1)
  345. };
  346. /*
  347. vertex_dirs: v3s16[4]
  348. */
  349. static void getNodeVertexDirs(const v3s16 &dir, v3s16 *vertex_dirs)
  350. {
  351. /*
  352. If looked from outside the node towards the face, the corners are:
  353. 0: bottom-right
  354. 1: bottom-left
  355. 2: top-left
  356. 3: top-right
  357. */
  358. // Direction must be (1,0,0), (-1,0,0), (0,1,0), (0,-1,0),
  359. // (0,0,1), (0,0,-1)
  360. assert(dir.X * dir.X + dir.Y * dir.Y + dir.Z * dir.Z == 1);
  361. // Convert direction to single integer for table lookup
  362. u8 idx = (dir.X + 2 * dir.Y + 3 * dir.Z) & 7;
  363. idx = (idx - 1) * 4;
  364. memcpy(vertex_dirs, &vertex_dirs_table[idx], 4 * sizeof(v3s16));
  365. }
  366. static void getNodeTextureCoords(v3f base, const v3f &scale, const v3s16 &dir, float *u, float *v)
  367. {
  368. if (dir.X > 0 || dir.Y > 0 || dir.Z < 0)
  369. base -= scale;
  370. if (dir == v3s16(0,0,1)) {
  371. *u = -base.X - 1;
  372. *v = -base.Y - 1;
  373. } else if (dir == v3s16(0,0,-1)) {
  374. *u = base.X + 1;
  375. *v = -base.Y - 2;
  376. } else if (dir == v3s16(1,0,0)) {
  377. *u = base.Z + 1;
  378. *v = -base.Y - 2;
  379. } else if (dir == v3s16(-1,0,0)) {
  380. *u = -base.Z - 1;
  381. *v = -base.Y - 1;
  382. } else if (dir == v3s16(0,1,0)) {
  383. *u = base.X + 1;
  384. *v = -base.Z - 2;
  385. } else if (dir == v3s16(0,-1,0)) {
  386. *u = base.X;
  387. *v = base.Z;
  388. }
  389. }
  390. struct FastFace
  391. {
  392. TileSpec tile;
  393. video::S3DVertex vertices[4]; // Precalculated vertices
  394. /*!
  395. * The face is divided into two triangles. If this is true,
  396. * vertices 0 and 2 are connected, othervise vertices 1 and 3
  397. * are connected.
  398. */
  399. bool vertex_0_2_connected;
  400. };
  401. static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li3,
  402. const v3f &tp, const v3f &p, const v3s16 &dir, const v3f &scale, std::vector<FastFace> &dest)
  403. {
  404. // Position is at the center of the cube.
  405. v3f pos = p * BS;
  406. float x0 = 0.0f;
  407. float y0 = 0.0f;
  408. float w = 1.0f;
  409. float h = 1.0f;
  410. v3f vertex_pos[4];
  411. v3s16 vertex_dirs[4];
  412. getNodeVertexDirs(dir, vertex_dirs);
  413. if (tile.world_aligned)
  414. getNodeTextureCoords(tp, scale, dir, &x0, &y0);
  415. v3s16 t;
  416. u16 t1;
  417. switch (tile.rotation) {
  418. case 0:
  419. break;
  420. case 1: //R90
  421. t = vertex_dirs[0];
  422. vertex_dirs[0] = vertex_dirs[3];
  423. vertex_dirs[3] = vertex_dirs[2];
  424. vertex_dirs[2] = vertex_dirs[1];
  425. vertex_dirs[1] = t;
  426. t1 = li0;
  427. li0 = li3;
  428. li3 = li2;
  429. li2 = li1;
  430. li1 = t1;
  431. break;
  432. case 2: //R180
  433. t = vertex_dirs[0];
  434. vertex_dirs[0] = vertex_dirs[2];
  435. vertex_dirs[2] = t;
  436. t = vertex_dirs[1];
  437. vertex_dirs[1] = vertex_dirs[3];
  438. vertex_dirs[3] = t;
  439. t1 = li0;
  440. li0 = li2;
  441. li2 = t1;
  442. t1 = li1;
  443. li1 = li3;
  444. li3 = t1;
  445. break;
  446. case 3: //R270
  447. t = vertex_dirs[0];
  448. vertex_dirs[0] = vertex_dirs[1];
  449. vertex_dirs[1] = vertex_dirs[2];
  450. vertex_dirs[2] = vertex_dirs[3];
  451. vertex_dirs[3] = t;
  452. t1 = li0;
  453. li0 = li1;
  454. li1 = li2;
  455. li2 = li3;
  456. li3 = t1;
  457. break;
  458. case 4: //FXR90
  459. t = vertex_dirs[0];
  460. vertex_dirs[0] = vertex_dirs[3];
  461. vertex_dirs[3] = vertex_dirs[2];
  462. vertex_dirs[2] = vertex_dirs[1];
  463. vertex_dirs[1] = t;
  464. t1 = li0;
  465. li0 = li3;
  466. li3 = li2;
  467. li2 = li1;
  468. li1 = t1;
  469. y0 += h;
  470. h *= -1;
  471. break;
  472. case 5: //FXR270
  473. t = vertex_dirs[0];
  474. vertex_dirs[0] = vertex_dirs[1];
  475. vertex_dirs[1] = vertex_dirs[2];
  476. vertex_dirs[2] = vertex_dirs[3];
  477. vertex_dirs[3] = t;
  478. t1 = li0;
  479. li0 = li1;
  480. li1 = li2;
  481. li2 = li3;
  482. li3 = t1;
  483. y0 += h;
  484. h *= -1;
  485. break;
  486. case 6: //FYR90
  487. t = vertex_dirs[0];
  488. vertex_dirs[0] = vertex_dirs[3];
  489. vertex_dirs[3] = vertex_dirs[2];
  490. vertex_dirs[2] = vertex_dirs[1];
  491. vertex_dirs[1] = t;
  492. t1 = li0;
  493. li0 = li3;
  494. li3 = li2;
  495. li2 = li1;
  496. li1 = t1;
  497. x0 += w;
  498. w *= -1;
  499. break;
  500. case 7: //FYR270
  501. t = vertex_dirs[0];
  502. vertex_dirs[0] = vertex_dirs[1];
  503. vertex_dirs[1] = vertex_dirs[2];
  504. vertex_dirs[2] = vertex_dirs[3];
  505. vertex_dirs[3] = t;
  506. t1 = li0;
  507. li0 = li1;
  508. li1 = li2;
  509. li2 = li3;
  510. li3 = t1;
  511. x0 += w;
  512. w *= -1;
  513. break;
  514. case 8: //FX
  515. y0 += h;
  516. h *= -1;
  517. break;
  518. case 9: //FY
  519. x0 += w;
  520. w *= -1;
  521. break;
  522. default:
  523. break;
  524. }
  525. for (u16 i = 0; i < 4; i++) {
  526. vertex_pos[i] = v3f(
  527. BS / 2 * vertex_dirs[i].X,
  528. BS / 2 * vertex_dirs[i].Y,
  529. BS / 2 * vertex_dirs[i].Z
  530. );
  531. }
  532. for (v3f &vpos : vertex_pos) {
  533. vpos.X *= scale.X;
  534. vpos.Y *= scale.Y;
  535. vpos.Z *= scale.Z;
  536. vpos += pos;
  537. }
  538. f32 abs_scale = 1.0f;
  539. if (scale.X < 0.999f || scale.X > 1.001f) abs_scale = scale.X;
  540. else if (scale.Y < 0.999f || scale.Y > 1.001f) abs_scale = scale.Y;
  541. else if (scale.Z < 0.999f || scale.Z > 1.001f) abs_scale = scale.Z;
  542. v3f normal(dir.X, dir.Y, dir.Z);
  543. u16 li[4] = { li0, li1, li2, li3 };
  544. u16 day[4];
  545. u16 night[4];
  546. for (u8 i = 0; i < 4; i++) {
  547. day[i] = li[i] >> 8;
  548. night[i] = li[i] & 0xFF;
  549. }
  550. bool vertex_0_2_connected = abs(day[0] - day[2]) + abs(night[0] - night[2])
  551. < abs(day[1] - day[3]) + abs(night[1] - night[3]);
  552. v2f32 f[4] = {
  553. core::vector2d<f32>(x0 + w * abs_scale, y0 + h),
  554. core::vector2d<f32>(x0, y0 + h),
  555. core::vector2d<f32>(x0, y0),
  556. core::vector2d<f32>(x0 + w * abs_scale, y0) };
  557. // equivalent to dest.push_back(FastFace()) but faster
  558. dest.emplace_back();
  559. FastFace& face = *dest.rbegin();
  560. for (u8 i = 0; i < 4; i++) {
  561. video::SColor c = encode_light(li[i], tile.emissive_light);
  562. if (!tile.emissive_light)
  563. applyFacesShading(c, normal);
  564. face.vertices[i] = video::S3DVertex(vertex_pos[i], normal, c, f[i]);
  565. }
  566. /*
  567. Revert triangles for nicer looking gradient if the
  568. brightness of vertices 1 and 3 differ less than
  569. the brightness of vertices 0 and 2.
  570. */
  571. face.vertex_0_2_connected = vertex_0_2_connected;
  572. face.tile = tile;
  573. }
  574. /*
  575. Nodes make a face if contents differ and solidness differs.
  576. Return value:
  577. 0: No face
  578. 1: Face uses m1's content
  579. 2: Face uses m2's content
  580. equivalent: Whether the blocks share the same face (eg. water and glass)
  581. TODO: Add 3: Both faces drawn with backface culling, remove equivalent
  582. */
  583. static u8 face_contents(content_t m1, content_t m2, bool *equivalent,
  584. const NodeDefManager *ndef)
  585. {
  586. *equivalent = false;
  587. if (m1 == m2 || m1 == CONTENT_IGNORE || m2 == CONTENT_IGNORE)
  588. return 0;
  589. const ContentFeatures &f1 = ndef->get(m1);
  590. const ContentFeatures &f2 = ndef->get(m2);
  591. // Contents don't differ for different forms of same liquid
  592. if (f1.sameLiquid(f2))
  593. return 0;
  594. u8 c1 = f1.solidness;
  595. u8 c2 = f2.solidness;
  596. if (c1 == c2)
  597. return 0;
  598. if (c1 == 0)
  599. c1 = f1.visual_solidness;
  600. else if (c2 == 0)
  601. c2 = f2.visual_solidness;
  602. if (c1 == c2) {
  603. *equivalent = true;
  604. // If same solidness, liquid takes precense
  605. if (f1.isLiquid())
  606. return 1;
  607. if (f2.isLiquid())
  608. return 2;
  609. }
  610. if (c1 > c2)
  611. return 1;
  612. return 2;
  613. }
  614. /*
  615. Gets nth node tile (0 <= n <= 5).
  616. */
  617. void getNodeTileN(MapNode mn, const v3s16 &p, u8 tileindex, MeshMakeData *data, TileSpec &tile)
  618. {
  619. const NodeDefManager *ndef = data->m_client->ndef();
  620. const ContentFeatures &f = ndef->get(mn);
  621. tile = f.tiles[tileindex];
  622. bool has_crack = p == data->m_crack_pos_relative;
  623. for (TileLayer &layer : tile.layers) {
  624. if (layer.texture_id == 0)
  625. continue;
  626. if (!layer.has_color)
  627. mn.getColor(f, &(layer.color));
  628. // Apply temporary crack
  629. if (has_crack)
  630. layer.material_flags |= MATERIAL_FLAG_CRACK;
  631. }
  632. }
  633. /*
  634. Gets node tile given a face direction.
  635. */
  636. void getNodeTile(MapNode mn, const v3s16 &p, const v3s16 &dir, MeshMakeData *data, TileSpec &tile)
  637. {
  638. const NodeDefManager *ndef = data->m_client->ndef();
  639. // Direction must be (1,0,0), (-1,0,0), (0,1,0), (0,-1,0),
  640. // (0,0,1), (0,0,-1) or (0,0,0)
  641. assert(dir.X * dir.X + dir.Y * dir.Y + dir.Z * dir.Z <= 1);
  642. // Convert direction to single integer for table lookup
  643. // 0 = (0,0,0)
  644. // 1 = (1,0,0)
  645. // 2 = (0,1,0)
  646. // 3 = (0,0,1)
  647. // 4 = invalid, treat as (0,0,0)
  648. // 5 = (0,0,-1)
  649. // 6 = (0,-1,0)
  650. // 7 = (-1,0,0)
  651. u8 dir_i = ((dir.X + 2 * dir.Y + 3 * dir.Z) & 7) * 2;
  652. // Get rotation for things like chests
  653. u8 facedir = mn.getFaceDir(ndef, true);
  654. static const u16 dir_to_tile[24 * 16] =
  655. {
  656. // 0 +X +Y +Z -Z -Y -X -> value=tile,rotation
  657. 0,0, 2,0 , 0,0 , 4,0 , 0,0, 5,0 , 1,0 , 3,0 , // rotate around y+ 0 - 3
  658. 0,0, 4,0 , 0,3 , 3,0 , 0,0, 2,0 , 1,1 , 5,0 ,
  659. 0,0, 3,0 , 0,2 , 5,0 , 0,0, 4,0 , 1,2 , 2,0 ,
  660. 0,0, 5,0 , 0,1 , 2,0 , 0,0, 3,0 , 1,3 , 4,0 ,
  661. 0,0, 2,3 , 5,0 , 0,2 , 0,0, 1,0 , 4,2 , 3,1 , // rotate around z+ 4 - 7
  662. 0,0, 4,3 , 2,0 , 0,1 , 0,0, 1,1 , 3,2 , 5,1 ,
  663. 0,0, 3,3 , 4,0 , 0,0 , 0,0, 1,2 , 5,2 , 2,1 ,
  664. 0,0, 5,3 , 3,0 , 0,3 , 0,0, 1,3 , 2,2 , 4,1 ,
  665. 0,0, 2,1 , 4,2 , 1,2 , 0,0, 0,0 , 5,0 , 3,3 , // rotate around z- 8 - 11
  666. 0,0, 4,1 , 3,2 , 1,3 , 0,0, 0,3 , 2,0 , 5,3 ,
  667. 0,0, 3,1 , 5,2 , 1,0 , 0,0, 0,2 , 4,0 , 2,3 ,
  668. 0,0, 5,1 , 2,2 , 1,1 , 0,0, 0,1 , 3,0 , 4,3 ,
  669. 0,0, 0,3 , 3,3 , 4,1 , 0,0, 5,3 , 2,3 , 1,3 , // rotate around x+ 12 - 15
  670. 0,0, 0,2 , 5,3 , 3,1 , 0,0, 2,3 , 4,3 , 1,0 ,
  671. 0,0, 0,1 , 2,3 , 5,1 , 0,0, 4,3 , 3,3 , 1,1 ,
  672. 0,0, 0,0 , 4,3 , 2,1 , 0,0, 3,3 , 5,3 , 1,2 ,
  673. 0,0, 1,1 , 2,1 , 4,3 , 0,0, 5,1 , 3,1 , 0,1 , // rotate around x- 16 - 19
  674. 0,0, 1,2 , 4,1 , 3,3 , 0,0, 2,1 , 5,1 , 0,0 ,
  675. 0,0, 1,3 , 3,1 , 5,3 , 0,0, 4,1 , 2,1 , 0,3 ,
  676. 0,0, 1,0 , 5,1 , 2,3 , 0,0, 3,1 , 4,1 , 0,2 ,
  677. 0,0, 3,2 , 1,2 , 4,2 , 0,0, 5,2 , 0,2 , 2,2 , // rotate around y- 20 - 23
  678. 0,0, 5,2 , 1,3 , 3,2 , 0,0, 2,2 , 0,1 , 4,2 ,
  679. 0,0, 2,2 , 1,0 , 5,2 , 0,0, 4,2 , 0,0 , 3,2 ,
  680. 0,0, 4,2 , 1,1 , 2,2 , 0,0, 3,2 , 0,3 , 5,2
  681. };
  682. u16 tile_index = facedir * 16 + dir_i;
  683. getNodeTileN(mn, p, dir_to_tile[tile_index], data, tile);
  684. tile.rotation = tile.world_aligned ? 0 : dir_to_tile[tile_index + 1];
  685. }
  686. static void getTileInfo(
  687. // Input:
  688. MeshMakeData *data,
  689. const v3s16 &p,
  690. const v3s16 &face_dir,
  691. // Output:
  692. bool &makes_face,
  693. v3s16 &p_corrected,
  694. v3s16 &face_dir_corrected,
  695. u16 *lights,
  696. u8 &waving,
  697. TileSpec &tile
  698. )
  699. {
  700. VoxelManipulator &vmanip = data->m_vmanip;
  701. const NodeDefManager *ndef = data->m_client->ndef();
  702. v3s16 blockpos_nodes = data->m_blockpos * MAP_BLOCKSIZE;
  703. const MapNode &n0 = vmanip.getNodeRefUnsafe(blockpos_nodes + p);
  704. // Don't even try to get n1 if n0 is already CONTENT_IGNORE
  705. if (n0.getContent() == CONTENT_IGNORE) {
  706. makes_face = false;
  707. return;
  708. }
  709. const MapNode &n1 = vmanip.getNodeRefUnsafeCheckFlags(blockpos_nodes + p + face_dir);
  710. if (n1.getContent() == CONTENT_IGNORE) {
  711. makes_face = false;
  712. return;
  713. }
  714. // This is hackish
  715. bool equivalent = false;
  716. u8 mf = face_contents(n0.getContent(), n1.getContent(),
  717. &equivalent, ndef);
  718. if (mf == 0) {
  719. makes_face = false;
  720. return;
  721. }
  722. makes_face = true;
  723. MapNode n = n0;
  724. if (mf == 1) {
  725. p_corrected = p;
  726. face_dir_corrected = face_dir;
  727. } else {
  728. n = n1;
  729. p_corrected = p + face_dir;
  730. face_dir_corrected = -face_dir;
  731. }
  732. getNodeTile(n, p_corrected, face_dir_corrected, data, tile);
  733. const ContentFeatures &f = ndef->get(n);
  734. waving = f.waving;
  735. tile.emissive_light = f.light_source;
  736. // eg. water and glass
  737. if (equivalent) {
  738. for (TileLayer &layer : tile.layers)
  739. layer.material_flags |= MATERIAL_FLAG_BACKFACE_CULLING;
  740. }
  741. if (!data->m_smooth_lighting) {
  742. lights[0] = lights[1] = lights[2] = lights[3] =
  743. getFaceLight(n0, n1, face_dir, ndef);
  744. } else {
  745. v3s16 vertex_dirs[4];
  746. getNodeVertexDirs(face_dir_corrected, vertex_dirs);
  747. v3s16 light_p = blockpos_nodes + p_corrected;
  748. for (u16 i = 0; i < 4; i++)
  749. lights[i] = getSmoothLightSolid(light_p, face_dir_corrected, vertex_dirs[i], data);
  750. }
  751. }
  752. /*
  753. startpos:
  754. translate_dir: unit vector with only one of x, y or z
  755. face_dir: unit vector with only one of x, y or z
  756. */
  757. static void updateFastFaceRow(
  758. MeshMakeData *data,
  759. const v3s16 &&startpos,
  760. v3s16 translate_dir,
  761. const v3f &&translate_dir_f,
  762. const v3s16 &&face_dir,
  763. std::vector<FastFace> &dest)
  764. {
  765. static thread_local const bool waving_liquids =
  766. g_settings->getBool("enable_shaders") &&
  767. g_settings->getBool("enable_waving_water");
  768. v3s16 p = startpos;
  769. u16 continuous_tiles_count = 1;
  770. bool makes_face = false;
  771. v3s16 p_corrected;
  772. v3s16 face_dir_corrected;
  773. u16 lights[4] = {0, 0, 0, 0};
  774. u8 waving;
  775. TileSpec tile;
  776. // Get info of first tile
  777. getTileInfo(data, p, face_dir,
  778. makes_face, p_corrected, face_dir_corrected,
  779. lights, waving, tile);
  780. // Unroll this variable which has a significant build cost
  781. TileSpec next_tile;
  782. for (u16 j = 0; j < MAP_BLOCKSIZE; j++) {
  783. // If tiling can be done, this is set to false in the next step
  784. bool next_is_different = true;
  785. bool next_makes_face = false;
  786. v3s16 next_p_corrected;
  787. v3s16 next_face_dir_corrected;
  788. u16 next_lights[4] = {0, 0, 0, 0};
  789. // If at last position, there is nothing to compare to and
  790. // the face must be drawn anyway
  791. if (j != MAP_BLOCKSIZE - 1) {
  792. p += translate_dir;
  793. getTileInfo(data, p, face_dir,
  794. next_makes_face, next_p_corrected,
  795. next_face_dir_corrected, next_lights,
  796. waving,
  797. next_tile);
  798. if (next_makes_face == makes_face
  799. && next_p_corrected == p_corrected + translate_dir
  800. && next_face_dir_corrected == face_dir_corrected
  801. && memcmp(next_lights, lights, sizeof(lights)) == 0
  802. // Don't apply fast faces to waving water.
  803. && (waving != 3 || !waving_liquids)
  804. && next_tile.isTileable(tile)) {
  805. next_is_different = false;
  806. continuous_tiles_count++;
  807. }
  808. }
  809. if (next_is_different) {
  810. /*
  811. Create a face if there should be one
  812. */
  813. if (makes_face) {
  814. // Floating point conversion of the position vector
  815. v3f pf(p_corrected.X, p_corrected.Y, p_corrected.Z);
  816. // Center point of face (kind of)
  817. v3f sp = pf - ((f32)continuous_tiles_count * 0.5f - 0.5f)
  818. * translate_dir_f;
  819. v3f scale(1, 1, 1);
  820. if (translate_dir.X != 0)
  821. scale.X = continuous_tiles_count;
  822. if (translate_dir.Y != 0)
  823. scale.Y = continuous_tiles_count;
  824. if (translate_dir.Z != 0)
  825. scale.Z = continuous_tiles_count;
  826. makeFastFace(tile, lights[0], lights[1], lights[2], lights[3],
  827. pf, sp, face_dir_corrected, scale, dest);
  828. g_profiler->avg("Meshgen: Tiles per face [#]", continuous_tiles_count);
  829. }
  830. continuous_tiles_count = 1;
  831. }
  832. makes_face = next_makes_face;
  833. p_corrected = next_p_corrected;
  834. face_dir_corrected = next_face_dir_corrected;
  835. memcpy(lights, next_lights, sizeof(lights));
  836. if (next_is_different)
  837. tile = std::move(next_tile); // faster than copy
  838. }
  839. }
  840. static void updateAllFastFaceRows(MeshMakeData *data,
  841. std::vector<FastFace> &dest)
  842. {
  843. /*
  844. Go through every y,z and get top(y+) faces in rows of x+
  845. */
  846. for (s16 y = 0; y < MAP_BLOCKSIZE; y++)
  847. for (s16 z = 0; z < MAP_BLOCKSIZE; z++)
  848. updateFastFaceRow(data,
  849. v3s16(0, y, z),
  850. v3s16(1, 0, 0), //dir
  851. v3f (1, 0, 0),
  852. v3s16(0, 1, 0), //face dir
  853. dest);
  854. /*
  855. Go through every x,y and get right(x+) faces in rows of z+
  856. */
  857. for (s16 x = 0; x < MAP_BLOCKSIZE; x++)
  858. for (s16 y = 0; y < MAP_BLOCKSIZE; y++)
  859. updateFastFaceRow(data,
  860. v3s16(x, y, 0),
  861. v3s16(0, 0, 1), //dir
  862. v3f (0, 0, 1),
  863. v3s16(1, 0, 0), //face dir
  864. dest);
  865. /*
  866. Go through every y,z and get back(z+) faces in rows of x+
  867. */
  868. for (s16 z = 0; z < MAP_BLOCKSIZE; z++)
  869. for (s16 y = 0; y < MAP_BLOCKSIZE; y++)
  870. updateFastFaceRow(data,
  871. v3s16(0, y, z),
  872. v3s16(1, 0, 0), //dir
  873. v3f (1, 0, 0),
  874. v3s16(0, 0, 1), //face dir
  875. dest);
  876. }
  877. static void applyTileColor(PreMeshBuffer &pmb)
  878. {
  879. video::SColor tc = pmb.layer.color;
  880. if (tc == video::SColor(0xFFFFFFFF))
  881. return;
  882. for (video::S3DVertex &vertex : pmb.vertices) {
  883. video::SColor *c = &vertex.Color;
  884. c->set(c->getAlpha(),
  885. c->getRed() * tc.getRed() / 255,
  886. c->getGreen() * tc.getGreen() / 255,
  887. c->getBlue() * tc.getBlue() / 255);
  888. }
  889. }
  890. /*
  891. MapBlockMesh
  892. */
  893. MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset):
  894. m_minimap_mapblock(NULL),
  895. m_tsrc(data->m_client->getTextureSource()),
  896. m_shdrsrc(data->m_client->getShaderSource()),
  897. m_animation_force_timer(0), // force initial animation
  898. m_last_crack(-1),
  899. m_last_daynight_ratio((u32) -1)
  900. {
  901. for (auto &m : m_mesh)
  902. m = new scene::SMesh();
  903. m_enable_shaders = data->m_use_shaders;
  904. m_use_tangent_vertices = data->m_use_tangent_vertices;
  905. m_enable_vbo = g_settings->getBool("enable_vbo");
  906. if (g_settings->getBool("enable_minimap")) {
  907. m_minimap_mapblock = new MinimapMapblock;
  908. m_minimap_mapblock->getMinimapNodes(
  909. &data->m_vmanip, data->m_blockpos * MAP_BLOCKSIZE);
  910. }
  911. // 4-21ms for MAP_BLOCKSIZE=16 (NOTE: probably outdated)
  912. // 24-155ms for MAP_BLOCKSIZE=32 (NOTE: probably outdated)
  913. //TimeTaker timer1("MapBlockMesh()");
  914. std::vector<FastFace> fastfaces_new;
  915. fastfaces_new.reserve(512);
  916. /*
  917. We are including the faces of the trailing edges of the block.
  918. This means that when something changes, the caller must
  919. also update the meshes of the blocks at the leading edges.
  920. NOTE: This is the slowest part of this method.
  921. */
  922. {
  923. // 4-23ms for MAP_BLOCKSIZE=16 (NOTE: probably outdated)
  924. //TimeTaker timer2("updateAllFastFaceRows()");
  925. updateAllFastFaceRows(data, fastfaces_new);
  926. }
  927. // End of slow part
  928. /*
  929. Convert FastFaces to MeshCollector
  930. */
  931. MeshCollector collector;
  932. {
  933. // avg 0ms (100ms spikes when loading textures the first time)
  934. // (NOTE: probably outdated)
  935. //TimeTaker timer2("MeshCollector building");
  936. for (const FastFace &f : fastfaces_new) {
  937. static const u16 indices[] = {0, 1, 2, 2, 3, 0};
  938. static const u16 indices_alternate[] = {0, 1, 3, 2, 3, 1};
  939. const u16 *indices_p =
  940. f.vertex_0_2_connected ? indices : indices_alternate;
  941. collector.append(f.tile, f.vertices, 4, indices_p, 6);
  942. }
  943. }
  944. /*
  945. Add special graphics:
  946. - torches
  947. - flowing water
  948. - fences
  949. - whatever
  950. */
  951. {
  952. MapblockMeshGenerator generator(data, &collector);
  953. generator.generate();
  954. }
  955. /*
  956. Convert MeshCollector to SMesh
  957. */
  958. for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
  959. for(u32 i = 0; i < collector.prebuffers[layer].size(); i++)
  960. {
  961. PreMeshBuffer &p = collector.prebuffers[layer][i];
  962. applyTileColor(p);
  963. // Generate animation data
  964. // - Cracks
  965. if (p.layer.material_flags & MATERIAL_FLAG_CRACK) {
  966. // Find the texture name plus ^[crack:N:
  967. std::ostringstream os(std::ios::binary);
  968. os << m_tsrc->getTextureName(p.layer.texture_id) << "^[crack";
  969. if (p.layer.material_flags & MATERIAL_FLAG_CRACK_OVERLAY)
  970. os << "o"; // use ^[cracko
  971. u8 tiles = p.layer.scale;
  972. if (tiles > 1)
  973. os << ":" << (u32)tiles;
  974. os << ":" << (u32)p.layer.animation_frame_count << ":";
  975. m_crack_materials.insert(std::make_pair(
  976. std::pair<u8, u32>(layer, i), os.str()));
  977. // Replace tile texture with the cracked one
  978. p.layer.texture = m_tsrc->getTextureForMesh(
  979. os.str() + "0",
  980. &p.layer.texture_id);
  981. }
  982. // - Texture animation
  983. if (p.layer.material_flags & MATERIAL_FLAG_ANIMATION) {
  984. // Add to MapBlockMesh in order to animate these tiles
  985. m_animation_tiles[std::pair<u8, u32>(layer, i)] = p.layer;
  986. m_animation_frames[std::pair<u8, u32>(layer, i)] = 0;
  987. if (g_settings->getBool(
  988. "desynchronize_mapblock_texture_animation")) {
  989. // Get starting position from noise
  990. m_animation_frame_offsets[std::pair<u8, u32>(layer, i)] =
  991. 100000 * (2.0 + noise3d(
  992. data->m_blockpos.X, data->m_blockpos.Y,
  993. data->m_blockpos.Z, 0));
  994. } else {
  995. // Play all synchronized
  996. m_animation_frame_offsets[std::pair<u8, u32>(layer, i)] = 0;
  997. }
  998. // Replace tile texture with the first animation frame
  999. p.layer.texture = (*p.layer.frames)[0].texture;
  1000. }
  1001. if (!m_enable_shaders) {
  1002. // Extract colors for day-night animation
  1003. // Dummy sunlight to handle non-sunlit areas
  1004. video::SColorf sunlight;
  1005. get_sunlight_color(&sunlight, 0);
  1006. u32 vertex_count = p.vertices.size();
  1007. for (u32 j = 0; j < vertex_count; j++) {
  1008. video::SColor *vc = &p.vertices[j].Color;
  1009. video::SColor copy = *vc;
  1010. if (vc->getAlpha() == 0) // No sunlight - no need to animate
  1011. final_color_blend(vc, copy, sunlight); // Finalize color
  1012. else // Record color to animate
  1013. m_daynight_diffs[std::pair<u8, u32>(layer, i)][j] = copy;
  1014. // The sunlight ratio has been stored,
  1015. // delete alpha (for the final rendering).
  1016. vc->setAlpha(255);
  1017. }
  1018. }
  1019. // Create material
  1020. video::SMaterial material;
  1021. material.setFlag(video::EMF_LIGHTING, false);
  1022. material.setFlag(video::EMF_BACK_FACE_CULLING, true);
  1023. material.setFlag(video::EMF_BILINEAR_FILTER, false);
  1024. material.setFlag(video::EMF_FOG_ENABLE, true);
  1025. material.setTexture(0, p.layer.texture);
  1026. if (m_enable_shaders) {
  1027. material.MaterialType = m_shdrsrc->getShaderInfo(
  1028. p.layer.shader_id).material;
  1029. p.layer.applyMaterialOptionsWithShaders(material);
  1030. if (p.layer.normal_texture)
  1031. material.setTexture(1, p.layer.normal_texture);
  1032. material.setTexture(2, p.layer.flags_texture);
  1033. } else {
  1034. p.layer.applyMaterialOptions(material);
  1035. }
  1036. scene::SMesh *mesh = (scene::SMesh *)m_mesh[layer];
  1037. // Create meshbuffer, add to mesh
  1038. if (m_use_tangent_vertices) {
  1039. scene::SMeshBufferTangents *buf =
  1040. new scene::SMeshBufferTangents();
  1041. buf->Material = material;
  1042. buf->Vertices.reallocate(p.vertices.size());
  1043. buf->Indices.reallocate(p.indices.size());
  1044. for (const video::S3DVertex &v: p.vertices)
  1045. buf->Vertices.push_back(video::S3DVertexTangents(v.Pos, v.Color, v.TCoords));
  1046. for (u16 i: p.indices)
  1047. buf->Indices.push_back(i);
  1048. buf->recalculateBoundingBox();
  1049. mesh->addMeshBuffer(buf);
  1050. buf->drop();
  1051. } else {
  1052. scene::SMeshBuffer *buf = new scene::SMeshBuffer();
  1053. buf->Material = material;
  1054. buf->append(&p.vertices[0], p.vertices.size(),
  1055. &p.indices[0], p.indices.size());
  1056. mesh->addMeshBuffer(buf);
  1057. buf->drop();
  1058. }
  1059. }
  1060. /*
  1061. Do some stuff to the mesh
  1062. */
  1063. m_camera_offset = camera_offset;
  1064. translateMesh(m_mesh[layer],
  1065. intToFloat(data->m_blockpos * MAP_BLOCKSIZE - camera_offset, BS));
  1066. if (m_use_tangent_vertices) {
  1067. scene::IMeshManipulator* meshmanip =
  1068. RenderingEngine::get_scene_manager()->getMeshManipulator();
  1069. meshmanip->recalculateTangents(m_mesh[layer], true, false, false);
  1070. }
  1071. if (m_mesh[layer]) {
  1072. #if 0
  1073. // Usually 1-700 faces and 1-7 materials
  1074. std::cout << "Updated MapBlock has " << fastfaces_new.size()
  1075. << " faces and uses " << m_mesh[layer]->getMeshBufferCount()
  1076. << " materials (meshbuffers)" << std::endl;
  1077. #endif
  1078. // Use VBO for mesh (this just would set this for ever buffer)
  1079. if (m_enable_vbo)
  1080. m_mesh[layer]->setHardwareMappingHint(scene::EHM_STATIC);
  1081. }
  1082. }
  1083. //std::cout<<"added "<<fastfaces.getSize()<<" faces."<<std::endl;
  1084. // Check if animation is required for this mesh
  1085. m_has_animation =
  1086. !m_crack_materials.empty() ||
  1087. !m_daynight_diffs.empty() ||
  1088. !m_animation_tiles.empty();
  1089. }
  1090. MapBlockMesh::~MapBlockMesh()
  1091. {
  1092. for (scene::IMesh *m : m_mesh) {
  1093. if (m_enable_vbo && m)
  1094. for (u32 i = 0; i < m->getMeshBufferCount(); i++) {
  1095. scene::IMeshBuffer *buf = m->getMeshBuffer(i);
  1096. RenderingEngine::get_video_driver()->removeHardwareBuffer(buf);
  1097. }
  1098. m->drop();
  1099. m = NULL;
  1100. }
  1101. delete m_minimap_mapblock;
  1102. }
  1103. bool MapBlockMesh::animate(bool faraway, float time, int crack,
  1104. u32 daynight_ratio)
  1105. {
  1106. if (!m_has_animation) {
  1107. m_animation_force_timer = 100000;
  1108. return false;
  1109. }
  1110. m_animation_force_timer = myrand_range(5, 100);
  1111. // Cracks
  1112. if (crack != m_last_crack) {
  1113. for (auto &crack_material : m_crack_materials) {
  1114. scene::IMeshBuffer *buf = m_mesh[crack_material.first.first]->
  1115. getMeshBuffer(crack_material.first.second);
  1116. std::string basename = crack_material.second;
  1117. // Create new texture name from original
  1118. std::ostringstream os;
  1119. os << basename << crack;
  1120. u32 new_texture_id = 0;
  1121. video::ITexture *new_texture =
  1122. m_tsrc->getTextureForMesh(os.str(), &new_texture_id);
  1123. buf->getMaterial().setTexture(0, new_texture);
  1124. // If the current material is also animated,
  1125. // update animation info
  1126. auto anim_iter = m_animation_tiles.find(crack_material.first);
  1127. if (anim_iter != m_animation_tiles.end()) {
  1128. TileLayer &tile = anim_iter->second;
  1129. tile.texture = new_texture;
  1130. tile.texture_id = new_texture_id;
  1131. // force animation update
  1132. m_animation_frames[crack_material.first] = -1;
  1133. }
  1134. }
  1135. m_last_crack = crack;
  1136. }
  1137. // Texture animation
  1138. for (auto &animation_tile : m_animation_tiles) {
  1139. const TileLayer &tile = animation_tile.second;
  1140. // Figure out current frame
  1141. int frameoffset = m_animation_frame_offsets[animation_tile.first];
  1142. int frame = (int)(time * 1000 / tile.animation_frame_length_ms
  1143. + frameoffset) % tile.animation_frame_count;
  1144. // If frame doesn't change, skip
  1145. if (frame == m_animation_frames[animation_tile.first])
  1146. continue;
  1147. m_animation_frames[animation_tile.first] = frame;
  1148. scene::IMeshBuffer *buf = m_mesh[animation_tile.first.first]->
  1149. getMeshBuffer(animation_tile.first.second);
  1150. const FrameSpec &animation_frame = (*tile.frames)[frame];
  1151. buf->getMaterial().setTexture(0, animation_frame.texture);
  1152. if (m_enable_shaders) {
  1153. if (animation_frame.normal_texture)
  1154. buf->getMaterial().setTexture(1,
  1155. animation_frame.normal_texture);
  1156. buf->getMaterial().setTexture(2, animation_frame.flags_texture);
  1157. }
  1158. }
  1159. // Day-night transition
  1160. if (!m_enable_shaders && (daynight_ratio != m_last_daynight_ratio)) {
  1161. // Force reload mesh to VBO
  1162. if (m_enable_vbo)
  1163. for (scene::IMesh *m : m_mesh)
  1164. m->setDirty();
  1165. video::SColorf day_color;
  1166. get_sunlight_color(&day_color, daynight_ratio);
  1167. for (auto &daynight_diff : m_daynight_diffs) {
  1168. scene::IMeshBuffer *buf = m_mesh[daynight_diff.first.first]->
  1169. getMeshBuffer(daynight_diff.first.second);
  1170. video::S3DVertex *vertices = (video::S3DVertex *)buf->getVertices();
  1171. for (const auto &j : daynight_diff.second)
  1172. final_color_blend(&(vertices[j.first].Color), j.second,
  1173. day_color);
  1174. }
  1175. m_last_daynight_ratio = daynight_ratio;
  1176. }
  1177. return true;
  1178. }
  1179. void MapBlockMesh::updateCameraOffset(v3s16 camera_offset)
  1180. {
  1181. if (camera_offset != m_camera_offset) {
  1182. for (scene::IMesh *layer : m_mesh) {
  1183. translateMesh(layer,
  1184. intToFloat(m_camera_offset - camera_offset, BS));
  1185. if (m_enable_vbo)
  1186. layer->setDirty();
  1187. }
  1188. m_camera_offset = camera_offset;
  1189. }
  1190. }
  1191. video::SColor encode_light(u16 light, u8 emissive_light)
  1192. {
  1193. // Get components
  1194. u32 day = (light & 0xff);
  1195. u32 night = (light >> 8);
  1196. // Add emissive light
  1197. night += emissive_light * 2.5f;
  1198. if (night > 255)
  1199. night = 255;
  1200. // Since we don't know if the day light is sunlight or
  1201. // artificial light, assume it is artificial when the night
  1202. // light bank is also lit.
  1203. if (day < night)
  1204. day = 0;
  1205. else
  1206. day = day - night;
  1207. u32 sum = day + night;
  1208. // Ratio of sunlight:
  1209. u32 r;
  1210. if (sum > 0)
  1211. r = day * 255 / sum;
  1212. else
  1213. r = 0;
  1214. // Average light:
  1215. float b = (day + night) / 2;
  1216. return video::SColor(r, b, b, b);
  1217. }