CCNode.cpp
53.6 KB
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
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2009 Valentin Milea
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of 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.
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.
****************************************************************************/
#include "2d/CCNode.h"
#include <algorithm>
#include <string>
#include <regex>
#include "base/CCDirector.h"
#include "base/CCScheduler.h"
#include "base/CCEventDispatcher.h"
#include "base/ccUTF8.h"
#include "2d/CCCamera.h"
#include "2d/CCActionManager.h"
#include "2d/CCScene.h"
#include "2d/CCComponent.h"
#include "renderer/CCMaterial.h"
#include "math/TransformUtils.h"
#if CC_NODE_RENDER_SUBPIXEL
#define RENDER_IN_SUBPIXEL
#else
#define RENDER_IN_SUBPIXEL(__ARGS__) (ceil(__ARGS__))
#endif
NS_CC_BEGIN
// FIXME:: Yes, nodes might have a sort problem once every 30 days if the game runs at 60 FPS and each frame sprites are reordered.
std::uint32_t Node::s_globalOrderOfArrival = 0;
int Node::__attachedNodeCount = 0;
// MARK: Constructor, Destructor, Init
Node::Node()
: _rotationX(0.0f)
, _rotationY(0.0f)
, _rotationZ_X(0.0f)
, _rotationZ_Y(0.0f)
, _scaleX(1.0f)
, _scaleY(1.0f)
, _scaleZ(1.0f)
, _positionZ(0.0f)
, _usingNormalizedPosition(false)
, _normalizedPositionDirty(false)
, _skewX(0.0f)
, _skewY(0.0f)
, _anchorPoint(0, 0)
, _contentSize(Size::ZERO)
, _contentSizeDirty(true)
, _transformDirty(true)
, _inverseDirty(true)
, _additionalTransform(nullptr)
, _additionalTransformDirty(false)
, _transformUpdated(true)
// children (lazy allocs)
// lazy alloc
, _localZOrder$Arrival(0LL)
, _globalZOrder(0)
, _parent(nullptr)
// "whole screen" objects. like Scenes and Layers, should set _ignoreAnchorPointForPosition to true
, _tag(Node::INVALID_TAG)
, _name("")
, _hashOfName(0)
// userData is always inited as nil
, _userData(nullptr)
, _userObject(nullptr)
, _running(false)
, _visible(true)
, _ignoreAnchorPointForPosition(false)
, _reorderChildDirty(false)
, _isTransitionFinished(false)
#if CC_ENABLE_SCRIPT_BINDING
, _updateScriptHandler(0)
#endif
, _componentContainer(nullptr)
, _displayedOpacity(255)
, _realOpacity(255)
, _displayedColor(Color3B::WHITE)
, _realColor(Color3B::WHITE)
, _cascadeColorEnabled(false)
, _cascadeOpacityEnabled(false)
, _cameraMask(1)
, _onEnterCallback(nullptr)
, _onExitCallback(nullptr)
, _onEnterTransitionDidFinishCallback(nullptr)
, _onExitTransitionDidStartCallback(nullptr)
#if CC_USE_PHYSICS
, _physicsBody(nullptr)
#endif
{
// set default scheduler and actionManager
_director = Director::getInstance();
_actionManager = _director->getActionManager();
_actionManager->retain();
_scheduler = _director->getScheduler();
_scheduler->retain();
_eventDispatcher = _director->getEventDispatcher();
_eventDispatcher->retain();
#if CC_ENABLE_SCRIPT_BINDING
ScriptEngineProtocol* engine = ScriptEngineManager::getInstance()->getScriptEngine();
_scriptType = engine != nullptr ? engine->getScriptType() : kScriptTypeNone;
#endif
_transform = _inverse = Mat4::IDENTITY;
}
Node * Node::create()
{
Node * ret = new (std::nothrow) Node();
if (ret && ret->init())
{
ret->autorelease();
}
else
{
CC_SAFE_DELETE(ret);
}
return ret;
}
Node::~Node()
{
CCLOGINFO( "deallocing Node: %p - tag: %i", this, _tag );
#if CC_ENABLE_SCRIPT_BINDING
if (_updateScriptHandler)
{
ScriptEngineManager::getInstance()->getScriptEngine()->removeScriptHandler(_updateScriptHandler);
}
#endif
// User object has to be released before others, since userObject may have a weak reference of this node
// It may invoke `node->stopAllActions();` while `_actionManager` is null if the next line is after `CC_SAFE_RELEASE_NULL(_actionManager)`.
CC_SAFE_RELEASE_NULL(_userObject);
for (auto& child : _children)
{
child->_parent = nullptr;
}
removeAllComponents();
CC_SAFE_DELETE(_componentContainer);
stopAllActions();
unscheduleAllCallbacks();
CC_SAFE_RELEASE_NULL(_actionManager);
CC_SAFE_RELEASE_NULL(_scheduler);
_eventDispatcher->removeEventListenersForTarget(this);
#if CC_NODE_DEBUG_VERIFY_EVENT_LISTENERS && COCOS2D_DEBUG > 0
_eventDispatcher->debugCheckNodeHasNoEventListenersOnDestruction(this);
#endif
CCASSERT(!_running, "Node still marked as running on node destruction! Was base class onExit() called in derived class onExit() implementations?");
CC_SAFE_RELEASE(_eventDispatcher);
delete[] _additionalTransform;
CC_SAFE_RELEASE(_programState);
}
bool Node::init()
{
return true;
}
void Node::cleanup()
{
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeJavascript)
{
if (ScriptEngineManager::sendNodeEventToJS(this, kNodeOnCleanup))
return;
}
else if (_scriptType == kScriptTypeLua)
{
ScriptEngineManager::sendNodeEventToLua(this, kNodeOnCleanup);
}
#endif // #if CC_ENABLE_SCRIPT_BINDING
// actions
this->stopAllActions();
// timers
this->unscheduleAllCallbacks();
// NOTE: Although it was correct that removing event listeners associated with current node in Node::cleanup.
// But it broke the compatibility to the versions before v3.16 .
// User code may call `node->removeFromParent(true)` which will trigger node's cleanup method, when the node
// is added to scene again, event listeners like EventListenerTouchOneByOne will be lost.
// In fact, user's code should use `node->removeFromParent(false)` in order not to do a cleanup and just remove node
// from its parent. For more discussion about why we revert this change is at https://github.com/cocos2d/cocos2d-x/issues/18104.
// We need to consider more before we want to correct the old and wrong logic code.
// For now, compatiblity is the most important for our users.
// _eventDispatcher->removeEventListenersForTarget(this);
for( const auto &child: _children)
child->cleanup();
}
std::string Node::getDescription() const
{
return StringUtils::format("<Node | Tag = %d", _tag);
}
// MARK: getters / setters
float Node::getSkewX() const
{
return _skewX;
}
void Node::setSkewX(float skewX)
{
if (_skewX == skewX)
return;
_skewX = skewX;
_transformUpdated = _transformDirty = _inverseDirty = true;
}
float Node::getSkewY() const
{
return _skewY;
}
void Node::setSkewY(float skewY)
{
if (_skewY == skewY)
return;
_skewY = skewY;
_transformUpdated = _transformDirty = _inverseDirty = true;
}
void Node::setLocalZOrder(std::int32_t z)
{
if (getLocalZOrder() == z)
return;
_setLocalZOrder(z);
if (_parent)
{
_parent->reorderChild(this, z);
}
_eventDispatcher->setDirtyForNode(this);
}
/// zOrder setter : private method
/// used internally to alter the zOrder variable. DON'T call this method manually
void Node::_setLocalZOrder(std::int32_t z)
{
_localZOrder = z;
}
void Node::updateOrderOfArrival()
{
_orderOfArrival = (++s_globalOrderOfArrival);
}
void Node::setGlobalZOrder(float globalZOrder)
{
if (_globalZOrder != globalZOrder)
{
_globalZOrder = globalZOrder;
_eventDispatcher->setDirtyForNode(this);
}
}
/// rotation getter
float Node::getRotation() const
{
CCASSERT(_rotationZ_X == _rotationZ_Y, "CCNode#rotation. RotationX != RotationY. Don't know which one to return");
return _rotationZ_X;
}
/// rotation setter
void Node::setRotation(float rotation)
{
if (_rotationZ_X == rotation)
return;
_rotationZ_X = _rotationZ_Y = rotation;
_transformUpdated = _transformDirty = _inverseDirty = true;
updateRotationQuat();
}
float Node::getRotationSkewX() const
{
return _rotationZ_X;
}
void Node::setRotation3D(const Vec3& rotation)
{
if (_rotationX == rotation.x &&
_rotationY == rotation.y &&
_rotationZ_X == rotation.z)
return;
_transformUpdated = _transformDirty = _inverseDirty = true;
_rotationX = rotation.x;
_rotationY = rotation.y;
// rotation Z is decomposed in 2 to simulate Skew for Flash animations
_rotationZ_Y = _rotationZ_X = rotation.z;
updateRotationQuat();
}
Vec3 Node::getRotation3D() const
{
// rotation Z is decomposed in 2 to simulate Skew for Flash animations
CCASSERT(_rotationZ_X == _rotationZ_Y, "_rotationZ_X != _rotationZ_Y");
return Vec3(_rotationX,_rotationY,_rotationZ_X);
}
void Node::updateRotationQuat()
{
// convert Euler angle to quaternion
// when _rotationZ_X == _rotationZ_Y, _rotationQuat = RotationZ_X * RotationY * RotationX
// when _rotationZ_X != _rotationZ_Y, _rotationQuat = RotationY * RotationX
float halfRadx = CC_DEGREES_TO_RADIANS(_rotationX / 2.f), halfRady = CC_DEGREES_TO_RADIANS(_rotationY / 2.f), halfRadz = _rotationZ_X == _rotationZ_Y ? -CC_DEGREES_TO_RADIANS(_rotationZ_X / 2.f) : 0;
float coshalfRadx = cosf(halfRadx), sinhalfRadx = sinf(halfRadx), coshalfRady = cosf(halfRady), sinhalfRady = sinf(halfRady), coshalfRadz = cosf(halfRadz), sinhalfRadz = sinf(halfRadz);
_rotationQuat.x = sinhalfRadx * coshalfRady * coshalfRadz - coshalfRadx * sinhalfRady * sinhalfRadz;
_rotationQuat.y = coshalfRadx * sinhalfRady * coshalfRadz + sinhalfRadx * coshalfRady * sinhalfRadz;
_rotationQuat.z = coshalfRadx * coshalfRady * sinhalfRadz - sinhalfRadx * sinhalfRady * coshalfRadz;
_rotationQuat.w = coshalfRadx * coshalfRady * coshalfRadz + sinhalfRadx * sinhalfRady * sinhalfRadz;
}
void Node::updateRotation3D()
{
//convert quaternion to Euler angle
float x = _rotationQuat.x, y = _rotationQuat.y, z = _rotationQuat.z, w = _rotationQuat.w;
_rotationX = atan2f(2.f * (w * x + y * z), 1.f - 2.f * (x * x + y * y));
float sy = 2.f * (w * y - z * x);
sy = clampf(sy, -1, 1);
_rotationY = asinf(sy);
_rotationZ_X = atan2f(2.f * (w * z + x * y), 1.f - 2.f * (y * y + z * z));
_rotationX = CC_RADIANS_TO_DEGREES(_rotationX);
_rotationY = CC_RADIANS_TO_DEGREES(_rotationY);
_rotationZ_X = _rotationZ_Y = -CC_RADIANS_TO_DEGREES(_rotationZ_X);
}
void Node::setRotationQuat(const Quaternion& quat)
{
_rotationQuat = quat;
updateRotation3D();
_transformUpdated = _transformDirty = _inverseDirty = true;
}
Quaternion Node::getRotationQuat() const
{
return _rotationQuat;
}
void Node::setRotationSkewX(float rotationX)
{
if (_rotationZ_X == rotationX)
return;
_rotationZ_X = rotationX;
_transformUpdated = _transformDirty = _inverseDirty = true;
updateRotationQuat();
}
float Node::getRotationSkewY() const
{
return _rotationZ_Y;
}
void Node::setRotationSkewY(float rotationY)
{
if (_rotationZ_Y == rotationY)
return;
_rotationZ_Y = rotationY;
_transformUpdated = _transformDirty = _inverseDirty = true;
updateRotationQuat();
}
/// scale getter
float Node::getScale() const
{
CCASSERT( _scaleX == _scaleY, "CCNode#scale. ScaleX != ScaleY. Don't know which one to return");
return _scaleX;
}
/// scale setter
void Node::setScale(float scale)
{
if (_scaleX == scale && _scaleY == scale && _scaleZ == scale)
return;
_scaleX = _scaleY = _scaleZ = scale;
_transformUpdated = _transformDirty = _inverseDirty = true;
}
/// scaleX getter
float Node::getScaleX() const
{
return _scaleX;
}
/// scale setter
void Node::setScale(float scaleX,float scaleY)
{
if (_scaleX == scaleX && _scaleY == scaleY)
return;
_scaleX = scaleX;
_scaleY = scaleY;
_transformUpdated = _transformDirty = _inverseDirty = true;
}
/// scaleX setter
void Node::setScaleX(float scaleX)
{
if (_scaleX == scaleX)
return;
_scaleX = scaleX;
_transformUpdated = _transformDirty = _inverseDirty = true;
}
/// scaleY getter
float Node::getScaleY() const
{
return _scaleY;
}
/// scaleY setter
void Node::setScaleZ(float scaleZ)
{
if (_scaleZ == scaleZ)
return;
_scaleZ = scaleZ;
_transformUpdated = _transformDirty = _inverseDirty = true;
}
/// scaleY getter
float Node::getScaleZ() const
{
return _scaleZ;
}
/// scaleY setter
void Node::setScaleY(float scaleY)
{
if (_scaleY == scaleY)
return;
_scaleY = scaleY;
_transformUpdated = _transformDirty = _inverseDirty = true;
}
/// position getter
const Vec2& Node::getPosition() const
{
return _position;
}
/// position setter
void Node::setPosition(const Vec2& position)
{
setPosition(position.x, position.y);
}
void Node::getPosition(float* x, float* y) const
{
*x = _position.x;
*y = _position.y;
}
void Node::setPosition(float x, float y)
{
if (_position.x == x && _position.y == y)
return;
_position.x = x;
_position.y = y;
_transformUpdated = _transformDirty = _inverseDirty = true;
_usingNormalizedPosition = false;
}
void Node::setPosition3D(const Vec3& position)
{
setPositionZ(position.z);
setPosition(position.x, position.y);
}
Vec3 Node::getPosition3D() const
{
return Vec3(_position.x, _position.y, _positionZ);
}
float Node::getPositionX() const
{
return _position.x;
}
void Node::setPositionX(float x)
{
setPosition(x, _position.y);
}
float Node::getPositionY() const
{
return _position.y;
}
void Node::setPositionY(float y)
{
setPosition(_position.x, y);
}
float Node::getPositionZ() const
{
return _positionZ;
}
void Node::setPositionZ(float positionZ)
{
if (_positionZ == positionZ)
return;
_transformUpdated = _transformDirty = _inverseDirty = true;
_positionZ = positionZ;
}
/// position getter
const Vec2& Node::getPositionNormalized() const
{
return _normalizedPosition;
}
/// position setter
void Node::setPositionNormalized(const Vec2& position)
{
if (_normalizedPosition.equals(position))
return;
_normalizedPosition = position;
_usingNormalizedPosition = true;
_normalizedPositionDirty = true;
_transformUpdated = _transformDirty = _inverseDirty = true;
}
ssize_t Node::getChildrenCount() const
{
return _children.size();
}
/// isVisible getter
bool Node::isVisible() const
{
return _visible;
}
/// isVisible setter
void Node::setVisible(bool visible)
{
if(visible != _visible)
{
_visible = visible;
if(_visible)
_transformUpdated = _transformDirty = _inverseDirty = true;
}
}
const Vec2& Node::getAnchorPointInPoints() const
{
return _anchorPointInPoints;
}
/// anchorPoint getter
const Vec2& Node::getAnchorPoint() const
{
return _anchorPoint;
}
void Node::setAnchorPoint(const Vec2& point)
{
if (! point.equals(_anchorPoint))
{
_anchorPoint = point;
_anchorPointInPoints.set(_contentSize.width * _anchorPoint.x, _contentSize.height * _anchorPoint.y);
_transformUpdated = _transformDirty = _inverseDirty = true;
}
}
/// contentSize getter
const Size& Node::getContentSize() const
{
return _contentSize;
}
void Node::setContentSize(const Size & size)
{
if (! size.equals(_contentSize))
{
_contentSize = size;
_anchorPointInPoints.set(_contentSize.width * _anchorPoint.x, _contentSize.height * _anchorPoint.y);
_transformUpdated = _transformDirty = _inverseDirty = _contentSizeDirty = true;
}
}
// isRunning getter
bool Node::isRunning() const
{
return _running;
}
/// parent setter
void Node::setParent(Node * parent)
{
_parent = parent;
_transformUpdated = _transformDirty = _inverseDirty = true;
}
/// isRelativeAnchorPoint getter
bool Node::isIgnoreAnchorPointForPosition() const
{
return _ignoreAnchorPointForPosition;
}
/// isRelativeAnchorPoint setter
void Node::setIgnoreAnchorPointForPosition(bool newValue)
{
if (newValue != _ignoreAnchorPointForPosition)
{
_ignoreAnchorPointForPosition = newValue;
_transformUpdated = _transformDirty = _inverseDirty = true;
}
}
/// tag getter
int Node::getTag() const
{
return _tag;
}
/// tag setter
void Node::setTag(int tag)
{
_tag = tag ;
}
const std::string& Node::getName() const
{
return _name;
}
void Node::setName(const std::string& name)
{
_name = name;
std::hash<std::string> h;
_hashOfName = h(name);
}
/// userData setter
void Node::setUserData(void *userData)
{
_userData = userData;
}
void Node::setUserObject(Ref* userObject)
{
#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
if (sEngine)
{
if (userObject)
sEngine->retainScriptObject(this, userObject);
if (_userObject)
sEngine->releaseScriptObject(this, _userObject);
}
#endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
CC_SAFE_RETAIN(userObject);
CC_SAFE_RELEASE(_userObject);
_userObject = userObject;
}
Scene* Node::getScene() const
{
if (!_parent)
return nullptr;
auto sceneNode = _parent;
while (sceneNode->_parent)
{
sceneNode = sceneNode->_parent;
}
return dynamic_cast<Scene*>(sceneNode);
}
Rect Node::getBoundingBox() const
{
Rect rect(0, 0, _contentSize.width, _contentSize.height);
return RectApplyAffineTransform(rect, getNodeToParentAffineTransform());
}
// MARK: Children logic
// lazy allocs
void Node::childrenAlloc()
{
_children.reserve(4);
}
Node* Node::getChildByTag(int tag) const
{
CCASSERT(tag != Node::INVALID_TAG, "Invalid tag");
for (const auto child : _children)
{
if(child && child->_tag == tag)
return child;
}
return nullptr;
}
Node* Node::getChildByName(const std::string& name) const
{
CCASSERT(!name.empty(), "Invalid name");
std::hash<std::string> h;
size_t hash = h(name);
for (const auto& child : _children)
{
// Different strings may have the same hash code, but can use it to compare first for speed
if(child->_hashOfName == hash && child->_name.compare(name) == 0)
return child;
}
return nullptr;
}
void Node::enumerateChildren(const std::string &name, std::function<bool (Node *)> callback) const
{
CCASSERT(!name.empty(), "Invalid name");
CCASSERT(callback != nullptr, "Invalid callback function");
size_t length = name.length();
size_t subStrStartPos = 0; // sub string start index
size_t subStrlength = length; // sub string length
// Starts with '//'?
bool searchRecursively = false;
if (length > 2 && name[0] == '/' && name[1] == '/')
{
searchRecursively = true;
subStrStartPos = 2;
subStrlength -= 2;
}
// End with '/..'?
bool searchFromParent = false;
if (length > 3 &&
name[length-3] == '/' &&
name[length-2] == '.' &&
name[length-1] == '.')
{
searchFromParent = true;
subStrlength -= 3;
}
// Remove '//', '/..' if exist
std::string newName = name.substr(subStrStartPos, subStrlength);
const Node* target = this;
if (searchFromParent)
{
if (nullptr == _parent)
{
return;
}
target = _parent;
}
if (searchRecursively)
{
// name is '//xxx'
target->doEnumerateRecursive(target, newName, callback);
}
else
{
// name is xxx
target->doEnumerate(newName, callback);
}
}
bool Node::doEnumerateRecursive(const Node* node, const std::string &name, std::function<bool (Node *)> callback) const
{
bool ret =false;
if (node->doEnumerate(name, callback))
{
// search itself
ret = true;
}
else
{
// search its children
for (const auto& child : node->getChildren())
{
if (doEnumerateRecursive(child, name, callback))
{
ret = true;
break;
}
}
}
return ret;
}
bool Node::doEnumerate(std::string name, std::function<bool (Node *)> callback) const
{
// name may be xxx/yyy, should find its parent
size_t pos = name.find('/');
std::string searchName = name;
bool needRecursive = false;
if (pos != name.npos)
{
searchName = name.substr(0, pos);
name.erase(0, pos+1);
needRecursive = true;
}
bool ret = false;
for (const auto& child : getChildren())
{
if (std::regex_match(child->_name, std::regex(searchName)))
{
if (!needRecursive)
{
// terminate enumeration if callback return true
if (callback(child))
{
ret = true;
break;
}
}
else
{
ret = child->doEnumerate(name, callback);
if (ret)
break;
}
}
}
return ret;
}
/* "add" logic MUST only be on this method
* If a class want's to extend the 'addChild' behavior it only needs
* to override this method
*/
void Node::addChild(Node *child, int localZOrder, int tag)
{
CCASSERT( child != nullptr, "Argument must be non-nil");
CCASSERT( child->_parent == nullptr, "child already added. It can't be added again");
addChildHelper(child, localZOrder, tag, "", true);
}
void Node::addChild(Node* child, int localZOrder, const std::string &name)
{
CCASSERT(child != nullptr, "Argument must be non-nil");
CCASSERT(child->_parent == nullptr, "child already added. It can't be added again");
addChildHelper(child, localZOrder, INVALID_TAG, name, false);
}
void Node::addChildHelper(Node* child, int localZOrder, int tag, const std::string &name, bool setTag)
{
auto assertNotSelfChild
( [ this, child ]() -> bool
{
for ( Node* parent( getParent() ); parent != nullptr;
parent = parent->getParent() )
if ( parent == child )
return false;
return true;
} );
(void)assertNotSelfChild;
CCASSERT( assertNotSelfChild(),
"A node cannot be the child of his own children" );
if (_children.empty())
{
this->childrenAlloc();
}
this->insertChild(child, localZOrder);
if (setTag)
child->setTag(tag);
else
child->setName(name);
child->setParent(this);
child->updateOrderOfArrival();
if( _running )
{
child->onEnter();
// prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter
if (_isTransitionFinished)
{
child->onEnterTransitionDidFinish();
}
}
if (_cascadeColorEnabled)
{
updateCascadeColor();
}
if (_cascadeOpacityEnabled)
{
updateCascadeOpacity();
}
}
void Node::addChild(Node *child, int zOrder)
{
CCASSERT( child != nullptr, "Argument must be non-nil");
this->addChild(child, zOrder, child->_name);
}
void Node::addChild(Node *child)
{
CCASSERT( child != nullptr, "Argument must be non-nil");
this->addChild(child, child->getLocalZOrder(), child->_name);
}
void Node::removeFromParent()
{
this->removeFromParentAndCleanup(true);
}
void Node::removeFromParentAndCleanup(bool cleanup)
{
if (_parent != nullptr)
{
_parent->removeChild(this,cleanup);
}
}
/* "remove" logic MUST only be on this method
* If a class want's to extend the 'removeChild' behavior it only needs
* to override this method
*/
void Node::removeChild(Node* child, bool cleanup /* = true */)
{
// explicit nil handling
if (_children.empty())
{
return;
}
ssize_t index = _children.getIndex(child);
if( index != CC_INVALID_INDEX )
this->detachChild( child, index, cleanup );
}
void Node::removeChildByTag(int tag, bool cleanup/* = true */)
{
CCASSERT( tag != Node::INVALID_TAG, "Invalid tag");
Node *child = this->getChildByTag(tag);
if (child == nullptr)
{
CCLOG("cocos2d: removeChildByTag(tag = %d): child not found!", tag);
}
else
{
this->removeChild(child, cleanup);
}
}
void Node::removeChildByName(const std::string &name, bool cleanup)
{
CCASSERT(!name.empty(), "Invalid name");
Node *child = this->getChildByName(name);
if (child == nullptr)
{
CCLOG("cocos2d: removeChildByName(name = %s): child not found!", name.c_str());
}
else
{
this->removeChild(child, cleanup);
}
}
void Node::removeAllChildren()
{
this->removeAllChildrenWithCleanup(true);
}
void Node::removeAllChildrenWithCleanup(bool cleanup)
{
// not using detachChild improves speed here
for (const auto& child : _children)
{
// IMPORTANT:
// -1st do onExit
// -2nd cleanup
if(_running)
{
child->onExitTransitionDidStart();
child->onExit();
}
if (cleanup)
{
child->cleanup();
}
#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
if (sEngine)
{
sEngine->releaseScriptObject(this, child);
}
#endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
// set parent nil at the end
child->setParent(nullptr);
}
_children.clear();
}
void Node::detachChild(Node *child, ssize_t childIndex, bool doCleanup)
{
// IMPORTANT:
// -1st do onExit
// -2nd cleanup
if (_running)
{
child->onExitTransitionDidStart();
child->onExit();
}
// If you don't do cleanup, the child's actions will not get removed and the
// its scheduledSelectors_ dict will not get released!
if (doCleanup)
{
child->cleanup();
}
#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
if (sEngine)
{
sEngine->releaseScriptObject(this, child);
}
#endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
// set parent nil at the end
child->setParent(nullptr);
_children.erase(childIndex);
}
// helper used by reorderChild & add
void Node::insertChild(Node* child, int z)
{
#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
if (sEngine)
{
sEngine->retainScriptObject(this, child);
}
#endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
_transformUpdated = true;
_reorderChildDirty = true;
_children.pushBack(child);
child->_setLocalZOrder(z);
}
void Node::reorderChild(Node *child, int zOrder)
{
CCASSERT( child != nullptr, "Child must be non-nil");
_reorderChildDirty = true;
child->updateOrderOfArrival();
child->_setLocalZOrder(zOrder);
}
void Node::sortAllChildren()
{
if (_reorderChildDirty)
{
sortNodes(_children);
_reorderChildDirty = false;
_eventDispatcher->setDirtyForNode(this);
}
}
// MARK: draw / visit
void Node::draw()
{
auto renderer = _director->getRenderer();
draw(renderer, _modelViewTransform, FLAGS_TRANSFORM_DIRTY);
}
void Node::draw(Renderer* /*renderer*/, const Mat4 & /*transform*/, uint32_t /*flags*/)
{
}
void Node::visit()
{
auto renderer = _director->getRenderer();
auto& parentTransform = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
visit(renderer, parentTransform, FLAGS_TRANSFORM_DIRTY);
}
uint32_t Node::processParentFlags(const Mat4& parentTransform, uint32_t parentFlags)
{
if(_usingNormalizedPosition)
{
CCASSERT(_parent, "setPositionNormalized() doesn't work with orphan nodes");
if ((parentFlags & FLAGS_CONTENT_SIZE_DIRTY) || _normalizedPositionDirty)
{
auto& s = _parent->getContentSize();
_position.x = _normalizedPosition.x * s.width;
_position.y = _normalizedPosition.y * s.height;
_transformUpdated = _transformDirty = _inverseDirty = true;
_normalizedPositionDirty = false;
}
}
// Fixes Github issue #16100. Basically when having two cameras, one camera might set as dirty the
// node that is not visited by it, and might affect certain calculations. Besides, it is faster to do this.
if (!isVisitableByVisitingCamera())
return parentFlags;
uint32_t flags = parentFlags;
flags |= (_transformUpdated ? FLAGS_TRANSFORM_DIRTY : 0);
flags |= (_contentSizeDirty ? FLAGS_CONTENT_SIZE_DIRTY : 0);
if(flags & FLAGS_DIRTY_MASK)
_modelViewTransform = this->transform(parentTransform);
_transformUpdated = false;
_contentSizeDirty = false;
return flags;
}
bool Node::isVisitableByVisitingCamera() const
{
auto camera = Camera::getVisitingCamera();
bool visibleByCamera = camera ? ((unsigned short)camera->getCameraFlag() & _cameraMask) != 0 : true;
return visibleByCamera;
}
void Node::visit(Renderer* renderer, const Mat4 &parentTransform, uint32_t parentFlags)
{
// quick return if not visible. children won't be drawn.
if (!_visible)
{
return;
}
uint32_t flags = processParentFlags(parentTransform, parentFlags);
// IMPORTANT:
// To ease the migration to v3.0, we still support the Mat4 stack,
// but it is deprecated and your code should not rely on it
_director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
_director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
bool visibleByCamera = isVisitableByVisitingCamera();
int i = 0;
if(!_children.empty())
{
sortAllChildren();
// draw children zOrder < 0
for(auto size = _children.size(); i < size; ++i)
{
auto node = _children.at(i);
if (node && node->_localZOrder < 0)
node->visit(renderer, _modelViewTransform, flags);
else
break;
}
// self draw
if (visibleByCamera)
this->draw(renderer, _modelViewTransform, flags);
for(auto it=_children.cbegin()+i, itCend = _children.cend(); it != itCend; ++it)
(*it)->visit(renderer, _modelViewTransform, flags);
}
else if (visibleByCamera)
{
this->draw(renderer, _modelViewTransform, flags);
}
_director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
// FIX ME: Why need to set _orderOfArrival to 0??
// Please refer to https://github.com/cocos2d/cocos2d-x/pull/6920
// reset for next frame
// _orderOfArrival = 0;
}
Mat4 Node::transform(const Mat4& parentTransform)
{
return parentTransform * this->getNodeToParentTransform();
}
// MARK: events
void Node::onEnter()
{
if (!_running)
{
++__attachedNodeCount;
}
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeJavascript)
{
if (ScriptEngineManager::sendNodeEventToJS(this, kNodeOnEnter))
return;
}
#endif
if (_onEnterCallback)
_onEnterCallback();
if (_componentContainer && !_componentContainer->isEmpty())
{
_componentContainer->onEnter();
}
_isTransitionFinished = false;
for( const auto &child: _children)
child->onEnter();
this->resume();
_running = true;
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeLua)
{
ScriptEngineManager::sendNodeEventToLua(this, kNodeOnEnter);
}
#endif
}
void Node::onEnterTransitionDidFinish()
{
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeJavascript)
{
if (ScriptEngineManager::sendNodeEventToJS(this, kNodeOnEnterTransitionDidFinish))
return;
}
#endif
if (_onEnterTransitionDidFinishCallback)
_onEnterTransitionDidFinishCallback();
_isTransitionFinished = true;
for( const auto &child: _children)
child->onEnterTransitionDidFinish();
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeLua)
{
ScriptEngineManager::sendNodeEventToLua(this, kNodeOnEnterTransitionDidFinish);
}
#endif
}
void Node::onExitTransitionDidStart()
{
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeJavascript)
{
if (ScriptEngineManager::sendNodeEventToJS(this, kNodeOnExitTransitionDidStart))
return;
}
#endif
if (_onExitTransitionDidStartCallback)
_onExitTransitionDidStartCallback();
for( const auto &child: _children)
child->onExitTransitionDidStart();
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeLua)
{
ScriptEngineManager::sendNodeEventToLua(this, kNodeOnExitTransitionDidStart);
}
#endif
}
void Node::onExit()
{
if (_running)
{
--__attachedNodeCount;
}
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeJavascript)
{
if (ScriptEngineManager::sendNodeEventToJS(this, kNodeOnExit))
return;
}
#endif
if (_onExitCallback)
_onExitCallback();
if (_componentContainer && !_componentContainer->isEmpty())
{
_componentContainer->onExit();
}
this->pause();
_running = false;
for( const auto &child: _children)
child->onExit();
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeLua)
{
ScriptEngineManager::sendNodeEventToLua(this, kNodeOnExit);
}
#endif
}
void Node::setEventDispatcher(EventDispatcher* dispatcher)
{
if (dispatcher != _eventDispatcher)
{
_eventDispatcher->removeEventListenersForTarget(this);
CC_SAFE_RETAIN(dispatcher);
CC_SAFE_RELEASE(_eventDispatcher);
_eventDispatcher = dispatcher;
}
}
void Node::setActionManager(ActionManager* actionManager)
{
if( actionManager != _actionManager )
{
this->stopAllActions();
CC_SAFE_RETAIN(actionManager);
CC_SAFE_RELEASE(_actionManager);
_actionManager = actionManager;
}
}
// MARK: actions
Action * Node::runAction(Action* action)
{
CCASSERT( action != nullptr, "Argument must be non-nil");
_actionManager->addAction(action, this, !_running);
return action;
}
void Node::stopAllActions()
{
_actionManager->removeAllActionsFromTarget(this);
}
void Node::stopAction(Action* action)
{
_actionManager->removeAction(action);
}
void Node::stopActionByTag(int tag)
{
CCASSERT( tag != Action::INVALID_TAG, "Invalid tag");
_actionManager->removeActionByTag(tag, this);
}
void Node::stopAllActionsByTag(int tag)
{
CCASSERT( tag != Action::INVALID_TAG, "Invalid tag");
_actionManager->removeAllActionsByTag(tag, this);
}
void Node::stopActionsByFlags(unsigned int flags)
{
if (flags > 0)
{
_actionManager->removeActionsByFlags(flags, this);
}
}
Action * Node::getActionByTag(int tag)
{
CCASSERT( tag != Action::INVALID_TAG, "Invalid tag");
return _actionManager->getActionByTag(tag, this);
}
ssize_t Node::getNumberOfRunningActions() const
{
return _actionManager->getNumberOfRunningActionsInTarget(this);
}
ssize_t Node::getNumberOfRunningActionsByTag(int tag) const
{
return _actionManager->getNumberOfRunningActionsInTargetByTag(this, tag);
}
// MARK: Callbacks
void Node::setScheduler(Scheduler* scheduler)
{
if( scheduler != _scheduler )
{
this->unscheduleAllCallbacks();
CC_SAFE_RETAIN(scheduler);
CC_SAFE_RELEASE(_scheduler);
_scheduler = scheduler;
}
}
bool Node::isScheduled(SEL_SCHEDULE selector) const
{
return _scheduler->isScheduled(selector, this);
}
bool Node::isScheduled(const std::string &key) const
{
return _scheduler->isScheduled(key, this);
}
void Node::scheduleUpdate()
{
scheduleUpdateWithPriority(0);
}
void Node::scheduleUpdateWithPriority(int priority)
{
_scheduler->scheduleUpdate(this, priority, !_running);
}
void Node::scheduleUpdateWithPriorityLua(int nHandler, int priority)
{
unscheduleUpdate();
#if CC_ENABLE_SCRIPT_BINDING
_updateScriptHandler = nHandler;
#endif
_scheduler->scheduleUpdate(this, priority, !_running);
}
void Node::unscheduleUpdate()
{
_scheduler->unscheduleUpdate(this);
#if CC_ENABLE_SCRIPT_BINDING
if (_updateScriptHandler)
{
ScriptEngineManager::getInstance()->getScriptEngine()->removeScriptHandler(_updateScriptHandler);
_updateScriptHandler = 0;
}
#endif
}
void Node::schedule(SEL_SCHEDULE selector)
{
this->schedule(selector, 0.0f, CC_REPEAT_FOREVER, 0.0f);
}
void Node::schedule(SEL_SCHEDULE selector, float interval)
{
this->schedule(selector, interval, CC_REPEAT_FOREVER, 0.0f);
}
void Node::schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay)
{
CCASSERT( selector, "Argument must be non-nil");
CCASSERT( interval >=0, "Argument must be positive");
_scheduler->schedule(selector, this, interval , repeat, delay, !_running);
}
void Node::schedule(const std::function<void(float)> &callback, const std::string &key)
{
_scheduler->schedule(callback, this, 0, !_running, key);
}
void Node::schedule(const std::function<void(float)> &callback, float interval, const std::string &key)
{
_scheduler->schedule(callback, this, interval, !_running, key);
}
void Node::schedule(const std::function<void(float)>& callback, float interval, unsigned int repeat, float delay, const std::string &key)
{
_scheduler->schedule(callback, this, interval, repeat, delay, !_running, key);
}
void Node::scheduleOnce(SEL_SCHEDULE selector, float delay)
{
this->schedule(selector, 0.0f, 0, delay);
}
void Node::scheduleOnce(const std::function<void(float)> &callback, float delay, const std::string &key)
{
_scheduler->schedule(callback, this, 0, 0, delay, !_running, key);
}
void Node::unschedule(SEL_SCHEDULE selector)
{
// explicit null handling
if (selector == nullptr)
return;
_scheduler->unschedule(selector, this);
}
void Node::unschedule(const std::string &key)
{
_scheduler->unschedule(key, this);
}
void Node::unscheduleAllCallbacks()
{
_scheduler->unscheduleAllForTarget(this);
}
void Node::resume()
{
_scheduler->resumeTarget(this);
_actionManager->resumeTarget(this);
_eventDispatcher->resumeEventListenersForTarget(this);
}
void Node::pause()
{
_scheduler->pauseTarget(this);
_actionManager->pauseTarget(this);
_eventDispatcher->pauseEventListenersForTarget(this);
}
// override me
void Node::update(float fDelta)
{
#if CC_ENABLE_SCRIPT_BINDING
if (0 != _updateScriptHandler)
{
//only lua use
SchedulerScriptData data(_updateScriptHandler,fDelta);
ScriptEvent event(kScheduleEvent,&data);
ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
}
#endif
if (_componentContainer && !_componentContainer->isEmpty())
{
_componentContainer->visit(fDelta);
}
}
// MARK: coordinates
AffineTransform Node::getNodeToParentAffineTransform() const
{
AffineTransform ret;
GLToCGAffine(getNodeToParentTransform().m, &ret);
return ret;
}
Mat4 Node::getNodeToParentTransform(Node* ancestor) const
{
Mat4 t(this->getNodeToParentTransform());
for (Node *p = _parent; p != nullptr && p != ancestor ; p = p->getParent())
{
t = p->getNodeToParentTransform() * t;
}
return t;
}
AffineTransform Node::getNodeToParentAffineTransform(Node* ancestor) const
{
AffineTransform t(this->getNodeToParentAffineTransform());
for (Node *p = _parent; p != nullptr && p != ancestor; p = p->getParent())
t = AffineTransformConcat(t, p->getNodeToParentAffineTransform());
return t;
}
const Mat4& Node::getNodeToParentTransform() const
{
if (_transformDirty)
{
// Translate values
float x = _position.x;
float y = _position.y;
float z = _positionZ;
if (_ignoreAnchorPointForPosition)
{
x += _anchorPointInPoints.x;
y += _anchorPointInPoints.y;
}
bool needsSkewMatrix = ( _skewX || _skewY );
// Build Transform Matrix = translation * rotation * scale
Mat4 translation;
//move to anchor point first, then rotate
Mat4::createTranslation(x, y, z, &translation);
Mat4::createRotation(_rotationQuat, &_transform);
if (_rotationZ_X != _rotationZ_Y)
{
// Rotation values
// Change rotation code to handle X and Y
// If we skew with the exact same value for both x and y then we're simply just rotating
float radiansX = -CC_DEGREES_TO_RADIANS(_rotationZ_X);
float radiansY = -CC_DEGREES_TO_RADIANS(_rotationZ_Y);
float cx = cosf(radiansX);
float sx = sinf(radiansX);
float cy = cosf(radiansY);
float sy = sinf(radiansY);
float m0 = _transform.m[0], m1 = _transform.m[1], m4 = _transform.m[4], m5 = _transform.m[5], m8 = _transform.m[8], m9 = _transform.m[9];
_transform.m[0] = cy * m0 - sx * m1;
_transform.m[4] = cy * m4 - sx * m5;
_transform.m[8] = cy * m8 - sx * m9;
_transform.m[1] = sy * m0 + cx * m1;
_transform.m[5] = sy * m4 + cx * m5;
_transform.m[9] = sy * m8 + cx * m9;
}
_transform = translation * _transform;
if (_scaleX != 1.f)
{
_transform.m[0] *= _scaleX;
_transform.m[1] *= _scaleX;
_transform.m[2] *= _scaleX;
}
if (_scaleY != 1.f)
{
_transform.m[4] *= _scaleY;
_transform.m[5] *= _scaleY;
_transform.m[6] *= _scaleY;
}
if (_scaleZ != 1.f)
{
_transform.m[8] *= _scaleZ;
_transform.m[9] *= _scaleZ;
_transform.m[10] *= _scaleZ;
}
// FIXME:: Try to inline skew
// If skew is needed, apply skew and then anchor point
if (needsSkewMatrix)
{
float skewMatArray[16] =
{
1, (float)tanf(CC_DEGREES_TO_RADIANS(_skewY)), 0, 0,
(float)tanf(CC_DEGREES_TO_RADIANS(_skewX)), 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
};
Mat4 skewMatrix(skewMatArray);
_transform = _transform * skewMatrix;
}
// adjust anchor point
if (!_anchorPointInPoints.isZero())
{
// FIXME:: Argh, Mat4 needs a "translate" method.
// FIXME:: Although this is faster than multiplying a vec4 * mat4
_transform.m[12] += _transform.m[0] * -_anchorPointInPoints.x + _transform.m[4] * -_anchorPointInPoints.y;
_transform.m[13] += _transform.m[1] * -_anchorPointInPoints.x + _transform.m[5] * -_anchorPointInPoints.y;
_transform.m[14] += _transform.m[2] * -_anchorPointInPoints.x + _transform.m[6] * -_anchorPointInPoints.y;
}
}
if (_additionalTransform)
{
// This is needed to support both Node::setNodeToParentTransform() and Node::setAdditionalTransform()
// at the same time. The scenario is this:
// at some point setNodeToParentTransform() is called.
// and later setAdditionalTransform() is called every time. And since _transform
// is being overwritten everyframe, _additionalTransform[1] is used to have a copy
// of the last "_transform without _additionalTransform"
if (_transformDirty)
_additionalTransform[1] = _transform;
if (_transformUpdated)
_transform = _additionalTransform[1] * _additionalTransform[0];
}
_transformDirty = _additionalTransformDirty = false;
return _transform;
}
void Node::setNodeToParentTransform(const Mat4& transform)
{
_transform = transform;
_transformDirty = false;
_transformUpdated = true;
if (_additionalTransform)
// _additionalTransform[1] has a copy of lastest transform
_additionalTransform[1] = transform;
}
void Node::setAdditionalTransform(const AffineTransform& additionalTransform)
{
Mat4 tmp;
CGAffineToGL(additionalTransform, tmp.m);
setAdditionalTransform(&tmp);
}
void Node::setAdditionalTransform(const Mat4* additionalTransform)
{
if (additionalTransform == nullptr)
{
if(_additionalTransform) _transform = _additionalTransform[1];
delete[] _additionalTransform;
_additionalTransform = nullptr;
}
else
{
if (!_additionalTransform) {
_additionalTransform = new Mat4[2];
// _additionalTransform[1] is used as a backup for _transform
_additionalTransform[1] = _transform;
}
_additionalTransform[0] = *additionalTransform;
}
_transformUpdated = _additionalTransformDirty = _inverseDirty = true;
}
void Node::setAdditionalTransform(const Mat4& additionalTransform)
{
setAdditionalTransform(&additionalTransform);
}
AffineTransform Node::getParentToNodeAffineTransform() const
{
AffineTransform ret;
GLToCGAffine(getParentToNodeTransform().m,&ret);
return ret;
}
const Mat4& Node::getParentToNodeTransform() const
{
if ( _inverseDirty )
{
_inverse = getNodeToParentTransform().getInversed();
_inverseDirty = false;
}
return _inverse;
}
AffineTransform Node::getNodeToWorldAffineTransform() const
{
return this->getNodeToParentAffineTransform(nullptr);
}
Mat4 Node::getNodeToWorldTransform() const
{
return this->getNodeToParentTransform(nullptr);
}
AffineTransform Node::getWorldToNodeAffineTransform() const
{
return AffineTransformInvert(this->getNodeToWorldAffineTransform());
}
Mat4 Node::getWorldToNodeTransform() const
{
return getNodeToWorldTransform().getInversed();
}
Vec2 Node::convertToNodeSpace(const Vec2& worldPoint) const
{
Mat4 tmp = getWorldToNodeTransform();
Vec3 vec3(worldPoint.x, worldPoint.y, 0);
Vec3 ret;
tmp.transformPoint(vec3,&ret);
return Vec2(ret.x, ret.y);
}
Vec2 Node::convertToWorldSpace(const Vec2& nodePoint) const
{
Mat4 tmp = getNodeToWorldTransform();
Vec3 vec3(nodePoint.x, nodePoint.y, 0);
Vec3 ret;
tmp.transformPoint(vec3,&ret);
return Vec2(ret.x, ret.y);
}
Vec2 Node::convertToNodeSpaceAR(const Vec2& worldPoint) const
{
Vec2 nodePoint(convertToNodeSpace(worldPoint));
return nodePoint - _anchorPointInPoints;
}
Vec2 Node::convertToWorldSpaceAR(const Vec2& nodePoint) const
{
return convertToWorldSpace(nodePoint + _anchorPointInPoints);
}
Vec2 Node::convertToWindowSpace(const Vec2& nodePoint) const
{
Vec2 worldPoint(this->convertToWorldSpace(nodePoint));
return _director->convertToUI(worldPoint);
}
// convenience methods which take a Touch instead of Vec2
Vec2 Node::convertTouchToNodeSpace(Touch *touch) const
{
return this->convertToNodeSpace(touch->getLocation());
}
Vec2 Node::convertTouchToNodeSpaceAR(Touch *touch) const
{
Vec2 point = touch->getLocation();
return this->convertToNodeSpaceAR(point);
}
void Node::updateTransform()
{
// Recursively iterate over children
for( const auto &child: _children)
child->updateTransform();
}
// MARK: components
Component* Node::getComponent(const std::string& name)
{
if (_componentContainer)
return _componentContainer->get(name);
return nullptr;
}
bool Node::addComponent(Component *component)
{
// lazy alloc
if (!_componentContainer)
_componentContainer = new (std::nothrow) ComponentContainer(this);
// should enable schedule update, then all components can receive this call back
scheduleUpdate();
return _componentContainer->add(component);
}
bool Node::removeComponent(const std::string& name)
{
if (_componentContainer)
return _componentContainer->remove(name);
return false;
}
bool Node::removeComponent(Component *component)
{
if (_componentContainer)
{
return _componentContainer->remove(component);
}
return false;
}
void Node::removeAllComponents()
{
if (_componentContainer)
_componentContainer->removeAll();
}
// MARK: Opacity and Color
uint8_t Node::getOpacity() const
{
return _realOpacity;
}
uint8_t Node::getDisplayedOpacity() const
{
return _displayedOpacity;
}
void Node::setOpacity(uint8_t opacity)
{
_displayedOpacity = _realOpacity = opacity;
updateCascadeOpacity();
}
void Node::updateDisplayedOpacity(uint8_t parentOpacity)
{
_displayedOpacity = _realOpacity * parentOpacity/255.0;
updateColor();
if (_cascadeOpacityEnabled)
{
for(const auto& child : _children)
{
child->updateDisplayedOpacity(_displayedOpacity);
}
}
}
bool Node::isCascadeOpacityEnabled() const
{
return _cascadeOpacityEnabled;
}
void Node::setCascadeOpacityEnabled(bool cascadeOpacityEnabled)
{
if (_cascadeOpacityEnabled == cascadeOpacityEnabled)
{
return;
}
_cascadeOpacityEnabled = cascadeOpacityEnabled;
if (cascadeOpacityEnabled)
{
updateCascadeOpacity();
}
else
{
disableCascadeOpacity();
}
}
void Node::updateCascadeOpacity()
{
uint8_t parentOpacity = 255;
if (_parent != nullptr && _parent->isCascadeOpacityEnabled())
{
parentOpacity = _parent->getDisplayedOpacity();
}
updateDisplayedOpacity(parentOpacity);
}
void Node::disableCascadeOpacity()
{
_displayedOpacity = _realOpacity;
for(const auto& child : _children)
{
child->updateDisplayedOpacity(255);
}
}
void Node::setOpacityModifyRGB(bool /*value*/)
{}
bool Node::isOpacityModifyRGB() const
{
return false;
}
const Color3B& Node::getColor() const
{
return _realColor;
}
const Color3B& Node::getDisplayedColor() const
{
return _displayedColor;
}
void Node::setColor(const Color3B& color)
{
_displayedColor = _realColor = color;
updateCascadeColor();
}
void Node::updateDisplayedColor(const Color3B& parentColor)
{
_displayedColor.r = _realColor.r * parentColor.r/255.0;
_displayedColor.g = _realColor.g * parentColor.g/255.0;
_displayedColor.b = _realColor.b * parentColor.b/255.0;
updateColor();
if (_cascadeColorEnabled)
{
for(const auto &child : _children)
{
child->updateDisplayedColor(_displayedColor);
}
}
}
bool Node::isCascadeColorEnabled() const
{
return _cascadeColorEnabled;
}
void Node::setCascadeColorEnabled(bool cascadeColorEnabled)
{
if (_cascadeColorEnabled == cascadeColorEnabled)
{
return;
}
_cascadeColorEnabled = cascadeColorEnabled;
if (_cascadeColorEnabled)
{
updateCascadeColor();
}
else
{
disableCascadeColor();
}
}
void Node::updateCascadeColor()
{
Color3B parentColor = Color3B::WHITE;
if (_parent && _parent->isCascadeColorEnabled())
{
parentColor = _parent->getDisplayedColor();
}
updateDisplayedColor(parentColor);
}
void Node::disableCascadeColor()
{
for(const auto& child : _children)
{
child->updateDisplayedColor(Color3B::WHITE);
}
}
bool isScreenPointInRect(const Vec2 &pt, const Camera* camera, const Mat4& w2l, const Rect& rect, Vec3 *p)
{
if (nullptr == camera || rect.size.width <= 0 || rect.size.height <= 0)
{
return false;
}
// first, convert pt to near/far plane, get Pn and Pf
Vec3 Pn(pt.x, pt.y, -1), Pf(pt.x, pt.y, 1);
Pn = camera->unprojectGL(Pn);
Pf = camera->unprojectGL(Pf);
// then convert Pn and Pf to node space
w2l.transformPoint(&Pn);
w2l.transformPoint(&Pf);
// Pn and Pf define a line Q(t) = D + t * E which D = Pn
auto E = Pf - Pn;
// second, get three points which define content plane
// these points define a plane P(u, w) = A + uB + wC
Vec3 A = Vec3(rect.origin.x, rect.origin.y, 0);
Vec3 B(rect.origin.x + rect.size.width, rect.origin.y, 0);
Vec3 C(rect.origin.x, rect.origin.y + rect.size.height, 0);
B = B - A;
C = C - A;
// the line Q(t) intercept with plane P(u, w)
// calculate the intercept point P = Q(t)
// (BxC).A - (BxC).D
// t = -----------------
// (BxC).E
Vec3 BxC;
Vec3::cross(B, C, &BxC);
auto BxCdotE = BxC.dot(E);
if (BxCdotE == 0) {
return false;
}
auto t = (BxC.dot(A) - BxC.dot(Pn)) / BxCdotE;
Vec3 P = Pn + t * E;
if (p) {
*p = P;
}
return rect.containsPoint(Vec2(P.x, P.y));
}
// MARK: Camera
void Node::setCameraMask(unsigned short mask, bool applyChildren)
{
_cameraMask = mask;
if (applyChildren)
{
for (const auto& child : _children)
{
child->setCameraMask(mask, applyChildren);
}
}
}
int Node::getAttachedNodeCount()
{
return __attachedNodeCount;
}
void Node::setProgramState(backend::ProgramState* programState)
{
if (_programState != programState)
{
CC_SAFE_RELEASE(_programState);
_programState = programState;
CC_SAFE_RETAIN(programState);
}
}
backend::ProgramState* Node::getProgramState() const
{
return _programState;
}
NS_CC_END