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 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
|
/*
* This program source code file is part of KICAD, a free EDA CAD application.
*
* Copyright (C) 2016 Kicad Developers, see change_log.txt for contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* or you may search the http://www.gnu.org website for the version 2 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "gl_builtin_shaders.h"
namespace KIGFX {
namespace BUILTIN_SHADERS {
/*
*
* KiCad shaders
*
*/
const char kicad_vertex_shader[] = R"SHADER_SOURCE(
/*
* This program source code file is part of KICAD, a free EDA CAD application.
*
* Copyright (C) 2013-2016 CERN
* @author Maciej Suminski <maciej.suminski@cern.ch>
*
* Vertex shader
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* or you may search the http://www.gnu.org website for the version 2 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#version 120
// Shader types
const float SHADER_LINE = 1.0;
const float SHADER_FILLED_CIRCLE = 2.0;
const float SHADER_STROKED_CIRCLE = 3.0;
const float SHADER_FONT = 4.0;
// Minimum line width
const float MIN_WIDTH = 1.0;
attribute vec4 attrShaderParams;
varying vec4 shaderParams;
varying vec2 circleCoords;
void main()
{
// Pass attributes to the fragment shader
shaderParams = attrShaderParams;
if( shaderParams[0] == SHADER_LINE )
{
float lineWidth = shaderParams[3];
float worldScale = abs( gl_ModelViewMatrix[0][0] );
// Make lines appear to be at least 1 pixel wide
if( worldScale * lineWidth < MIN_WIDTH )
gl_Position = gl_ModelViewProjectionMatrix *
( gl_Vertex + vec4( shaderParams.yz * MIN_WIDTH / ( worldScale * lineWidth ), 0.0, 0.0 ) );
else
gl_Position = gl_ModelViewProjectionMatrix *
( gl_Vertex + vec4( shaderParams.yz, 0.0, 0.0 ) );
}
else if( ( shaderParams[0] == SHADER_STROKED_CIRCLE ) ||
( shaderParams[0] == SHADER_FILLED_CIRCLE ) )
{
// Compute relative circle coordinates basing on indices
// Circle
if( shaderParams[1] == 1.0 )
circleCoords = vec2( -sqrt( 3.0 ), -1.0 );
else if( shaderParams[1] == 2.0 )
circleCoords = vec2( sqrt( 3.0 ), -1.0 );
else if( shaderParams[1] == 3.0 )
circleCoords = vec2( 0.0, 2.0 );
// Semicircle
else if( shaderParams[1] == 4.0 )
circleCoords = vec2( -3.0 / sqrt( 3.0 ), 0.0 );
else if( shaderParams[1] == 5.0 )
circleCoords = vec2( 3.0 / sqrt( 3.0 ), 0.0 );
else if( shaderParams[1] == 6.0 )
circleCoords = vec2( 0.0, 2.0 );
// Make the line appear to be at least 1 pixel wide
float lineWidth = shaderParams[3];
float worldScale = abs( gl_ModelViewMatrix[0][0] );
if( worldScale * lineWidth < MIN_WIDTH )
shaderParams[3] = shaderParams[3] / ( worldScale * lineWidth );
gl_Position = ftransform();
}
else
{
// Pass through the coordinates like in the fixed pipeline
gl_Position = ftransform();
}
gl_FrontColor = gl_Color;
}
)SHADER_SOURCE";
const char kicad_fragment_shader[] = R"SHADER_SOURCE(
/*
* This program source code file is part of KICAD, a free EDA CAD application.
*
* Copyright (C) 2013-2016 CERN
* Copyright (C) 2016 Kicad Developers, see authors.txt for contributors.
* @author Maciej Suminski <maciej.suminski@cern.ch>
*
* Fragment shader
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* or you may search the http://www.gnu.org website for the version 2 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#version 120
// Multi-channel signed distance field
#define USE_MSDF
// Shader types
const float SHADER_LINE = 1.0;
const float SHADER_FILLED_CIRCLE = 2.0;
const float SHADER_STROKED_CIRCLE = 3.0;
const float SHADER_FONT = 4.0;
varying vec4 shaderParams;
varying vec2 circleCoords;
uniform sampler2D fontTexture;
// Needed to reconstruct the mipmap level / texel derivative
uniform int fontTextureWidth;
void filledCircle( vec2 aCoord )
{
if( dot( aCoord, aCoord ) < 1.0 )
gl_FragColor = gl_Color;
else
discard;
}
void strokedCircle( vec2 aCoord, float aRadius, float aWidth )
{
float outerRadius = max( aRadius + ( aWidth / 2 ), 0.0 );
float innerRadius = max( aRadius - ( aWidth / 2 ), 0.0 );
float relWidth = innerRadius / outerRadius;
if( ( dot( aCoord, aCoord ) < 1.0 ) &&
( dot( aCoord, aCoord ) > relWidth * relWidth ) )
gl_FragColor = gl_Color;
else
discard;
}
#ifdef USE_MSDF
float median( vec3 v )
{
return max( min( v.r, v.g ), min( max( v.r, v.g ), v.b ) );
}
#endif
void main()
{
if( shaderParams[0] == SHADER_FILLED_CIRCLE )
{
filledCircle( circleCoords );
}
else if( shaderParams[0] == SHADER_STROKED_CIRCLE )
{
strokedCircle( circleCoords, shaderParams[2], shaderParams[3] );
}
else if( shaderParams[0] == SHADER_FONT )
{
vec2 tex = shaderParams.yz;
// Unless we're stretching chars it is okay to consider
// one derivative for filtering
float derivative = length( dFdx( tex ) ) * fontTextureWidth / 4;
#ifdef USE_MSDF
float dist = median( texture2D( fontTexture, tex ).rgb );
#else
float dist = texture2D( fontTexture, tex ).r;
#endif
// use the derivative for zoom-adaptive filtering
float alpha = smoothstep( 0.5 - derivative, 0.5 + derivative, dist );
gl_FragColor = vec4( gl_Color.rgb, alpha );
}
else
{
// Simple pass-through
gl_FragColor = gl_Color;
}
}
)SHADER_SOURCE";
const char ssaa_x4_vertex_shader[] = R"SHADER_SOURCE(
#version 120
varying vec2 texcoord;
void main()
{
texcoord = gl_MultiTexCoord0.st;
gl_Position = ftransform();
}
)SHADER_SOURCE";
const char ssaa_x4_fragment_shader[] = R"SHADER_SOURCE(
#version 120
varying vec2 texcoord;
uniform sampler2D source;
void main()
{
float step_x = dFdx(texcoord.x)/4.;
float step_y = dFdy(texcoord.y)/4.;
vec4 q00 = texture2D( source, texcoord + vec2(-step_x, -step_y) );
vec4 q01 = texture2D( source, texcoord + vec2( step_x, -step_y) );
vec4 q10 = texture2D( source, texcoord + vec2(-step_x, step_y) );
vec4 q11 = texture2D( source, texcoord + vec2( step_x, step_y) );
gl_FragColor = (q00+q01+q10+q11)/4;
}
)SHADER_SOURCE";
const char smaa_base_shader_p1[] = R"SHADER_SOURCE(
/**
* Copyright (C) 2013 Jorge Jimenez (jorge@iryoku.com)
* Copyright (C) 2013 Jose I. Echevarria (joseignacioechevarria@gmail.com)
* Copyright (C) 2013 Belen Masia (bmasia@unizar.es)
* Copyright (C) 2013 Fernando Navarro (fernandn@microsoft.com)
* Copyright (C) 2013 Diego Gutierrez (diegog@unizar.es)
*
* Made compatible to OpenGL 2.1 (KiCad Developers 2016)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to
* do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. As clarification, there
* is no requirement that the copyright notice and permission be included in
* binary distributions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* _______ ___ ___ ___ ___
* / || \/ | / \ / \
* | (---- | \ / | / ^ \ / ^ \
* \ \ | |\/| | / /_\ \ / /_\ \
* ----) | | | | | / _____ \ / _____ \
* |_______/ |__| |__| /__/ \__\ /__/ \__\
*
* E N H A N C E D
* S U B P I X E L M O R P H O L O G I C A L A N T I A L I A S I N G
*
* http://www.iryoku.com/smaa/
*
* Hi, welcome aboard!
*
* Here you'll find instructions to get the shader up and running as fast as
* possible.
*
* IMPORTANTE NOTICE: when updating, remember to update both this file and the
* precomputed textures! They may change from version to version.
*
* The shader has three passes, chained together as follows:
*
* |input|------------------\
* v |
* [ SMAA*EdgeDetection ] |
* v |
* |edgesTex| |
* v |
* [ SMAABlendingWeightCalculation ] |
* v |
* |blendTex| |
* v |
* [ SMAANeighborhoodBlending ] <------/
* v
* |output|
*
* Note that each [pass] has its own vertex and pixel shader. Remember to use
* oversized triangles instead of quads to avoid overshading along the
* diagonal.
*
* You've three edge detection methods to choose from: luma, color or depth.
* They represent different quality/performance and anti-aliasing/sharpness
* tradeoffs, so our recommendation is for you to choose the one that best
* suits your particular scenario:
*
* - Depth edge detection is usually the fastest but it may miss some edges.
*
* - Luma edge detection is usually more expensive than depth edge detection,
* but catches visible edges that depth edge detection can miss.
*
* - Color edge detection is usually the most expensive one but catches
* chroma-only edges.
*
* For quickstarters: just use luma edge detection.
*
* The general advice is to not rush the integration process and ensure each
* step is done correctly (don't try to integrate SMAA T2x with predicated edge
* detection from the start!). Ok then, let's go!
*
* 1. The first step is to create two RGBA temporal render targets for holding
* |edgesTex| and |blendTex|.
*
* In DX10 or DX11, you can use a RG render target for the edges texture.
* In the case of NVIDIA GPUs, using RG render targets seems to actually be
* slower.
*
* On the Xbox 360, you can use the same render target for resolving both
* |edgesTex| and |blendTex|, as they aren't needed simultaneously.
*
* 2. Both temporal render targets |edgesTex| and |blendTex| must be cleared
* each frame. Do not forget to clear the alpha channel!
*
* 3. The next step is loading the two supporting precalculated textures,
* 'areaTex' and 'searchTex'. You'll find them in the 'Textures' folder as
* C++ headers, and also as regular DDS files. They'll be needed for the
* 'SMAABlendingWeightCalculation' pass.
*
* If you use the C++ headers, be sure to load them in the format specified
* inside of them.
*
* You can also compress 'areaTex' and 'searchTex' using BC5 and BC4
* respectively, if you have that option in your content processor pipeline.
* When compressing then, you get a non-perceptible quality decrease, and a
* marginal performance increase.
*
* 4. All samplers must be set to linear filtering and clamp.
*
* After you get the technique working, remember that 64-bit inputs have
* half-rate linear filtering on GCN.
*
* If SMAA is applied to 64-bit color buffers, switching to point filtering
* when accessing them will increase the performance. Search for
* 'SMAASamplePoint' to see which textures may benefit from point
* filtering, and where (which is basically the color input in the edge
* detection and resolve passes).
*
* 5. All texture reads and buffer writes must be non-sRGB, with the exception
* of the input read and the output write in
* 'SMAANeighborhoodBlending' (and only in this pass!). If sRGB reads in
* this last pass are not possible, the technique will work anyway, but
* will perform antialiasing in gamma space.
*
* IMPORTANT: for best results the input read for the color/luma edge
* detection should *NOT* be sRGB.
*
* 6. Before including SMAA.h you'll have to setup the render target metrics,
* the target and any optional configuration defines. Optionally you can
* use a preset.
*
* You have the following targets available:
* SMAA_HLSL_3
* SMAA_HLSL_4
* SMAA_HLSL_4_1
* SMAA_GLSL_3 *
* SMAA_GLSL_4 *
*
* * (See SMAA_INCLUDE_VS and SMAA_INCLUDE_PS below).
*
* And four presets:
* SMAA_PRESET_LOW (%60 of the quality)
* SMAA_PRESET_MEDIUM (%80 of the quality)
* SMAA_PRESET_HIGH (%95 of the quality)
* SMAA_PRESET_ULTRA (%99 of the quality)
*
* For example:
* #define SMAA_RT_METRICS float4(1.0 / 1280.0, 1.0 / 720.0, 1280.0, 720.0)
* #define SMAA_HLSL_4
* #define SMAA_PRESET_HIGH
* #include "SMAA.h"
*
* Note that SMAA_RT_METRICS doesn't need to be a macro, it can be a
* uniform variable. The code is designed to minimize the impact of not
* using a constant value, but it is still better to hardcode it.
*
* Depending on how you encoded 'areaTex' and 'searchTex', you may have to
* add (and customize) the following defines before including SMAA.h:
* #define SMAA_AREATEX_SELECT(sample) sample.rg
* #define SMAA_SEARCHTEX_SELECT(sample) sample.r
*
* If your engine is already using porting macros, you can define
* SMAA_CUSTOM_SL, and define the porting functions by yourself.
*
* 7. Then, you'll have to setup the passes as indicated in the scheme above.
* You can take a look into SMAA.fx, to see how we did it for our demo.
* Checkout the function wrappers, you may want to copy-paste them!
*
* 8. It's recommended to validate the produced |edgesTex| and |blendTex|.
* You can use a screenshot from your engine to compare the |edgesTex|
* and |blendTex| produced inside of the engine with the results obtained
* with the reference demo.
*
* 9. After you get the last pass to work, it's time to optimize. You'll have
* to initialize a stencil buffer in the first pass (discard is already in
* the code), then mask execution by using it the second pass. The last
* pass should be executed in all pixels.
*
*
* After this point you can choose to enable predicated thresholding,
* temporal supersampling and motion blur integration:
*
* a) If you want to use predicated thresholding, take a look into
* SMAA_PREDICATION; you'll need to pass an extra texture in the edge
* detection pass.
*
* b) If you want to enable temporal supersampling (SMAA T2x):
*
* 1. The first step is to render using subpixel jitters. I won't go into
* detail, but it's as simple as moving each vertex position in the
* vertex shader, you can check how we do it in our DX10 demo.
*
* 2. Then, you must setup the temporal resolve. You may want to take a look
* into SMAAResolve for resolving 2x modes. After you get it working, you'll
* probably see ghosting everywhere. But fear not, you can enable the
* CryENGINE temporal reprojection by setting the SMAA_REPROJECTION macro.
* Check out SMAA_DECODE_VELOCITY if your velocity buffer is encoded.
*
* 3. The next step is to apply SMAA to each subpixel jittered frame, just as
* done for 1x.
*
* 4. At this point you should already have something usable, but for best
* results the proper area textures must be set depending on current jitter.
* For this, the parameter 'subsampleIndices' of
* 'SMAABlendingWeightCalculationPS' must be set as follows, for our T2x
* mode:
*
* @SUBSAMPLE_INDICES
*
* | S# | Camera Jitter | subsampleIndices |
* +----+------------------+---------------------+
* | 0 | ( 0.25, -0.25) | float4(1, 1, 1, 0) |
* | 1 | (-0.25, 0.25) | float4(2, 2, 2, 0) |
*
* These jitter positions assume a bottom-to-top y axis. S# stands for the
* sample number.
*
* More information about temporal supersampling here:
* http://iryoku.com/aacourse/downloads/13-Anti-Aliasing-Methods-in-CryENGINE-3.pdf
*
* c) If you want to enable spatial multisampling (SMAA S2x):
*
* 1. The scene must be rendered using MSAA 2x. The MSAA 2x buffer must be
* created with:
* - DX10: see below (*)
* - DX10.1: D3D10_STANDARD_MULTISAMPLE_PATTERN or
* - DX11: D3D11_STANDARD_MULTISAMPLE_PATTERN
*
* This allows one to ensure that the subsample order matches the table in
* @SUBSAMPLE_INDICES.
*
* (*) In the case of DX10, we refer the reader to:
* - SMAA::detectMSAAOrder and
* - SMAA::msaaReorder
*
* These functions allows one to match the standard multisample patterns by
* detecting the subsample order for a specific GPU, and reordering
* them appropriately.
*
* 2. A shader must be run to output each subsample into a separate buffer
* (DX10 is required). You can use SMAASeparate for this purpose, or just do
* it in an existing pass (for example, in the tone mapping pass, which has
* the advantage of feeding tone mapped subsamples to SMAA, which will yield
* better results).
*
* 3. The full SMAA 1x pipeline must be run for each separated buffer, storing
* the results in the final buffer. The second run should alpha blend with
* the existing final buffer using a blending factor of 0.5.
* 'subsampleIndices' must be adjusted as in the SMAA T2x case (see point
* b).
*
* d) If you want to enable temporal supersampling on top of SMAA S2x
* (which actually is SMAA 4x):
*
* 1. SMAA 4x consists on temporally jittering SMAA S2x, so the first step is
* to calculate SMAA S2x for current frame. In this case, 'subsampleIndices'
* must be set as follows:
*
* | F# | S# | Camera Jitter | Net Jitter | subsampleIndices |
* +----+----+--------------------+-------------------+----------------------+
* | 0 | 0 | ( 0.125, 0.125) | ( 0.375, -0.125) | float4(5, 3, 1, 3) |
* | 0 | 1 | ( 0.125, 0.125) | (-0.125, 0.375) | float4(4, 6, 2, 3) |
* +----+----+--------------------+-------------------+----------------------+
* | 1 | 2 | (-0.125, -0.125) | ( 0.125, -0.375) | float4(3, 5, 1, 4) |
* | 1 | 3 | (-0.125, -0.125) | (-0.375, 0.125) | float4(6, 4, 2, 4) |
*
* These jitter positions assume a bottom-to-top y axis. F# stands for the
* frame number. S# stands for the sample number.
*
* 2. After calculating SMAA S2x for current frame (with the new subsample
* indices), previous frame must be reprojected as in SMAA T2x mode (see
* point b).
*
* e) If motion blur is used, you may want to do the edge detection pass
* together with motion blur. This has two advantages:
*
* 1. Pixels under heavy motion can be omitted from the edge detection process.
* For these pixels we can just store "no edge", as motion blur will take
* care of them.
* 2. The center pixel tap is reused.
*
* Note that in this case depth testing should be used instead of stenciling,
* as we have to write all the pixels in the motion blur pass.
*
* That's it!
*/
//-----------------------------------------------------------------------------
// SMAA Presets
/**
* Note that if you use one of these presets, the following configuration
* macros will be ignored if set in the "Configurable Defines" section.
*/
#if defined(SMAA_PRESET_LOW)
#define SMAA_THRESHOLD 0.15
#define SMAA_MAX_SEARCH_STEPS 4
#define SMAA_DISABLE_DIAG_DETECTION
#define SMAA_DISABLE_CORNER_DETECTION
#elif defined(SMAA_PRESET_MEDIUM)
#define SMAA_THRESHOLD 0.1
#define SMAA_MAX_SEARCH_STEPS 8
#define SMAA_DISABLE_DIAG_DETECTION
#define SMAA_DISABLE_CORNER_DETECTION
#elif defined(SMAA_PRESET_HIGH)
#define SMAA_THRESHOLD 0.1
#define SMAA_MAX_SEARCH_STEPS 16
#define SMAA_MAX_SEARCH_STEPS_DIAG 8
#define SMAA_CORNER_ROUNDING 25
#elif defined(SMAA_PRESET_ULTRA)
#define SMAA_THRESHOLD 0.005
//0.05
#define SMAA_MAX_SEARCH_STEPS 64
//32
#define SMAA_MAX_SEARCH_STEPS_DIAG 32
//16
#define SMAA_CORNER_ROUNDING 25
#endif
//-----------------------------------------------------------------------------
// Configurable Defines
/**
* SMAA_THRESHOLD specifies the threshold or sensitivity to edges.
* Lowering this value you will be able to detect more edges at the expense of
* performance.
*
* Range: [0, 0.5]
* 0.1 is a reasonable value, and allows one to catch most visible edges.
* 0.05 is a rather overkill value, that allows one to catch 'em all.
*
* If temporal supersampling is used, 0.2 could be a reasonable value, as low
* contrast edges are properly filtered by just 2x.
*/
#ifndef SMAA_THRESHOLD
#define SMAA_THRESHOLD 0.1
#endif
/**
* SMAA_DEPTH_THRESHOLD specifies the threshold for depth edge detection.
*
* Range: depends on the depth range of the scene.
*/
#ifndef SMAA_DEPTH_THRESHOLD
#define SMAA_DEPTH_THRESHOLD (0.1 * SMAA_THRESHOLD)
#endif
/**
* SMAA_MAX_SEARCH_STEPS specifies the maximum steps performed in the
* horizontal/vertical pattern searches, at each side of the pixel.
*
* In number of pixels, it's actually the double. So the maximum line length
* perfectly handled by, for example 16, is 64 (by perfectly, we meant that
* longer lines won't look as good, but still antialiased).
*
* Range: [0, 112]
*/
#ifndef SMAA_MAX_SEARCH_STEPS
#define SMAA_MAX_SEARCH_STEPS 16
#endif
)SHADER_SOURCE";
const char smaa_base_shader_p2[] = R"SHADER_SOURCE(
/**
* SMAA_MAX_SEARCH_STEPS_DIAG specifies the maximum steps performed in the
* diagonal pattern searches, at each side of the pixel. In this case we jump
* one pixel at time, instead of two.
*
* Range: [0, 20]
*
* On high-end machines it is cheap (between a 0.8x and 0.9x slower for 16
* steps), but it can have a significant impact on older machines.
*
* Define SMAA_DISABLE_DIAG_DETECTION to disable diagonal processing.
*/
#ifndef SMAA_MAX_SEARCH_STEPS_DIAG
#define SMAA_MAX_SEARCH_STEPS_DIAG 8
#endif
/**
* SMAA_CORNER_ROUNDING specifies how much sharp corners will be rounded.
*
* Range: [0, 100]
*
* Define SMAA_DISABLE_CORNER_DETECTION to disable corner processing.
*/
#ifndef SMAA_CORNER_ROUNDING
#define SMAA_CORNER_ROUNDING 25
#endif
/**
* If there is an neighbor edge that has SMAA_LOCAL_CONTRAST_FACTOR times
* bigger contrast than current edge, current edge will be discarded.
*
* This allows one to eliminate spurious crossing edges, and is based on the fact
* that, if there is too much contrast in a direction, that will hide
* perceptually contrast in the other neighbors.
*/
#ifndef SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR
#define SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR 2.0
#endif
/**
* Predicated thresholding allows one to better preserve texture details and to
* improve performance, by decreasing the number of detected edges using an
* additional buffer like the light accumulation buffer, object ids or even the
* depth buffer (the depth buffer usage may be limited to indoor or short range
* scenes).
*
* It locally decreases the luma or color threshold if an edge is found in an
* additional buffer (so the global threshold can be higher).
*
* This method was developed by Playstation EDGE MLAA team, and used in
* Killzone 3, by using the light accumulation buffer. More information here:
* http://iryoku.com/aacourse/downloads/06-MLAA-on-PS3.pptx
*/
#ifndef SMAA_PREDICATION
#define SMAA_PREDICATION 0
#endif
/**
* Threshold to be used in the additional predication buffer.
*
* Range: depends on the input, so you'll have to find the magic number that
* works for you.
*/
#ifndef SMAA_PREDICATION_THRESHOLD
#define SMAA_PREDICATION_THRESHOLD 0.01
#endif
/**
* How much to scale the global threshold used for luma or color edge
* detection when using predication.
*
* Range: [1, 5]
*/
#ifndef SMAA_PREDICATION_SCALE
#define SMAA_PREDICATION_SCALE 2.0
#endif
/**
* How much to locally decrease the threshold.
*
* Range: [0, 1]
*/
#ifndef SMAA_PREDICATION_STRENGTH
#define SMAA_PREDICATION_STRENGTH 0.4
#endif
/**
* Temporal reprojection allows one to remove ghosting artifacts when using
* temporal supersampling. We use the CryEngine 3 method which also introduces
* velocity weighting. This feature is of extreme importance for totally
* removing ghosting. More information here:
* http://iryoku.com/aacourse/downloads/13-Anti-Aliasing-Methods-in-CryENGINE-3.pdf
*
* Note that you'll need to setup a velocity buffer for enabling reprojection.
* For static geometry, saving the previous depth buffer is a viable
* alternative.
*/
#ifndef SMAA_REPROJECTION
#define SMAA_REPROJECTION 0
#endif
/**
* SMAA_REPROJECTION_WEIGHT_SCALE controls the velocity weighting. It allows one
* to remove ghosting trails behind the moving object, which are not removed by
* just using reprojection. Using low values will exhibit ghosting, while using
* high values will disable temporal supersampling under motion.
*
* Behind the scenes, velocity weighting removes temporal supersampling when
* the velocity of the subsamples differs (meaning they are different objects).
*
* Range: [0, 80]
*/
#ifndef SMAA_REPROJECTION_WEIGHT_SCALE
#define SMAA_REPROJECTION_WEIGHT_SCALE 30.0
#endif
/**
* On some compilers, discard cannot be used in vertex shaders. Thus, they need
* to be compiled separately.
*/
#ifndef SMAA_INCLUDE_VS
#define SMAA_INCLUDE_VS 1
#endif
#ifndef SMAA_INCLUDE_PS
#define SMAA_INCLUDE_PS 1
#endif
//-----------------------------------------------------------------------------
// Texture Access Defines
#ifndef SMAA_AREATEX_SELECT
#if defined(SMAA_HLSL_3)
#define SMAA_AREATEX_SELECT(sample) sample.ra
#else
#define SMAA_AREATEX_SELECT(sample) sample.rg
#endif
#endif
#ifndef SMAA_SEARCHTEX_SELECT
#define SMAA_SEARCHTEX_SELECT(sample) sample.r
#endif
#ifndef SMAA_DECODE_VELOCITY
#define SMAA_DECODE_VELOCITY(sample) sample.rg
#endif
//-----------------------------------------------------------------------------
// Non-Configurable Defines
#define SMAA_AREATEX_MAX_DISTANCE 16
#define SMAA_AREATEX_MAX_DISTANCE_DIAG 20
#define SMAA_AREATEX_PIXEL_SIZE (1.0 / float2(160.0, 560.0))
#define SMAA_AREATEX_SUBTEX_SIZE (1.0 / 7.0)
#define SMAA_SEARCHTEX_SIZE float2(66.0, 33.0)
#define SMAA_SEARCHTEX_PACKED_SIZE float2(64.0, 16.0)
#define SMAA_CORNER_ROUNDING_NORM (float(SMAA_CORNER_ROUNDING) / 100.0)
//-----------------------------------------------------------------------------
// Porting Functions
#if defined(SMAA_HLSL_3)
#define SMAATexture2D(tex) sampler2D tex
#define SMAATexturePass2D(tex) tex
#define SMAASampleLevelZero(tex, coord) tex2Dlod(tex, float4(coord, 0.0, 0.0))
#define SMAASampleLevelZeroPoint(tex, coord) tex2Dlod(tex, float4(coord, 0.0, 0.0))
#define SMAASampleLevelZeroOffset(tex, coord, offset) tex2Dlod(tex, float4(coord + offset * SMAA_RT_METRICS.xy, 0.0, 0.0))
#define SMAASample(tex, coord) tex2D(tex, coord)
#define SMAASamplePoint(tex, coord) tex2D(tex, coord)
#define SMAASampleOffset(tex, coord, offset) tex2D(tex, coord + offset * SMAA_RT_METRICS.xy)
#define SMAA_FLATTEN [flatten]
#define SMAA_BRANCH [branch]
#endif
#if defined(SMAA_HLSL_4) || defined(SMAA_HLSL_4_1)
SamplerState LinearSampler { Filter = MIN_MAG_LINEAR_MIP_POINT; AddressU = Clamp; AddressV = Clamp; };
SamplerState PointSampler { Filter = MIN_MAG_MIP_POINT; AddressU = Clamp; AddressV = Clamp; };
#define SMAATexture2D(tex) Texture2D tex
#define SMAATexturePass2D(tex) tex
#define SMAASampleLevelZero(tex, coord) tex.SampleLevel(LinearSampler, coord, 0)
#define SMAASampleLevelZeroPoint(tex, coord) tex.SampleLevel(PointSampler, coord, 0)
#define SMAASampleLevelZeroOffset(tex, coord, offset) tex.SampleLevel(LinearSampler, coord, 0, offset)
#define SMAASample(tex, coord) tex.Sample(LinearSampler, coord)
#define SMAASamplePoint(tex, coord) tex.Sample(PointSampler, coord)
#define SMAASampleOffset(tex, coord, offset) tex.Sample(LinearSampler, coord, offset)
#define SMAA_FLATTEN [flatten]
#define SMAA_BRANCH [branch]
#define SMAATexture2DMS2(tex) Texture2DMS<float4, 2> tex
#define SMAALoad(tex, pos, sample) tex.Load(pos, sample)
#if defined(SMAA_HLSL_4_1)
#define SMAAGather(tex, coord) tex.Gather(LinearSampler, coord, 0)
#endif
#endif
#if defined(SMAA_GLSL_2_1) || defined(SMAA_GLSL_3) || defined(SMAA_GLSL_4)
#define SMAATexture2D(tex) sampler2D tex
#define SMAATexturePass2D(tex) tex
#define SMAASampleLevelZero(tex, coord) textureLod(tex, coord, 0.0)
#define SMAASampleLevelZeroPoint(tex, coord) textureLod(tex, coord, 0.0)
#define SMAASampleLevelZeroOffset(tex, coord, offset) textureLodOffset(tex, coord, 0.0, offset)
#if defined(SMAA_GLSL_2_1)
#define SMAASample(tex, coord) texture2D(tex, coord)
#define SMAASamplePoint(tex, coord) texture2D(tex, coord)
#define SMAASampleOffset(tex, coord, offset) texture2D(tex, coord + offset * SMAA_RT_METRICS.rg)
#define round(x) floor(x + 0.5)
#define textureLod(tex, coord, level) texture2D(tex, coord)
#define textureLodOffset(tex, coord, level, offset) texture2D(tex, coord + offset * SMAA_RT_METRICS.rg)
#else
#define SMAASample(tex, coord) texture(tex, coord)
#define SMAASamplePoint(tex, coord) texture(tex, coord)
#define SMAASampleOffset(tex, coord, offset) texture(tex, coord, offset)
#endif
#define SMAA_FLATTEN
#define SMAA_BRANCH
#define lerp(a, b, t) mix(a, b, t)
#define saturate(a) clamp(a, 0.0, 1.0)
#if defined(SMAA_GLSL_4)
#define mad(a, b, c) fma(a, b, c)
#define SMAAGather(tex, coord) textureGather(tex, coord)
#else
#define mad(a, b, c) (a * b + c)
#endif
#define float2 vec2
#define float3 vec3
#define float4 vec4
#define int2 ivec2
#define int3 ivec3
#define int4 ivec4
#define bool2 bvec2
#define bool3 bvec3
#define bool4 bvec4
#endif
#if !defined(SMAA_HLSL_3) && !defined(SMAA_HLSL_4) && !defined(SMAA_HLSL_4_1) && !defined(SMAA_GLSL_2_1) && !defined(SMAA_GLSL_3) && !defined(SMAA_GLSL_4) && !defined(SMAA_CUSTOM_SL)
#error you must define the shading language: SMAA_HLSL_*, SMAA_GLSL_* or SMAA_CUSTOM_SL
#endif
//-----------------------------------------------------------------------------
// Misc functions
/**
* Gathers current pixel, and the top-left neighbors.
*/
float3 SMAAGatherNeighbours(float2 texcoord,
float4 offset[3],
SMAATexture2D(tex)) {
#ifdef SMAAGather
return SMAAGather(tex, texcoord + SMAA_RT_METRICS.xy * float2(-0.5, -0.5)).grb;
#else
float P = SMAASamplePoint(tex, texcoord).r;
float Pleft = SMAASamplePoint(tex, offset[0].xy).r;
float Ptop = SMAASamplePoint(tex, offset[0].zw).r;
return float3(P, Pleft, Ptop);
#endif
}
/**
* Adjusts the threshold by means of predication.
*/
float2 SMAACalculatePredicatedThreshold(float2 texcoord,
float4 offset[3],
SMAATexture2D(predicationTex)) {
float3 neighbours = SMAAGatherNeighbours(texcoord, offset, SMAATexturePass2D(predicationTex));
float2 delta = abs(neighbours.xx - neighbours.yz);
float2 edges = step(SMAA_PREDICATION_THRESHOLD, delta);
return SMAA_PREDICATION_SCALE * SMAA_THRESHOLD * (1.0 - SMAA_PREDICATION_STRENGTH * edges);
}
/**
* Conditional move:
*/
void SMAAMovc(bool2 cond, inout float2 variable, float2 value) {
SMAA_FLATTEN if (cond.x) variable.x = value.x;
SMAA_FLATTEN if (cond.y) variable.y = value.y;
}
void SMAAMovc(bool4 cond, inout float4 variable, float4 value) {
SMAAMovc(cond.xy, variable.xy, value.xy);
SMAAMovc(cond.zw, variable.zw, value.zw);
}
#if SMAA_INCLUDE_VS
//-----------------------------------------------------------------------------
// Vertex Shaders
/**
* Edge Detection Vertex Shader
*/
void SMAAEdgeDetectionVS(float2 texcoord,
out float4 offset[3]) {
offset[0] = mad(SMAA_RT_METRICS.xyxy, float4(-1.0, 0.0, 0.0, -1.0), texcoord.xyxy);
offset[1] = mad(SMAA_RT_METRICS.xyxy, float4( 1.0, 0.0, 0.0, 1.0), texcoord.xyxy);
offset[2] = mad(SMAA_RT_METRICS.xyxy, float4(-2.0, 0.0, 0.0, -2.0), texcoord.xyxy);
}
/**
* Blend Weight Calculation Vertex Shader
*/
void SMAABlendingWeightCalculationVS(float2 texcoord,
out float2 pixcoord,
out float4 offset[3]) {
pixcoord = texcoord * SMAA_RT_METRICS.zw;
// We will use these offsets for the searches later on (see @PSEUDO_GATHER4):
offset[0] = mad(SMAA_RT_METRICS.xyxy, float4(-0.25, -0.125, 1.25, -0.125), texcoord.xyxy);
offset[1] = mad(SMAA_RT_METRICS.xyxy, float4(-0.125, -0.25, -0.125, 1.25), texcoord.xyxy);
// And these for the searches, they indicate the ends of the loops:
offset[2] = mad(SMAA_RT_METRICS.xxyy,
float4(-2.0, 2.0, -2.0, 2.0) * float(SMAA_MAX_SEARCH_STEPS),
float4(offset[0].xz, offset[1].yw));
}
/**
* Neighborhood Blending Vertex Shader
*/
void SMAANeighborhoodBlendingVS(float2 texcoord,
out float4 offset) {
offset = mad(SMAA_RT_METRICS.xyxy, float4( 1.0, 0.0, 0.0, 1.0), texcoord.xyxy);
}
#endif // SMAA_INCLUDE_VS
#if SMAA_INCLUDE_PS
//-----------------------------------------------------------------------------
// Edge Detection Pixel Shaders (First Pass)
/**
* Luma Edge Detection
*
* IMPORTANT NOTICE: luma edge detection requires gamma-corrected colors, and
* thus 'colorTex' should be a non-sRGB texture.
*/
float2 SMAALumaEdgeDetectionPS(float2 texcoord,
float4 offset[3],
SMAATexture2D(colorTex)
#if SMAA_PREDICATION
, SMAATexture2D(predicationTex)
#endif
) {
// Calculate the threshold:
#if SMAA_PREDICATION
float2 threshold = SMAACalculatePredicatedThreshold(texcoord, offset, SMAATexturePass2D(predicationTex));
#else
float2 threshold = float2(SMAA_THRESHOLD, SMAA_THRESHOLD);
#endif
// Calculate lumas:
float3 weights = float3(0.2126, 0.7152, 0.0722);
float L = dot(SMAASamplePoint(colorTex, texcoord).rgb, weights);
float Lleft = dot(SMAASamplePoint(colorTex, offset[0].xy).rgb, weights);
float Ltop = dot(SMAASamplePoint(colorTex, offset[0].zw).rgb, weights);
// We do the usual threshold:
float4 delta;
delta.xy = abs(L - float2(Lleft, Ltop));
float2 edges = step(threshold, delta.xy);
// Then discard if there is no edge:
if (dot(edges, float2(1.0, 1.0)) == 0.0)
discard;
// Calculate right and bottom deltas:
float Lright = dot(SMAASamplePoint(colorTex, offset[1].xy).rgb, weights);
float Lbottom = dot(SMAASamplePoint(colorTex, offset[1].zw).rgb, weights);
delta.zw = abs(L - float2(Lright, Lbottom));
// Calculate the maximum delta in the direct neighborhood:
float2 maxDelta = max(delta.xy, delta.zw);
// Calculate left-left and top-top deltas:
float Lleftleft = dot(SMAASamplePoint(colorTex, offset[2].xy).rgb, weights);
float Ltoptop = dot(SMAASamplePoint(colorTex, offset[2].zw).rgb, weights);
delta.zw = abs(float2(Lleft, Ltop) - float2(Lleftleft, Ltoptop));
// Calculate the final maximum delta:
maxDelta = max(maxDelta.xy, delta.zw);
float finalDelta = max(maxDelta.x, maxDelta.y);
// Local contrast adaptation:
edges.xy *= step(finalDelta, SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR * delta.xy);
return edges;
}
/**
* Color Edge Detection
*
* IMPORTANT NOTICE: color edge detection requires gamma-corrected colors, and
* thus 'colorTex' should be a non-sRGB texture.
*/
float2 SMAAColorEdgeDetectionPS(float2 texcoord,
float4 offset[3],
SMAATexture2D(colorTex)
#if SMAA_PREDICATION
, SMAATexture2D(predicationTex)
#endif
) {
// Calculate the threshold:
#if SMAA_PREDICATION
float2 threshold = SMAACalculatePredicatedThreshold(texcoord, offset, predicationTex);
#else
float2 threshold = float2(SMAA_THRESHOLD, SMAA_THRESHOLD);
#endif
// Calculate color deltas:
float4 delta;
float3 C = SMAASamplePoint(colorTex, texcoord).rgb;
float3 Cleft = SMAASamplePoint(colorTex, offset[0].xy).rgb;
float3 t = abs(C - Cleft);
delta.x = max(max(t.r, t.g), t.b);
float3 Ctop = SMAASamplePoint(colorTex, offset[0].zw).rgb;
t = abs(C - Ctop);
delta.y = max(max(t.r, t.g), t.b);
// We do the usual threshold:
float2 edges = step(threshold, delta.xy);
// Then discard if there is no edge:
if (dot(edges, float2(1.0, 1.0)) == 0.0)
discard;
// Calculate right and bottom deltas:
float3 Cright = SMAASamplePoint(colorTex, offset[1].xy).rgb;
t = abs(C - Cright);
delta.z = max(max(t.r, t.g), t.b);
float3 Cbottom = SMAASamplePoint(colorTex, offset[1].zw).rgb;
t = abs(C - Cbottom);
delta.w = max(max(t.r, t.g), t.b);
// Calculate the maximum delta in the direct neighborhood:
float2 maxDelta = max(delta.xy, delta.zw);
// Calculate left-left and top-top deltas:
float3 Cleftleft = SMAASamplePoint(colorTex, offset[2].xy).rgb;
t = abs(C - Cleftleft);
delta.z = max(max(t.r, t.g), t.b);
float3 Ctoptop = SMAASamplePoint(colorTex, offset[2].zw).rgb;
t = abs(C - Ctoptop);
delta.w = max(max(t.r, t.g), t.b);
// Calculate the final maximum delta:
maxDelta = max(maxDelta.xy, delta.zw);
float finalDelta = max(maxDelta.x, maxDelta.y);
// Local contrast adaptation:
edges.xy *= step(finalDelta, SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR * delta.xy);
return edges;
}
)SHADER_SOURCE";
extern const char smaa_base_shader_p3[] = R"SHADER_SOURCE(
/**
* Depth Edge Detection
*/
float2 SMAADepthEdgeDetectionPS(float2 texcoord,
float4 offset[3],
SMAATexture2D(depthTex)) {
float3 neighbours = SMAAGatherNeighbours(texcoord, offset, SMAATexturePass2D(depthTex));
float2 delta = abs(neighbours.xx - float2(neighbours.y, neighbours.z));
float2 edges = step(SMAA_DEPTH_THRESHOLD, delta);
if (dot(edges, float2(1.0, 1.0)) == 0.0)
discard;
return edges;
}
//-----------------------------------------------------------------------------
// Diagonal Search Functions
#if !defined(SMAA_DISABLE_DIAG_DETECTION)
/**
* Allows one to decode two binary values from a bilinear-filtered access.
*/
float2 SMAADecodeDiagBilinearAccess(float2 e) {
// Bilinear access for fetching 'e' have a 0.25 offset, and we are
// interested in the R and G edges:
//
// +---G---+-------+
// | x o R x |
// +-------+-------+
//
// Then, if one of these edge is enabled:
// Red: (0.75 * X + 0.25 * 1) => 0.25 or 1.0
// Green: (0.75 * 1 + 0.25 * X) => 0.75 or 1.0
//
// This function will unpack the values (mad + mul + round):
// wolframalpha.com: round(x * abs(5 * x - 5 * 0.75)) plot 0 to 1
e.r = e.r * abs(5.0 * e.r - 5.0 * 0.75);
return round(e);
}
float4 SMAADecodeDiagBilinearAccess(float4 e) {
e.rb = e.rb * abs(5.0 * e.rb - 5.0 * 0.75);
return round(e);
}
/**
* These functions allows one to perform diagonal pattern searches.
*/
float2 SMAASearchDiag1(SMAATexture2D(edgesTex), float2 texcoord, float2 dir, out float2 e) {
float4 coord = float4(texcoord, -1.0, 1.0);
float3 t = float3(SMAA_RT_METRICS.xy, 1.0);
while (coord.z < float(SMAA_MAX_SEARCH_STEPS_DIAG - 1) &&
coord.w > 0.9) {
coord.xyz = mad(t, float3(dir, 1.0), coord.xyz);
e = SMAASampleLevelZero(edgesTex, coord.xy).rg;
coord.w = dot(e, float2(0.5, 0.5));
}
return coord.zw;
}
float2 SMAASearchDiag2(SMAATexture2D(edgesTex), float2 texcoord, float2 dir, out float2 e) {
float4 coord = float4(texcoord, -1.0, 1.0);
coord.x += 0.25 * SMAA_RT_METRICS.x; // See @SearchDiag2Optimization
float3 t = float3(SMAA_RT_METRICS.xy, 1.0);
while (coord.z < float(SMAA_MAX_SEARCH_STEPS_DIAG - 1) &&
coord.w > 0.9) {
coord.xyz = mad(t, float3(dir, 1.0), coord.xyz);
// @SearchDiag2Optimization
// Fetch both edges at once using bilinear filtering:
e = SMAASampleLevelZero(edgesTex, coord.xy).rg;
e = SMAADecodeDiagBilinearAccess(e);
// Non-optimized version:
// e.g = SMAASampleLevelZero(edgesTex, coord.xy).g;
// e.r = SMAASampleLevelZeroOffset(edgesTex, coord.xy, int2(1, 0)).r;
coord.w = dot(e, float2(0.5, 0.5));
}
return coord.zw;
}
/**
* Similar to SMAAArea, this calculates the area corresponding to a certain
* diagonal distance and crossing edges 'e'.
*/
float2 SMAAAreaDiag(SMAATexture2D(areaTex), float2 dist, float2 e, float offset) {
float2 texcoord = mad(float2(SMAA_AREATEX_MAX_DISTANCE_DIAG, SMAA_AREATEX_MAX_DISTANCE_DIAG), e, dist);
// We do a scale and bias for mapping to texel space:
texcoord = mad(SMAA_AREATEX_PIXEL_SIZE, texcoord, 0.5 * SMAA_AREATEX_PIXEL_SIZE);
// Diagonal areas are on the second half of the texture:
texcoord.x += 0.5;
// Move to proper place, according to the subpixel offset:
texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset;
// Do it!
return SMAA_AREATEX_SELECT(SMAASampleLevelZero(areaTex, texcoord));
}
/**
* This searches for diagonal patterns and returns the corresponding weights.
*/
float2 SMAACalculateDiagWeights(SMAATexture2D(edgesTex), SMAATexture2D(areaTex), float2 texcoord, float2 e, float4 subsampleIndices) {
float2 weights = float2(0.0, 0.0);
// Search for the line ends:
float4 d;
float2 end;
if (e.r > 0.0) {
d.xz = SMAASearchDiag1(SMAATexturePass2D(edgesTex), texcoord, float2(-1.0, 1.0), end);
d.x += float(end.y > 0.9);
} else
d.xz = float2(0.0, 0.0);
d.yw = SMAASearchDiag1(SMAATexturePass2D(edgesTex), texcoord, float2(1.0, -1.0), end);
SMAA_BRANCH
if (d.x + d.y > 2.0) { // d.x + d.y + 1 > 3
// Fetch the crossing edges:
float4 coords = mad(float4(-d.x + 0.25, d.x, d.y, -d.y - 0.25), SMAA_RT_METRICS.xyxy, texcoord.xyxy);
float4 c;
c.xy = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(-1, 0)).rg;
c.zw = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, 0)).rg;
c.yxwz = SMAADecodeDiagBilinearAccess(c.xyzw);
// Non-optimized version:
// float4 coords = mad(float4(-d.x, d.x, d.y, -d.y), SMAA_RT_METRICS.xyxy, texcoord.xyxy);
// float4 c;
// c.x = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(-1, 0)).g;
// c.y = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2( 0, 0)).r;
// c.z = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, 0)).g;
// c.w = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, -1)).r;
// Merge crossing edges at each side into a single value:
float2 cc = mad(float2(2.0, 2.0), c.xz, c.yw);
// Remove the crossing edge if we didn't found the end of the line:
SMAAMovc(bool2(step(0.9, d.zw)), cc, float2(0.0, 0.0));
// Fetch the areas for this line:
weights += SMAAAreaDiag(SMAATexturePass2D(areaTex), d.xy, cc, subsampleIndices.z);
}
// Search for the line ends:
d.xz = SMAASearchDiag2(SMAATexturePass2D(edgesTex), texcoord, float2(-1.0, -1.0), end);
if (SMAASampleLevelZeroOffset(edgesTex, texcoord, int2(1, 0)).r > 0.0) {
d.yw = SMAASearchDiag2(SMAATexturePass2D(edgesTex), texcoord, float2(1.0, 1.0), end);
d.y += float(end.y > 0.9);
} else
d.yw = float2(0.0, 0.0);
SMAA_BRANCH
if (d.x + d.y > 2.0) { // d.x + d.y + 1 > 3
// Fetch the crossing edges:
float4 coords = mad(float4(-d.x, -d.x, d.y, d.y), SMAA_RT_METRICS.xyxy, texcoord.xyxy);
float4 c;
c.x = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(-1, 0)).g;
c.y = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2( 0, -1)).r;
c.zw = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, 0)).gr;
float2 cc = mad(float2(2.0, 2.0), c.xz, c.yw);
// Remove the crossing edge if we didn't found the end of the line:
SMAAMovc(bool2(step(0.9, d.zw)), cc, float2(0.0, 0.0));
// Fetch the areas for this line:
weights += SMAAAreaDiag(SMAATexturePass2D(areaTex), d.xy, cc, subsampleIndices.w).gr;
}
return weights;
}
#endif
//-----------------------------------------------------------------------------
// Horizontal/Vertical Search Functions
/**
* This allows one to determine how much length should we add in the last step
* of the searches. It takes the bilinearly interpolated edge (see
* @PSEUDO_GATHER4), and adds 0, 1 or 2, depending on which edges and
* crossing edges are active.
*/
float SMAASearchLength(SMAATexture2D(searchTex), float2 e, float offset) {
// The texture is flipped vertically, with left and right cases taking half
// of the space horizontally:
float2 scale = SMAA_SEARCHTEX_SIZE * float2(0.5, -1.0);
float2 bias = SMAA_SEARCHTEX_SIZE * float2(offset, 1.0);
// Scale and bias to access texel centers:
scale += float2(-1.0, 1.0);
bias += float2( 0.5, -0.5);
// Convert from pixel coordinates to texcoords:
// (We use SMAA_SEARCHTEX_PACKED_SIZE because the texture is cropped)
scale *= 1.0 / SMAA_SEARCHTEX_PACKED_SIZE;
bias *= 1.0 / SMAA_SEARCHTEX_PACKED_SIZE;
// Lookup the search texture:
return SMAA_SEARCHTEX_SELECT(SMAASampleLevelZero(searchTex, mad(scale, e, bias)));
}
/**
* Horizontal/vertical search functions for the 2nd pass.
*/
float SMAASearchXLeft(SMAATexture2D(edgesTex), SMAATexture2D(searchTex), float2 texcoord, float end) {
/**
* @PSEUDO_GATHER4
* This texcoord has been offset by (-0.25, -0.125) in the vertex shader to
* sample between edge, thus fetching four edges in a row.
* Sampling with different offsets in each direction allows one to
* disambiguate which edges are active from the four fetched ones.
*/
float2 e = float2(0.0, 1.0);
while (texcoord.x > end &&
e.g > 0.8281 && // Is there some edge not activated?
e.r == 0.0) { // Or is there a crossing edge that breaks the line?
e = SMAASampleLevelZero(edgesTex, texcoord).rg;
texcoord = mad(-float2(2.0, 0.0), SMAA_RT_METRICS.xy, texcoord);
}
float offset = mad(-(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e, 0.0), 3.25);
return mad(SMAA_RT_METRICS.x, offset, texcoord.x);
// Non-optimized version:
// We correct the previous (-0.25, -0.125) offset we applied:
// texcoord.x += 0.25 * SMAA_RT_METRICS.x;
// The searches are bias by 1, so adjust the coords accordingly:
// texcoord.x += SMAA_RT_METRICS.x;
// Disambiguate the length added by the last step:
// texcoord.x += 2.0 * SMAA_RT_METRICS.x; // Undo last step
// texcoord.x -= SMAA_RT_METRICS.x * (255.0 / 127.0) * SMAASearchLength(SMAATexturePass2D(searchTex), e, 0.0);
// return mad(SMAA_RT_METRICS.x, offset, texcoord.x);
}
float SMAASearchXRight(SMAATexture2D(edgesTex), SMAATexture2D(searchTex), float2 texcoord, float end) {
float2 e = float2(0.0, 1.0);
while (texcoord.x < end &&
e.g > 0.8281 && // Is there some edge not activated?
e.r == 0.0) { // Or is there a crossing edge that breaks the line?
e = SMAASampleLevelZero(edgesTex, texcoord).rg;
texcoord = mad(float2(2.0, 0.0), SMAA_RT_METRICS.xy, texcoord);
}
float offset = mad(-(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e, 0.5), 3.25);
return mad(-SMAA_RT_METRICS.x, offset, texcoord.x);
}
float SMAASearchYUp(SMAATexture2D(edgesTex), SMAATexture2D(searchTex), float2 texcoord, float end) {
float2 e = float2(1.0, 0.0);
while (texcoord.y > end &&
e.r > 0.8281 && // Is there some edge not activated?
e.g == 0.0) { // Or is there a crossing edge that breaks the line?
e = SMAASampleLevelZero(edgesTex, texcoord).rg;
texcoord = mad(-float2(0.0, 2.0), SMAA_RT_METRICS.xy, texcoord);
}
float offset = mad(-(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e.gr, 0.0), 3.25);
return mad(SMAA_RT_METRICS.y, offset, texcoord.y);
}
float SMAASearchYDown(SMAATexture2D(edgesTex), SMAATexture2D(searchTex), float2 texcoord, float end) {
float2 e = float2(1.0, 0.0);
while (texcoord.y < end &&
e.r > 0.8281 && // Is there some edge not activated?
e.g == 0.0) { // Or is there a crossing edge that breaks the line?
e = SMAASampleLevelZero(edgesTex, texcoord).rg;
texcoord = mad(float2(0.0, 2.0), SMAA_RT_METRICS.xy, texcoord);
}
float offset = mad(-(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e.gr, 0.5), 3.25);
return mad(-SMAA_RT_METRICS.y, offset, texcoord.y);
}
/**
* Ok, we have the distance and both crossing edges. So, what are the areas
* at each side of current edge?
*/
float2 SMAAArea(SMAATexture2D(areaTex), float2 dist, float e1, float e2, float offset) {
// Rounding prevents precision errors of bilinear filtering:
float2 texcoord = mad(float2(SMAA_AREATEX_MAX_DISTANCE, SMAA_AREATEX_MAX_DISTANCE), round(4.0 * float2(e1, e2)), dist);
// We do a scale and bias for mapping to texel space:
texcoord = mad(SMAA_AREATEX_PIXEL_SIZE, texcoord, 0.5 * SMAA_AREATEX_PIXEL_SIZE);
// Move to proper place, according to the subpixel offset:
texcoord.y = mad(SMAA_AREATEX_SUBTEX_SIZE, offset, texcoord.y);
// Do it!
return SMAA_AREATEX_SELECT(SMAASampleLevelZero(areaTex, texcoord));
}
//-----------------------------------------------------------------------------
// Corner Detection Functions
void SMAADetectHorizontalCornerPattern(SMAATexture2D(edgesTex), inout float2 weights, float4 texcoord, float2 d) {
#if !defined(SMAA_DISABLE_CORNER_DETECTION)
float2 leftRight = step(d.xy, d.yx);
float2 rounding = (1.0 - SMAA_CORNER_ROUNDING_NORM) * leftRight;
rounding /= leftRight.x + leftRight.y; // Reduce blending for pixels in the center of a line.
float2 factor = float2(1.0, 1.0);
factor.x -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(0, 1)).r;
factor.x -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(1, 1)).r;
factor.y -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(0, -2)).r;
factor.y -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(1, -2)).r;
weights *= saturate(factor);
#endif
}
void SMAADetectVerticalCornerPattern(SMAATexture2D(edgesTex), inout float2 weights, float4 texcoord, float2 d) {
#if !defined(SMAA_DISABLE_CORNER_DETECTION)
float2 leftRight = step(d.xy, d.yx);
float2 rounding = (1.0 - SMAA_CORNER_ROUNDING_NORM) * leftRight;
rounding /= leftRight.x + leftRight.y;
float2 factor = float2(1.0, 1.0);
factor.x -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2( 1, 0)).g;
factor.x -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2( 1, 1)).g;
factor.y -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(-2, 0)).g;
factor.y -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(-2, 1)).g;
weights *= saturate(factor);
#endif
}
//-----------------------------------------------------------------------------
// Blending Weight Calculation Pixel Shader (Second Pass)
float4 SMAABlendingWeightCalculationPS(float2 texcoord,
float2 pixcoord,
float4 offset[3],
SMAATexture2D(edgesTex),
SMAATexture2D(areaTex),
SMAATexture2D(searchTex),
float4 subsampleIndices) { // Just pass zero for SMAA 1x, see @SUBSAMPLE_INDICES.
float4 weights = float4(0.0, 0.0, 0.0, 0.0);
float2 e = SMAASample(edgesTex, texcoord).rg;
SMAA_BRANCH
if (e.g > 0.0) { // Edge at north
#if !defined(SMAA_DISABLE_DIAG_DETECTION)
// Diagonals have both north and west edges, so searching for them in
// one of the boundaries is enough.
weights.rg = SMAACalculateDiagWeights(SMAATexturePass2D(edgesTex), SMAATexturePass2D(areaTex), texcoord, e, subsampleIndices);
// We give priority to diagonals, so if we find a diagonal we skip
// horizontal/vertical processing.
SMAA_BRANCH
if (weights.r == -weights.g) { // weights.r + weights.g == 0.0
#endif
float2 d;
// Find the distance to the left:
float3 coords;
coords.x = SMAASearchXLeft(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[0].xy, offset[2].x);
coords.y = offset[1].y; // offset[1].y = texcoord.y - 0.25 * SMAA_RT_METRICS.y (@CROSSING_OFFSET)
d.x = coords.x;
// Now fetch the left crossing edges, two at a time using bilinear
// filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to
// discern what value each edge has:
float e1 = SMAASampleLevelZero(edgesTex, coords.xy).r;
// Find the distance to the right:
coords.z = SMAASearchXRight(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[0].zw, offset[2].y);
d.y = coords.z;
// We want the distances to be in pixel units (doing this here allow one
// to better interleave arithmetic and memory accesses):
d = abs(round(mad(SMAA_RT_METRICS.zz, d, -pixcoord.xx)));
// SMAAArea below needs a sqrt, as the areas texture is compressed
// quadratically:
float2 sqrt_d = sqrt(d);
)SHADER_SOURCE";
extern const char smaa_base_shader_p4[] = R"SHADER_SOURCE(
// Fetch the right crossing edges:
float e2 = SMAASampleLevelZeroOffset(edgesTex, coords.zy, int2(1, 0)).r;
// Ok, we know how this pattern looks like, now it is time for getting
// the actual area:
weights.rg = SMAAArea(SMAATexturePass2D(areaTex), sqrt_d, e1, e2, subsampleIndices.y);
// Fix corners:
coords.y = texcoord.y;
SMAADetectHorizontalCornerPattern(SMAATexturePass2D(edgesTex), weights.rg, coords.xyzy, d);
#if !defined(SMAA_DISABLE_DIAG_DETECTION)
} else
e.r = 0.0; // Skip vertical processing.
#endif
}
SMAA_BRANCH
if (e.r > 0.0) { // Edge at west
float2 d;
// Find the distance to the top:
float3 coords;
coords.y = SMAASearchYUp(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[1].xy, offset[2].z);
coords.x = offset[0].x; // offset[1].x = texcoord.x - 0.25 * SMAA_RT_METRICS.x;
d.x = coords.y;
// Fetch the top crossing edges:
float e1 = SMAASampleLevelZero(edgesTex, coords.xy).g;
// Find the distance to the bottom:
coords.z = SMAASearchYDown(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[1].zw, offset[2].w);
d.y = coords.z;
// We want the distances to be in pixel units:
d = abs(round(mad(SMAA_RT_METRICS.ww, d, -pixcoord.yy)));
// SMAAArea below needs a sqrt, as the areas texture is compressed
// quadratically:
float2 sqrt_d = sqrt(d);
// Fetch the bottom crossing edges:
float e2 = SMAASampleLevelZeroOffset(edgesTex, coords.xz, int2(0, 1)).g;
// Get the area for this direction:
weights.ba = SMAAArea(SMAATexturePass2D(areaTex), sqrt_d, e1, e2, subsampleIndices.x);
// Fix corners:
coords.x = texcoord.x;
SMAADetectVerticalCornerPattern(SMAATexturePass2D(edgesTex), weights.ba, coords.xyxz, d);
}
return weights;
}
//-----------------------------------------------------------------------------
// Neighborhood Blending Pixel Shader (Third Pass)
float4 SMAANeighborhoodBlendingPS(float2 texcoord,
float4 offset,
SMAATexture2D(colorTex),
SMAATexture2D(blendTex)
#if SMAA_REPROJECTION
, SMAATexture2D(velocityTex)
#endif
) {
// Fetch the blending weights for current pixel:
float4 a;
a.x = SMAASample(blendTex, offset.xy).a; // Right
a.y = SMAASample(blendTex, offset.zw).g; // Top
a.wz = SMAASample(blendTex, texcoord).xz; // Bottom / Left
// Is there any blending weight with a value greater than 0.0?
SMAA_BRANCH
if (dot(a, float4(1.0, 1.0, 1.0, 1.0)) < 1e-5) {
float4 color = SMAASampleLevelZero(colorTex, texcoord);
#if SMAA_REPROJECTION
float2 velocity = SMAA_DECODE_VELOCITY(SMAASampleLevelZero(velocityTex, texcoord));
// Pack velocity into the alpha channel:
color.a = sqrt(5.0 * length(velocity));
#endif
return color;
} else {
bool h = max(a.x, a.z) > max(a.y, a.w); // max(horizontal) > max(vertical)
// Calculate the blending offsets:
float4 blendingOffset = float4(0.0, a.y, 0.0, a.w);
float2 blendingWeight = a.yw;
SMAAMovc(bool4(h, h, h, h), blendingOffset, float4(a.x, 0.0, a.z, 0.0));
SMAAMovc(bool2(h, h), blendingWeight, a.xz);
blendingWeight /= dot(blendingWeight, float2(1.0, 1.0));
// Calculate the texture coordinates:
float4 blendingCoord = mad(blendingOffset, float4(SMAA_RT_METRICS.xy, -SMAA_RT_METRICS.xy), texcoord.xyxy);
// We exploit bilinear filtering to mix current pixel with the chosen
// neighbor:
float4 color = blendingWeight.x * SMAASampleLevelZero(colorTex, blendingCoord.xy);
color += blendingWeight.y * SMAASampleLevelZero(colorTex, blendingCoord.zw);
#if SMAA_REPROJECTION
// Antialias velocity for proper reprojection in a later stage:
float2 velocity = blendingWeight.x * SMAA_DECODE_VELOCITY(SMAASampleLevelZero(velocityTex, blendingCoord.xy));
velocity += blendingWeight.y * SMAA_DECODE_VELOCITY(SMAASampleLevelZero(velocityTex, blendingCoord.zw));
// Pack velocity into the alpha channel:
color.a = sqrt(5.0 * length(velocity));
#endif
return color;
}
}
//-----------------------------------------------------------------------------
// Temporal Resolve Pixel Shader (Optional Pass)
float4 SMAAResolvePS(float2 texcoord,
SMAATexture2D(currentColorTex),
SMAATexture2D(previousColorTex)
#if SMAA_REPROJECTION
, SMAATexture2D(velocityTex)
#endif
) {
#if SMAA_REPROJECTION
// Velocity is assumed to be calculated for motion blur, so we need to
// inverse it for reprojection:
float2 velocity = -SMAA_DECODE_VELOCITY(SMAASamplePoint(velocityTex, texcoord).rg);
// Fetch current pixel:
float4 current = SMAASamplePoint(currentColorTex, texcoord);
// Reproject current coordinates and fetch previous pixel:
float4 previous = SMAASamplePoint(previousColorTex, texcoord + velocity);
// Attenuate the previous pixel if the velocity is different:
float delta = abs(current.a * current.a - previous.a * previous.a) / 5.0;
float weight = 0.5 * saturate(1.0 - sqrt(delta) * SMAA_REPROJECTION_WEIGHT_SCALE);
// Blend the pixels according to the calculated weight:
return lerp(current, previous, weight);
#else
// Just blend the pixels:
float4 current = SMAASamplePoint(currentColorTex, texcoord);
float4 previous = SMAASamplePoint(previousColorTex, texcoord);
return lerp(current, previous, 0.5);
#endif
}
//-----------------------------------------------------------------------------
// Separate Multisamples Pixel Shader (Optional Pass)
#ifdef SMAALoad
void SMAASeparatePS(float4 position,
float2 texcoord,
out float4 target0,
out float4 target1,
SMAATexture2DMS2(colorTexMS)) {
int2 pos = int2(position.xy);
target0 = SMAALoad(colorTexMS, pos, 0);
target1 = SMAALoad(colorTexMS, pos, 1);
}
#endif
//-----------------------------------------------------------------------------
#endif // SMAA_INCLUDE_PS
)SHADER_SOURCE";
const char smaa_pass_1_vertex_shader[] = R"SHADER_SOURCE(
varying vec4 offset[3];
varying vec2 texcoord;
void main()
{
texcoord = gl_MultiTexCoord0.st;
SMAAEdgeDetectionVS( texcoord, offset);
gl_Position = ftransform();
}
)SHADER_SOURCE";
const char smaa_pass_1_fragment_shader[] = R"SHADER_SOURCE(
varying vec2 texcoord;
varying vec4 offset[3];
uniform sampler2D colorTex;
void main()
{
gl_FragColor.xy = SMAALumaEdgeDetectionPS(texcoord, offset, colorTex).xy;
}
)SHADER_SOURCE";
const char smaa_pass_2_vertex_shader[] = R"SHADER_SOURCE(
varying vec4 offset[3];
varying vec2 texcoord;
varying vec2 pixcoord;
void main()
{
texcoord = gl_MultiTexCoord0.st;
SMAABlendingWeightCalculationVS( texcoord, pixcoord, offset );
gl_Position = ftransform();
}
)SHADER_SOURCE";
const char smaa_pass_2_fragment_shader[] = R"SHADER_SOURCE(
varying vec2 texcoord;
varying vec2 pixcoord;
varying vec4 offset[3];
uniform sampler2D edgesTex;
uniform sampler2D areaTex;
uniform sampler2D searchTex;
void main()
{
gl_FragColor = SMAABlendingWeightCalculationPS(texcoord, pixcoord, offset, edgesTex, areaTex, searchTex, vec4(0.,0.,0.,0.));
}
)SHADER_SOURCE";
const char smaa_pass_3_vertex_shader[] = R"SHADER_SOURCE(
varying vec4 offset;
varying vec2 texcoord;
void main()
{
texcoord = gl_MultiTexCoord0.st;
SMAANeighborhoodBlendingVS( texcoord, offset );
gl_Position = ftransform();
}
)SHADER_SOURCE";
const char smaa_pass_3_fragment_shader[] = R"SHADER_SOURCE(
varying vec2 texcoord;
varying vec4 offset;
uniform sampler2D colorTex;
uniform sampler2D blendTex;
void main()
{
gl_FragColor = SMAANeighborhoodBlendingPS(texcoord, offset, colorTex, blendTex);
}
)SHADER_SOURCE";
}
}
|