Debian Codegraph @

Shaders/ws30-ALS-landclass-search-functions.frag

raw
1 // WS30 FRAGMENT SHADER
2 // -*-C++-*-
3 #version 130
4 // WS30 terrain - Landclass search functions used by fragment shaders
5 // Split off from from ws30-ALS-ultra.frag
6
7
8 //////////////////////////////////////////////////////////////////
9 // TEST PHASE TOGGLES AND CONTROLS FOR PROFILING ON DIFFERENT GPUS
10 //
11
12 // Instructions for power users:
13 // Change the numbers for values and controls, save the file, and
14 // reload shaders to compare the difference.
15 // In-sim menu > debug > configure development extensions > reload shaders.
16 // It's safe to tinker with things in this section.
17 // At worst the terrain will look odd. If there's an error or a stray
18 // character, the shader will just not compile - the terrain changes
19 // appearance to black.
20 // Simply try again and hit reload shaders button. You can also save a backup
21 // of this file.
22 // "//" means everything on that line is a comment.
23 // Lines assigning numbers to variables end in a ";"
24
25 // Testing performance:
26 // Use the UFO or video assistant. Turn all scenery layers off (vegetation,
27 // buildings, random scenery objects etc.).
28 // The terrain quality shader level determines the shaders used. Set it to ultra.
29 // The view should be 100% terrain. No sky. Try to minimise parts of terrain
30 // or scenery rendered by other shaders, as the results will be inaccurate.
31 // Avoid clouds in view. Minimise water in view.
32 // WS3 OSM roads must be turned off to get accurate results:
33 // in-sim menu > view > adjust LoD ranges > set all "Minimum Line Feature
34 // Width" sliders to 50m (move sliders slightly if initial value = 9999).
35 // Going closer or reducing FoV works, but these also can change performance.
36 // Looking towards the horizon at high altitude may cause perfomance to be CPU
37 // bound due to OSG scene traveral.
38 // Remember to mention factors that change performance:
39 // resolution, the rough area (regional definitions at work), altitude,
40 // WS3 scenery package, AA settings, driver control panel settings and overrides
41 // - (you can set these to application controlled)
42
43
44 // Comparing performance:
45 // GPU bound: To use FPS to compare performance you must be bottlenecked by
46 // the GPU (GPU bound).
47 // When GPU bound (fragment bound), changing the window size slightly should
48 // result in a change in FPS.
49 // You can also tell if you are GPU bound, as GPU utilisation will be 100%.
50 // Change in performance = FPS2/FPS1.
51 // e.g. increase of 15 FPS to 30 FPS = 30/15 = 2x or 200% increase.
52 // Not GPU bound: If your bottleneck is not the GPU, you need to measure
53 // GPU utilisation.
54 // GPU utilisation is the GPU load - it will be less than 100%.
55 // Change in performance = utilisation1/utilisation2.
56 // e.g. Drop from 40% to 20% = 40/20 = 2x increase in performance or
57 // doubling of FPS. e.g 40% to 30% = 40/30 = 1.33x increase.
58 // CPU bound FPS limit: You can usually find your CPU bound FPS limit by
59 // reducing window size until FPS stops increasing. This depends on what's
60 // in view.
61 // To Compare performace with WS2: untick the WS3 tick box in render settings,
62 // and make sure both WS2 and WS3 are GPU bound, and not CPU bound.
63
64
65 //
66 // Note:
67 // Ensure in-sim menu > view > rendering options > throttle FPS is off.
68 // Ensure vsync is off.
69 // Ensure WS3 OSM roads are off (see testing performance section).
70 // Make sure your power plan is set to maximum or balanced in Windows, or
71 // results could be inaccurate - laptops may be on a power saving plan
72 // by default.
73
74 // To test: All transitions are off by default. Set both remove squareness and
75 // enable large scale transitions to 1 to get a quality with most features
76 // turned on.
77
78 // Maximum number of neighbor landclass textures to lookup if neighbors are found.
79 // The more landclass textures are looked up the more pressure on VRAM.
80 // Performance hit varies by altitude and how small the landclass blobs are.
81 // More ground texture lookups may run slower on older generation GPUs - test and see.
82 // Possible values: 0,1,2. Default: 2. To see texture mixing transitions you need 1 or 2.
83 const int max_neighbor_landclass_texture_lookups = 2;
84
85
86
87 // Small scale transition controls
88
89 // Remove squareness due to landclass texture by growing higher priority neighbors.
90 // This adds 2 extra lookups of the landclass texture, and one math/noise lookup.
91 // Large scale transition searches do not use this - as it triples the number of
92 // landclass texture acceses, as well as adding 1 noise lookup per search point.
93 // This should be expected to be used on old GPUs, except when running at the absolute
94 // lowest graphics quality. It's faster than large scale transition searches.
95 // Possible values: 1:enabled, 0:disabled. Default:0
96 const int remove_squareness_from_landclass_texture = 0;
97
98 // Transition at landclass texel scale
99 // Mix in neighbor textures so landclass boundaries are not hard at the
100 // landclass texel scale.
101 // Note: Disable enable large scale transition search, if using this.
102 // This needs extra ground texture lookups. It looks fine with 1 extra lookup.
103 // This can be combined with removing squareness by growing borders.
104 // Possible values: 1:enabled, 0:disabled
105 const int use_landclass_texel_scale_transition_only = 0;
106
107
108
109 // Large scale transition controls
110
111 // Enable large scale transitions: 1=on, 0=off
112 // Disable use landclass texel scale transition, if using this.
113 const int enable_large_scale_transition_search = 1;
114
115
116 // The search pattern is center + n points in four directions forming a cross.
117 // e.g. 1 search point = 1 + 4 * 1 = 5 points total.
118 // 4 search points: 17 total. 10 search points = 41
119 // The transition distance is the distance from the center to the furtherst
120 // point in any direction.
121
122
123 // Landclass transition search distance in meters
124 // Note: transitions occur on both sides of the landclass borders.
125 // The width of the transition is equal to 2x this value.
126 // Default: 100m
127 const float transition_search_distance_in_m = 25.0;
128
129 // Number of points to search in any direction, in addition to this fragment
130 // Default:4 points. Fewer points results in a less smooth transition (more banding)
131 // Choose the lowest number of points to get a desired transition quality.
132 const int num_search_points_in_a_direction = 4;
133
134
135
136
137 // Landclass transition weightings options
138 // More options mean slightly more GPU math load
139 //
140 // Use 2nd closest neighbour for transition weighting.
141 // Note this won't lookup a ground texture by itself, just sort through results
142 // Possible values: 1:enable, 0=disable. Default: 1
143 const int enable_2nd_closest_neighbor_for_large_scale_transition_weights = 0;
144
145 // Enable dithering to smooth transitions by reducing visible banding
146 // Possible values: 1=enable, 0=disable. Default = 1
147 const int enable_dithering_for_large_scale_transitions = 1;
148
149 // Scale of dithering as a faction of the size of the bands - distance between
150 // search points (=transition distance / number of steps)
151 // 0.2 seems to work ok - not real need to tinker with this.
152 // Different values won't change performance.
153 const float dithering_noise_wavelength_as_fraction_of_step_size = 0.2;
154
155 // Grow the borders of landclasses a bit when large scale transitions are used
156 // Higher priority landclasses grow onto lower priority ones.
157 // Landclass numbers are used as a placeholder for landclass priority.
158 // This works by changing the weighting in the transition region using a
159 // noise lookup
160 // Possibe values: 0=off, 1=on. Default:0
161 const int grow_landclass_borders_with_large_scale_transition = 1;
162
163 // Use the edge-hardness parameter from materials.xml to determine
164 // weighting of the landclass in transitions
165 const int use_edge_hardness_with_large_scale_transition = 1;
166
167
168 //////////////////////////////////////////////////////////////////
169 // Advanced controls - these are for testing scenery generation and rendering
170
171
172 // Landclass source:
173 // Possible values: Default=1;
174 // 0=Normal landclass texture, 1 = Random landclass squares along s and t axes.
175 // Choose 1 to test impact of searching a texture. You should normally leave
176 // it at default.
177 const int landclass_source = 0;
178
179 // Random landclass square size in meters. Remember to adjust transition search distance.
180 // Default: 200m
181 const float random_landclass_square_size_in_m = 3.3*transition_search_distance_in_m;
182
183 // Detiling noise source
184 // Possible values: 0 = texture source, 1 = math source
185 // The texture source still shows some tiling. The math source detiles better, but might
186 // be slightly slower.
187 const int detiling_noise_type = 1;
188
189 // Development tools - 2 controls, now located at the top of WS30-ALS-ultra.frag:
190 // 1. Reduce haze to almost zero, while preserving lighting. Useful for observing distant tiles.
191 // Keeps the calculation overhead. This can be used for profiling.
192 // 2. Remove haze and lighting and shows just the texture.
193 // Useful for checking texture rendering and scenery.
194 // The compiler will likely optimise out the haze and lighting calculations.
195 //
196
197 // Debugging: ground texture array lookup function
198 // Possible values:
199 // 0: Normal: TextureGrad() with partial derivatives. GLSL 1.30.
200 // 1: textureLod() using partial derivatives to manually calculate LoD. GLSL 1.20
201 // 2: texture() without partial derivatives. GLSL 1.20
202 const int tex_lookup_type = 0;
203
204 //
205 // End of test phase controls
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 // Test-phase code:
236
237 // Uniforms used by landclass search functions.
238 // If any uniforms change name or form, remember to update here and in fragment shaders.
239
240
241 uniform sampler2D landclass;
242 uniform sampler2DArray textureArray;
243 uniform sampler2D perlin;
244
245 // Passed from VPBTechnique, not the Effect
246 uniform float fg_tileWidth;
247 uniform float fg_tileHeight;
248 uniform bool fg_photoScenery;
249 uniform vec4 fg_dimensionsArray[128];
250 uniform vec4 fg_ambientArray[128];
251 uniform vec4 fg_diffuseArray[128];
252 uniform vec4 fg_specularArray[128];
253 uniform vec4 fg_textureLookup1[128];
254 uniform vec4 fg_textureLookup2[128];
255 uniform mat4 fg_zUpTransform;
256 uniform vec3 fg_modelOffset;
257
258 // These should be sent as uniforms
259
260 // Tile dimensions in meters
261 // vec2 tile_size = vec2(tile_width , tile_height);
262 // Testing: texture coords are sent flipped right now:
263 vec2 tile_size = vec2(fg_tileHeight , fg_tileWidth);
264
265 // These are defined in noise.frag
266 float rand2D(in vec2 co);
267 float Noise2D(in vec2 coord, in float wavelength);
268
269 // Generates a full precision 32 bit random number from 2 seeds
270 // as well as 6 random integers between 0 and factor that are rescaled 0.0-1.0
271 // by re-using the significant figures from the full precision number.
272 // This avoids having to generate 6 random numbers when
273 // limited variation is needed: say 6 numbers with 100 levels (i.e between 0 and 100).
274 // Seed 2 is incremented so the function can be called again to generate
275 // a different set of numbers
276 float get6_rand_nums(in float PRNGseed1, inout float PRNGseed2, float factor, out float [6] random_integers)
277 {
278
279 float r = fract(sin(dot(vec2(PRNGseed1,PRNGseed2),vec2(12.9898,78.233))) * 43758.5453);
280
281 // random number left over after extracting some decimal places
282 float rlo = r;
283 // To look at: can this be made simd friendly?
284 for (int i=0;i<6;i++)
285 {
286 rlo = (rlo*factor);
287 random_integers[i] = floor(rlo)/factor;
288 rlo = fract(rlo);
289 }
290
291 PRNGseed2+=1.0;
292 return r;
293 }
294
295
296 // Create random landclasses without a texture lookup to stress test.
297 // Each square of square_size in m is assigned a random landclass value.
298 int get_random_landclass(in vec2 co, in vec2 tile_size)
299 {
300 float r = rand2D( floor(vec2(co.s*tile_size.x, co.t*tile_size.y)/random_landclass_square_size_in_m) );
301 int lc = int(r*48.0); // only 48 landclasses mapped so far
302 return lc;
303 }
304
305
306 /*
307 // Look up stretching scale of ground textures for the base texture.
308 // Note terrain default effect only has controls for the texture stretching dimensions for the base texture.
309 // Non-base textures use hardcoded stretching of the ground texture coords, which are in units of meters.
310 vec2 get_ground_texture_scale(in int lc)
311 {
312 // Look up stretching dimensions of ground textures in m - scaled to
313 // fit in [0..1], so rescale
314 vec2 g_texture_stretch_dim = fg_dimensionsArray[lc].st;
315 return (tile_size.xy / g_texture_stretch_dim.xy);
316 }
317 */
318
319
320 // Look up texture coordinates and stretching scale of ground textures for the base texture.
321 // Note terrain default effect only has controls for the texture stretching dimensions for the base texture.
322 // Non-base textures use hardcoded stretching of the ground texture coords, which are in units of meters.
323 void get_ground_texture_data(in int lc, in vec2 tile_coord,
324 out vec2 st, out vec2 g_texture_scale, inout vec4 dFdx_and_dFdy)
325 {
326 // Look up stretching dimensions of ground textures in m - scaled to
327 // fit in [0..1], so rescale
328 vec2 g_texture_stretch_dim = fg_dimensionsArray[lc].st;
329 g_texture_scale = tile_size.xy / g_texture_stretch_dim.xy;
330 // Correct partial derivatives to account for stretching of different textures
331 dFdx_and_dFdy = dFdx_and_dFdy * vec4(g_texture_scale.st, g_texture_scale.st);
332 // Ground texture coords
333 st = g_texture_scale * tile_coord.st;
334 }
335
336
337 // Rotate texture using the perlin texture as a mask to reduce tiling.
338 // type=0: use perlin texture, type = 1: use Noise2D to avoid texture lookup
339 // Testing: if this or get_ground_texture_data used in final WS3 to handle
340 // many base texture lookups, see if optimising to handle many inputs helps
341 // (vectorising Noise2D versus just many texture calls)
342 // To do: adjust for non-tile based ground coords.
343 vec2 detile_texcoords_with_perlin_noise(in vec2 st, in vec2 ground_texture_scale,
344 in vec2 tile_coord, inout vec4 dFdx_and_dFdy)
345 {
346 vec4 dxdy = dFdx_and_dFdy;
347
348 vec2 pnoise;
349
350 // Ratio tile dimensions are stretched relative to s.
351 // Tiles may not have equal dimensions.
352 vec2 stretch_r = tile_size.st/tile_size.s;
353
354 // Note: unresolved texture discontinuties (i.e. mipmap problems) with unequal stretch factors
355 const vec2 local_stretch_factors = vec2(8.0, 8.0 /*16.0*/);
356
357 if (detiling_noise_type==1)
358 {
359 pnoise[0] = texture(perlin, st / local_stretch_factors[0]).r;
360 pnoise[1] = texture(perlin, - st / local_stretch_factors[1]).r;
361 }
362 else
363 {
364 //Testing: Non texture alternative
365
366 // Estimate of wavelength in /Textures/perlin.png in normalised texture coords
367 const float ptex_wavelength = (1.0/7.0);
368
369 pnoise[0] = Noise2D(st / (local_stretch_factors[0]), ptex_wavelength);
370 pnoise[1] = Noise2D(-st / (local_stretch_factors[1]), ptex_wavelength);
371 }
372
373 if (pnoise[0] >= 0.5)
374 {
375 // To do: fix once ground coords are no longer tile based
376 st = ground_texture_scale.st * (tile_coord * stretch_r).ts;
377 // Get back original partial derivatives by undoing
378 // previous texture stretching adjustment done in get_ground_data
379 dxdy = dxdy / vec4(ground_texture_scale.st, ground_texture_scale.st);
380
381 // Recalculate new derivatives
382 vec2 factor = ground_texture_scale.st * stretch_r.ts;
383 dxdy.st = dxdy.ts * factor;
384 dxdy.pq = dxdy.qp * factor;
385
386 }
387
388 if (pnoise[1] >= 0.5)
389 {
390 st = -st; dxdy = -dxdy;
391 }
392
393 dFdx_and_dFdy = dxdy;
394 return st;
395 }
396
397
398 // Lookup a ground texture at a point based on the landclass at that point, without visible
399 // seams at coordinate discontinuities or at landclass boundaries where texture are switched.
400 // The partial derivatives of the tile_coord at the fragment is needed to adjust for
401 // the stretching of different textures, so that the correct mip-map level is looked
402 // up and there are no seams.
403 // Texture types: 0: base texture, 1: grain texture, 2: gradient texture, 3 dot texture,
404 // 4: mix texture, 5: detail texture.
405
406 vec4 lookup_ground_texture_array(in int texture_type, in vec2 ground_texture_coord, in int landclass_id,
407 in vec4 dFdx_and_dFdy)
408 {
409 // Testing: may be able to save 1 or 2 op slots by combining dx/dy in a vec4 and
410 // using swizzles which are free, but mostly operations are working independenly on s and t.
411 // Only 1 place so far that just multiplies everything by a scalar.
412 vec2 st;
413 vec2 g_tex_coord = ground_texture_coord;
414 vec2 g_texture_scale;
415 vec4 texel;
416 int lc = landclass_id;
417 vec4 dxdy = dFdx_and_dFdy;
418
419 // Find the index of the specified texture type (e.g. mix or gradient texture ) in
420 // the ground texture lookup array.
421 // Since texture_type is a constant in the fragment shader, there should be no performance hit for branching.
422
423 int tex_idx = 0;
424 int type = texture_type;
425
426 // Index for the base texture is contained fg_textureLookup1[lc].r
427 if (type == 0) tex_idx = int(uint(fg_textureLookup1[lc].r * 255.0 + 0.5));
428
429 // Grain texture is material texture slot 14, the index of which is mapped to the r channel of fg_textureLookup2
430 else if (type == 1) tex_idx = int(fg_textureLookup2[lc].r * 255.0 + 0.5);
431
432 // Gradient texture is material texture 13, the index of which is mapped to the a channel of fg_textureLookup1
433 else if (type == 2) tex_idx = int(fg_textureLookup1[lc].a * 255.0 + 0.5);
434
435 // Dot texture is material texture 15, the index of which is mapped to the g channel of fg_textureLookup2
436 else if (type == 3) tex_idx = int(fg_textureLookup2[lc].g * 255.0 + 0.5);
437
438 // Mix texture is material texture 12, the index of which is mapped to the b channel of fg_textureLookup1
439 else if (type == 4) tex_idx = int(fg_textureLookup1[lc].b * 255.0 + 0.5);
440
441 // Detail texture is material texture 11, the index of which is mapped to the g channel of fg_textureLookup1
442 else if (type == 5) tex_idx = int(fg_textureLookup1[lc].g * 255.0 + 0.5);
443
444
445 if (type == 0)
446 {
447 // Scale normalised tile coords by stretching factor, and get info
448 vec2 tile_coord = g_tex_coord;
449 get_ground_texture_data(lc, tile_coord, st, g_texture_scale, dxdy);
450 st = detile_texcoords_with_perlin_noise(st, g_texture_scale, tile_coord, dxdy);
451 }
452 else
453 {
454 st = g_tex_coord;
455 }
456
457
458 // Debugging: multiple texture lookup functions if there are issues
459 // with old GPUs and compilers.
460 if (tex_lookup_type == 0)
461 {
462 texel = textureGrad(textureArray, vec3(st, tex_idx), dxdy.st, dxdy.pq);
463 }
464 else if (tex_lookup_type == 1)
465 {
466 float lod = max(length(dxdy.sp), length(dxdy.tq));
467 lod = log2(lod);
468 texel = textureLod(textureArray, vec3(st, tex_idx), lod);
469 }
470 else texel = texture(textureArray, vec3(st, tex_idx));
471
472
473 //texel = textureGrad(textureArray, vec3(st, tex_idx), dxdy.st, dxdy.pq);
474 return texel;
475 }
476
477
478 // Look up the texel of the specified texture type (e.g. grain or detail textures) for this fragment
479 // and any neighbor texels, then mix.
480
481 vec4 get_mixed_texel(in int texture_type, in vec2 g_texture_coord,
482 in int landclass_id, in int num_unique_neighbors,
483 in ivec4 neighbor_texel_landclass_ids, in vec4 neighbor_mix_factors,
484 in vec4 dFdx_and_dFdy
485 )
486 {
487 vec2 st = g_texture_coord;
488 int lc = landclass_id;
489 ivec4 lc_n = neighbor_texel_landclass_ids;
490 // Not implemented yet
491 int type = texture_type;
492 vec4 dxdy = dFdx_and_dFdy;
493 vec4 mfact = neighbor_mix_factors;
494
495 vec4 texel = lookup_ground_texture_array(0, st, lc, dxdy);
496
497
498 // Mix texels - to work consistently it needs a more preceptual interpolation than mix()
499 if (num_unique_neighbors != 0)
500 {
501 // Closest neighbor landclass
502 vec4 texel_closest = lookup_ground_texture_array(0, st, lc_n[0], dxdy);
503
504 // Neighbor contributions
505 vec4 texel_nc=texel_closest;
506
507 if (num_unique_neighbors > 1)
508 {
509 // 2nd Closest neighbor landclass
510 vec4 texel_2nd_closest = lookup_ground_texture_array(0, st, lc_n[1], dxdy);
511
512 texel_nc = mix(texel_closest, texel_2nd_closest, mfact[1]);
513 }
514
515 texel = mix(texel, texel_nc, mfact[0]);
516 }
517 return texel;
518 }
519
520
521 // Landclass sources: texture or random
522 int read_landclass_id(in vec2 tile_coord)
523 {
524 int lc;
525
526 if (landclass_source == 0) lc = (int(texture2D(landclass, tile_coord.st).g * 255.0 + 0.5));
527 else lc = (get_random_landclass(tile_coord.st, tile_size));
528 return lc;
529 }
530
531 // Landclass sources: texture or random
532 ivec2 read_landclass_id_and_water(in vec2 tile_coord)
533 {
534 int lc = (int(texture2D(landclass, tile_coord.st).g * 255.0 + 0.5));
535 return ivec2(lc, (texture2D(landclass, tile_coord.st).b > 0.9) ? 1 : 0);
536 }
537
538
539 int read_landclass_id_non_pixelated(in vec2 tile_coord,
540 const in float landclass_texel_size_m)
541 {
542 vec2 c0 = tile_coord;
543 vec2 sz = tile_size;
544 vec2 tsz = vec2(landclass_texel_size_m)/tile_size;
545
546 // Landclass sources: texture or random
547 int lc = read_landclass_id(c0);
548
549 return lc;
550 }
551
552
553 // Determine whether to grow a neighbor landclass onto current.
554 // 1 = grow neighbor, 0 = don't grow neighbor
555 float get_growth_priority(in int current_landclass, in int neighbor_landclass)
556 {
557 int lc1 = current_landclass;
558 int lc2 = neighbor_landclass;
559 return ((lc1 < lc2)?1.0:0.0);
560 }
561
562
563 // Determine whether to grow a one of 2 neighbor landclasses onto current.
564 // 1 = grow neighbor, 0 = don't grow neighbor
565 float get_growth_priority(in int current_landclass, in int neighbor_landclass1, in int neighbor_landclass2)
566 {
567 int lc1 = current_landclass;
568 int lc2 = neighbor_landclass1;
569 int lc3 = neighbor_landclass2;
570 return ((lc1 < max(lc2,lc3))?1.0:0.0);
571 }
572
573
574 int lookup_landclass_id(in vec2 tile_coord, in vec4 dFdx_and_dFdy,
575 out ivec4 neighbor_texel_landclass_ids,
576 out int number_of_unique_neighbors_found, out vec4 landclass_neighbor_texel_weights)
577 {
578
579 // To do: fix landclass border artifacts, with all shaders.
580
581 vec4 dxdy = dFdx_and_dFdy;
582
583 // Number of unique neighbours found
584 int num_n = 0;
585
586 vec2 c0 = tile_coord;
587 vec2 sz = tile_size;
588
589 // Landclass sources: texture or random
590 int lc = read_landclass_id(c0);
591 int output_landclass = lc;
592
593 // Landclasses of up to 4 neighbor texels
594 ivec4 lc_n = ivec4(lc);
595
596 // Landclasses sorted
597 ivec4 lc_n_s;
598
599 // Combined weight from 2 neighbor texels
600 float w = 0.0;
601
602 // Landclass neighbor weights - for texel mixing only
603 vec4 lc_n_w = vec4(0.0);
604
605 // Test phase controls
606 if ( (remove_squareness_from_landclass_texture == 1) ||
607 ( (use_landclass_texel_scale_transition_only == 1) &&
608 (enable_large_scale_transition_search == 0) )
609 )
610 {
611
612
613 // Remove squareness from the landclass texture due to nearest neighbour interpolation
614 // A landclass with higher growth priority grows on to an adjacent landclass
615 // with lower priority
616
617 // Landclass texture dimensions, in texels - Needs glsl 1.30+
618 // Probably best to just send as uniforms if texture sizes don't vary, or are fixed per terrain LoD level.
619 vec2 texture_dim_tx = vec2(textureSize(landclass, 0));
620
621 // Coordinates of current fragment, in texels
622 vec2 c0_tx = c0 * texture_dim_tx;
623
624 // Coordinates of the center of the current texel, in texels
625 // centers are n+(0.5,0.5) for n = 0,1,2...
626 vec2 ct_c0_tx = floor(c0_tx) + 0.5;
627 // center in normalised tex coords
628 vec2 ct_c0 = ct_c0_tx/texture_dim_tx;
629
630 // Landclass at center of current texel - same anywhere within a texel
631 int lc_ct = lc;
632
633 // Coords of centers of closest neighbors, in texels
634 vec2 c_n_tx[2];
635
636
637 // Coordinate of fragment relative to center of texel, in texels
638 vec2 c0_rel_ct_tx = c0_tx - ct_c0_tx;
639
640 float dist_ct = length(c0_rel_ct_tx);
641
642 // need to avoid division by 0?
643 if (dist_ct < 0.00001) dist_ct += 0.00001;
644
645 // Choose closest neighbor based on angle wrt. to
646 // c0, center of texel, and s & t axes.
647 // Choose the texel in the direction of the largest s & t component.
648 // NB: This method will select a diagonal neighbor if
649 // both components of c0_rel_ct_tx are equal to cos(45).
650 // Testing: look for a way that uses fewer instructions,
651 // maybe calculating 2 neighbors at once using a vec4.
652
653 //vec2 a = abs(c0_rel_ct_tx);
654 //offset_ct0 = ((a.s > a.t)?vec2(1.0,0.0):vec2(0.0,1.0))*sign(c0_rel_ct_tx);
655
656 // Vectorisable
657 const float cos45deg = cos(radians(45.0));
658 vec2 offset_ct0 = step(cos45deg, abs(c0_rel_ct_tx/dist_ct))
659 *sign(c0_rel_ct_tx);
660
661 c_n_tx[0] = (ct_c0_tx + offset_ct0);
662
663 // Landclass of closest neighbor
664 lc_n[0] = read_landclass_id(c_n_tx[0]/texture_dim_tx);
665
666
667 // Choose 2nd closest neighbor
668 // Choose texels in the direction of the smaller of s & t components
669 vec2 offset_ct1 = abs(offset_ct0.ts)*step(0.0, abs(c0_rel_ct_tx/dist_ct))
670 * sign(c0_rel_ct_tx);
671
672 c_n_tx[1] = (ct_c0_tx + offset_ct1);
673
674 // Land class of 2nd closest neighbor
675 lc_n[1] = read_landclass_id(c_n_tx[1]/texture_dim_tx);
676
677
678 // Distinct neighbors found
679 // Testing: possible optimisation, use booleans.
680 // Needs ivec4/1.30+, or vec4/1.20 - reliably supported by old compilers?
681 // bvec4 n_found = notEqual(lc_n, ivec4(lc));
682
683 ivec4 n_found = ivec4(((lc_n[0] != lc)?1:0), ((lc_n[1] != lc)?1:0), 0, 0);
684
685 num_n = n_found[0]+ n_found[1];
686
687
688 //if (any(n_found))
689 if ((n_found[0] == 1) || (n_found[1] == 1))
690 {
691
692 // Weights for influence from neighbor landclasses
693 // The distance away from the neighbor texel side is used to determine influence.
694 // w_n: 0.5 at minimum possible distance, 0.0 at maximum possible distance
695
696 // Neighbor weights
697 vec4 w_n = vec4(0.0);
698
699
700 // Method 1:
701 // Use distance from side of neighbor texel for mixing
702 // This is has some issues, including with corners
703
704 vec2 dir0 = offset_ct0;
705 vec2 dir1 = offset_ct1;
706
707 // Distance from side of neighbor texel, in texels
708 vec2 d0 = dir0*c0_rel_ct_tx;
709 vec2 d1 =dir1*c0_rel_ct_tx;
710
711 w_n[0] = max(d0.x, d0.y);
712 w_n[1] = max(d1.x, d1.y);
713
714
715
716 /*
717 //Method 2:
718 // use distance from center of neighbor texel for mixing
719 // This doesn't really give better results than 1
720
721 // Distance from center of neighbor texels, in texels
722 vec2 dist_n_tx = vec2(0.0);
723
724 dist_n_tx[0] = length(c0_tx - c_n_tx[0]);
725 dist_n_tx[1] = length(c0_tx - c_n_tx[1]);
726
727
728 // Weighting for closest neighbor - [0.5 to 0.0] as distance goes from [min to max]
729 const float max_dist = sqrt(0.5*0.5+1.0);
730 const float min_dist = 0.5;
731 w_n[0] = (dist_n_tx[0]-min_dist)/(max_dist - min_dist);
732 w_n[0] = mix(0.5, 0.0, w_n[0]);
733
734
735 // Weighting for 2nd closest neighbor - [0.5 to 0.0] as distance goes from [min to max]
736 //const float max_dist1 = sqrt(0.5*0.5+1.0);
737 //const float min_dist = 0.5;
738 w_n[1] = (dist_n_tx[1]-min_dist)/(max_dist-min_dist);
739 w_n[1] = mix(0.5, 0.0, w_n[1]);
740 */
741
742
743 // Use weighting only if neighbour is different from landclass for this fragment
744 // Testing: Can be omitted if not doing texture mixing as it doesn't really
745 // make a difference.
746 w_n = w_n * vec4(n_found);
747
748 // Combined weighting - increase w_n[0] if the 2nd closest neigbour is
749 // different such that w_n[0] remains under 0.5
750 w = w_n[0];
751 w = w + (0.5-w)*2.0*w_n[1];
752
753 // Sort landclasses and weights
754 lc_n_s = lc_n;
755 // If closest neighbour is lc, move 2nd closest neighbour to closest slot, and
756 // clear the 2nd closest slot
757 if (n_found[0] == 0)
758 {
759 lc_n_s.xy = lc_n.yz;
760 w_n.xy = w_n.yz;
761 }
762
763
764 // Testing phase controls
765 if ( (use_landclass_texel_scale_transition_only == 1) &&
766 (max_neighbor_landclass_texture_lookups > 0) &&
767 (enable_large_scale_transition_search == 0)
768 )
769 {
770 // Assign mix factors for transitions by mixing texels
771 // [0]: 0 to 0.5
772 // [1]: split [0 to 1] between closest and 2nd closest landclass
773 lc_n_w[0] = w;
774 lc_n_w[1] = w_n[1]/(w_n[0]+w_n[1]);
775 }
776
777
778 } // Testing controls: End if ((remove_squareness_from_landclass_texture == 1) || (use_landclass_texel_scale_transition_only == 1))
779
780
781 if (remove_squareness_from_landclass_texture == 1)
782 {
783 // Turn neighbor growth off at longer ranges, otherwise there is flickering noise
784 // Testing: The exact cutoff could be done sooner to save some performance - needs
785 // to be part of a larger solution to similar issues. User should set a tolerance factor.
786 // Effectively: lod_factor = min(length(vec2(dFdx(..).s, dFdy(..).s)),length(vec2(dFdx(..).t, dFdy(..).t)));
787 float lod_factor = min(length(vec2(dxdy.s, dxdy.p)),length(vec2(dxdy.t, dxdy.q)));
788
789 // Estimate of frequency of growth noise in texels - i.e. how many peaks and troughs fit in one texel
790 const float frequency_g_n = 1000.0;
791 const float cutoff = 1.0/frequency_g_n;
792
793 if (lod_factor < cutoff)
794 {
795 // Decide whether to grow neighbor on to lc
796 float grow_n = get_growth_priority(lc,lc_n[0]);
797
798 // Noise on the scale of landclass texels in the texture
799 // Testing: reduce instructions if this method is to be used.
800 // To look at: corner visuals & sharp diagonals.
801
802 // Minimum wavelength of transition noise
803 const float wl_tn = (1.0/8.0);
804 float tn = Noise2D(c0*texture_dim_tx, wl_tn); // old val 1.6
805
806 float threshold = mix(1.0,0.0, w);
807
808 float neighbor_growth_weight = (0.3*2.0)*w*step(threshold-0.15, tn);
809
810 // Growth factor
811 float g = ((grow_n > 0.0)?neighbor_growth_weight:-neighbor_growth_weight);
812 //g = sqrt(abs(g))*sign(g);
813
814 // Neighbor growth value
815 float v;
816 //v=w+g;
817 v = w*(0.7+50.5*g);
818
819 // Whether or not to grow neighbour onto nearby pixel
820
821 // To do - mix factor between different neighbour lanclasses
822 // when using an extra ground texture lookup
823
824 if (v > 0.5) output_landclass = lc_n_s[0];
825
826
827
828
829 // Testing phase controls
830 if ( (use_landclass_texel_scale_transition_only == 1) &&
831 (max_neighbor_landclass_texture_lookups > 0) &&
832 (enable_large_scale_transition_search == 0)
833 )
834 {
835
836 lc_n_w[0] = 0.0;
837 /*
838 // Adjust mix factor weights and swap landclasses for extrusions
839
840 // Method 1:
841
842 lc_n_w[0] = (w-0.5*neighbor_growth_weight);
843 if (v > 0.5) lc_n_s[0] = lc;
844 */
845
846
847 // Method 2:
848 // Mix in neighbour texel, instead of change output landclass.
849
850 // Undo previous output class assignment
851 output_landclass = lc;
852
853 // Reduce flickering noise due to small detail added when far away. Contrasting colors mean more visible issues.
854 // Fade 0 to 1 as lod_factor goes from 1.0 to 4.0
855 // The goal is to avoid flickering with worst case texture filtering and supersampling.
856 // Testing: However, the quicker the detil fades, the more square distant ladnclasses look.
857 // Right now the noise function generates too many high frequency components (small detail)
858
859 //const float mmax = 4000.0; const float mmin = mmax-1000.0; /* no flickering */
860 const float mmax = 3000.0; const float mmin = mmax-1000.0; /* bit of filckering */
861 float fade = smoothstep(mmin, mmax, 1.0/lod_factor);
862
863 lc_n_w[0] = (w-0.5*3.333*0.9*(neighbor_growth_weight*fade));
864 if (v > 0.5) lc_n_w[0] = w+0.4*fade;
865
866
867
868 }
869
870
871
872 } // End if (lod_factor > some value)
873
874
875 } // Testing code: End if (remove_squareness_from_landclass_texture == 1)
876
877
878
879 } // End if (nfound[0] == 1) || (n_found[1] == 1)
880
881
882
883
884 landclass_neighbor_texel_weights = lc_n_w;
885 neighbor_texel_landclass_ids = lc_n_s;
886 number_of_unique_neighbors_found = num_n;
887 return output_landclass;
888
889 }
890
891
892
893 // Look up the landclass id [0 .. 255] for this particular fragment.
894 // Lookup id of any neighbouring landclass that is within the search distance.
895 // Searches are performed in upto 4 directions right now, but only one landclass is looked up
896 // Create a mix factor werighting the influences of nearby landclasses
897
898 void get_landclass_id(in vec2 tile_coord, in vec4 dFdx_and_dFdy,
899 out int landclass_id, out ivec4 neighbor_landclass_ids,
900 out int num_unique_neighbors,out vec4 mix_factor
901 )
902
903 {
904 // Each tile has 1 texture containing landclass ids stetched over it
905
906 // Landclass source type: 0=texture, 1=random squares
907 // Controls are defined at global scope.
908 vec2 sz = tile_size;
909
910 vec4 dxdy = dFdx_and_dFdy;
911
912 // Number of unique neighbors found
913 int num_n = 0;
914
915 // Only used for mixing textures of neighboring texels:
916 // Landclass ids of neigbors in neighboring texels
917 ivec4 lc_n_tx;
918 // Weights of neighbour landclass texels
919 vec4 lc_n_w;
920 // Number of unique neighbors in neighboring texels
921 int num_n_tx = 0;
922
923 int lc = lookup_landclass_id(tile_coord, dxdy, lc_n_tx, num_n_tx, lc_n_w);
924
925 float edge_hardness = 0.0;
926 if (use_edge_hardness_with_large_scale_transition == 1) {
927 edge_hardness = fg_dimensionsArray[lc].a;
928 }
929
930 // Neighbor landclass ids
931 ivec4 lc_n = ivec4(lc);
932
933 // Mix factors: texels are mixed in from furthest, to closest
934 // mfact[1]: [0 to 1] mixing 1st and 2nd closest texels
935 // mfact[0]: [0 to 0.5] texel and previous neighbour contributions
936 vec4 mfact = vec4(0.0);
937
938
939 // Testing phase controls
940 if ( (use_landclass_texel_scale_transition_only == 1) &&
941 (max_neighbor_landclass_texture_lookups > 0) &&
942 (enable_large_scale_transition_search == 0)
943 )
944
945 {
946 // Use the ground texture lookups to do a transition on the scale of
947 // the landclass textures instead of doing a large scale transition
948 num_n = num_n_tx;
949 lc_n = lc_n_tx;
950 mfact = lc_n_w;
951 }
952
953
954 // Testing phase controls
955 if ( (enable_large_scale_transition_search == 1) &&
956 (max_neighbor_landclass_texture_lookups > 0) &&
957 (use_landclass_texel_scale_transition_only == 0)
958 )
959 {
960
961
962 // Transition search
963 const int n = num_search_points_in_a_direction;
964
965 const float search_dist = transition_search_distance_in_m;
966 vec2 step_size_m = vec2(search_dist/float(n));
967 // step size in tile coords. Modulated by the edge hardness which makes
968 // the step size smaller and hence the range of adjacent landclasses
969 // smaller.
970 vec2 steps = step_size_m.st / tile_size.st * (1.0 - edge_hardness);
971
972 vec2 c0 = tile_coord;
973
974 // Min number of points (loop counter value (i)) before
975 // a different landclass is found
976 ivec4 mi = ivec4(n+1);
977
978 // landclass - l can be accessed as an array e.g. l[0]=l.x
979 ivec4 l = ivec4(lc);
980
981 // Search in 4 directions. These for loops likely need unrolling,
982 // and optimising to use minimum instructions, if they are
983 // to be used outside of testing the search concept.
984 // The texture access patterns may be suboptimal as well.
985 // Travelling along s and t axes might work better.
986 // Note: this returns the closest neighbor. There could be blobs
987 // of multiple neighbors, or a tiny islands of neighbors among this
988 // landclass.
989
990
991 // Testing: breaking the loop once the closest neighbour is found
992 // results in very slightly lower FPS on a 10 series GPU for 100m search
993 // distance and 4 points. May be faster on old GPUs with slow caching.
994
995
996 // +s direction
997 vec2 dir = vec2(steps.s, 0.0);
998
999 for (int i=1;i<=n;i++) {
1000 vec2 c = c0+float(i)*dir;
1001 ivec2 v = read_landclass_id_and_water(c);
1002 if ((v[0] != lc) && (v[1] != 1) && (mi[0] > n)) {l[0] = v[0]; mi[0] = i; }
1003 }
1004
1005
1006 // -s direction
1007 dir = vec2(-steps.s, 0.0);
1008 for (int i=1;i<=n;i++)
1009 {
1010 vec2 c = c0+float(i)*dir;
1011 ivec2 v = read_landclass_id_and_water(c);
1012 if ((v[0] != lc) && (v[1] != 1) && (mi[1] > n)) {l[1] = v[0]; mi[1] = i; }
1013 }
1014
1015
1016 // +t direction
1017 dir = vec2(0.0, steps.t);
1018 for (int i=1;i<=n;i++)
1019 {
1020 vec2 c = c0+float(i)*dir;
1021 ivec2 v = read_landclass_id_and_water(c);
1022 if ((v[0] != lc) && (v[1] != 1) && (mi[2] > n)) {l[2] = v[0]; mi[2] = i; }
1023 }
1024
1025
1026 // -t direction
1027 dir = vec2(0.0, -steps.t);
1028 for (int i=1;i<=n;i++)
1029 {
1030 vec2 c = c0+float(i)*dir;
1031 ivec2 v = read_landclass_id_and_water(c);
1032 if ((v[0] != lc) && (v[1] != 1) && (mi[3] > n)) {l[3] = v[0]; mi[3] = i; }
1033 }
1034
1035
1036 // Set neighbour landclass
1037
1038 // Choose closest neighbor
1039 // min number of steps before a neighbor was found in any direction
1040 int mns = n+1;
1041 // index of mi[] with min number of steps
1042 int idx1=-1;
1043 for (int j=0;j<4;j++)
1044 {
1045 if (mi[j] < mns) {mns = mi[j]; idx1 = j; lc_n[0] = l[j]; num_n=1;}
1046 }
1047
1048 // Transitions:
1049 // Possible landclass property: Transition distance or weighting
1050 // e.g. larger transition between sand/grass terrain compared to forest/agriculture
1051
1052 // Find mix factor and increase influence for 2, 3 or 4 nearby landclass blobs.
1053 // If one neighbor landclass texture is looked up, even if the nearby landclasses
1054 // are different only one texture will get prominence
1055
1056 // At the boundary between landclasses there should be 50% influence.
1057 // If needed it's possible to add a dominance factor.
1058
1059 // mi ranges from n+1 to 1. Mix factor ranges from [0.0 to 0.5]
1060 // 3 point search example:
1061 // [Num steps=Mixfactor value]: [no neighbor found = 0.0], [1 = 0.25], [2 = 0.5]
1062
1063
1064 // Calculate weights: map [n+1 to 1] to [0.0 to 0.5]
1065 vec4 w = 0.5*(1.0-(vec4(mi-1)/float(n)));
1066
1067
1068 // Calculate mix factor to draw one neighbor landclass
1069 float mf1=0.0;
1070
1071 // Method 1:
1072 float max_w = max(max(max(w[0],w[1]),w[2]),w[3]);
1073 //mf1 = max_w;
1074
1075 // Method 2: add up the influence and clamp to 0.5
1076 //mf1 = min(w.x+w.y+w.z+w.w, 0.5);
1077
1078
1079 // Method 3: weight influence without going over limit or needing to clamp
1080 // Example with influence [0 to 1]:
1081 // 2 neighbors with 0.5 influence: 0.75 . 3 neighbors with 0.5 = 87.25
1082 // of course influence is [0 to 0.5] but idea is the same
1083 mf1 = w[0];
1084 mf1 += (0.5-mf1)*w[1];
1085 mf1 += (0.5-mf1)*w[2];
1086 mf1 += (0.5-mf1)*w[3];
1087
1088 // Mix factors: texels are mixed in from furthest, to closest
1089 // mfact[0]: [0 to 0.5] texel and previous neighbour contributions
1090 // mfact[1]: [0 to 1] mixing 1st and 2nd closest texels
1091 mfact[0] = mf1;
1092
1093
1094 // Test phase controls:
1095 if (enable_2nd_closest_neighbor_for_large_scale_transition_weights == 1)
1096 {
1097
1098 // Calculate mix factor for the case of two neighbour landclasses
1099
1100 // index of mi[] with the 2nd lowest number of steps
1101 int idx2=-1;
1102 if (idx1 != -1) {
1103
1104 // Choose 2nd closest neighbor
1105 // Testing: look at a way to find 2 closest neighbors with less instructions
1106 // 2nd lowest number of steps
1107 int mns2 = n+1;
1108 for (int j=0;j<4;j++) {
1109 if ((mi[j] < mns2) && (mi[j] >= mns) && (j != idx1))
1110 {mns2 = mi[j]; lc_n[1] = l[j]; idx2=j; num_n=2;}
1111 }
1112 }
1113
1114
1115 // If two neighbors are found split available mix factor (mf1) by relative weights
1116 if (idx2 != -1) {
1117 float rw = w[idx2]/(w[idx1]+w[idx2]);
1118 mfact[1] = rw;
1119 }
1120
1121
1122 } // End if (enable_2nd_closest_neighbor_for_large_scale_transition_weights == 1)
1123
1124
1125 // Test phase controls
1126 if (enable_dithering_for_large_scale_transitions == 1)
1127 {
1128 // Add noise to change transition
1129 float tnoise1= Noise2D(tile_coord, dithering_noise_wavelength_as_fraction_of_step_size*steps.x);
1130 float noise = 0.5*(1.0-tnoise1)/float(n);
1131 mfact[0]=mfact[0]+noise;
1132 mfact[0]=clamp(mfact[0],0.0,0.5);
1133 }
1134
1135
1136 // Test phase controls
1137 if (grow_landclass_borders_with_large_scale_transition == 1)
1138 {
1139
1140 // Grow landclass borders with noise so landclass blobs that are too artificial
1141 // looking or coarse look natural.
1142 // A landclass with higher growth priority grows on to an adjacent landclass
1143 // with lower priority
1144
1145 // Decide whether to grow neighbor on to lc
1146 float grow_n = get_growth_priority(lc,lc_n[0],lc_n[1]);
1147
1148 // Noise on the scale of landclass texels in the texture
1149 float tnoise2 = Noise2D(tile_coord, 0.4*transition_search_distance_in_m/tile_size.x);
1150 float threshold = mix(1.0,0.0, mfact[0]);
1151 float neighbor_growth_mixf = 0.3*mix(0.0,1.0,mfact[0]*2.0)*step(threshold-0.15,tnoise2);
1152
1153 mfact[0] = mfact[0]+((grow_n > 0.0)?neighbor_growth_mixf:-neighbor_growth_mixf);
1154 mfact[0] = clamp(mfact[0],0.0,1.0);
1155
1156
1157 // Decide whether to extrude furthest neighbor or closest neighbor onto lc
1158 float grow_n1 = get_growth_priority(lc_n[0],lc_n[1]);
1159
1160 mfact[1] = mfact[1]+((grow_n > 0.0)?neighbor_growth_mixf:-neighbor_growth_mixf);
1161 mfact[1] = clamp(mfact[1],0.0,1.0);
1162
1163
1164 } // Testing: End if (grow_landclass_borders_with_large_scale_transition == 1)
1165
1166
1167 } // Testing: End if ((enable_large_scale_transition_search == 1) && (max_neighbor_landclass_texture_lookups > 0))
1168
1169
1170 //lc = int(t);
1171 //mfact[2] = t;
1172
1173 landclass_id = lc;
1174 neighbor_landclass_ids=lc_n;
1175 num_unique_neighbors = num_n;
1176 mix_factor = mfact;
1177 }
1178
1179
1180
1181 // End Test-phase code
1182 ////////////////////////
1183
1184
1185 // Determine the texel and material parameters for a particular fragment,
1186 // Taking into account photoscenery etc.
1187 void get_material(in int landclass,
1188 in vec2 ground_tex_coord,
1189 in vec4 dxdy_gc,
1190 out float mat_shininess,
1191 out vec4 mat_ambient,
1192 out vec4 mat_diffuse,
1193 out vec4 mat_specular,
1194 out vec4 dxdy,
1195 out vec2 st
1196 )
1197 {
1198 // Calculate texture coords for ground textures
1199 // Textures are stretched along the ground to different
1200 // lengths along each axes as set by <xsize> and <ysize>
1201 // regional definitions parameters.
1202 vec2 stretch_dimensions = fg_dimensionsArray[landclass].st;
1203 vec2 tileSize = vec2(fg_tileWidth, fg_tileHeight);
1204 vec2 texture_scaling = tileSize.yx / stretch_dimensions.st;
1205 st = texture_scaling.st * ground_tex_coord.st;
1206
1207 // Scale partial derivatives
1208 dxdy = vec4(texture_scaling.st, texture_scaling.st) * dxdy_gc;
1209
1210 if (fg_photoScenery) {
1211 // In the photoscenery case we don't have landclass or materials available, so we
1212 // just use constants for the material properties.
1213 mat_ambient = vec4(0.2,0.2,0.2,1.0);
1214 mat_diffuse = vec4(0.8,0.8,0.8,1.0);
1215 mat_specular = vec4(0.0,0.0,0.0,1.0);
1216 mat_shininess = 1.2;
1217 } else {
1218 // Color Mode is always AMBIENT_AND_DIFFUSE, which means
1219 // using a base colour of white for ambient/diffuse,
1220 // rather than the material color from ambientArray/diffuseArray.
1221 mat_ambient = vec4(1.0,1.0,1.0,1.0);
1222 mat_diffuse = vec4(1.0,1.0,1.0,1.0);
1223 mat_specular = fg_specularArray[landclass];
1224 mat_shininess = fg_dimensionsArray[landclass].z;
1225 }
1226 }