Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/scene/2d/line_builder.cpp
9903 views
1
/**************************************************************************/
2
/* line_builder.cpp */
3
/**************************************************************************/
4
/* This file is part of: */
5
/* GODOT ENGINE */
6
/* https://godotengine.org */
7
/**************************************************************************/
8
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10
/* */
11
/* Permission is hereby granted, free of charge, to any person obtaining */
12
/* a copy of this software and associated documentation files (the */
13
/* "Software"), to deal in the Software without restriction, including */
14
/* without limitation the rights to use, copy, modify, merge, publish, */
15
/* distribute, sublicense, and/or sell copies of the Software, and to */
16
/* permit persons to whom the Software is furnished to do so, subject to */
17
/* the following conditions: */
18
/* */
19
/* The above copyright notice and this permission notice shall be */
20
/* included in all copies or substantial portions of the Software. */
21
/* */
22
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29
/**************************************************************************/
30
31
#include "line_builder.h"
32
33
#include "core/math/geometry_2d.h"
34
35
// Utility method.
36
static inline Vector2 interpolate(const Rect2 &r, const Vector2 &v) {
37
return Vector2(
38
Math::lerp(r.position.x, r.position.x + r.get_size().x, v.x),
39
Math::lerp(r.position.y, r.position.y + r.get_size().y, v.y));
40
}
41
42
LineBuilder::LineBuilder() {
43
}
44
45
void LineBuilder::build() {
46
// Need at least 2 points to draw a line, so clear the output and return.
47
if (points.size() < 2) {
48
vertices.clear();
49
colors.clear();
50
indices.clear();
51
uvs.clear();
52
return;
53
}
54
55
ERR_FAIL_COND(tile_aspect <= 0.f);
56
57
const float hw = width / 2.f;
58
const float hw_sq = hw * hw;
59
const float sharp_limit_sq = sharp_limit * sharp_limit;
60
const int point_count = points.size();
61
const bool wrap_around = closed && point_count > 2;
62
63
_interpolate_color = gradient != nullptr;
64
const bool retrieve_curve = curve != nullptr;
65
const bool distance_required = _interpolate_color || retrieve_curve ||
66
texture_mode == Line2D::LINE_TEXTURE_TILE ||
67
texture_mode == Line2D::LINE_TEXTURE_STRETCH;
68
69
// Initial values
70
71
Vector2 pos0 = points[0];
72
Vector2 pos1 = points[1];
73
Vector2 f0 = (pos1 - pos0).normalized();
74
Vector2 u0 = f0.orthogonal();
75
Vector2 pos_up0 = pos0;
76
Vector2 pos_down0 = pos0;
77
78
Color color0;
79
Color color1;
80
81
float current_distance0 = 0.f;
82
float current_distance1 = 0.f;
83
float total_distance = 0.f;
84
85
float width_factor = 1.f;
86
float modified_hw = hw;
87
if (retrieve_curve) {
88
width_factor = curve->sample_baked(0.f);
89
modified_hw = hw * width_factor;
90
}
91
92
if (distance_required) {
93
// Calculate the total distance.
94
for (int i = 1; i < point_count; ++i) {
95
total_distance += points[i].distance_to(points[i - 1]);
96
}
97
if (wrap_around) {
98
total_distance += points[point_count - 1].distance_to(pos0);
99
} else {
100
// Adjust the total distance.
101
// The line's outer length may be a little higher due to the end caps.
102
if (begin_cap_mode == Line2D::LINE_CAP_BOX || begin_cap_mode == Line2D::LINE_CAP_ROUND) {
103
total_distance += modified_hw;
104
}
105
if (end_cap_mode == Line2D::LINE_CAP_BOX || end_cap_mode == Line2D::LINE_CAP_ROUND) {
106
if (retrieve_curve) {
107
total_distance += hw * curve->sample_baked(1.f);
108
} else {
109
total_distance += hw;
110
}
111
}
112
}
113
}
114
115
if (point_count < 2 || (distance_required && Math::is_zero_approx(total_distance))) {
116
// Zero-length line, nothing to build.
117
return;
118
}
119
120
if (_interpolate_color) {
121
color0 = gradient->get_color(0);
122
} else {
123
colors.push_back(default_color);
124
}
125
126
float uvx0 = 0.f;
127
float uvx1 = 0.f;
128
129
pos_up0 += u0 * modified_hw;
130
pos_down0 -= u0 * modified_hw;
131
132
// Begin cap
133
if (!wrap_around) {
134
if (begin_cap_mode == Line2D::LINE_CAP_BOX) {
135
// Push back first vertices a little bit.
136
pos_up0 -= f0 * modified_hw;
137
pos_down0 -= f0 * modified_hw;
138
139
current_distance0 += modified_hw;
140
current_distance1 = current_distance0;
141
} else if (begin_cap_mode == Line2D::LINE_CAP_ROUND) {
142
if (texture_mode == Line2D::LINE_TEXTURE_TILE) {
143
uvx0 = width_factor * 0.5f / tile_aspect;
144
} else if (texture_mode == Line2D::LINE_TEXTURE_STRETCH) {
145
uvx0 = width * width_factor / total_distance;
146
}
147
new_arc(pos0, pos_up0 - pos0, -Math::PI, color0, Rect2(0.f, 0.f, uvx0 * 2, 1.f));
148
current_distance0 += modified_hw;
149
current_distance1 = current_distance0;
150
}
151
strip_begin(pos_up0, pos_down0, color0, uvx0);
152
}
153
154
/*
155
* pos_up0 ------------- pos_up1 --------------------
156
* | |
157
* pos0 - - - - - - - - - pos1 - - - - - - - - - pos2
158
* | |
159
* pos_down0 ------------ pos_down1 ------------------
160
*
161
* i-1 i i+1
162
*/
163
164
// http://labs.hyperandroid.com/tag/opengl-lines
165
// (not the same implementation but visuals help a lot)
166
167
// If the polyline wraps around, then draw two more segments with joints:
168
// The last one, which should normally end with an end cap, and the one that matches the end and the beginning.
169
int segments_count = wrap_around ? point_count : (point_count - 2);
170
// The wraparound case starts with a "fake walk" from the end of the polyline
171
// to its beginning, so that its first joint is correct, without drawing anything.
172
int first_point = wrap_around ? -1 : 1;
173
174
// If the line wraps around, these variables will be used for the final segment.
175
Vector2 first_pos_up, first_pos_down;
176
bool is_first_joint_sharp = false;
177
178
// For each additional segment
179
for (int i = first_point; i <= segments_count; ++i) {
180
pos1 = points[(i == -1) ? point_count - 1 : i % point_count]; // First point.
181
Vector2 pos2 = points[(i + 1) % point_count]; // Second point.
182
183
Vector2 f1 = (pos2 - pos1).normalized();
184
Vector2 u1 = f1.orthogonal();
185
186
// Determine joint orientation.
187
float dp = u0.dot(f1);
188
const Orientation orientation = (dp > 0.f ? UP : DOWN);
189
190
if (distance_required && i >= 1) {
191
current_distance1 += pos0.distance_to(pos1);
192
}
193
if (_interpolate_color) {
194
color1 = gradient->get_color_at_offset(current_distance1 / total_distance);
195
}
196
if (retrieve_curve) {
197
width_factor = curve->sample_baked(current_distance1 / total_distance);
198
modified_hw = hw * width_factor;
199
}
200
201
Vector2 inner_normal0 = u0 * modified_hw;
202
Vector2 inner_normal1 = u1 * modified_hw;
203
if (orientation == DOWN) {
204
inner_normal0 = -inner_normal0;
205
inner_normal1 = -inner_normal1;
206
}
207
208
/*
209
* ---------------------------
210
* /
211
* 0 / 1
212
* / /
213
* --------------------x------ /
214
* / / (here shown with orientation == DOWN)
215
* / /
216
* / /
217
* / /
218
* 2 /
219
* /
220
*/
221
222
// Find inner intersection at the joint.
223
Vector2 corner_pos_in, corner_pos_out;
224
bool is_intersecting = Geometry2D::segment_intersects_segment(
225
pos0 + inner_normal0, pos1 + inner_normal0,
226
pos1 + inner_normal1, pos2 + inner_normal1,
227
&corner_pos_in);
228
229
if (is_intersecting) {
230
// Inner parts of the segments intersect.
231
corner_pos_out = 2.f * pos1 - corner_pos_in;
232
} else {
233
// No intersection, segments are too sharp or they overlap.
234
corner_pos_in = pos1 + inner_normal0;
235
corner_pos_out = pos1 - inner_normal0;
236
}
237
238
Vector2 corner_pos_up, corner_pos_down;
239
if (orientation == UP) {
240
corner_pos_up = corner_pos_in;
241
corner_pos_down = corner_pos_out;
242
} else {
243
corner_pos_up = corner_pos_out;
244
corner_pos_down = corner_pos_in;
245
}
246
247
Line2D::LineJointMode current_joint_mode = joint_mode;
248
249
Vector2 pos_up1, pos_down1;
250
if (is_intersecting) {
251
// Fallback on bevel if sharp angle is too high (because it would produce very long miters).
252
float width_factor_sq = width_factor * width_factor;
253
if (current_joint_mode == Line2D::LINE_JOINT_SHARP && corner_pos_out.distance_squared_to(pos1) / (hw_sq * width_factor_sq) > sharp_limit_sq) {
254
current_joint_mode = Line2D::LINE_JOINT_BEVEL;
255
}
256
if (current_joint_mode == Line2D::LINE_JOINT_SHARP) {
257
// In this case, we won't create joint geometry,
258
// The previous and next line quads will directly share an edge.
259
pos_up1 = corner_pos_up;
260
pos_down1 = corner_pos_down;
261
} else {
262
// Bevel or round
263
if (orientation == UP) {
264
pos_up1 = corner_pos_up;
265
pos_down1 = pos1 - u0 * modified_hw;
266
} else {
267
pos_up1 = pos1 + u0 * modified_hw;
268
pos_down1 = corner_pos_down;
269
}
270
}
271
} else {
272
// No intersection: fallback
273
if (current_joint_mode == Line2D::LINE_JOINT_SHARP) {
274
// There is no fallback implementation for LINE_JOINT_SHARP so switch to the LINE_JOINT_BEVEL.
275
current_joint_mode = Line2D::LINE_JOINT_BEVEL;
276
}
277
pos_up1 = corner_pos_up;
278
pos_down1 = corner_pos_down;
279
}
280
281
// Triangles are clockwise.
282
if (texture_mode == Line2D::LINE_TEXTURE_TILE) {
283
uvx1 = current_distance1 / (width * tile_aspect);
284
} else if (texture_mode == Line2D::LINE_TEXTURE_STRETCH) {
285
uvx1 = current_distance1 / total_distance;
286
}
287
288
// Swap vars for use in the next line.
289
color0 = color1;
290
u0 = u1;
291
f0 = f1;
292
pos0 = pos1;
293
if (is_intersecting) {
294
if (current_joint_mode == Line2D::LINE_JOINT_SHARP) {
295
pos_up0 = pos_up1;
296
pos_down0 = pos_down1;
297
} else {
298
if (orientation == UP) {
299
pos_up0 = corner_pos_up;
300
pos_down0 = pos1 - u1 * modified_hw;
301
} else {
302
pos_up0 = pos1 + u1 * modified_hw;
303
pos_down0 = corner_pos_down;
304
}
305
}
306
} else {
307
pos_up0 = pos1 + u1 * modified_hw;
308
pos_down0 = pos1 - u1 * modified_hw;
309
}
310
311
// End the "fake pass" in the closed line case before the drawing subroutine.
312
if (i == -1) {
313
continue;
314
}
315
316
// For wrap-around polylines, store some kind of start positions of the first joint for the final connection.
317
if (wrap_around && i == 0) {
318
Vector2 first_pos_center = (pos_up1 + pos_down1) / 2;
319
float lerp_factor = 1.0 / width_factor;
320
first_pos_up = first_pos_center.lerp(pos_up1, lerp_factor);
321
first_pos_down = first_pos_center.lerp(pos_down1, lerp_factor);
322
is_first_joint_sharp = current_joint_mode == Line2D::LINE_JOINT_SHARP;
323
}
324
325
// Add current line body quad.
326
if (wrap_around && retrieve_curve && !is_first_joint_sharp && i == segments_count) {
327
// If the width curve is not seamless, we might need to fetch the line's start points to use them for the final connection.
328
Vector2 first_pos_center = (first_pos_up + first_pos_down) / 2;
329
strip_add_quad(first_pos_center.lerp(first_pos_up, width_factor), first_pos_center.lerp(first_pos_down, width_factor), color1, uvx1);
330
return;
331
} else {
332
strip_add_quad(pos_up1, pos_down1, color1, uvx1);
333
}
334
335
// From this point, bu0 and bd0 concern the next segment.
336
// Add joint geometry.
337
if (current_joint_mode != Line2D::LINE_JOINT_SHARP) {
338
/* ________________ cbegin
339
* / \
340
* / \
341
* ____________/_ _ _\ cend
342
* | |
343
* | |
344
* | |
345
*/
346
347
Vector2 cbegin, cend;
348
if (orientation == UP) {
349
cbegin = pos_down1;
350
cend = pos_down0;
351
} else {
352
cbegin = pos_up1;
353
cend = pos_up0;
354
}
355
356
if (current_joint_mode == Line2D::LINE_JOINT_BEVEL && !(wrap_around && i == segments_count)) {
357
strip_add_tri(cend, orientation);
358
} else if (current_joint_mode == Line2D::LINE_JOINT_ROUND && !(wrap_around && i == segments_count)) {
359
Vector2 vbegin = cbegin - pos1;
360
Vector2 vend = cend - pos1;
361
// We want to use vbegin.angle_to(vend) below, which evaluates to
362
// Math::atan2(vbegin.cross(vend), vbegin.dot(vend)) but we need to
363
// calculate this ourselves as we need to check if the cross product
364
// in that calculation ends up being -0.f and flip it if so, effectively
365
// flipping the resulting angle_delta to not return -PI but +PI instead
366
float cross_product = vbegin.cross(vend);
367
float dot_product = vbegin.dot(vend);
368
// Note that we're comparing against -0.f for clarity but 0.f would
369
// match as well, therefore we need the explicit signbit check too.
370
if (cross_product == -0.f && std::signbit(cross_product)) {
371
cross_product = 0.f;
372
}
373
float angle_delta = Math::atan2(cross_product, dot_product);
374
strip_add_arc(pos1, angle_delta, orientation);
375
}
376
377
if (!is_intersecting) {
378
// In this case the joint is too corrupted to be reused,
379
// start again the strip with fallback points
380
strip_begin(pos_up0, pos_down0, color1, uvx1);
381
}
382
}
383
}
384
385
// Draw the last (or only) segment, with its end cap logic.
386
if (!wrap_around) {
387
pos1 = points[point_count - 1];
388
389
if (distance_required) {
390
current_distance1 += pos0.distance_to(pos1);
391
}
392
if (_interpolate_color) {
393
color1 = gradient->get_color(gradient->get_point_count() - 1);
394
}
395
if (retrieve_curve) {
396
width_factor = curve->sample_baked(1.f);
397
modified_hw = hw * width_factor;
398
}
399
400
Vector2 pos_up1 = pos1 + u0 * modified_hw;
401
Vector2 pos_down1 = pos1 - u0 * modified_hw;
402
403
// Add extra distance for a box end cap.
404
if (end_cap_mode == Line2D::LINE_CAP_BOX) {
405
pos_up1 += f0 * modified_hw;
406
pos_down1 += f0 * modified_hw;
407
408
current_distance1 += modified_hw;
409
}
410
411
if (texture_mode == Line2D::LINE_TEXTURE_TILE) {
412
uvx1 = current_distance1 / (width * tile_aspect);
413
} else if (texture_mode == Line2D::LINE_TEXTURE_STRETCH) {
414
uvx1 = current_distance1 / total_distance;
415
}
416
417
strip_add_quad(pos_up1, pos_down1, color1, uvx1);
418
419
// Custom drawing for a round end cap.
420
if (end_cap_mode == Line2D::LINE_CAP_ROUND) {
421
// Note: color is not used in case we don't interpolate.
422
Color color = _interpolate_color ? gradient->get_color(gradient->get_point_count() - 1) : Color(0, 0, 0);
423
float dist = 0;
424
if (texture_mode == Line2D::LINE_TEXTURE_TILE) {
425
dist = width_factor / tile_aspect;
426
} else if (texture_mode == Line2D::LINE_TEXTURE_STRETCH) {
427
dist = width * width_factor / total_distance;
428
}
429
new_arc(pos1, pos_up1 - pos1, Math::PI, color, Rect2(uvx1 - 0.5f * dist, 0.f, dist, 1.f));
430
}
431
}
432
}
433
434
void LineBuilder::strip_begin(Vector2 up, Vector2 down, Color color, float uvx) {
435
int vi = vertices.size();
436
437
vertices.push_back(up);
438
vertices.push_back(down);
439
440
if (_interpolate_color) {
441
colors.push_back(color);
442
colors.push_back(color);
443
}
444
445
if (texture_mode != Line2D::LINE_TEXTURE_NONE) {
446
uvs.push_back(Vector2(uvx, 0.f));
447
uvs.push_back(Vector2(uvx, 1.f));
448
}
449
450
_last_index[UP] = vi;
451
_last_index[DOWN] = vi + 1;
452
}
453
454
void LineBuilder::strip_add_quad(Vector2 up, Vector2 down, Color color, float uvx) {
455
int vi = vertices.size();
456
457
vertices.push_back(up);
458
vertices.push_back(down);
459
460
if (_interpolate_color) {
461
colors.push_back(color);
462
colors.push_back(color);
463
}
464
465
if (texture_mode != Line2D::LINE_TEXTURE_NONE) {
466
uvs.push_back(Vector2(uvx, 0.f));
467
uvs.push_back(Vector2(uvx, 1.f));
468
}
469
470
indices.push_back(_last_index[UP]);
471
indices.push_back(vi + 1);
472
indices.push_back(_last_index[DOWN]);
473
indices.push_back(_last_index[UP]);
474
indices.push_back(vi);
475
indices.push_back(vi + 1);
476
477
_last_index[UP] = vi;
478
_last_index[DOWN] = vi + 1;
479
}
480
481
void LineBuilder::strip_add_tri(Vector2 up, Orientation orientation) {
482
int vi = vertices.size();
483
484
vertices.push_back(up);
485
486
if (_interpolate_color) {
487
colors.push_back(colors[colors.size() - 1]);
488
}
489
490
Orientation opposite_orientation = orientation == UP ? DOWN : UP;
491
492
if (texture_mode != Line2D::LINE_TEXTURE_NONE) {
493
// UVs are just one slice of the texture all along
494
// (otherwise we can't share the bottom vertex)
495
uvs.push_back(uvs[_last_index[opposite_orientation]]);
496
}
497
498
indices.push_back(_last_index[opposite_orientation]);
499
indices.push_back(vi);
500
indices.push_back(_last_index[orientation]);
501
502
_last_index[opposite_orientation] = vi;
503
}
504
505
void LineBuilder::strip_add_arc(Vector2 center, float angle_delta, Orientation orientation) {
506
// Take the two last vertices and extrude an arc made of triangles
507
// that all share one of the initial vertices
508
509
Orientation opposite_orientation = orientation == UP ? DOWN : UP;
510
Vector2 vbegin = vertices[_last_index[opposite_orientation]] - center;
511
float radius = vbegin.length();
512
float angle_step = Math::PI / static_cast<float>(round_precision);
513
float steps = Math::abs(angle_delta) / angle_step;
514
515
if (angle_delta < 0.f) {
516
angle_step = -angle_step;
517
}
518
519
float t = Vector2(1, 0).angle_to(vbegin);
520
float end_angle = t + angle_delta;
521
Vector2 rpos(0, 0);
522
523
// Arc vertices
524
for (int ti = 0; ti < steps; ++ti, t += angle_step) {
525
rpos = center + Vector2(Math::cos(t), Math::sin(t)) * radius;
526
strip_add_tri(rpos, orientation);
527
}
528
529
// Last arc vertex
530
rpos = center + Vector2(Math::cos(end_angle), Math::sin(end_angle)) * radius;
531
strip_add_tri(rpos, orientation);
532
}
533
534
void LineBuilder::new_arc(Vector2 center, Vector2 vbegin, float angle_delta, Color color, Rect2 uv_rect) {
535
// Make a standalone arc that doesn't use existing vertices,
536
// with undistorted UVs from within a square section
537
538
float radius = vbegin.length();
539
float angle_step = Math::PI / static_cast<float>(round_precision);
540
float steps = Math::abs(angle_delta) / angle_step;
541
542
if (angle_delta < 0.f) {
543
angle_step = -angle_step;
544
}
545
546
float t = Vector2(1, 0).angle_to(vbegin);
547
float end_angle = t + angle_delta;
548
Vector2 rpos(0, 0);
549
float tt_begin = -Math::PI / 2.0f;
550
float tt = tt_begin;
551
552
// Center vertice
553
int vi = vertices.size();
554
vertices.push_back(center);
555
if (_interpolate_color) {
556
colors.push_back(color);
557
}
558
if (texture_mode != Line2D::LINE_TEXTURE_NONE) {
559
uvs.push_back(interpolate(uv_rect, Vector2(0.5f, 0.5f)));
560
}
561
562
// Arc vertices
563
for (int ti = 0; ti < steps; ++ti, t += angle_step) {
564
Vector2 sc = Vector2(Math::cos(t), Math::sin(t));
565
rpos = center + sc * radius;
566
567
vertices.push_back(rpos);
568
if (_interpolate_color) {
569
colors.push_back(color);
570
}
571
if (texture_mode != Line2D::LINE_TEXTURE_NONE) {
572
Vector2 tsc = Vector2(Math::cos(tt), Math::sin(tt));
573
uvs.push_back(interpolate(uv_rect, 0.5f * (tsc + Vector2(1.f, 1.f))));
574
tt += angle_step;
575
}
576
}
577
578
// Last arc vertex
579
Vector2 sc = Vector2(Math::cos(end_angle), Math::sin(end_angle));
580
rpos = center + sc * radius;
581
vertices.push_back(rpos);
582
if (_interpolate_color) {
583
colors.push_back(color);
584
}
585
if (texture_mode != Line2D::LINE_TEXTURE_NONE) {
586
tt = tt_begin + angle_delta;
587
Vector2 tsc = Vector2(Math::cos(tt), Math::sin(tt));
588
uvs.push_back(interpolate(uv_rect, 0.5f * (tsc + Vector2(1.f, 1.f))));
589
}
590
591
// Make up triangles
592
int vi0 = vi;
593
for (int ti = 0; ti < steps; ++ti) {
594
indices.push_back(vi0);
595
indices.push_back(++vi);
596
indices.push_back(vi + 1);
597
}
598
}
599
600