aboutsummaryrefslogtreecommitdiff
path: root/src/clouds.cpp
blob: 13051f32ce16d5c03344312e69ab05c4dbabbab5 (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "client/renderingengine.h"
#include "clouds.h"
#include "noise.h"
#include "constants.h"
#include "debug.h"
#include "profiler.h"
#include "settings.h"
#include <cmath>


// Menu clouds are created later
class Clouds;
Clouds *g_menuclouds = NULL;
irr::scene::ISceneManager *g_menucloudsmgr = NULL;

// Constant for now
static constexpr const float cloud_size = BS * 64.0f;

static void cloud_3d_setting_changed(const std::string &settingname, void *data)
{
	((Clouds *)data)->readSettings();
}

Clouds::Clouds(scene::ISceneManager* mgr,
		s32 id,
		u32 seed
):
	scene::ISceneNode(mgr->getRootSceneNode(), mgr, id),
	m_seed(seed)
{
	m_material.setFlag(video::EMF_LIGHTING, false);
	//m_material.setFlag(video::EMF_BACK_FACE_CULLING, false);
	m_material.setFlag(video::EMF_BACK_FACE_CULLING, true);
	m_material.setFlag(video::EMF_BILINEAR_FILTER, false);
	m_material.setFlag(video::EMF_FOG_ENABLE, true);
	m_material.setFlag(video::EMF_ANTI_ALIASING, true);
	//m_material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;
	m_material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;

	m_params.height        = 120;
	m_params.density       = 0.4f;
	m_params.thickness     = 16.0f;
	m_params.color_bright  = video::SColor(229, 240, 240, 255);
	m_params.color_ambient = video::SColor(255, 0, 0, 0);
	m_params.speed         = v2f(0.0f, -2.0f);

	readSettings();
	g_settings->registerChangedCallback("enable_3d_clouds",
		&cloud_3d_setting_changed, this);

	updateBox();
}

Clouds::~Clouds()
{
	g_settings->deregisterChangedCallback("enable_3d_clouds",
		&cloud_3d_setting_changed, this);
}

void Clouds::OnRegisterSceneNode()
{
	if(IsVisible)
	{
		SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
		//SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
	}

	ISceneNode::OnRegisterSceneNode();
}

void Clouds::render()
{

	if (m_params.density <= 0.0f)
		return; // no need to do anything

	video::IVideoDriver* driver = SceneManager->getVideoDriver();

	if(SceneManager->getSceneNodeRenderPass() != scene::ESNRP_TRANSPARENT)
	//if(SceneManager->getSceneNodeRenderPass() != scene::ESNRP_SOLID)
		return;

	ScopeProfiler sp(g_profiler, "Rendering of clouds, avg", SPT_AVG);

	int num_faces_to_draw = m_enable_3d ? 6 : 1;

	m_material.setFlag(video::EMF_BACK_FACE_CULLING, m_enable_3d);

	driver->setTransform(video::ETS_WORLD, AbsoluteTransformation);
	driver->setMaterial(m_material);

	/*
		Clouds move from Z+ towards Z-
	*/

	const float cloud_full_radius = cloud_size * m_cloud_radius_i;

	v2f camera_pos_2d(m_camera_pos.X, m_camera_pos.Z);
	// Position of cloud noise origin from the camera
	v2f cloud_origin_from_camera_f = m_origin - camera_pos_2d;
	// The center point of drawing in the noise
	v2f center_of_drawing_in_noise_f = -cloud_origin_from_camera_f;
	// The integer center point of drawing in the noise
	v2s16 center_of_drawing_in_noise_i(
		std::floor(center_of_drawing_in_noise_f.X / cloud_size),
		std::floor(center_of_drawing_in_noise_f.Y / cloud_size)
	);

	// The world position of the integer center point of drawing in the noise
	v2f world_center_of_drawing_in_noise_f = v2f(
		center_of_drawing_in_noise_i.X * cloud_size,
		center_of_drawing_in_noise_i.Y * cloud_size
	) + m_origin;

	/*video::SColor c_top(128,b*240,b*240,b*255);
	video::SColor c_side_1(128,b*230,b*230,b*255);
	video::SColor c_side_2(128,b*220,b*220,b*245);
	video::SColor c_bottom(128,b*205,b*205,b*230);*/
	video::SColorf c_top_f(m_color);
	video::SColorf c_side_1_f(m_color);
	video::SColorf c_side_2_f(m_color);
	video::SColorf c_bottom_f(m_color);
	c_side_1_f.r *= 0.95;
	c_side_1_f.g *= 0.95;
	c_side_1_f.b *= 0.95;
	c_side_2_f.r *= 0.90;
	c_side_2_f.g *= 0.90;
	c_side_2_f.b *= 0.90;
	c_bottom_f.r *= 0.80;
	c_bottom_f.g *= 0.80;
	c_bottom_f.b *= 0.80;
	video::SColor c_top = c_top_f.toSColor();
	video::SColor c_side_1 = c_side_1_f.toSColor();
	video::SColor c_side_2 = c_side_2_f.toSColor();
	video::SColor c_bottom = c_bottom_f.toSColor();

	// Get fog parameters for setting them back later
	video::SColor fog_color(0,0,0,0);
	video::E_FOG_TYPE fog_type = video::EFT_FOG_LINEAR;
	f32 fog_start = 0;
	f32 fog_end = 0;
	f32 fog_density = 0;
	bool fog_pixelfog = false;
	bool fog_rangefog = false;
	driver->getFog(fog_color, fog_type, fog_start, fog_end, fog_density,
			fog_pixelfog, fog_rangefog);

	// Set our own fog
	driver->setFog(fog_color, fog_type, cloud_full_radius * 0.5,
			cloud_full_radius*1.2, fog_density, fog_pixelfog, fog_rangefog);

	// Read noise

	bool *grid = new bool[m_cloud_radius_i * 2 * m_cloud_radius_i * 2];


	for(s16 zi = -m_cloud_radius_i; zi < m_cloud_radius_i; zi++) {
		u32 si = (zi + m_cloud_radius_i) * m_cloud_radius_i * 2 + m_cloud_radius_i;

		for (s16 xi = -m_cloud_radius_i; xi < m_cloud_radius_i; xi++) {
			u32 i = si + xi;

			grid[i] = gridFilled(
				xi + center_of_drawing_in_noise_i.X,
				zi + center_of_drawing_in_noise_i.Y
			);
		}
	}

#define GETINDEX(x, z, radius) (((z)+(radius))*(radius)*2 + (x)+(radius))
#define INAREA(x, z, radius) \
	((x) >= -(radius) && (x) < (radius) && (z) >= -(radius) && (z) < (radius))

	for (s16 zi0= -m_cloud_radius_i; zi0 < m_cloud_radius_i; zi0++)
	for (s16 xi0= -m_cloud_radius_i; xi0 < m_cloud_radius_i; xi0++)
	{
		s16 zi = zi0;
		s16 xi = xi0;
		// Draw from front to back (needed for transparency)
		/*if(zi <= 0)
			zi = -m_cloud_radius_i - zi;
		if(xi <= 0)
			xi = -m_cloud_radius_i - xi;*/
		// Draw from back to front
		if(zi >= 0)
			zi = m_cloud_radius_i - zi - 1;
		if(xi >= 0)
			xi = m_cloud_radius_i - xi - 1;

		u32 i = GETINDEX(xi, zi, m_cloud_radius_i);

		if (!grid[i])
			continue;

		v2f p0 = v2f(xi,zi)*cloud_size + world_center_of_drawing_in_noise_f;

		video::S3DVertex v[4] = {
			video::S3DVertex(0,0,0, 0,0,0, c_top, 0, 1),
			video::S3DVertex(0,0,0, 0,0,0, c_top, 1, 1),
			video::S3DVertex(0,0,0, 0,0,0, c_top, 1, 0),
			video::S3DVertex(0,0,0, 0,0,0, c_top, 0, 0)
		};

		/*if(zi <= 0 && xi <= 0){
			v[0].Color.setBlue(255);
			v[1].Color.setBlue(255);
			v[2].Color.setBlue(255);
			v[3].Color.setBlue(255);
		}*/

		f32 rx = cloud_size / 2.0f;
		// if clouds are flat, the top layer should be at the given height
		f32 ry = m_enable_3d ? m_params.thickness * BS : 0.0f;
		f32 rz = cloud_size / 2;

		for(int i=0; i<num_faces_to_draw; i++)
		{
			switch(i)
			{
			case 0:	// top
				for (video::S3DVertex &vertex : v) {
					vertex.Normal.set(0,1,0);
				}
				v[0].Pos.set(-rx, ry,-rz);
				v[1].Pos.set(-rx, ry, rz);
				v[2].Pos.set( rx, ry, rz);
				v[3].Pos.set( rx, ry,-rz);
				break;
			case 1: // back
				if (INAREA(xi, zi - 1, m_cloud_radius_i)) {
					u32 j = GETINDEX(xi, zi - 1, m_cloud_radius_i);
					if(grid[j])
						continue;
				}
				for (video::S3DVertex &vertex : v) {
					vertex.Color = c_side_1;
					vertex.Normal.set(0,0,-1);
				}
				v[0].Pos.set(-rx, ry,-rz);
				v[1].Pos.set( rx, ry,-rz);
				v[2].Pos.set( rx,  0,-rz);
				v[3].Pos.set(-rx,  0,-rz);
				break;
			case 2: //right
				if (INAREA(xi + 1, zi, m_cloud_radius_i)) {
					u32 j = GETINDEX(xi+1, zi, m_cloud_radius_i);
					if(grid[j])
						continue;
				}
				for (video::S3DVertex &vertex : v) {
					vertex.Color = c_side_2;
					vertex.Normal.set(1,0,0);
				}
				v[0].Pos.set( rx, ry,-rz);
				v[1].Pos.set( rx, ry, rz);
				v[2].Pos.set( rx,  0, rz);
				v[3].Pos.set( rx,  0,-rz);
				break;
			case 3: // front
				if (INAREA(xi, zi + 1, m_cloud_radius_i)) {
					u32 j = GETINDEX(xi, zi + 1, m_cloud_radius_i);
					if(grid[j])
						continue;
				}
				for (video::S3DVertex &vertex : v) {
					vertex.Color = c_side_1;
					vertex.Normal.set(0,0,-1);
				}
				v[0].Pos.set( rx, ry, rz);
				v[1].Pos.set(-rx, ry, rz);
				v[2].Pos.set(-rx,  0, rz);
				v[3].Pos.set( rx,  0, rz);
				break;
			case 4: // left
				if (INAREA(xi-1, zi, m_cloud_radius_i)) {
					u32 j = GETINDEX(xi-1, zi, m_cloud_radius_i);
					if(grid[j])
						continue;
				}
				for (video::S3DVertex &vertex : v) {
					vertex.Color = c_side_2;
					vertex.Normal.set(-1,0,0);
				}
				v[0].Pos.set(-rx, ry, rz);
				v[1].Pos.set(-rx, ry,-rz);
				v[2].Pos.set(-rx,  0,-rz);
				v[3].Pos.set(-rx,  0, rz);
				break;
			case 5: // bottom
				for (video::S3DVertex &vertex : v) {
					vertex.Color = c_bottom;
					vertex.Normal.set(0,-1,0);
				}
				v[0].Pos.set( rx,  0, rz);
				v[1].Pos.set(-rx,  0, rz);
				v[2].Pos.set(-rx,  0,-rz);
				v[3].Pos.set( rx,  0,-rz);
				break;
			}

			v3f pos(p0.X, m_params.height * BS, p0.Y);
			pos -= intToFloat(m_camera_offset, BS);

			for (video::S3DVertex &vertex : v)
				vertex.Pos += pos;
			u16 indices[] = {0,1,2,2,3,0};
			driver->drawVertexPrimitiveList(v, 4, indices, 2,
					video::EVT_STANDARD, scene::EPT_TRIANGLES, video::EIT_16BIT);
		}
	}

	delete[] grid;

	// Restore fog settings
	driver->setFog(fog_color, fog_type, fog_start, fog_end, fog_density,
			fog_pixelfog, fog_rangefog);
}

void Clouds::step(float dtime)
{
	m_origin = m_origin + dtime * BS * m_params.speed;
}

void Clouds::update(const v3f &camera_p, const video::SColorf &color_diffuse)
{
	m_camera_pos = camera_p;
	m_color.r = MYMIN(MYMAX(color_diffuse.r * m_params.color_bright.getRed(),
			m_params.color_ambient.getRed()), 255) / 255.0f;
	m_color.g = MYMIN(MYMAX(color_diffuse.g * m_params.color_bright.getGreen(),
			m_params.color_ambient.getGreen()), 255) / 255.0f;
	m_color.b = MYMIN(MYMAX(color_diffuse.b * m_params.color_bright.getBlue(),
			m_params.color_ambient.getBlue()), 255) / 255.0f;
	m_color.a = m_params.color_bright.getAlpha() / 255.0f;

	// is the camera inside the cloud mesh?
	m_camera_inside_cloud = false; // default
	if (m_enable_3d) {
		float camera_height = camera_p.Y;
		if (camera_height >= m_box.MinEdge.Y &&
				camera_height <= m_box.MaxEdge.Y) {
			v2f camera_in_noise;
			camera_in_noise.X = floor((camera_p.X - m_origin.X) / cloud_size + 0.5);
			camera_in_noise.Y = floor((camera_p.Z - m_origin.Y) / cloud_size + 0.5);
			bool filled = gridFilled(camera_in_noise.X, camera_in_noise.Y);
			m_camera_inside_cloud = filled;
		}
	}
}

void Clouds::readSettings()
{
	m_cloud_radius_i = g_settings->getU16("cloud_radius");
	m_enable_3d = g_settings->getBool("enable_3d_clouds");
}

bool Clouds::gridFilled(int x, int y) const
{
	float cloud_size_noise = cloud_size / (BS * 200.f);
	float noise = noise2d_perlin(
			(float)x * cloud_size_noise,
			(float)y * cloud_size_noise,
			m_seed, 3, 0.5);
	// normalize to 0..1 (given 3 octaves)
	static constexpr const float noise_bound = 1.0f + 0.5f + 0.25f;
	float density = noise / noise_bound * 0.5f + 0.5f;
	return (density < m_params.density);
}
l num">0) m_crack_pos_relative = crack_pos - m_blockpos*MAP_BLOCKSIZE; } void MeshMakeData::setSmoothLighting(bool smooth_lighting) { m_smooth_lighting = smooth_lighting; } /* Light and vertex color functions */ /* Calculate non-smooth lighting at interior of node. Single light bank. */ static u8 getInteriorLight(enum LightBank bank, MapNode n, s32 increment, INodeDefManager *ndef) { u8 light = n.getLight(bank, ndef); while(increment > 0) { light = undiminish_light(light); --increment; } while(increment < 0) { light = diminish_light(light); ++increment; } return decode_light(light); } /* Calculate non-smooth lighting at interior of node. Both light banks. */ u16 getInteriorLight(MapNode n, s32 increment, INodeDefManager *ndef) { u16 day = getInteriorLight(LIGHTBANK_DAY, n, increment, ndef); u16 night = getInteriorLight(LIGHTBANK_NIGHT, n, increment, ndef); return day | (night << 8); } /* Calculate non-smooth lighting at face of node. Single light bank. */ static u8 getFaceLight(enum LightBank bank, MapNode n, MapNode n2, v3s16 face_dir, INodeDefManager *ndef) { u8 light; u8 l1 = n.getLight(bank, ndef); u8 l2 = n2.getLight(bank, ndef); if(l1 > l2) light = l1; else light = l2; // Boost light level for light sources u8 light_source = MYMAX(ndef->get(n).light_source, ndef->get(n2).light_source); if(light_source > light) light = light_source; return decode_light(light); } /* Calculate non-smooth lighting at face of node. Both light banks. */ u16 getFaceLight(MapNode n, MapNode n2, v3s16 face_dir, INodeDefManager *ndef) { u16 day = getFaceLight(LIGHTBANK_DAY, n, n2, face_dir, ndef); u16 night = getFaceLight(LIGHTBANK_NIGHT, n, n2, face_dir, ndef); return day | (night << 8); } /* Calculate smooth lighting at the XYZ- corner of p. Both light banks */ static u16 getSmoothLightCombined(v3s16 p, MeshMakeData *data) { static const v3s16 dirs8[8] = { v3s16(0,0,0), v3s16(0,0,1), v3s16(0,1,0), v3s16(0,1,1), v3s16(1,0,0), v3s16(1,1,0), v3s16(1,0,1), v3s16(1,1,1), }; INodeDefManager *ndef = data->m_gamedef->ndef(); u16 ambient_occlusion = 0; u16 light_count = 0; u8 light_source_max = 0; u16 light_day = 0; u16 light_night = 0; for (u32 i = 0; i < 8; i++) { const MapNode &n = data->m_vmanip.getNodeRefUnsafeCheckFlags(p - dirs8[i]); // if it's CONTENT_IGNORE we can't do any light calculations if (n.getContent() == CONTENT_IGNORE) { continue; } const ContentFeatures &f = ndef->get(n); if (f.light_source > light_source_max) light_source_max = f.light_source; // Check f.solidness because fast-style leaves look better this way if (f.param_type == CPT_LIGHT && f.solidness != 2) { light_day += decode_light(n.getLightNoChecks(LIGHTBANK_DAY, &f)); light_night += decode_light(n.getLightNoChecks(LIGHTBANK_NIGHT, &f)); light_count++; } else { ambient_occlusion++; } } if(light_count == 0) return 0xffff; light_day /= light_count; light_night /= light_count; // Boost brightness around light sources bool skip_ambient_occlusion_day = false; if(decode_light(light_source_max) >= light_day) { light_day = decode_light(light_source_max); skip_ambient_occlusion_day = true; } bool skip_ambient_occlusion_night = false; if(decode_light(light_source_max) >= light_night) { light_night = decode_light(light_source_max); skip_ambient_occlusion_night = true; } if (ambient_occlusion > 4) { static const float ao_gamma = rangelim( g_settings->getFloat("ambient_occlusion_gamma"), 0.25, 4.0); // Table of gamma space multiply factors. static const float light_amount[3] = { powf(0.75, 1.0 / ao_gamma), powf(0.5, 1.0 / ao_gamma), powf(0.25, 1.0 / ao_gamma) }; //calculate table index for gamma space multiplier ambient_occlusion -= 5; if (!skip_ambient_occlusion_day) light_day = rangelim(core::round32(light_day*light_amount[ambient_occlusion]), 0, 255); if (!skip_ambient_occlusion_night) light_night = rangelim(core::round32(light_night*light_amount[ambient_occlusion]), 0, 255); } return light_day | (light_night << 8); } /* Calculate smooth lighting at the given corner of p. Both light banks. */ u16 getSmoothLight(v3s16 p, v3s16 corner, MeshMakeData *data) { if(corner.X == 1) p.X += 1; // else corner.X == -1 if(corner.Y == 1) p.Y += 1; // else corner.Y == -1 if(corner.Z == 1) p.Z += 1; // else corner.Z == -1 return getSmoothLightCombined(p, data); } /* Converts from day + night color values (0..255) and a given daynight_ratio to the final SColor shown on screen. */ void finalColorBlend(video::SColor& result, u8 day, u8 night, u32 daynight_ratio) { s32 rg = (day * daynight_ratio + night * (1000-daynight_ratio)) / 1000; s32 b = rg; // Moonlight is blue b += (day - night) / 13; rg -= (day - night) / 23; // Emphase blue a bit in darker places // Each entry of this array represents a range of 8 blue levels static const u8 emphase_blue_when_dark[32] = { 1, 4, 6, 6, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; b += emphase_blue_when_dark[irr::core::clamp(b, 0, 255) / 8]; b = irr::core::clamp(b, 0, 255); // Artificial light is yellow-ish static const u8 emphase_yellow_when_artificial[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 15, 15, 15 }; rg += emphase_yellow_when_artificial[night/16]; rg = irr::core::clamp(rg, 0, 255); result.setRed(rg); result.setGreen(rg); result.setBlue(b); } /* Mesh generation helpers */ /* vertex_dirs: v3s16[4] */ static void getNodeVertexDirs(v3s16 dir, v3s16 *vertex_dirs) { /* If looked from outside the node towards the face, the corners are: 0: bottom-right 1: bottom-left 2: top-left 3: top-right */ if(dir == v3s16(0,0,1)) { // If looking towards z+, this is the face that is behind // the center point, facing towards z+. vertex_dirs[0] = v3s16(-1,-1, 1); vertex_dirs[1] = v3s16( 1,-1, 1); vertex_dirs[2] = v3s16( 1, 1, 1); vertex_dirs[3] = v3s16(-1, 1, 1); } else if(dir == v3s16(0,0,-1)) { // faces towards Z- vertex_dirs[0] = v3s16( 1,-1,-1); vertex_dirs[1] = v3s16(-1,-1,-1); vertex_dirs[2] = v3s16(-1, 1,-1); vertex_dirs[3] = v3s16( 1, 1,-1); } else if(dir == v3s16(1,0,0)) { // faces towards X+ vertex_dirs[0] = v3s16( 1,-1, 1); vertex_dirs[1] = v3s16( 1,-1,-1); vertex_dirs[2] = v3s16( 1, 1,-1); vertex_dirs[3] = v3s16( 1, 1, 1); } else if(dir == v3s16(-1,0,0)) { // faces towards X- vertex_dirs[0] = v3s16(-1,-1,-1); vertex_dirs[1] = v3s16(-1,-1, 1); vertex_dirs[2] = v3s16(-1, 1, 1); vertex_dirs[3] = v3s16(-1, 1,-1); } else if(dir == v3s16(0,1,0)) { // faces towards Y+ (assume Z- as "down" in texture) vertex_dirs[0] = v3s16( 1, 1,-1); vertex_dirs[1] = v3s16(-1, 1,-1); vertex_dirs[2] = v3s16(-1, 1, 1); vertex_dirs[3] = v3s16( 1, 1, 1); } else if(dir == v3s16(0,-1,0)) { // faces towards Y- (assume Z+ as "down" in texture) vertex_dirs[0] = v3s16( 1,-1, 1); vertex_dirs[1] = v3s16(-1,-1, 1); vertex_dirs[2] = v3s16(-1,-1,-1); vertex_dirs[3] = v3s16( 1,-1,-1); } } struct FastFace { TileSpec tile; video::S3DVertex vertices[4]; // Precalculated vertices }; static void makeFastFace(TileSpec tile, u16 li0, u16 li1, u16 li2, u16 li3, v3f p, v3s16 dir, v3f scale, u8 light_source, std::vector<FastFace> &dest) { // Position is at the center of the cube. v3f pos = p * BS; float x0 = 0.0; float y0 = 0.0; float w = 1.0; float h = 1.0; v3f vertex_pos[4]; v3s16 vertex_dirs[4]; getNodeVertexDirs(dir, vertex_dirs); v3s16 t; u16 t1; switch (tile.rotation) { case 0: break; case 1: //R90 t = vertex_dirs[0]; vertex_dirs[0] = vertex_dirs[3]; vertex_dirs[3] = vertex_dirs[2]; vertex_dirs[2] = vertex_dirs[1]; vertex_dirs[1] = t; t1=li0; li0=li3; li3=li2; li2=li1; li1=t1; break; case 2: //R180 t = vertex_dirs[0]; vertex_dirs[0] = vertex_dirs[2]; vertex_dirs[2] = t; t = vertex_dirs[1]; vertex_dirs[1] = vertex_dirs[3]; vertex_dirs[3] = t; t1 = li0; li0 = li2; li2 = t1; t1 = li1; li1 = li3; li3 = t1; break; case 3: //R270 t = vertex_dirs[0]; vertex_dirs[0] = vertex_dirs[1]; vertex_dirs[1] = vertex_dirs[2]; vertex_dirs[2] = vertex_dirs[3]; vertex_dirs[3] = t; t1 = li0; li0 = li1; li1 = li2; li2 = li3; li3 = t1; break; case 4: //FXR90 t = vertex_dirs[0]; vertex_dirs[0] = vertex_dirs[3]; vertex_dirs[3] = vertex_dirs[2]; vertex_dirs[2] = vertex_dirs[1]; vertex_dirs[1] = t; t1 = li0; li0 = li3; li3 = li2; li2 = li1; li1 = t1; y0 += h; h *= -1; break; case 5: //FXR270 t = vertex_dirs[0]; vertex_dirs[0] = vertex_dirs[1]; vertex_dirs[1] = vertex_dirs[2]; vertex_dirs[2] = vertex_dirs[3]; vertex_dirs[3] = t; t1 = li0; li0 = li1; li1 = li2; li2 = li3; li3 = t1; y0 += h; h *= -1; break; case 6: //FYR90 t = vertex_dirs[0]; vertex_dirs[0] = vertex_dirs[3]; vertex_dirs[3] = vertex_dirs[2]; vertex_dirs[2] = vertex_dirs[1]; vertex_dirs[1] = t; t1 = li0; li0 = li3; li3 = li2; li2 = li1; li1 = t1; x0 += w; w *= -1; break; case 7: //FYR270 t = vertex_dirs[0]; vertex_dirs[0] = vertex_dirs[1]; vertex_dirs[1] = vertex_dirs[2]; vertex_dirs[2] = vertex_dirs[3]; vertex_dirs[3] = t; t1 = li0; li0 = li1; li1 = li2; li2 = li3; li3 = t1; x0 += w; w *= -1; break; case 8: //FX y0 += h; h *= -1; break; case 9: //FY x0 += w; w *= -1; break; default: break; } for(u16 i=0; i<4; i++) { vertex_pos[i] = v3f( BS/2*vertex_dirs[i].X, BS/2*vertex_dirs[i].Y, BS/2*vertex_dirs[i].Z ); } for(u16 i=0; i<4; i++) { vertex_pos[i].X *= scale.X; vertex_pos[i].Y *= scale.Y; vertex_pos[i].Z *= scale.Z; vertex_pos[i] += pos; } f32 abs_scale = 1.0; if (scale.X < 0.999 || scale.X > 1.001) abs_scale = scale.X; else if(scale.Y < 0.999 || scale.Y > 1.001) abs_scale = scale.Y; else if(scale.Z < 0.999 || scale.Z > 1.001) abs_scale = scale.Z; v3f normal(dir.X, dir.Y, dir.Z); u8 alpha = tile.alpha; dest.push_back(FastFace()); FastFace& face = *dest.rbegin(); face.vertices[0] = video::S3DVertex(vertex_pos[0], normal, MapBlock_LightColor(alpha, li0, light_source), core::vector2d<f32>(x0+w*abs_scale, y0+h)); face.vertices[1] = video::S3DVertex(vertex_pos[1], normal, MapBlock_LightColor(alpha, li1, light_source), core::vector2d<f32>(x0, y0+h)); face.vertices[2] = video::S3DVertex(vertex_pos[2], normal, MapBlock_LightColor(alpha, li2, light_source), core::vector2d<f32>(x0, y0)); face.vertices[3] = video::S3DVertex(vertex_pos[3], normal, MapBlock_LightColor(alpha, li3, light_source), core::vector2d<f32>(x0+w*abs_scale, y0)); face.tile = tile; } /* Nodes make a face if contents differ and solidness differs. Return value: 0: No face 1: Face uses m1's content 2: Face uses m2's content equivalent: Whether the blocks share the same face (eg. water and glass) TODO: Add 3: Both faces drawn with backface culling, remove equivalent */ static u8 face_contents(content_t m1, content_t m2, bool *equivalent, INodeDefManager *ndef) { *equivalent = false; if(m1 == CONTENT_IGNORE || m2 == CONTENT_IGNORE) return 0; bool contents_differ = (m1 != m2); const ContentFeatures &f1 = ndef->get(m1); const ContentFeatures &f2 = ndef->get(m2); // Contents don't differ for different forms of same liquid if(f1.sameLiquid(f2)) contents_differ = false; u8 c1 = f1.solidness; u8 c2 = f2.solidness; bool solidness_differs = (c1 != c2); bool makes_face = contents_differ && solidness_differs; if(makes_face == false) return 0; if(c1 == 0) c1 = f1.visual_solidness; if(c2 == 0) c2 = f2.visual_solidness; if(c1 == c2){ *equivalent = true; // If same solidness, liquid takes precense if(f1.isLiquid()) return 1; if(f2.isLiquid()) return 2; } if(c1 > c2) return 1; else return 2; } /* Gets nth node tile (0 <= n <= 5). */ TileSpec getNodeTileN(MapNode mn, v3s16 p, u8 tileindex, MeshMakeData *data) { INodeDefManager *ndef = data->m_gamedef->ndef(); TileSpec spec = ndef->get(mn).tiles[tileindex]; // Apply temporary crack if (p == data->m_crack_pos_relative) spec.material_flags |= MATERIAL_FLAG_CRACK; return spec; } /* Gets node tile given a face direction. */ TileSpec getNodeTile(MapNode mn, v3s16 p, v3s16 dir, MeshMakeData *data) { INodeDefManager *ndef = data->m_gamedef->ndef(); // Direction must be (1,0,0), (-1,0,0), (0,1,0), (0,-1,0), // (0,0,1), (0,0,-1) or (0,0,0) assert(dir.X * dir.X + dir.Y * dir.Y + dir.Z * dir.Z <= 1); // Convert direction to single integer for table lookup // 0 = (0,0,0) // 1 = (1,0,0) // 2 = (0,1,0) // 3 = (0,0,1) // 4 = invalid, treat as (0,0,0) // 5 = (0,0,-1) // 6 = (0,-1,0) // 7 = (-1,0,0) u8 dir_i = ((dir.X + 2 * dir.Y + 3 * dir.Z) & 7)*2; // Get rotation for things like chests u8 facedir = mn.getFaceDir(ndef); static const u16 dir_to_tile[24 * 16] = { // 0 +X +Y +Z -Z -Y -X -> value=tile,rotation 0,0, 2,0 , 0,0 , 4,0 , 0,0, 5,0 , 1,0 , 3,0 , // rotate around y+ 0 - 3 0,0, 4,0 , 0,3 , 3,0 , 0,0, 2,0 , 1,1 , 5,0 , 0,0, 3,0 , 0,2 , 5,0 , 0,0, 4,0 , 1,2 , 2,0 , 0,0, 5,0 , 0,1 , 2,0 , 0,0, 3,0 , 1,3 , 4,0 , 0,0, 2,3 , 5,0 , 0,2 , 0,0, 1,0 , 4,2 , 3,1 , // rotate around z+ 4 - 7 0,0, 4,3 , 2,0 , 0,1 , 0,0, 1,1 , 3,2 , 5,1 , 0,0, 3,3 , 4,0 , 0,0 , 0,0, 1,2 , 5,2 , 2,1 , 0,0, 5,3 , 3,0 , 0,3 , 0,0, 1,3 , 2,2 , 4,1 , 0,0, 2,1 , 4,2 , 1,2 , 0,0, 0,0 , 5,0 , 3,3 , // rotate around z- 8 - 11 0,0, 4,1 , 3,2 , 1,3 , 0,0, 0,3 , 2,0 , 5,3 , 0,0, 3,1 , 5,2 , 1,0 , 0,0, 0,2 , 4,0 , 2,3 , 0,0, 5,1 , 2,2 , 1,1 , 0,0, 0,1 , 3,0 , 4,3 , 0,0, 0,3 , 3,3 , 4,1 , 0,0, 5,3 , 2,3 , 1,3 , // rotate around x+ 12 - 15 0,0, 0,2 , 5,3 , 3,1 , 0,0, 2,3 , 4,3 , 1,0 , 0,0, 0,1 , 2,3 , 5,1 , 0,0, 4,3 , 3,3 , 1,1 , 0,0, 0,0 , 4,3 , 2,1 , 0,0, 3,3 , 5,3 , 1,2 , 0,0, 1,1 , 2,1 , 4,3 , 0,0, 5,1 , 3,1 , 0,1 , // rotate around x- 16 - 19 0,0, 1,2 , 4,1 , 3,3 , 0,0, 2,1 , 5,1 , 0,0 , 0,0, 1,3 , 3,1 , 5,3 , 0,0, 4,1 , 2,1 , 0,3 , 0,0, 1,0 , 5,1 , 2,3 , 0,0, 3,1 , 4,1 , 0,2 , 0,0, 3,2 , 1,2 , 4,2 , 0,0, 5,2 , 0,2 , 2,2 , // rotate around y- 20 - 23 0,0, 5,2 , 1,3 , 3,2 , 0,0, 2,2 , 0,1 , 4,2 , 0,0, 2,2 , 1,0 , 5,2 , 0,0, 4,2 , 0,0 , 3,2 , 0,0, 4,2 , 1,1 , 2,2 , 0,0, 3,2 , 0,3 , 5,2 }; u16 tile_index=facedir*16 + dir_i; TileSpec spec = getNodeTileN(mn, p, dir_to_tile[tile_index], data); spec.rotation=dir_to_tile[tile_index + 1]; spec.texture = data->m_gamedef->tsrc()->getTexture(spec.texture_id); return spec; } static void getTileInfo( // Input: MeshMakeData *data, const v3s16 &p, const v3s16 &face_dir, // Output: bool &makes_face, v3s16 &p_corrected, v3s16 &face_dir_corrected, u16 *lights, TileSpec &tile, u8 &light_source ) { VoxelManipulator &vmanip = data->m_vmanip; INodeDefManager *ndef = data->m_gamedef->ndef(); v3s16 blockpos_nodes = data->m_blockpos * MAP_BLOCKSIZE; MapNode &n0 = vmanip.getNodeRefUnsafe(blockpos_nodes + p); // Don't even try to get n1 if n0 is already CONTENT_IGNORE if (n0.getContent() == CONTENT_IGNORE) { makes_face = false; return; } const MapNode &n1 = vmanip.getNodeRefUnsafeCheckFlags(blockpos_nodes + p + face_dir); if (n1.getContent() == CONTENT_IGNORE) { makes_face = false; return; } // This is hackish bool equivalent = false; u8 mf = face_contents(n0.getContent(), n1.getContent(), &equivalent, ndef); if(mf == 0) { makes_face = false; return; } makes_face = true; if(mf == 1) { tile = getNodeTile(n0, p, face_dir, data); p_corrected = p; face_dir_corrected = face_dir; light_source = ndef->get(n0).light_source; } else { tile = getNodeTile(n1, p + face_dir, -face_dir, data); p_corrected = p + face_dir; face_dir_corrected = -face_dir; light_source = ndef->get(n1).light_source; } // eg. water and glass if(equivalent) tile.material_flags |= MATERIAL_FLAG_BACKFACE_CULLING; if(data->m_smooth_lighting == false) { lights[0] = lights[1] = lights[2] = lights[3] = getFaceLight(n0, n1, face_dir, ndef); } else { v3s16 vertex_dirs[4]; getNodeVertexDirs(face_dir_corrected, vertex_dirs); for(u16 i=0; i<4; i++) { lights[i] = getSmoothLight( blockpos_nodes + p_corrected, vertex_dirs[i], data); } } return; } /* startpos: translate_dir: unit vector with only one of x, y or z face_dir: unit vector with only one of x, y or z */ static void updateFastFaceRow( MeshMakeData *data, v3s16 startpos, v3s16 translate_dir, v3f translate_dir_f, v3s16 face_dir, v3f face_dir_f, std::vector<FastFace> &dest) { v3s16 p = startpos; u16 continuous_tiles_count = 0; bool makes_face = false; v3s16 p_corrected; v3s16 face_dir_corrected; u16 lights[4] = {0,0,0,0}; TileSpec tile; u8 light_source = 0; getTileInfo(data, p, face_dir, makes_face, p_corrected, face_dir_corrected, lights, tile, light_source); for(u16 j=0; j<MAP_BLOCKSIZE; j++) { // If tiling can be done, this is set to false in the next step bool next_is_different = true; v3s16 p_next; bool next_makes_face = false; v3s16 next_p_corrected; v3s16 next_face_dir_corrected; u16 next_lights[4] = {0,0,0,0}; TileSpec next_tile; u8 next_light_source = 0; // If at last position, there is nothing to compare to and // the face must be drawn anyway if(j != MAP_BLOCKSIZE - 1) { p_next = p + translate_dir; getTileInfo(data, p_next, face_dir, next_makes_face, next_p_corrected, next_face_dir_corrected, next_lights, next_tile, next_light_source); if(next_makes_face == makes_face && next_p_corrected == p_corrected + translate_dir && next_face_dir_corrected == face_dir_corrected && next_lights[0] == lights[0] && next_lights[1] == lights[1] && next_lights[2] == lights[2] && next_lights[3] == lights[3] && next_tile == tile && tile.rotation == 0 && next_light_source == light_source && (tile.material_flags & MATERIAL_FLAG_TILEABLE_HORIZONTAL) && (tile.material_flags & MATERIAL_FLAG_TILEABLE_VERTICAL)) { next_is_different = false; } else{ /*if(makes_face){ g_profiler->add("Meshgen: diff: next_makes_face != makes_face", next_makes_face != makes_face ? 1 : 0); g_profiler->add("Meshgen: diff: n_p_corr != p_corr + t_dir", (next_p_corrected != p_corrected + translate_dir) ? 1 : 0); g_profiler->add("Meshgen: diff: next_f_dir_corr != f_dir_corr", next_face_dir_corrected != face_dir_corrected ? 1 : 0); g_profiler->add("Meshgen: diff: next_lights[] != lights[]", (next_lights[0] != lights[0] || next_lights[0] != lights[0] || next_lights[0] != lights[0] || next_lights[0] != lights[0]) ? 1 : 0); g_profiler->add("Meshgen: diff: !(next_tile == tile)", !(next_tile == tile) ? 1 : 0); }*/ } /*g_profiler->add("Meshgen: Total faces checked", 1); if(makes_face) g_profiler->add("Meshgen: Total makes_face checked", 1);*/ } else { /*if(makes_face) g_profiler->add("Meshgen: diff: last position", 1);*/ } continuous_tiles_count++; if(next_is_different) { /* Create a face if there should be one */ if(makes_face) { // Floating point conversion of the position vector v3f pf(p_corrected.X, p_corrected.Y, p_corrected.Z); // Center point of face (kind of) v3f sp = pf - ((f32)continuous_tiles_count / 2.0 - 0.5) * translate_dir_f; if(continuous_tiles_count != 1) sp += translate_dir_f; v3f scale(1,1,1); if(translate_dir.X != 0) { scale.X = continuous_tiles_count; } if(translate_dir.Y != 0) { scale.Y = continuous_tiles_count; } if(translate_dir.Z != 0) { scale.Z = continuous_tiles_count; } makeFastFace(tile, lights[0], lights[1], lights[2], lights[3], sp, face_dir_corrected, scale, light_source, dest); g_profiler->avg("Meshgen: faces drawn by tiling", 0); for(int i = 1; i < continuous_tiles_count; i++){ g_profiler->avg("Meshgen: faces drawn by tiling", 1); } } continuous_tiles_count = 0; makes_face = next_makes_face; p_corrected = next_p_corrected; face_dir_corrected = next_face_dir_corrected; lights[0] = next_lights[0]; lights[1] = next_lights[1]; lights[2] = next_lights[2]; lights[3] = next_lights[3]; tile = next_tile; light_source = next_light_source; } p = p_next; } } static void updateAllFastFaceRows(MeshMakeData *data, std::vector<FastFace> &dest) { /* Go through every y,z and get top(y+) faces in rows of x+ */ for(s16 y = 0; y < MAP_BLOCKSIZE; y++) { for(s16 z = 0; z < MAP_BLOCKSIZE; z++) { updateFastFaceRow(data, v3s16(0,y,z), v3s16(1,0,0), //dir v3f (1,0,0), v3s16(0,1,0), //face dir v3f (0,1,0), dest); } } /* Go through every x,y and get right(x+) faces in rows of z+ */ for(s16 x = 0; x < MAP_BLOCKSIZE; x++) { for(s16 y = 0; y < MAP_BLOCKSIZE; y++) { updateFastFaceRow(data, v3s16(x,y,0), v3s16(0,0,1), //dir v3f (0,0,1), v3s16(1,0,0), //face dir v3f (1,0,0), dest); } } /* Go through every y,z and get back(z+) faces in rows of x+ */ for(s16 z = 0; z < MAP_BLOCKSIZE; z++) { for(s16 y = 0; y < MAP_BLOCKSIZE; y++) { updateFastFaceRow(data, v3s16(0,y,z), v3s16(1,0,0), //dir v3f (1,0,0), v3s16(0,0,1), //face dir v3f (0,0,1), dest); } } } /* MapBlockMesh */ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): m_mesh(new scene::SMesh()), m_minimap_mapblock(NULL), m_gamedef(data->m_gamedef), m_driver(m_gamedef->tsrc()->getDevice()->getVideoDriver()), m_tsrc(m_gamedef->getTextureSource()), m_shdrsrc(m_gamedef->getShaderSource()), m_animation_force_timer(0), // force initial animation m_last_crack(-1), m_crack_materials(), m_last_daynight_ratio((u32) -1), m_daynight_diffs() { m_enable_shaders = data->m_use_shaders; m_use_tangent_vertices = data->m_use_tangent_vertices; m_enable_vbo = g_settings->getBool("enable_vbo"); if (g_settings->getBool("enable_minimap")) { m_minimap_mapblock = new MinimapMapblock; m_minimap_mapblock->getMinimapNodes( &data->m_vmanip, data->m_blockpos * MAP_BLOCKSIZE); } // 4-21ms for MAP_BLOCKSIZE=16 (NOTE: probably outdated) // 24-155ms for MAP_BLOCKSIZE=32 (NOTE: probably outdated) //TimeTaker timer1("MapBlockMesh()"); std::vector<FastFace> fastfaces_new; fastfaces_new.reserve(512); /* We are including the faces of the trailing edges of the block. This means that when something changes, the caller must