mirror of
https://github.com/4ian/GDevelop.git
synced 2025-10-15 10:19:04 +00:00
Compare commits
435 Commits
hide-toolb
...
move-insta
Author | SHA1 | Date | |
---|---|---|---|
![]() |
34fb7a054f | ||
![]() |
d474c2a47e | ||
![]() |
086d4a1c6f | ||
![]() |
65bc9ef4a8 | ||
![]() |
073268160f | ||
![]() |
40c576bc2d | ||
![]() |
0bbf7ed804 | ||
![]() |
f05fa88eec | ||
![]() |
6d67965c63 | ||
![]() |
dc5dab7086 | ||
![]() |
98a24dc8fc | ||
![]() |
7fa55409ed | ||
![]() |
20f2c0460e | ||
![]() |
dc36bf96f1 | ||
![]() |
426e654f44 | ||
![]() |
dad7546099 | ||
![]() |
6d0f93c3ce | ||
![]() |
0a55eb46d3 | ||
![]() |
2678d86783 | ||
![]() |
b31618568a | ||
![]() |
b3b4681c51 | ||
![]() |
b1b7643efc | ||
![]() |
d43479cbe5 | ||
![]() |
11d3c52197 | ||
![]() |
2ee1050083 | ||
![]() |
ca00afb918 | ||
![]() |
02953a1436 | ||
![]() |
e14215c679 | ||
![]() |
c60ea0701a | ||
![]() |
de6ae1cc8f | ||
![]() |
ad24acd72f | ||
![]() |
3c0bb83032 | ||
![]() |
d5c96d74ed | ||
![]() |
43aada8ae7 | ||
![]() |
17a7c2815f | ||
![]() |
9441774a22 | ||
![]() |
d279276cc0 | ||
![]() |
c7f8a7a2eb | ||
![]() |
0fb92e000b | ||
![]() |
76d43e1695 | ||
![]() |
d70e3f71a6 | ||
![]() |
fe50ea3c01 | ||
![]() |
77f821250a | ||
![]() |
c3ee9d9891 | ||
![]() |
313f7857e2 | ||
![]() |
ff028ffa62 | ||
![]() |
3ac2aec229 | ||
![]() |
92e8dfdf04 | ||
![]() |
80726da56d | ||
![]() |
3098fb034f | ||
![]() |
64cc788d43 | ||
![]() |
a85668c8d9 | ||
![]() |
9d0f172663 | ||
![]() |
e0d2f16dc1 | ||
![]() |
0578c45b0f | ||
![]() |
a8866a7bd6 | ||
![]() |
ec62e33530 | ||
![]() |
e1f12837f1 | ||
![]() |
732f3c14b9 | ||
![]() |
7fdad45192 | ||
![]() |
add042ec16 | ||
![]() |
94590d3713 | ||
![]() |
de310512a3 | ||
![]() |
a9edd2f21a | ||
![]() |
0cc03bd4b5 | ||
![]() |
cdbcaf59d9 | ||
![]() |
4e9b09e426 | ||
![]() |
e174136fb4 | ||
![]() |
3d843a0170 | ||
![]() |
ee2f7fb8dc | ||
![]() |
a780601230 | ||
![]() |
cc42923e16 | ||
![]() |
0e8a223b24 | ||
![]() |
c2f17f9348 | ||
![]() |
0ba59d5d7f | ||
![]() |
6878a4cd75 | ||
![]() |
33eed58c62 | ||
![]() |
f516eff739 | ||
![]() |
baefc272f6 | ||
![]() |
2badc72dfb | ||
![]() |
5e54f02061 | ||
![]() |
827bb2d08d | ||
![]() |
0fda0baa48 | ||
![]() |
e655cc0661 | ||
![]() |
225d1b37ab | ||
![]() |
5a0ab9dffa | ||
![]() |
9300604d56 | ||
![]() |
02fcf1dbc2 | ||
![]() |
a70b2e2c2c | ||
![]() |
3e04b5a82f | ||
![]() |
cbcf0b7b70 | ||
![]() |
5d1fe83655 | ||
![]() |
7cf70a6fd7 | ||
![]() |
24c2dbc340 | ||
![]() |
290901849c | ||
![]() |
59721cba7e | ||
![]() |
53cd78bb45 | ||
![]() |
49f8ce9385 | ||
![]() |
de2a9725f9 | ||
![]() |
b2ec3b5387 | ||
![]() |
1873b5e592 | ||
![]() |
e47e35c090 | ||
![]() |
ae572683f1 | ||
![]() |
f8e387230f | ||
![]() |
9451e5969f | ||
![]() |
ad7ddf09a3 | ||
![]() |
8e70930d8d | ||
![]() |
ab3bda24dc | ||
![]() |
d33a7331b3 | ||
![]() |
4d3793815f | ||
![]() |
e1835d1144 | ||
![]() |
72068460e1 | ||
![]() |
5da76ae655 | ||
![]() |
b5b25ad710 | ||
![]() |
2279f069af | ||
![]() |
f0a68db0d4 | ||
![]() |
15ed28ad8d | ||
![]() |
4291d5597a | ||
![]() |
7af3fa5f2f | ||
![]() |
5ce9591f68 | ||
![]() |
d5929010a7 | ||
![]() |
30f2f5256b | ||
![]() |
806d59fb88 | ||
![]() |
e5f18ae2d8 | ||
![]() |
15a7fd1f85 | ||
![]() |
3678a0dd45 | ||
![]() |
197bd913b8 | ||
![]() |
baef911d61 | ||
![]() |
771e16e779 | ||
![]() |
a2cf8e694b | ||
![]() |
cb151ea30e | ||
![]() |
7d1ebc8963 | ||
![]() |
510a699c03 | ||
![]() |
08892b68d4 | ||
![]() |
e079fa4108 | ||
![]() |
5a26e883b8 | ||
![]() |
6bf5b389b5 | ||
![]() |
2837a2906a | ||
![]() |
8c63fae2f2 | ||
![]() |
f837c22290 | ||
![]() |
465bfa4deb | ||
![]() |
a047ecdf9c | ||
![]() |
04c28de00b | ||
![]() |
a7df6de044 | ||
![]() |
81c3199d00 | ||
![]() |
dbe93a4bfd | ||
![]() |
e0edbe8d57 | ||
![]() |
c25d51805f | ||
![]() |
ab695370bb | ||
![]() |
15ee216e33 | ||
![]() |
3fac0522c9 | ||
![]() |
8d502d7c5c | ||
![]() |
12d18c45bc | ||
![]() |
d255ab458b | ||
![]() |
fbfa0315de | ||
![]() |
9575705d29 | ||
![]() |
1223eaa348 | ||
![]() |
21ea077768 | ||
![]() |
11895decd9 | ||
![]() |
c0e1e9fac6 | ||
![]() |
bd9c631e1b | ||
![]() |
4a6e8ef664 | ||
![]() |
e25345000d | ||
![]() |
111d37fc15 | ||
![]() |
4a83c9eb59 | ||
![]() |
177cb2c519 | ||
![]() |
b5d69dee4c | ||
![]() |
fbdaebe575 | ||
![]() |
2a2fd75ca3 | ||
![]() |
af7563b4b7 | ||
![]() |
1861c3be41 | ||
![]() |
895dc625eb | ||
![]() |
52aea76677 | ||
![]() |
4f87191176 | ||
![]() |
43d4e2e8cc | ||
![]() |
cbfaa13978 | ||
![]() |
0aba5cf551 | ||
![]() |
a3ef07c163 | ||
![]() |
a8ede5eee7 | ||
![]() |
ce965ca31c | ||
![]() |
039fbb8b1b | ||
![]() |
80c1e67146 | ||
![]() |
2591cabdd0 | ||
![]() |
45620d6bf4 | ||
![]() |
89a59cdd35 | ||
![]() |
17b819a423 | ||
![]() |
afb4e3c1c6 | ||
![]() |
e5f8fe1bf8 | ||
![]() |
30de5c6fa9 | ||
![]() |
79a29cf7d5 | ||
![]() |
98a1323bf5 | ||
![]() |
0fe6585897 | ||
![]() |
33dd605c57 | ||
![]() |
bab0c227f8 | ||
![]() |
5ad2be4a8a | ||
![]() |
39e18678f5 | ||
![]() |
f54b13a9f5 | ||
![]() |
703adc090a | ||
![]() |
81f0047dab | ||
![]() |
ef70add27b | ||
![]() |
d45932cc04 | ||
![]() |
081a97a5fc | ||
![]() |
2b3cedb441 | ||
![]() |
76426117ff | ||
![]() |
e8720780eb | ||
![]() |
e5ed642121 | ||
![]() |
a6602292b7 | ||
![]() |
859d8e08a0 | ||
![]() |
8128adfd7b | ||
![]() |
f9317dd17f | ||
![]() |
32a169014a | ||
![]() |
37d3fd99eb | ||
![]() |
e0973a8231 | ||
![]() |
876ce0d0a5 | ||
![]() |
9f614ce7e0 | ||
![]() |
63de997e60 | ||
![]() |
d2aa49fd1c | ||
![]() |
d355c16bdf | ||
![]() |
8c7f5d1ea8 | ||
![]() |
08635de08e | ||
![]() |
4dc8676848 | ||
![]() |
164a230cbc | ||
![]() |
f3dc551284 | ||
![]() |
ec674e85d6 | ||
![]() |
32f47900cd | ||
![]() |
320774c8d8 | ||
![]() |
1594f44a72 | ||
![]() |
726d3a8816 | ||
![]() |
097f13db42 | ||
![]() |
15585c2007 | ||
![]() |
ca0a2c3215 | ||
![]() |
d2820bdf2a | ||
![]() |
947e5eb9a3 | ||
![]() |
5901e34f6d | ||
![]() |
1c942d2f9d | ||
![]() |
b419bf8f35 | ||
![]() |
7edfa1284a | ||
![]() |
32e4006b2c | ||
![]() |
e773a1dbfc | ||
![]() |
3942214ba1 | ||
![]() |
461fc36401 | ||
![]() |
fa9198174e | ||
![]() |
96460d92d3 | ||
![]() |
e0d376c15b | ||
![]() |
46e0301dd0 | ||
![]() |
14aa26c651 | ||
![]() |
ab59dfaa86 | ||
![]() |
4841f46d95 | ||
![]() |
faccc6a6f2 | ||
![]() |
f336e76a86 | ||
![]() |
811604d15a | ||
![]() |
dd005941e9 | ||
![]() |
311381332f | ||
![]() |
50173c4127 | ||
![]() |
e030adbb72 | ||
![]() |
3762ccf639 | ||
![]() |
d2758400e0 | ||
![]() |
1551ec440e | ||
![]() |
bd493e39e4 | ||
![]() |
2fb663b63f | ||
![]() |
3878f35107 | ||
![]() |
e055c0edbf | ||
![]() |
a02afc4c68 | ||
![]() |
30130df6fb | ||
![]() |
400cd2e22c | ||
![]() |
dc25a0e87f | ||
![]() |
d21abd97a7 | ||
![]() |
bd38eaf924 | ||
![]() |
360e98b3ee | ||
![]() |
e03908da83 | ||
![]() |
64e7afea7c | ||
![]() |
13077f7ce8 | ||
![]() |
ef68f4e7f6 | ||
![]() |
eaeef23bc6 | ||
![]() |
5a3b12a257 | ||
![]() |
794b74a90c | ||
![]() |
ac4a500fff | ||
![]() |
13a5939550 | ||
![]() |
e560f0f08b | ||
![]() |
3894720a93 | ||
![]() |
2a89b95510 | ||
![]() |
e8e4bf07df | ||
![]() |
4d3b98f78b | ||
![]() |
42ee73b046 | ||
![]() |
0a5df21c1b | ||
![]() |
b0ea0c262b | ||
![]() |
ffa9c45692 | ||
![]() |
15f6f16d22 | ||
![]() |
c3240b6767 | ||
![]() |
2f7fe905b8 | ||
![]() |
0de1d42d73 | ||
![]() |
c4c8931c73 | ||
![]() |
1c9eb654ce | ||
![]() |
ee5b55cfbb | ||
![]() |
7e121526ca | ||
![]() |
79dfec1feb | ||
![]() |
d30a278b97 | ||
![]() |
5ae9e80987 | ||
![]() |
245fb1b3ab | ||
![]() |
bedf8a48a2 | ||
![]() |
3c77c9e2d8 | ||
![]() |
92ba2c3111 | ||
![]() |
3ea754bba2 | ||
![]() |
a3429fb687 | ||
![]() |
476a107c46 | ||
![]() |
f98d28bee2 | ||
![]() |
df5ee8732a | ||
![]() |
bd500f5a90 | ||
![]() |
536518f4bb | ||
![]() |
7e11936fee | ||
![]() |
b0da0508e1 | ||
![]() |
48cc5a27f6 | ||
![]() |
d470513f84 | ||
![]() |
baaeb4317f | ||
![]() |
40156c5e74 | ||
![]() |
da0a47b487 | ||
![]() |
ee12b0b372 | ||
![]() |
31f7ec3a17 | ||
![]() |
3ec7617b14 | ||
![]() |
69e9eebd8e | ||
![]() |
268af00ce8 | ||
![]() |
ad748e4ed5 | ||
![]() |
f933736f1f | ||
![]() |
89861de544 | ||
![]() |
d503fff76b | ||
![]() |
e8dc9e3b20 | ||
![]() |
e40cdfca95 | ||
![]() |
e357fca9c0 | ||
![]() |
6b4f022157 | ||
![]() |
29c276d061 | ||
![]() |
b28eec1071 | ||
![]() |
c3c774579d | ||
![]() |
193977d6d2 | ||
![]() |
931bb10edb | ||
![]() |
408b9c151c | ||
![]() |
bd96a63087 | ||
![]() |
dd5eb3b96f | ||
![]() |
cd46428b81 | ||
![]() |
29926f057e | ||
![]() |
5444896b76 | ||
![]() |
4adb7295bd | ||
![]() |
2edd127d68 | ||
![]() |
eb45ed8b9a | ||
![]() |
3a81c76741 | ||
![]() |
14e2a6236a | ||
![]() |
1ea065dec6 | ||
![]() |
db42bbef62 | ||
![]() |
bd0b610a90 | ||
![]() |
f46213ce6e | ||
![]() |
0909e1d5fe | ||
![]() |
95c15b2edb | ||
![]() |
e48115336d | ||
![]() |
daa957fa7b | ||
![]() |
3d5a997633 | ||
![]() |
ca15d0316d | ||
![]() |
96a9c28e44 | ||
![]() |
006f8b1900 | ||
![]() |
d576b3ede8 | ||
![]() |
195664ee09 | ||
![]() |
bf85daf354 | ||
![]() |
d3192734a1 | ||
![]() |
16f5ecdd0b | ||
![]() |
b17fa8e9ae | ||
![]() |
88bcd797e9 | ||
![]() |
577d605b87 | ||
![]() |
a5e29a7f14 | ||
![]() |
7f27526c7c | ||
![]() |
f3adb4e876 | ||
![]() |
c571a65a32 | ||
![]() |
55f38231a9 | ||
![]() |
6a2e37d147 | ||
![]() |
f6ec9634ce | ||
![]() |
eedb030619 | ||
![]() |
c828c2cace | ||
![]() |
b4188893a0 | ||
![]() |
8ea26ec148 | ||
![]() |
bf73e430f8 | ||
![]() |
343f6a572d | ||
![]() |
66134e95ce | ||
![]() |
1ffb03ccd5 | ||
![]() |
998bf76e72 | ||
![]() |
47553bc020 | ||
![]() |
c84b2410b9 | ||
![]() |
fbbac73e94 | ||
![]() |
c2f0f9b9a3 | ||
![]() |
4d02ae092b | ||
![]() |
7db2849404 | ||
![]() |
d5a3b55e98 | ||
![]() |
79206fbfee | ||
![]() |
2089e29664 | ||
![]() |
38c5425d0c | ||
![]() |
b0d45e80de | ||
![]() |
2ac5beee0c | ||
![]() |
c99c73fa96 | ||
![]() |
f796228d06 | ||
![]() |
ca3836b3c7 | ||
![]() |
918f8ec989 | ||
![]() |
f44d9682ee | ||
![]() |
ce6800164d | ||
![]() |
4afb2de178 | ||
![]() |
9865fd3663 | ||
![]() |
5501527974 | ||
![]() |
3e4826bafc | ||
![]() |
d914f9f5be | ||
![]() |
ab8c90dd41 | ||
![]() |
8882841a8d | ||
![]() |
3d357950f9 | ||
![]() |
ef5d2651c0 | ||
![]() |
1dd4bb9b7a | ||
![]() |
682e6f6b03 | ||
![]() |
b468c28ae8 | ||
![]() |
9fc9452a08 | ||
![]() |
3b176b7152 | ||
![]() |
f1d1a9b66b | ||
![]() |
c0d2f491a8 | ||
![]() |
aeecce2ea8 | ||
![]() |
647ee149ff | ||
![]() |
22313e148a | ||
![]() |
31f2d7ce2e | ||
![]() |
4a0efec6c2 | ||
![]() |
5f555df5c1 | ||
![]() |
53a611a1b9 | ||
![]() |
14511b23af | ||
![]() |
fa2371274d | ||
![]() |
0aea8dfa0f | ||
![]() |
81ca18098d | ||
![]() |
b6e44a022f | ||
![]() |
1a8eee2477 | ||
![]() |
d0ef92da03 | ||
![]() |
9c98cb3b3b | ||
![]() |
3681542056 | ||
![]() |
7c0bf135d7 | ||
![]() |
9a31dd046c | ||
![]() |
74401a1f9c | ||
![]() |
cedc6ea3e9 |
@@ -42,15 +42,19 @@ gd::String EventsCodeGenerator::GenerateRelationalOperatorCall(
|
||||
const vector<gd::String>& arguments,
|
||||
const gd::String& callStartString,
|
||||
std::size_t startFromArgument) {
|
||||
std::size_t relationalOperatorIndex = instrInfos.parameters.GetParametersCount();
|
||||
for (std::size_t i = startFromArgument; i < instrInfos.parameters.GetParametersCount();
|
||||
std::size_t relationalOperatorIndex =
|
||||
instrInfos.parameters.GetParametersCount();
|
||||
for (std::size_t i = startFromArgument;
|
||||
i < instrInfos.parameters.GetParametersCount();
|
||||
++i) {
|
||||
if (instrInfos.parameters.GetParameter(i).GetType() == "relationalOperator") {
|
||||
if (instrInfos.parameters.GetParameter(i).GetType() ==
|
||||
"relationalOperator") {
|
||||
relationalOperatorIndex = i;
|
||||
}
|
||||
}
|
||||
// Ensure that there is at least one parameter after the relational operator
|
||||
if (relationalOperatorIndex + 1 >= instrInfos.parameters.GetParametersCount()) {
|
||||
if (relationalOperatorIndex + 1 >=
|
||||
instrInfos.parameters.GetParametersCount()) {
|
||||
ReportError();
|
||||
return "";
|
||||
}
|
||||
@@ -87,20 +91,23 @@ gd::String EventsCodeGenerator::GenerateRelationalOperation(
|
||||
const gd::String& relationalOperator,
|
||||
const gd::String& lhs,
|
||||
const gd::String& rhs) {
|
||||
return lhs + " " + GenerateRelationalOperatorCodes(relationalOperator) + " " + rhs;
|
||||
return lhs + " " + GenerateRelationalOperatorCodes(relationalOperator) + " " +
|
||||
rhs;
|
||||
}
|
||||
|
||||
const gd::String EventsCodeGenerator::GenerateRelationalOperatorCodes(const gd::String &operatorString) {
|
||||
if (operatorString == "=") {
|
||||
return "==";
|
||||
}
|
||||
if (operatorString != "<" && operatorString != ">" &&
|
||||
operatorString != "<=" && operatorString != ">=" && operatorString != "!=" &&
|
||||
operatorString != "startsWith" && operatorString != "endsWith" && operatorString != "contains") {
|
||||
cout << "Warning: Bad relational operator: Set to == by default." << endl;
|
||||
return "==";
|
||||
}
|
||||
return operatorString;
|
||||
const gd::String EventsCodeGenerator::GenerateRelationalOperatorCodes(
|
||||
const gd::String& operatorString) {
|
||||
if (operatorString == "=") {
|
||||
return "==";
|
||||
}
|
||||
if (operatorString != "<" && operatorString != ">" &&
|
||||
operatorString != "<=" && operatorString != ">=" &&
|
||||
operatorString != "!=" && operatorString != "startsWith" &&
|
||||
operatorString != "endsWith" && operatorString != "contains") {
|
||||
cout << "Warning: Bad relational operator: Set to == by default." << endl;
|
||||
return "==";
|
||||
}
|
||||
return operatorString;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -124,7 +131,8 @@ gd::String EventsCodeGenerator::GenerateOperatorCall(
|
||||
const gd::String& getterStartString,
|
||||
std::size_t startFromArgument) {
|
||||
std::size_t operatorIndex = instrInfos.parameters.GetParametersCount();
|
||||
for (std::size_t i = startFromArgument; i < instrInfos.parameters.GetParametersCount();
|
||||
for (std::size_t i = startFromArgument;
|
||||
i < instrInfos.parameters.GetParametersCount();
|
||||
++i) {
|
||||
if (instrInfos.parameters.GetParameter(i).GetType() == "operator") {
|
||||
operatorIndex = i;
|
||||
@@ -195,7 +203,8 @@ gd::String EventsCodeGenerator::GenerateCompoundOperatorCall(
|
||||
const gd::String& callStartString,
|
||||
std::size_t startFromArgument) {
|
||||
std::size_t operatorIndex = instrInfos.parameters.GetParametersCount();
|
||||
for (std::size_t i = startFromArgument; i < instrInfos.parameters.GetParametersCount();
|
||||
for (std::size_t i = startFromArgument;
|
||||
i < instrInfos.parameters.GetParametersCount();
|
||||
++i) {
|
||||
if (instrInfos.parameters.GetParameter(i).GetType() == "operator") {
|
||||
operatorIndex = i;
|
||||
@@ -248,7 +257,8 @@ gd::String EventsCodeGenerator::GenerateMutatorCall(
|
||||
const gd::String& callStartString,
|
||||
std::size_t startFromArgument) {
|
||||
std::size_t operatorIndex = instrInfos.parameters.GetParametersCount();
|
||||
for (std::size_t i = startFromArgument; i < instrInfos.parameters.GetParametersCount();
|
||||
for (std::size_t i = startFromArgument;
|
||||
i < instrInfos.parameters.GetParametersCount();
|
||||
++i) {
|
||||
if (instrInfos.parameters.GetParameter(i).GetType() == "operator") {
|
||||
operatorIndex = i;
|
||||
@@ -323,34 +333,42 @@ gd::String EventsCodeGenerator::GenerateConditionCode(
|
||||
}
|
||||
|
||||
// Insert code only parameters and be sure there is no lack of parameter.
|
||||
while (condition.GetParameters().size() < instrInfos.parameters.GetParametersCount()) {
|
||||
while (condition.GetParameters().size() <
|
||||
instrInfos.parameters.GetParametersCount()) {
|
||||
vector<gd::Expression> parameters = condition.GetParameters();
|
||||
parameters.push_back(gd::Expression(""));
|
||||
condition.SetParameters(parameters);
|
||||
}
|
||||
|
||||
// Verify that there are no mismatches between object type in parameters.
|
||||
for (std::size_t pNb = 0; pNb < instrInfos.parameters.GetParametersCount(); ++pNb) {
|
||||
if (ParameterMetadata::IsObject(instrInfos.parameters.GetParameter(pNb).GetType())) {
|
||||
for (std::size_t pNb = 0; pNb < instrInfos.parameters.GetParametersCount();
|
||||
++pNb) {
|
||||
if (ParameterMetadata::IsObject(
|
||||
instrInfos.parameters.GetParameter(pNb).GetType())) {
|
||||
gd::String objectInParameter =
|
||||
condition.GetParameter(pNb).GetPlainString();
|
||||
|
||||
const auto &expectedObjectType =
|
||||
const auto& expectedObjectType =
|
||||
instrInfos.parameters.GetParameter(pNb).GetExtraInfo();
|
||||
const auto &actualObjectType =
|
||||
const auto& actualObjectType =
|
||||
GetObjectsContainersList().GetTypeOfObject(objectInParameter);
|
||||
if (!GetObjectsContainersList().HasObjectOrGroupNamed(
|
||||
objectInParameter)) {
|
||||
gd::ProjectDiagnostic projectDiagnostic(
|
||||
gd::ProjectDiagnostic::ErrorType::UnknownObject, "",
|
||||
objectInParameter, "");
|
||||
gd::ProjectDiagnostic::ErrorType::UnknownObject,
|
||||
"",
|
||||
objectInParameter,
|
||||
"");
|
||||
if (diagnosticReport) diagnosticReport->Add(projectDiagnostic);
|
||||
return "/* Unknown object - skipped. */";
|
||||
} else if (!expectedObjectType.empty() &&
|
||||
actualObjectType != expectedObjectType) {
|
||||
gd::ProjectDiagnostic projectDiagnostic(
|
||||
gd::ProjectDiagnostic::ErrorType::MismatchedObjectType, "",
|
||||
actualObjectType, expectedObjectType, objectInParameter);
|
||||
gd::ProjectDiagnostic::ErrorType::MismatchedObjectType,
|
||||
"",
|
||||
actualObjectType,
|
||||
expectedObjectType,
|
||||
objectInParameter);
|
||||
if (diagnosticReport) diagnosticReport->Add(projectDiagnostic);
|
||||
return "/* Mismatched object type - skipped. */";
|
||||
}
|
||||
@@ -366,44 +384,46 @@ gd::String EventsCodeGenerator::GenerateConditionCode(
|
||||
gd::String objectName = condition.GetParameter(0).GetPlainString();
|
||||
if (!objectName.empty() && instrInfos.parameters.GetParametersCount() > 0) {
|
||||
std::vector<gd::String> realObjects =
|
||||
GetObjectsContainersList().ExpandObjectName(objectName, context.GetCurrentObject());
|
||||
GetObjectsContainersList().ExpandObjectName(
|
||||
objectName, context.GetCurrentObject());
|
||||
for (std::size_t i = 0; i < realObjects.size(); ++i) {
|
||||
// Set up the context
|
||||
gd::String objectType = GetObjectsContainersList().GetTypeOfObject(realObjects[i]);
|
||||
gd::String objectType =
|
||||
GetObjectsContainersList().GetTypeOfObject(realObjects[i]);
|
||||
const ObjectMetadata& objInfo =
|
||||
MetadataProvider::GetObjectMetadata(platform, objectType);
|
||||
|
||||
AddIncludeFiles(objInfo.includeFiles);
|
||||
context.SetCurrentObject(realObjects[i]);
|
||||
context.ObjectsListNeeded(realObjects[i]);
|
||||
AddIncludeFiles(objInfo.includeFiles);
|
||||
context.SetCurrentObject(realObjects[i]);
|
||||
context.ObjectsListNeeded(realObjects[i]);
|
||||
|
||||
// Prepare arguments and generate the condition whole code
|
||||
vector<gd::String> arguments = GenerateParametersCodes(
|
||||
condition.GetParameters(), instrInfos.parameters, context);
|
||||
conditionCode += GenerateObjectCondition(realObjects[i],
|
||||
objInfo,
|
||||
arguments,
|
||||
instrInfos,
|
||||
returnBoolean,
|
||||
condition.IsInverted(),
|
||||
context);
|
||||
// Prepare arguments and generate the condition whole code
|
||||
vector<gd::String> arguments = GenerateParametersCodes(
|
||||
condition.GetParameters(), instrInfos.parameters, context);
|
||||
conditionCode += GenerateObjectCondition(realObjects[i],
|
||||
objInfo,
|
||||
arguments,
|
||||
instrInfos,
|
||||
returnBoolean,
|
||||
condition.IsInverted(),
|
||||
context);
|
||||
|
||||
context.SetNoCurrentObject();
|
||||
context.SetNoCurrentObject();
|
||||
}
|
||||
}
|
||||
} else if (instrInfos.IsBehaviorInstruction()) {
|
||||
if (instrInfos.parameters.GetParametersCount() >= 2) {
|
||||
const gd::String &objectName = condition.GetParameter(0).GetPlainString();
|
||||
const gd::String &behaviorName =
|
||||
const gd::String& objectName = condition.GetParameter(0).GetPlainString();
|
||||
const gd::String& behaviorName =
|
||||
condition.GetParameter(1).GetPlainString();
|
||||
const gd::String &actualBehaviorType =
|
||||
const gd::String& actualBehaviorType =
|
||||
GetObjectsContainersList().GetTypeOfBehavior(behaviorName);
|
||||
|
||||
std::vector<gd::String> realObjects =
|
||||
GetObjectsContainersList().ExpandObjectName(
|
||||
objectName, context.GetCurrentObject());
|
||||
|
||||
const BehaviorMetadata &autoInfo =
|
||||
const BehaviorMetadata& autoInfo =
|
||||
MetadataProvider::GetBehaviorMetadata(platform, actualBehaviorType);
|
||||
|
||||
for (std::size_t i = 0; i < realObjects.size(); ++i) {
|
||||
@@ -415,15 +435,14 @@ gd::String EventsCodeGenerator::GenerateConditionCode(
|
||||
// Prepare arguments and generate the whole condition code
|
||||
vector<gd::String> arguments = GenerateParametersCodes(
|
||||
condition.GetParameters(), instrInfos.parameters, context);
|
||||
conditionCode += GenerateBehaviorCondition(
|
||||
realObjects[i],
|
||||
behaviorName,
|
||||
autoInfo,
|
||||
arguments,
|
||||
instrInfos,
|
||||
returnBoolean,
|
||||
condition.IsInverted(),
|
||||
context);
|
||||
conditionCode += GenerateBehaviorCondition(realObjects[i],
|
||||
behaviorName,
|
||||
autoInfo,
|
||||
arguments,
|
||||
instrInfos,
|
||||
returnBoolean,
|
||||
condition.IsInverted(),
|
||||
context);
|
||||
|
||||
context.SetNoCurrentObject();
|
||||
}
|
||||
@@ -493,26 +512,29 @@ gd::String EventsCodeGenerator::GenerateConditionsListCode(
|
||||
}
|
||||
|
||||
bool EventsCodeGenerator::CheckBehaviorParameters(
|
||||
const gd::Instruction &instruction,
|
||||
const gd::InstructionMetadata &instrInfos) {
|
||||
const gd::Instruction& instruction,
|
||||
const gd::InstructionMetadata& instrInfos) {
|
||||
bool isAnyBehaviorMissing = false;
|
||||
gd::ParameterMetadataTools::IterateOverParametersWithIndex(
|
||||
instruction.GetParameters(), instrInfos.parameters,
|
||||
[this, &isAnyBehaviorMissing,
|
||||
&instrInfos](const gd::ParameterMetadata ¶meterMetadata,
|
||||
const gd::Expression ¶meterValue, size_t parameterIndex,
|
||||
const gd::String &lastObjectName, size_t lastObjectIndex) {
|
||||
instruction.GetParameters(),
|
||||
instrInfos.parameters,
|
||||
[this, &isAnyBehaviorMissing, &instrInfos](
|
||||
const gd::ParameterMetadata& parameterMetadata,
|
||||
const gd::Expression& parameterValue,
|
||||
size_t parameterIndex,
|
||||
const gd::String& lastObjectName,
|
||||
size_t lastObjectIndex) {
|
||||
if (ParameterMetadata::IsBehavior(parameterMetadata.GetType())) {
|
||||
const gd::String &behaviorName = parameterValue.GetPlainString();
|
||||
const gd::String &actualBehaviorType =
|
||||
const gd::String& behaviorName = parameterValue.GetPlainString();
|
||||
const gd::String& actualBehaviorType =
|
||||
GetObjectsContainersList().GetTypeOfBehaviorInObjectOrGroup(
|
||||
lastObjectName, behaviorName);
|
||||
const gd::String &expectedBehaviorType =
|
||||
const gd::String& expectedBehaviorType =
|
||||
parameterMetadata.GetExtraInfo();
|
||||
|
||||
if (!expectedBehaviorType.empty() &&
|
||||
actualBehaviorType != expectedBehaviorType) {
|
||||
const auto &objectParameterMetadata =
|
||||
const auto& objectParameterMetadata =
|
||||
instrInfos.GetParameter(lastObjectIndex);
|
||||
// Event functions crash if some objects in a group are missing
|
||||
// the required behaviors, since they lose reference to the original
|
||||
@@ -523,10 +545,12 @@ bool EventsCodeGenerator::CheckBehaviorParameters(
|
||||
isAnyBehaviorMissing = true;
|
||||
}
|
||||
gd::ProjectDiagnostic projectDiagnostic(
|
||||
gd::ProjectDiagnostic::ErrorType::MissingBehavior, "",
|
||||
actualBehaviorType, expectedBehaviorType, lastObjectName);
|
||||
if (diagnosticReport)
|
||||
diagnosticReport->Add(projectDiagnostic);
|
||||
gd::ProjectDiagnostic::ErrorType::MissingBehavior,
|
||||
"",
|
||||
actualBehaviorType,
|
||||
expectedBehaviorType,
|
||||
lastObjectName);
|
||||
if (diagnosticReport) diagnosticReport->Add(projectDiagnostic);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -539,7 +563,8 @@ bool EventsCodeGenerator::CheckBehaviorParameters(
|
||||
gd::String EventsCodeGenerator::GenerateActionCode(
|
||||
gd::Instruction& action,
|
||||
EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName) {
|
||||
const gd::String& optionalAsyncCallbackName,
|
||||
const gd::String& optionalAsyncCallbackId) {
|
||||
gd::String actionCode;
|
||||
|
||||
const gd::InstructionMetadata& instrInfos =
|
||||
@@ -564,33 +589,41 @@ gd::String EventsCodeGenerator::GenerateActionCode(
|
||||
: instrInfos.codeExtraInformation.functionCallName;
|
||||
|
||||
// Be sure there is no lack of parameter.
|
||||
while (action.GetParameters().size() < instrInfos.parameters.GetParametersCount()) {
|
||||
while (action.GetParameters().size() <
|
||||
instrInfos.parameters.GetParametersCount()) {
|
||||
vector<gd::Expression> parameters = action.GetParameters();
|
||||
parameters.push_back(gd::Expression(""));
|
||||
action.SetParameters(parameters);
|
||||
}
|
||||
|
||||
// Verify that there are no mismatches between object type in parameters.
|
||||
for (std::size_t pNb = 0; pNb < instrInfos.parameters.GetParametersCount(); ++pNb) {
|
||||
if (ParameterMetadata::IsObject(instrInfos.parameters.GetParameter(pNb).GetType())) {
|
||||
for (std::size_t pNb = 0; pNb < instrInfos.parameters.GetParametersCount();
|
||||
++pNb) {
|
||||
if (ParameterMetadata::IsObject(
|
||||
instrInfos.parameters.GetParameter(pNb).GetType())) {
|
||||
gd::String objectInParameter = action.GetParameter(pNb).GetPlainString();
|
||||
|
||||
const auto &expectedObjectType =
|
||||
const auto& expectedObjectType =
|
||||
instrInfos.parameters.GetParameter(pNb).GetExtraInfo();
|
||||
const auto &actualObjectType =
|
||||
const auto& actualObjectType =
|
||||
GetObjectsContainersList().GetTypeOfObject(objectInParameter);
|
||||
if (!GetObjectsContainersList().HasObjectOrGroupNamed(
|
||||
objectInParameter)) {
|
||||
gd::ProjectDiagnostic projectDiagnostic(
|
||||
gd::ProjectDiagnostic::ErrorType::UnknownObject, "",
|
||||
objectInParameter, "");
|
||||
gd::ProjectDiagnostic::ErrorType::UnknownObject,
|
||||
"",
|
||||
objectInParameter,
|
||||
"");
|
||||
if (diagnosticReport) diagnosticReport->Add(projectDiagnostic);
|
||||
return "/* Unknown object - skipped. */";
|
||||
} else if (!expectedObjectType.empty() &&
|
||||
actualObjectType != expectedObjectType) {
|
||||
gd::ProjectDiagnostic projectDiagnostic(
|
||||
gd::ProjectDiagnostic::ErrorType::MismatchedObjectType, "",
|
||||
actualObjectType, expectedObjectType, objectInParameter);
|
||||
gd::ProjectDiagnostic::ErrorType::MismatchedObjectType,
|
||||
"",
|
||||
actualObjectType,
|
||||
expectedObjectType,
|
||||
objectInParameter);
|
||||
if (diagnosticReport) diagnosticReport->Add(projectDiagnostic);
|
||||
return "/* Mismatched object type - skipped. */";
|
||||
}
|
||||
@@ -608,43 +641,46 @@ gd::String EventsCodeGenerator::GenerateActionCode(
|
||||
|
||||
if (instrInfos.parameters.GetParametersCount() > 0) {
|
||||
std::vector<gd::String> realObjects =
|
||||
GetObjectsContainersList().ExpandObjectName(objectName, context.GetCurrentObject());
|
||||
GetObjectsContainersList().ExpandObjectName(
|
||||
objectName, context.GetCurrentObject());
|
||||
for (std::size_t i = 0; i < realObjects.size(); ++i) {
|
||||
// Setup context
|
||||
gd::String objectType = GetObjectsContainersList().GetTypeOfObject(realObjects[i]);
|
||||
gd::String objectType =
|
||||
GetObjectsContainersList().GetTypeOfObject(realObjects[i]);
|
||||
const ObjectMetadata& objInfo =
|
||||
MetadataProvider::GetObjectMetadata(platform, objectType);
|
||||
|
||||
AddIncludeFiles(objInfo.includeFiles);
|
||||
context.SetCurrentObject(realObjects[i]);
|
||||
context.ObjectsListNeeded(realObjects[i]);
|
||||
AddIncludeFiles(objInfo.includeFiles);
|
||||
context.SetCurrentObject(realObjects[i]);
|
||||
context.ObjectsListNeeded(realObjects[i]);
|
||||
|
||||
// Prepare arguments and generate the whole action code
|
||||
vector<gd::String> arguments = GenerateParametersCodes(
|
||||
action.GetParameters(), instrInfos.parameters, context);
|
||||
actionCode += GenerateObjectAction(realObjects[i],
|
||||
objInfo,
|
||||
functionCallName,
|
||||
arguments,
|
||||
instrInfos,
|
||||
context,
|
||||
optionalAsyncCallbackName);
|
||||
// Prepare arguments and generate the whole action code
|
||||
vector<gd::String> arguments = GenerateParametersCodes(
|
||||
action.GetParameters(), instrInfos.parameters, context);
|
||||
actionCode += GenerateObjectAction(realObjects[i],
|
||||
objInfo,
|
||||
functionCallName,
|
||||
arguments,
|
||||
instrInfos,
|
||||
context,
|
||||
optionalAsyncCallbackName,
|
||||
optionalAsyncCallbackId);
|
||||
|
||||
context.SetNoCurrentObject();
|
||||
context.SetNoCurrentObject();
|
||||
}
|
||||
}
|
||||
} else if (instrInfos.IsBehaviorInstruction()) {
|
||||
if (instrInfos.parameters.GetParametersCount() >= 2) {
|
||||
const gd::String &objectName = action.GetParameter(0).GetPlainString();
|
||||
const gd::String &behaviorName = action.GetParameter(1).GetPlainString();
|
||||
const gd::String &actualBehaviorType =
|
||||
const gd::String& objectName = action.GetParameter(0).GetPlainString();
|
||||
const gd::String& behaviorName = action.GetParameter(1).GetPlainString();
|
||||
const gd::String& actualBehaviorType =
|
||||
GetObjectsContainersList().GetTypeOfBehavior(behaviorName);
|
||||
|
||||
std::vector<gd::String> realObjects =
|
||||
GetObjectsContainersList().ExpandObjectName(
|
||||
objectName, context.GetCurrentObject());
|
||||
|
||||
const BehaviorMetadata &autoInfo =
|
||||
const BehaviorMetadata& autoInfo =
|
||||
MetadataProvider::GetBehaviorMetadata(platform, actualBehaviorType);
|
||||
|
||||
AddIncludeFiles(autoInfo.includeFiles);
|
||||
@@ -656,15 +692,15 @@ gd::String EventsCodeGenerator::GenerateActionCode(
|
||||
// Prepare arguments and generate the whole action code
|
||||
vector<gd::String> arguments = GenerateParametersCodes(
|
||||
action.GetParameters(), instrInfos.parameters, context);
|
||||
actionCode +=
|
||||
GenerateBehaviorAction(realObjects[i],
|
||||
behaviorName,
|
||||
autoInfo,
|
||||
functionCallName,
|
||||
arguments,
|
||||
instrInfos,
|
||||
context,
|
||||
optionalAsyncCallbackName);
|
||||
actionCode += GenerateBehaviorAction(realObjects[i],
|
||||
behaviorName,
|
||||
autoInfo,
|
||||
functionCallName,
|
||||
arguments,
|
||||
instrInfos,
|
||||
context,
|
||||
optionalAsyncCallbackName,
|
||||
optionalAsyncCallbackId);
|
||||
|
||||
context.SetNoCurrentObject();
|
||||
}
|
||||
@@ -676,7 +712,8 @@ gd::String EventsCodeGenerator::GenerateActionCode(
|
||||
arguments,
|
||||
instrInfos,
|
||||
context,
|
||||
optionalAsyncCallbackName);
|
||||
optionalAsyncCallbackName,
|
||||
optionalAsyncCallbackId);
|
||||
}
|
||||
|
||||
return actionCode;
|
||||
@@ -689,8 +726,8 @@ gd::String EventsCodeGenerator::GenerateLocalVariablesStackAccessor() {
|
||||
}
|
||||
|
||||
gd::String EventsCodeGenerator::GenerateAnyOrSceneVariableGetter(
|
||||
const gd::Expression &variableExpression,
|
||||
EventsCodeGenerationContext &context) {
|
||||
const gd::Expression& variableExpression,
|
||||
EventsCodeGenerationContext& context) {
|
||||
const auto variableName = gd::ExpressionVariableNameFinder::GetVariableName(
|
||||
*variableExpression.GetRootNode());
|
||||
|
||||
@@ -701,8 +738,12 @@ gd::String EventsCodeGenerator::GenerateAnyOrSceneVariableGetter(
|
||||
: "scenevar";
|
||||
|
||||
return gd::ExpressionCodeGenerator::GenerateExpressionCode(
|
||||
*this, context, variableParameterType,
|
||||
variableExpression.GetPlainString(), "", "AllowUndeclaredVariable");
|
||||
*this,
|
||||
context,
|
||||
variableParameterType,
|
||||
variableExpression.GetPlainString(),
|
||||
"",
|
||||
"AllowUndeclaredVariable");
|
||||
}
|
||||
|
||||
const EventsCodeGenerator::CallbackDescriptor
|
||||
@@ -749,6 +790,11 @@ EventsCodeGenerator::GenerateCallback(
|
||||
|
||||
AddCustomCodeOutsideMain(callbackCode);
|
||||
|
||||
const gd::String idToCallbackMapUpdate = GetCodeNamespaceAccessor() +
|
||||
"idToCallbackMap.set(" + callbackID +
|
||||
", " + callbackFunctionName + ");\n";
|
||||
AddCustomCodeOutsideMain(idToCallbackMapUpdate);
|
||||
|
||||
std::set<gd::String> requiredObjects;
|
||||
// Build the list of all objects required by the callback. Any object that has
|
||||
// already been declared could have gone through previous object picking, so
|
||||
@@ -808,13 +854,28 @@ gd::String EventsCodeGenerator::GenerateParameterCodes(
|
||||
|
||||
if (ParameterMetadata::IsExpression("number", metadata.GetType())) {
|
||||
argOutput = gd::ExpressionCodeGenerator::GenerateExpressionCode(
|
||||
*this, context, "number", parameter, lastObjectName, metadata.GetExtraInfo());
|
||||
*this,
|
||||
context,
|
||||
"number",
|
||||
parameter,
|
||||
lastObjectName,
|
||||
metadata.GetExtraInfo());
|
||||
} else if (ParameterMetadata::IsExpression("string", metadata.GetType())) {
|
||||
argOutput = gd::ExpressionCodeGenerator::GenerateExpressionCode(
|
||||
*this, context, "string", parameter, lastObjectName, metadata.GetExtraInfo());
|
||||
*this,
|
||||
context,
|
||||
"string",
|
||||
parameter,
|
||||
lastObjectName,
|
||||
metadata.GetExtraInfo());
|
||||
} else if (ParameterMetadata::IsExpression("variable", metadata.GetType())) {
|
||||
argOutput = gd::ExpressionCodeGenerator::GenerateExpressionCode(
|
||||
*this, context, metadata.GetType(), parameter, lastObjectName, metadata.GetExtraInfo());
|
||||
*this,
|
||||
context,
|
||||
metadata.GetType(),
|
||||
parameter,
|
||||
lastObjectName,
|
||||
metadata.GetExtraInfo());
|
||||
} else if (ParameterMetadata::IsObject(metadata.GetType())) {
|
||||
// It would be possible to run a gd::ExpressionCodeGenerator if later
|
||||
// objects can have nested objects, or function returning objects.
|
||||
@@ -849,7 +910,8 @@ gd::String EventsCodeGenerator::GenerateParameterCodes(
|
||||
metadata.GetType() == "atlasResource" ||
|
||||
metadata.GetType() == "spineResource" ||
|
||||
// Deprecated, old parameter names:
|
||||
metadata.GetType() == "password" || metadata.GetType() == "musicfile" ||
|
||||
metadata.GetType() == "password" ||
|
||||
metadata.GetType() == "musicfile" ||
|
||||
metadata.GetType() == "soundfile") {
|
||||
argOutput = "\"" + ConvertToString(parameter.GetPlainString()) + "\"";
|
||||
} else if (metadata.GetType() == "mouse") {
|
||||
@@ -999,7 +1061,8 @@ gd::String EventsCodeGenerator::GenerateEventsListCode(
|
||||
for (std::size_t eId = 0; eId < events.size(); ++eId) {
|
||||
auto& event = events[eId];
|
||||
if (event.HasVariables()) {
|
||||
GetProjectScopedContainers().GetVariablesContainersList().Push(event.GetVariables());
|
||||
GetProjectScopedContainers().GetVariablesContainersList().Push(
|
||||
event.GetVariables());
|
||||
}
|
||||
|
||||
// Each event has its own context : Objects picked in an event are totally
|
||||
@@ -1124,7 +1187,7 @@ gd::String EventsCodeGenerator::GenerateFreeCondition(
|
||||
instrInfos.codeExtraInformation.functionCallName);
|
||||
} else {
|
||||
predicate = instrInfos.codeExtraInformation.functionCallName + "(" +
|
||||
GenerateArgumentsList(arguments, 0) + ")";
|
||||
GenerateArgumentsList(arguments, 0) + ")";
|
||||
}
|
||||
|
||||
// Add logical not if needed
|
||||
@@ -1168,7 +1231,7 @@ gd::String EventsCodeGenerator::GenerateObjectCondition(
|
||||
instrInfos, arguments, objectFunctionCallNamePart, 1);
|
||||
} else {
|
||||
predicate = objectFunctionCallNamePart + "(" +
|
||||
GenerateArgumentsList(arguments, 1) + ")";
|
||||
GenerateArgumentsList(arguments, 1) + ")";
|
||||
}
|
||||
if (conditionInverted) predicate = GenerateNegatedPredicate(predicate);
|
||||
|
||||
@@ -1200,18 +1263,20 @@ gd::String EventsCodeGenerator::GenerateBehaviorCondition(
|
||||
}
|
||||
|
||||
gd::String EventsCodeGenerator::GenerateFreeAction(
|
||||
const gd::String& functionCallName,
|
||||
const gd::String& functionCallName,
|
||||
const std::vector<gd::String>& arguments,
|
||||
const gd::InstructionMetadata& instrInfos,
|
||||
gd::EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName) {
|
||||
const gd::String& optionalAsyncCallbackName,
|
||||
const gd::String& optionalAsyncCallbackId) {
|
||||
// Generate call
|
||||
gd::String call;
|
||||
if (instrInfos.codeExtraInformation.type == "number" ||
|
||||
instrInfos.codeExtraInformation.type == "string" ||
|
||||
// Boolean actions declared with addExpressionAndConditionAndAction uses
|
||||
// MutatorAndOrAccessor even though they don't declare an operator parameter.
|
||||
// Boolean operators are only used with SetMutators or SetCustomCodeGenerator.
|
||||
// MutatorAndOrAccessor even though they don't declare an operator
|
||||
// parameter. Boolean operators are only used with SetMutators or
|
||||
// SetCustomCodeGenerator.
|
||||
(instrInfos.codeExtraInformation.type == "boolean" &&
|
||||
instrInfos.codeExtraInformation.accessType ==
|
||||
gd::InstructionMetadata::ExtraInformation::AccessType::Mutators)) {
|
||||
@@ -1224,23 +1289,19 @@ gd::String EventsCodeGenerator::GenerateFreeAction(
|
||||
instrInfos.codeExtraInformation.optionalAssociatedInstruction);
|
||||
else if (instrInfos.codeExtraInformation.accessType ==
|
||||
gd::InstructionMetadata::ExtraInformation::Mutators)
|
||||
call =
|
||||
GenerateMutatorCall(instrInfos,
|
||||
arguments,
|
||||
functionCallName);
|
||||
call = GenerateMutatorCall(instrInfos, arguments, functionCallName);
|
||||
else
|
||||
call = GenerateCompoundOperatorCall(
|
||||
instrInfos,
|
||||
arguments,
|
||||
functionCallName);
|
||||
call =
|
||||
GenerateCompoundOperatorCall(instrInfos, arguments, functionCallName);
|
||||
} else {
|
||||
call = functionCallName + "(" +
|
||||
GenerateArgumentsList(arguments) + ")";
|
||||
call = functionCallName + "(" + GenerateArgumentsList(arguments) + ")";
|
||||
}
|
||||
|
||||
if (!optionalAsyncCallbackName.empty())
|
||||
if (!optionalAsyncCallbackName.empty() && !optionalAsyncCallbackId.empty()) {
|
||||
call = "runtimeScene.getAsyncTasksManager().addTask(" + call + ", " +
|
||||
optionalAsyncCallbackName + ")";
|
||||
optionalAsyncCallbackName + ", " + optionalAsyncCallbackId +
|
||||
", asyncObjectsList)";
|
||||
}
|
||||
|
||||
return call + ";\n";
|
||||
}
|
||||
@@ -1252,7 +1313,8 @@ gd::String EventsCodeGenerator::GenerateObjectAction(
|
||||
const std::vector<gd::String>& arguments,
|
||||
const gd::InstructionMetadata& instrInfos,
|
||||
gd::EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName) {
|
||||
const gd::String& optionalAsyncCallbackName,
|
||||
const gd::String& optionalAsyncCallbackId) {
|
||||
// Create call
|
||||
gd::String call;
|
||||
if ((instrInfos.codeExtraInformation.type == "number" ||
|
||||
@@ -1293,7 +1355,8 @@ gd::String EventsCodeGenerator::GenerateBehaviorAction(
|
||||
const std::vector<gd::String>& arguments,
|
||||
const gd::InstructionMetadata& instrInfos,
|
||||
gd::EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName) {
|
||||
const gd::String& optionalAsyncCallbackName,
|
||||
const gd::String& optionalAsyncCallbackId) {
|
||||
// Create call
|
||||
gd::String call;
|
||||
if ((instrInfos.codeExtraInformation.type == "number" ||
|
||||
@@ -1308,17 +1371,13 @@ gd::String EventsCodeGenerator::GenerateBehaviorAction(
|
||||
2);
|
||||
else
|
||||
call = GenerateCompoundOperatorCall(
|
||||
instrInfos,
|
||||
arguments,
|
||||
functionCallName,
|
||||
2);
|
||||
instrInfos, arguments, functionCallName, 2);
|
||||
return "For each picked object \"" + objectName + "\", call " + call +
|
||||
" for behavior \"" + behaviorName + "\".\n";
|
||||
} else {
|
||||
gd::String argumentsStr = GenerateArgumentsList(arguments, 2);
|
||||
|
||||
call = functionCallName + "(" +
|
||||
argumentsStr + ")";
|
||||
call = functionCallName + "(" + argumentsStr + ")";
|
||||
|
||||
return "For each picked object \"" + objectName + "\", call " + call + "(" +
|
||||
argumentsStr + ")" + " for behavior \"" + behaviorName + "\"" +
|
||||
@@ -1373,42 +1432,47 @@ gd::String EventsCodeGenerator::GenerateArgumentsList(
|
||||
return argumentsStr;
|
||||
}
|
||||
|
||||
gd::String EventsCodeGenerator::GeneratePropertyGetter(const gd::PropertiesContainer& propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor& property,
|
||||
const gd::String& type,
|
||||
gd::EventsCodeGenerationContext& context) {
|
||||
gd::String EventsCodeGenerator::GeneratePropertyGetter(
|
||||
const gd::PropertiesContainer& propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor& property,
|
||||
const gd::String& type,
|
||||
gd::EventsCodeGenerationContext& context) {
|
||||
return "getProperty" + property.GetName() + "As" + type + "()";
|
||||
}
|
||||
|
||||
gd::String EventsCodeGenerator::GeneratePropertyGetterWithoutCasting(
|
||||
const gd::PropertiesContainer &propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor &property) {
|
||||
const gd::PropertiesContainer& propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor& property) {
|
||||
return "getProperty" + property.GetName() + "()";
|
||||
}
|
||||
|
||||
gd::String EventsCodeGenerator::GeneratePropertySetterWithoutCasting(
|
||||
const gd::PropertiesContainer &propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor &property,
|
||||
const gd::String &operandCode) {
|
||||
const gd::PropertiesContainer& propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor& property,
|
||||
const gd::String& operandCode) {
|
||||
return "setProperty" + property.GetName() + "(" + operandCode + ")";
|
||||
}
|
||||
}
|
||||
|
||||
gd::String EventsCodeGenerator::GenerateParameterGetter(const gd::ParameterMetadata& parameter,
|
||||
const gd::String& type,
|
||||
gd::EventsCodeGenerationContext& context) {
|
||||
gd::String EventsCodeGenerator::GenerateParameterGetter(
|
||||
const gd::ParameterMetadata& parameter,
|
||||
const gd::String& type,
|
||||
gd::EventsCodeGenerationContext& context) {
|
||||
return "getParameter" + parameter.GetName() + "As" + type + "()";
|
||||
}
|
||||
|
||||
gd::String EventsCodeGenerator::GenerateParameterGetterWithoutCasting(
|
||||
const gd::ParameterMetadata ¶meter) {
|
||||
return "getParameter" + parameter.GetName() + "()";
|
||||
}
|
||||
const gd::ParameterMetadata& parameter) {
|
||||
return "getParameter" + parameter.GetName() + "()";
|
||||
}
|
||||
|
||||
EventsCodeGenerator::EventsCodeGenerator(const gd::Project& project_,
|
||||
const gd::Layout& layout,
|
||||
const gd::Platform& platform_)
|
||||
: platform(platform_),
|
||||
projectScopedContainers(gd::ProjectScopedContainers::MakeNewProjectScopedContainersForProjectAndLayout(project_, layout)),
|
||||
projectScopedContainers(
|
||||
gd::ProjectScopedContainers::
|
||||
MakeNewProjectScopedContainersForProjectAndLayout(project_,
|
||||
layout)),
|
||||
hasProjectAndLayout(true),
|
||||
project(&project_),
|
||||
scene(&layout),
|
||||
@@ -1417,7 +1481,7 @@ EventsCodeGenerator::EventsCodeGenerator(const gd::Project& project_,
|
||||
maxCustomConditionsDepth(0),
|
||||
maxConditionsListsSize(0),
|
||||
eventsListNextUniqueId(0),
|
||||
diagnosticReport(nullptr){};
|
||||
diagnosticReport(nullptr) {};
|
||||
|
||||
EventsCodeGenerator::EventsCodeGenerator(
|
||||
const gd::Platform& platform_,
|
||||
@@ -1432,6 +1496,6 @@ EventsCodeGenerator::EventsCodeGenerator(
|
||||
maxCustomConditionsDepth(0),
|
||||
maxConditionsListsSize(0),
|
||||
eventsListNextUniqueId(0),
|
||||
diagnosticReport(nullptr){};
|
||||
diagnosticReport(nullptr) {};
|
||||
|
||||
} // namespace gd
|
||||
|
@@ -9,9 +9,9 @@
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "GDCore/Events/CodeGeneration/DiagnosticReport.h"
|
||||
#include "GDCore/Events/Event.h"
|
||||
#include "GDCore/Events/Instruction.h"
|
||||
#include "GDCore/Events/CodeGeneration/DiagnosticReport.h"
|
||||
#include "GDCore/Project/ProjectScopedContainers.h"
|
||||
#include "GDCore/String.h"
|
||||
|
||||
@@ -62,7 +62,7 @@ class GD_CORE_API EventsCodeGenerator {
|
||||
EventsCodeGenerator(
|
||||
const gd::Platform& platform,
|
||||
const gd::ProjectScopedContainers& projectScopedContainers_);
|
||||
virtual ~EventsCodeGenerator(){};
|
||||
virtual ~EventsCodeGenerator() {};
|
||||
|
||||
/**
|
||||
* \brief Preprocess an events list (replacing for example links with the
|
||||
@@ -160,7 +160,8 @@ class GD_CORE_API EventsCodeGenerator {
|
||||
gd::String GenerateActionCode(
|
||||
gd::Instruction& action,
|
||||
EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName = "");
|
||||
const gd::String& optionalAsyncCallbackName = "",
|
||||
const gd::String& optionalAsyncCallbackId = "");
|
||||
|
||||
struct CallbackDescriptor {
|
||||
CallbackDescriptor(const gd::String functionName_,
|
||||
@@ -168,7 +169,7 @@ class GD_CORE_API EventsCodeGenerator {
|
||||
const std::set<gd::String> requiredObjects_)
|
||||
: functionName(functionName_),
|
||||
argumentsList(argumentsList_),
|
||||
requiredObjects(requiredObjects_){};
|
||||
requiredObjects(requiredObjects_) {};
|
||||
/**
|
||||
* The name by which the function can be invoked.
|
||||
*/
|
||||
@@ -338,9 +339,9 @@ class GD_CORE_API EventsCodeGenerator {
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Give access to the project scoped containers as code generation might
|
||||
* push and pop variable containers (for local variables).
|
||||
* This could be passed as a parameter recursively in code generation, but this requires
|
||||
* @brief Give access to the project scoped containers as code generation
|
||||
* might push and pop variable containers (for local variables). This could be
|
||||
* passed as a parameter recursively in code generation, but this requires
|
||||
* heavy refactoring. Instead, we use this single instance.
|
||||
*/
|
||||
gd::ProjectScopedContainers& GetProjectScopedContainers() {
|
||||
@@ -387,9 +388,7 @@ class GD_CORE_API EventsCodeGenerator {
|
||||
diagnosticReport = diagnosticReport_;
|
||||
}
|
||||
|
||||
gd::DiagnosticReport* GetDiagnosticReport() {
|
||||
return diagnosticReport;
|
||||
}
|
||||
gd::DiagnosticReport* GetDiagnosticReport() { return diagnosticReport; }
|
||||
|
||||
/**
|
||||
* \brief Generate the full name for accessing to a boolean variable used for
|
||||
@@ -513,16 +512,16 @@ class GD_CORE_API EventsCodeGenerator {
|
||||
* \brief Generate an any variable getter that fallbacks on scene variable for
|
||||
* compatibility reason.
|
||||
*/
|
||||
gd::String
|
||||
GenerateAnyOrSceneVariableGetter(const gd::Expression &variableExpression,
|
||||
EventsCodeGenerationContext &context);
|
||||
gd::String GenerateAnyOrSceneVariableGetter(
|
||||
const gd::Expression& variableExpression,
|
||||
EventsCodeGenerationContext& context);
|
||||
|
||||
virtual gd::String GeneratePropertySetterWithoutCasting(
|
||||
const gd::PropertiesContainer &propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor &property,
|
||||
const gd::String &operandCode);
|
||||
const gd::PropertiesContainer& propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor& property,
|
||||
const gd::String& operandCode);
|
||||
|
||||
protected:
|
||||
protected:
|
||||
virtual const gd::String GenerateRelationalOperatorCodes(
|
||||
const gd::String& operatorString);
|
||||
|
||||
@@ -643,16 +642,16 @@ protected:
|
||||
gd::EventsCodeGenerationContext& context);
|
||||
|
||||
virtual gd::String GeneratePropertyGetterWithoutCasting(
|
||||
const gd::PropertiesContainer &propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor &property);
|
||||
const gd::PropertiesContainer& propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor& property);
|
||||
|
||||
virtual gd::String GenerateParameterGetter(
|
||||
const gd::ParameterMetadata& parameter,
|
||||
const gd::String& type,
|
||||
gd::EventsCodeGenerationContext& context);
|
||||
|
||||
virtual gd::String
|
||||
GenerateParameterGetterWithoutCasting(const gd::ParameterMetadata ¶meter);
|
||||
virtual gd::String GenerateParameterGetterWithoutCasting(
|
||||
const gd::ParameterMetadata& parameter);
|
||||
|
||||
/**
|
||||
* \brief Generate the code to reference an object which is
|
||||
@@ -769,7 +768,8 @@ protected:
|
||||
const std::vector<gd::String>& arguments,
|
||||
const gd::InstructionMetadata& instrInfos,
|
||||
gd::EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName = "");
|
||||
const gd::String& optionalAsyncCallbackName = "",
|
||||
const gd::String& optionalAsyncCallbackId = "");
|
||||
|
||||
virtual gd::String GenerateObjectAction(
|
||||
const gd::String& objectName,
|
||||
@@ -778,7 +778,8 @@ protected:
|
||||
const std::vector<gd::String>& arguments,
|
||||
const gd::InstructionMetadata& instrInfos,
|
||||
gd::EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName = "");
|
||||
const gd::String& optionalAsyncCallbackName = "",
|
||||
const gd::String& optionalAsyncCallbackId = "");
|
||||
|
||||
virtual gd::String GenerateBehaviorAction(
|
||||
const gd::String& objectName,
|
||||
@@ -788,7 +789,8 @@ protected:
|
||||
const std::vector<gd::String>& arguments,
|
||||
const gd::InstructionMetadata& instrInfos,
|
||||
gd::EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName = "");
|
||||
const gd::String& optionalAsyncCallbackName = "",
|
||||
const gd::String& optionalAsyncCallbackId = "");
|
||||
|
||||
gd::String GenerateRelationalOperatorCall(
|
||||
const gd::InstructionMetadata& instrInfos,
|
||||
@@ -837,9 +839,8 @@ protected:
|
||||
virtual gd::String GenerateGetBehaviorNameCode(
|
||||
const gd::String& behaviorName);
|
||||
|
||||
bool CheckBehaviorParameters(
|
||||
const gd::Instruction &instruction,
|
||||
const gd::InstructionMetadata &instrInfos);
|
||||
bool CheckBehaviorParameters(const gd::Instruction& instruction,
|
||||
const gd::InstructionMetadata& instrInfos);
|
||||
|
||||
const gd::Platform& platform; ///< The platform being used.
|
||||
|
||||
@@ -876,4 +877,3 @@ protected:
|
||||
};
|
||||
|
||||
} // namespace gd
|
||||
|
||||
|
@@ -293,6 +293,25 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.MarkAsAdvanced();
|
||||
|
||||
obj.AddAction(
|
||||
"RotateTowardObject",
|
||||
_("Rotate toward another object"),
|
||||
_("Rotate an object towards another object, with the specified speed. "
|
||||
"Note that if multiple instances of the target object are picked, "
|
||||
"only the first one will be used. Use a For Each event or actions "
|
||||
"like \"Pick nearest object\", \"Pick a random object\" to refine "
|
||||
"the choice of the target object."),
|
||||
_("Rotate _PARAM0_ towards _PARAM1_ at speed _PARAM2_ deg/second"),
|
||||
_("Angle"),
|
||||
"res/actions/rotate24_black.png",
|
||||
"res/actions/rotate_black.png")
|
||||
.AddParameter("object", _("Object"))
|
||||
.AddParameter("objectPtr", _("Target object"))
|
||||
.AddParameter("expression", _("Angular speed (in degrees per second)"))
|
||||
.SetParameterLongDescription(_("Enter 0 for an immediate rotation."))
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.MarkAsAdvanced();
|
||||
|
||||
obj.AddAction(
|
||||
"AddForceXY",
|
||||
_("Add a force"),
|
||||
@@ -1617,7 +1636,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
|
||||
extension
|
||||
.AddAction("AjoutObjConcern",
|
||||
_("Pick all instances"),
|
||||
_("Pick all object instances"),
|
||||
_("Pick all instances of the specified object(s). When you "
|
||||
"pick all instances, "
|
||||
"the next conditions and actions of this event work on all "
|
||||
@@ -1631,20 +1650,34 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
.MarkAsAdvanced();
|
||||
|
||||
extension
|
||||
.AddAction(
|
||||
"AjoutHasard",
|
||||
_("Pick a random object"),
|
||||
_("Pick one object from all the specified objects. When an object "
|
||||
"is picked, the next conditions and actions of this event work "
|
||||
"only on that object."),
|
||||
_("Pick a random _PARAM1_"),
|
||||
_("Objects"),
|
||||
"res/actions/ajouthasard24.png",
|
||||
"res/actions/ajouthasard.png")
|
||||
.AddAction("AjoutHasard",
|
||||
_("Pick a random object"),
|
||||
_("Pick one instance from all the specified objects. When an "
|
||||
"instance is picked, the next conditions and actions of "
|
||||
"this event work only on that object instance."),
|
||||
_("Pick a random _PARAM1_"),
|
||||
_("Objects"),
|
||||
"res/actions/ajouthasard24.png",
|
||||
"res/actions/ajouthasard.png")
|
||||
.AddCodeOnlyParameter("objectsContext", "")
|
||||
.AddParameter("objectList", _("Object"))
|
||||
.MarkAsSimple();
|
||||
|
||||
extension
|
||||
.AddAction(
|
||||
"PickNearest",
|
||||
_("Pick nearest object"),
|
||||
_("Pick the instance of this object that is nearest to the specified "
|
||||
"position."),
|
||||
_("Pick the _PARAM0_ that is nearest to _PARAM1_;_PARAM2_"),
|
||||
_("Objects"),
|
||||
"res/conditions/distance24.png",
|
||||
"res/conditions/distance.png")
|
||||
.AddParameter("objectList", _("Object"))
|
||||
.AddParameter("expression", _("X position"))
|
||||
.AddParameter("expression", _("Y position"))
|
||||
.MarkAsSimple();
|
||||
|
||||
extension
|
||||
.AddAction(
|
||||
"MoveObjects",
|
||||
@@ -1694,11 +1727,12 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
extension
|
||||
.AddCondition(
|
||||
"AjoutObjConcern",
|
||||
_("Pick all objects"),
|
||||
_("Pick all the specified objects. When you pick all objects, "
|
||||
_("Pick all object instances"),
|
||||
_("Pick all instances of the specified object(s). When you "
|
||||
"pick all instances, "
|
||||
"the next conditions and actions of this event work on all "
|
||||
"of them."),
|
||||
_("Pick all _PARAM1_ objects"),
|
||||
_("Pick all instances of _PARAM1_"),
|
||||
_("Objects"),
|
||||
"res/conditions/add24.png",
|
||||
"res/conditions/add.png")
|
||||
@@ -1707,16 +1741,15 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
.MarkAsAdvanced();
|
||||
|
||||
extension
|
||||
.AddCondition(
|
||||
"AjoutHasard",
|
||||
_("Pick a random object"),
|
||||
_("Pick one object from all the specified objects. When an object "
|
||||
"is picked, the next conditions and actions of this event work "
|
||||
"only on that object."),
|
||||
_("Pick a random _PARAM1_"),
|
||||
_("Objects"),
|
||||
"res/conditions/ajouthasard24.png",
|
||||
"res/conditions/ajouthasard.png")
|
||||
.AddCondition("AjoutHasard",
|
||||
_("Pick a random object"),
|
||||
_("Pick one instance from all the specified objects. When "
|
||||
"an instance is picked, the next conditions and actions "
|
||||
"of this event work only on that object instance."),
|
||||
_("Pick a random _PARAM1_"),
|
||||
_("Objects"),
|
||||
"res/conditions/ajouthasard24.png",
|
||||
"res/conditions/ajouthasard.png")
|
||||
.AddCodeOnlyParameter("objectsContext", "")
|
||||
.AddParameter("objectList", _("Object"))
|
||||
.MarkAsSimple();
|
||||
@@ -1725,9 +1758,9 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
.AddCondition(
|
||||
"PickNearest",
|
||||
_("Pick nearest object"),
|
||||
_("Pick the object of this type that is nearest to the specified "
|
||||
"position. If the condition is inverted, the object farthest from "
|
||||
"the specified position is picked instead."),
|
||||
_("Pick the instance of this object that is nearest to the specified "
|
||||
"position. If the condition is inverted, the instance farthest "
|
||||
"from the specified position is picked instead."),
|
||||
_("Pick the _PARAM0_ that is nearest to _PARAM1_;_PARAM2_"),
|
||||
_("Objects"),
|
||||
"res/conditions/distance24.png",
|
||||
|
@@ -813,6 +813,13 @@ gd::String PlatformExtension::GetObjectFullType(const gd::String& extensionName,
|
||||
return extensionName + separator + objectName;
|
||||
}
|
||||
|
||||
gd::String PlatformExtension::GetVariantFullType(const gd::String& extensionName,
|
||||
const gd::String& objectName,
|
||||
const gd::String& variantName) {
|
||||
const auto& separator = GetNamespaceSeparator();
|
||||
return extensionName + separator + objectName + separator + variantName;
|
||||
}
|
||||
|
||||
gd::String PlatformExtension::GetExtensionFromFullObjectType(
|
||||
const gd::String& type) {
|
||||
const auto separatorIndex =
|
||||
|
@@ -663,6 +663,10 @@ class GD_CORE_API PlatformExtension {
|
||||
static gd::String GetObjectFullType(const gd::String& extensionName,
|
||||
const gd::String& objectName);
|
||||
|
||||
static gd::String GetVariantFullType(const gd::String& extensionName,
|
||||
const gd::String& objectName,
|
||||
const gd::String& variantName);
|
||||
|
||||
static gd::String GetExtensionFromFullObjectType(const gd::String& type);
|
||||
|
||||
static gd::String GetObjectNameFromFullObjectType(const gd::String& type);
|
||||
|
23
Core/GDCore/IDE/Events/UsedObjectTypeFinder.cpp
Normal file
23
Core/GDCore/IDE/Events/UsedObjectTypeFinder.cpp
Normal file
@@ -0,0 +1,23 @@
|
||||
#include "UsedObjectTypeFinder.h"
|
||||
|
||||
#include "GDCore/Events/Instruction.h"
|
||||
#include "GDCore/IDE/ProjectBrowserHelper.h"
|
||||
#include "GDCore/Project/Object.h"
|
||||
#include "GDCore/Project/Project.h"
|
||||
|
||||
namespace gd {
|
||||
|
||||
bool UsedObjectTypeFinder::ScanProject(gd::Project &project,
|
||||
const gd::String &objectType) {
|
||||
UsedObjectTypeFinder worker(project, objectType);
|
||||
gd::ProjectBrowserHelper::ExposeProjectObjects(project, worker);
|
||||
return worker.hasFoundObjectType;
|
||||
};
|
||||
|
||||
void UsedObjectTypeFinder::DoVisitObject(gd::Object &object) {
|
||||
if (!hasFoundObjectType && object.GetType() == objectType) {
|
||||
hasFoundObjectType = true;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace gd
|
39
Core/GDCore/IDE/Events/UsedObjectTypeFinder.h
Normal file
39
Core/GDCore/IDE/Events/UsedObjectTypeFinder.h
Normal file
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* GDevelop Core
|
||||
* Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights
|
||||
* reserved. This project is released under the MIT License.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include <set>
|
||||
|
||||
#include "GDCore/Events/Parsers/ExpressionParser2NodeWorker.h"
|
||||
#include "GDCore/Extensions/Metadata/SourceFileMetadata.h"
|
||||
#include "GDCore/Extensions/PlatformExtension.h"
|
||||
#include "GDCore/IDE/Events/ArbitraryEventsWorker.h"
|
||||
#include "GDCore/IDE/Project/ArbitraryObjectsWorker.h"
|
||||
#include "GDCore/String.h"
|
||||
|
||||
namespace gd {
|
||||
class Project;
|
||||
class Object;
|
||||
} // namespace gd
|
||||
|
||||
namespace gd {
|
||||
|
||||
class GD_CORE_API UsedObjectTypeFinder : public ArbitraryObjectsWorker {
|
||||
public:
|
||||
static bool ScanProject(gd::Project &project, const gd::String &objectType);
|
||||
|
||||
private:
|
||||
UsedObjectTypeFinder(gd::Project &project_, const gd::String &objectType_)
|
||||
: project(project_), objectType(objectType_){};
|
||||
gd::Project &project;
|
||||
const gd::String &objectType;
|
||||
bool hasFoundObjectType = false;
|
||||
|
||||
// Object Visitor
|
||||
void DoVisitObject(gd::Object &object) override;
|
||||
};
|
||||
|
||||
}; // namespace gd
|
@@ -7,7 +7,6 @@
|
||||
#include <map>
|
||||
#include "GDCore/CommonTools.h"
|
||||
#include "GDCore/IDE/AbstractFileSystem.h"
|
||||
#include "GDCore/IDE/Project/ResourcesAbsolutePathChecker.h"
|
||||
#include "GDCore/IDE/Project/ResourcesMergingHelper.h"
|
||||
#include "GDCore/Project/Project.h"
|
||||
#include "GDCore/Tools/Localization.h"
|
||||
@@ -26,42 +25,37 @@ bool ProjectResourcesCopier::CopyAllResourcesTo(
|
||||
bool preserveAbsoluteFilenames,
|
||||
bool preserveDirectoryStructure) {
|
||||
if (updateOriginalProject) {
|
||||
gd::ProjectResourcesCopier::CopyAllResourcesTo(
|
||||
originalProject, originalProject, fs, destinationDirectory,
|
||||
preserveAbsoluteFilenames, preserveDirectoryStructure);
|
||||
gd::ProjectResourcesCopier::AdaptFilePathsAndCopyAllResourcesTo(
|
||||
originalProject, fs, destinationDirectory, preserveAbsoluteFilenames,
|
||||
preserveDirectoryStructure);
|
||||
} else {
|
||||
gd::Project clonedProject = originalProject;
|
||||
gd::ProjectResourcesCopier::CopyAllResourcesTo(
|
||||
originalProject, clonedProject, fs, destinationDirectory,
|
||||
preserveAbsoluteFilenames, preserveDirectoryStructure);
|
||||
gd::ProjectResourcesCopier::AdaptFilePathsAndCopyAllResourcesTo(
|
||||
clonedProject, fs, destinationDirectory, preserveAbsoluteFilenames,
|
||||
preserveDirectoryStructure);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ProjectResourcesCopier::CopyAllResourcesTo(
|
||||
gd::Project& originalProject,
|
||||
gd::Project& clonedProject,
|
||||
bool ProjectResourcesCopier::AdaptFilePathsAndCopyAllResourcesTo(
|
||||
gd::Project& project,
|
||||
AbstractFileSystem& fs,
|
||||
gd::String destinationDirectory,
|
||||
bool preserveAbsoluteFilenames,
|
||||
bool preserveDirectoryStructure) {
|
||||
|
||||
// Check if there are some resources with absolute filenames
|
||||
gd::ResourcesAbsolutePathChecker absolutePathChecker(originalProject.GetResourcesManager(), fs);
|
||||
gd::ResourceExposer::ExposeWholeProjectResources(originalProject, absolutePathChecker);
|
||||
|
||||
auto projectDirectory = fs.DirNameFrom(originalProject.GetProjectFile());
|
||||
auto projectDirectory = fs.DirNameFrom(project.GetProjectFile());
|
||||
std::cout << "Copying all resources from " << projectDirectory << " to "
|
||||
<< destinationDirectory << "..." << std::endl;
|
||||
|
||||
// Get the resources to be copied
|
||||
gd::ResourcesMergingHelper resourcesMergingHelper(
|
||||
clonedProject.GetResourcesManager(), fs);
|
||||
project.GetResourcesManager(), fs);
|
||||
resourcesMergingHelper.SetBaseDirectory(projectDirectory);
|
||||
resourcesMergingHelper.PreserveDirectoriesStructure(
|
||||
preserveDirectoryStructure);
|
||||
resourcesMergingHelper.PreserveAbsoluteFilenames(preserveAbsoluteFilenames);
|
||||
gd::ResourceExposer::ExposeWholeProjectResources(clonedProject,
|
||||
gd::ResourceExposer::ExposeWholeProjectResources(project,
|
||||
resourcesMergingHelper);
|
||||
|
||||
// Copy resources
|
||||
|
@@ -50,12 +50,10 @@ class GD_CORE_API ProjectResourcesCopier {
|
||||
bool preserveDirectoryStructure = true);
|
||||
|
||||
private:
|
||||
static bool CopyAllResourcesTo(gd::Project& originalProject,
|
||||
gd::Project& clonedProject,
|
||||
gd::AbstractFileSystem& fs,
|
||||
gd::String destinationDirectory,
|
||||
bool preserveAbsoluteFilenames = true,
|
||||
bool preserveDirectoryStructure = true);
|
||||
static bool AdaptFilePathsAndCopyAllResourcesTo(
|
||||
gd::Project &project, gd::AbstractFileSystem &fs,
|
||||
gd::String destinationDirectory, bool preserveAbsoluteFilenames = true,
|
||||
bool preserveDirectoryStructure = true);
|
||||
};
|
||||
|
||||
} // namespace gd
|
||||
|
@@ -1,17 +0,0 @@
|
||||
/*
|
||||
* GDevelop Core
|
||||
* Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights
|
||||
* reserved. This project is released under the MIT License.
|
||||
*/
|
||||
|
||||
#include "ResourcesAbsolutePathChecker.h"
|
||||
#include "GDCore/IDE/AbstractFileSystem.h"
|
||||
#include "GDCore/String.h"
|
||||
|
||||
namespace gd {
|
||||
|
||||
void ResourcesAbsolutePathChecker::ExposeFile(gd::String& resourceFilename) {
|
||||
if (fs.IsAbsolute(resourceFilename)) hasAbsoluteFilenames = true;
|
||||
}
|
||||
|
||||
} // namespace gd
|
@@ -1,48 +0,0 @@
|
||||
/*
|
||||
* GDevelop Core
|
||||
* Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights
|
||||
* reserved. This project is released under the MIT License.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "GDCore/IDE/AbstractFileSystem.h"
|
||||
#include "GDCore/IDE/Project/ArbitraryResourceWorker.h"
|
||||
#include "GDCore/String.h"
|
||||
|
||||
namespace gd {
|
||||
|
||||
/**
|
||||
* \brief Helper used to check if a project has at least a resource with an
|
||||
* absolute filename.
|
||||
*
|
||||
* \see ArbitraryResourceWorker
|
||||
*
|
||||
* \ingroup IDE
|
||||
*/
|
||||
class GD_CORE_API ResourcesAbsolutePathChecker
|
||||
: public ArbitraryResourceWorker {
|
||||
public:
|
||||
ResourcesAbsolutePathChecker(gd::ResourcesManager &resourcesManager,
|
||||
AbstractFileSystem &fileSystem)
|
||||
: ArbitraryResourceWorker(resourcesManager), hasAbsoluteFilenames(false),
|
||||
fs(fileSystem){};
|
||||
virtual ~ResourcesAbsolutePathChecker(){};
|
||||
|
||||
/**
|
||||
* Return true if there is at least a resource with an absolute filename.
|
||||
*/
|
||||
bool HasResourceWithAbsoluteFilenames() const {
|
||||
return hasAbsoluteFilenames;
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if there is a resource with an absolute path
|
||||
*/
|
||||
virtual void ExposeFile(gd::String& resource);
|
||||
|
||||
private:
|
||||
bool hasAbsoluteFilenames;
|
||||
AbstractFileSystem& fs;
|
||||
};
|
||||
|
||||
} // namespace gd
|
@@ -22,6 +22,14 @@ void ResourcesMergingHelper::ExposeFile(gd::String& resourceFilename) {
|
||||
resourceFullFilename = gd::AbstractFileSystem::NormalizeSeparator(
|
||||
resourceFullFilename); // Protect against \ on Linux.
|
||||
|
||||
if (shouldUseOriginalAbsoluteFilenames) {
|
||||
// There is no need to fill `newFilenames` and `oldFilenames` since the file
|
||||
// location stays the same.
|
||||
fs.MakeAbsolute(resourceFullFilename, baseDirectory);
|
||||
resourceFilename = resourceFullFilename;
|
||||
return;
|
||||
}
|
||||
|
||||
// In the case of absolute filenames that we don't want to preserve, or
|
||||
// in the case of copying files without preserving relative folders, the new
|
||||
// names will be generated from the filename alone (with collision protection).
|
||||
|
@@ -3,8 +3,7 @@
|
||||
* Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights
|
||||
* reserved. This project is released under the MIT License.
|
||||
*/
|
||||
#ifndef RESOURCESMERGINGHELPER_H
|
||||
#define RESOURCESMERGINGHELPER_H
|
||||
#pragma once
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
@@ -58,6 +57,15 @@ public:
|
||||
preserveAbsoluteFilenames = preserveAbsoluteFilenames_;
|
||||
};
|
||||
|
||||
/**
|
||||
* \brief Set if the absolute filenames of original files must be used for
|
||||
* any resource.
|
||||
*/
|
||||
void SetShouldUseOriginalAbsoluteFilenames(
|
||||
bool shouldUseOriginalAbsoluteFilenames_ = true) {
|
||||
shouldUseOriginalAbsoluteFilenames = shouldUseOriginalAbsoluteFilenames_;
|
||||
};
|
||||
|
||||
/**
|
||||
* \brief Return a map containing the resources old absolute filename as key,
|
||||
* and the resources new filenames as value. The new filenames are relative to
|
||||
@@ -93,10 +101,13 @@ public:
|
||||
///< absolute (C:\MyFile.png will not be
|
||||
///< transformed into a relative filename
|
||||
///< (MyFile.png).
|
||||
/**
|
||||
* Set to true if the absolute filenames of original files must be used for
|
||||
* any resource.
|
||||
*/
|
||||
bool shouldUseOriginalAbsoluteFilenames = false;
|
||||
gd::AbstractFileSystem&
|
||||
fs; ///< The gd::AbstractFileSystem used to manipulate files.
|
||||
};
|
||||
|
||||
} // namespace gd
|
||||
|
||||
#endif // RESOURCESMERGINGHELPER_H
|
||||
|
@@ -6,6 +6,7 @@
|
||||
#include "SceneResourcesFinder.h"
|
||||
|
||||
#include "GDCore/IDE/ResourceExposer.h"
|
||||
#include "GDCore/Project/EventsBasedObjectVariant.h"
|
||||
#include "GDCore/Project/Layout.h"
|
||||
#include "GDCore/Project/Project.h"
|
||||
#include "GDCore/Serialization/SerializerElement.h"
|
||||
@@ -27,6 +28,14 @@ std::set<gd::String> SceneResourcesFinder::FindSceneResources(gd::Project &proje
|
||||
return resourceWorker.resourceNames;
|
||||
}
|
||||
|
||||
std::set<gd::String> SceneResourcesFinder::FindEventsBasedObjectVariantResources(gd::Project &project,
|
||||
gd::EventsBasedObjectVariant &variant) {
|
||||
gd::SceneResourcesFinder resourceWorker(project.GetResourcesManager());
|
||||
|
||||
gd::ResourceExposer::ExposeEventsBasedObjectVariantResources(project, variant, resourceWorker);
|
||||
return resourceWorker.resourceNames;
|
||||
}
|
||||
|
||||
void SceneResourcesFinder::AddUsedResource(gd::String &resourceName) {
|
||||
if (resourceName.empty()) {
|
||||
return;
|
||||
|
@@ -15,6 +15,7 @@ namespace gd {
|
||||
class Project;
|
||||
class Layout;
|
||||
class SerializerElement;
|
||||
class EventsBasedObjectVariant;
|
||||
} // namespace gd
|
||||
|
||||
namespace gd {
|
||||
@@ -27,7 +28,7 @@ namespace gd {
|
||||
class SceneResourcesFinder : private gd::ArbitraryResourceWorker {
|
||||
public:
|
||||
/**
|
||||
* @brief Find resource usages in a given scenes.
|
||||
* @brief Find resource usages in a given scene.
|
||||
*
|
||||
* It doesn't include resources used globally.
|
||||
*/
|
||||
@@ -41,6 +42,13 @@ public:
|
||||
*/
|
||||
static std::set<gd::String> FindProjectResources(gd::Project &project);
|
||||
|
||||
/**
|
||||
* @brief Find resource usages in a given events-based object variant.
|
||||
*/
|
||||
static std::set<gd::String>
|
||||
FindEventsBasedObjectVariantResources(gd::Project &project,
|
||||
gd::EventsBasedObjectVariant &variant);
|
||||
|
||||
virtual ~SceneResourcesFinder(){};
|
||||
|
||||
private:
|
||||
|
@@ -332,6 +332,12 @@ void ProjectBrowserHelper::ExposeLayoutObjects(gd::Layout &layout,
|
||||
worker.Launch(layout.GetObjects());
|
||||
}
|
||||
|
||||
void ProjectBrowserHelper::ExposeEventsBasedObjectVariantObjects(
|
||||
gd::EventsBasedObjectVariant &eventsBasedObjectVariant,
|
||||
gd::ArbitraryObjectsWorker &worker) {
|
||||
worker.Launch(eventsBasedObjectVariant.GetObjects());
|
||||
}
|
||||
|
||||
void ProjectBrowserHelper::ExposeProjectFunctions(
|
||||
gd::Project &project, gd::ArbitraryEventsFunctionsWorker &worker) {
|
||||
|
||||
|
@@ -13,6 +13,7 @@ class EventsFunctionsExtension;
|
||||
class EventsFunction;
|
||||
class EventsBasedBehavior;
|
||||
class EventsBasedObject;
|
||||
class EventsBasedObjectVariant;
|
||||
class ArbitraryEventsWorker;
|
||||
class ArbitraryEventsWorkerWithContext;
|
||||
class ArbitraryEventsFunctionsWorker;
|
||||
@@ -207,6 +208,17 @@ public:
|
||||
static void ExposeLayoutObjects(gd::Layout &layout,
|
||||
gd::ArbitraryObjectsWorker &worker);
|
||||
|
||||
/**
|
||||
* \brief Call the specified worker on all ObjectContainers of the
|
||||
* events-based object variant.
|
||||
*
|
||||
* This should be the preferred way to traverse all the objects of an
|
||||
* events-based object variant.
|
||||
*/
|
||||
static void ExposeEventsBasedObjectVariantObjects(
|
||||
gd::EventsBasedObjectVariant &eventsBasedObjectVariant,
|
||||
gd::ArbitraryObjectsWorker &worker);
|
||||
|
||||
/**
|
||||
* \brief Call the specified worker on all FunctionsContainers of the project
|
||||
* (global, layouts...)
|
||||
|
@@ -116,6 +116,34 @@ void ResourceExposer::ExposeLayoutResources(
|
||||
project, layout, eventWorker);
|
||||
}
|
||||
|
||||
void ResourceExposer::ExposeEventsBasedObjectVariantResources(
|
||||
gd::Project &project,
|
||||
gd::EventsBasedObjectVariant &eventsBasedObjectVariant,
|
||||
gd::ArbitraryResourceWorker &worker) {
|
||||
// Expose object configuration resources
|
||||
auto objectWorker = gd::GetResourceWorkerOnObjects(project, worker);
|
||||
gd::ProjectBrowserHelper::ExposeEventsBasedObjectVariantObjects(
|
||||
eventsBasedObjectVariant, objectWorker);
|
||||
|
||||
// Expose layer effect resources
|
||||
auto &layers = eventsBasedObjectVariant.GetLayers();
|
||||
for (std::size_t layerIndex = 0; layerIndex < layers.GetLayersCount();
|
||||
layerIndex++) {
|
||||
auto &layer = layers.GetLayer(layerIndex);
|
||||
|
||||
auto &effects = layer.GetEffects();
|
||||
for (size_t effectIndex = 0; effectIndex < effects.GetEffectsCount();
|
||||
effectIndex++) {
|
||||
auto &effect = effects.GetEffect(effectIndex);
|
||||
gd::ResourceExposer::ExposeEffectResources(project.GetCurrentPlatform(),
|
||||
effect, worker);
|
||||
}
|
||||
}
|
||||
// We don't check the events because it would cost too much to do it for every
|
||||
// variant. Resource usage in events-based object events and their
|
||||
// dependencies should be rare.
|
||||
}
|
||||
|
||||
void ResourceExposer::ExposeEffectResources(
|
||||
gd::Platform &platform,
|
||||
gd::Effect &effect,
|
||||
|
@@ -9,10 +9,11 @@ namespace gd {
|
||||
class Platform;
|
||||
class Project;
|
||||
class ArbitraryResourceWorker;
|
||||
class EventsBasedObjectVariant;
|
||||
class EventsFunctionsExtension;
|
||||
class Effect;
|
||||
class Layout;
|
||||
} // namespace gd
|
||||
} // namespace gd
|
||||
|
||||
namespace gd {
|
||||
|
||||
@@ -20,7 +21,7 @@ namespace gd {
|
||||
* \brief
|
||||
*/
|
||||
class GD_CORE_API ResourceExposer {
|
||||
public:
|
||||
public:
|
||||
/**
|
||||
* \brief Called ( e.g. during compilation ) so as to inventory internal
|
||||
* resources, sometimes update their filename or any other work or resources.
|
||||
@@ -50,6 +51,14 @@ class GD_CORE_API ResourceExposer {
|
||||
gd::Layout &layout,
|
||||
gd::ArbitraryResourceWorker &worker);
|
||||
|
||||
/**
|
||||
* @brief Expose the resources used in a given events-based object variant.
|
||||
*/
|
||||
static void ExposeEventsBasedObjectVariantResources(
|
||||
gd::Project &project,
|
||||
gd::EventsBasedObjectVariant &eventsBasedObjectVariant,
|
||||
gd::ArbitraryResourceWorker &worker);
|
||||
|
||||
/**
|
||||
* @brief Expose the resources used in a given effect.
|
||||
*/
|
||||
|
@@ -37,6 +37,7 @@ void EventsBasedObjectVariant::SerializeTo(SerializerElement &element) const {
|
||||
|
||||
layers.SerializeLayersTo(element.AddChild("layers"));
|
||||
initialInstances.SerializeTo(element.AddChild("instances"));
|
||||
editorSettings.SerializeTo(element.AddChild("editionSettings"));
|
||||
}
|
||||
|
||||
void EventsBasedObjectVariant::UnserializeFrom(
|
||||
@@ -66,6 +67,7 @@ void EventsBasedObjectVariant::UnserializeFrom(
|
||||
layers.Reset();
|
||||
}
|
||||
initialInstances.UnserializeFrom(element.GetChild("instances"));
|
||||
editorSettings.UnserializeFrom(element.GetChild("editionSettings"));
|
||||
}
|
||||
|
||||
} // namespace gd
|
||||
|
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "GDCore/IDE/Dialogs/LayoutEditorCanvas/EditorSettings.h"
|
||||
#include "GDCore/Project/InitialInstancesContainer.h"
|
||||
#include "GDCore/Project/LayersContainer.h"
|
||||
#include "GDCore/Project/ObjectsContainer.h"
|
||||
@@ -199,6 +200,19 @@ public:
|
||||
const gd::String &GetAssetStoreOriginalName() const {
|
||||
return assetStoreOriginalName;
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* \brief Get the user settings for the IDE.
|
||||
*/
|
||||
const gd::EditorSettings& GetAssociatedEditorSettings() const {
|
||||
return editorSettings;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Get the user settings for the IDE.
|
||||
*/
|
||||
gd::EditorSettings& GetAssociatedEditorSettings() { return editorSettings; }
|
||||
|
||||
void SerializeTo(SerializerElement &element) const;
|
||||
|
||||
@@ -224,6 +238,7 @@ private:
|
||||
* store.
|
||||
*/
|
||||
gd::String assetStoreOriginalName;
|
||||
gd::EditorSettings editorSettings;
|
||||
};
|
||||
|
||||
} // namespace gd
|
||||
|
@@ -60,6 +60,18 @@ void InitialInstance::UnserializeFrom(const SerializerElement& element) {
|
||||
} else {
|
||||
SetHasCustomDepth(false);
|
||||
}
|
||||
if (element.HasChild("defaultWidth") ||
|
||||
element.HasAttribute("defaultWidth")) {
|
||||
defaultWidth = element.GetDoubleAttribute("defaultWidth");
|
||||
}
|
||||
if (element.HasChild("defaultHeight") ||
|
||||
element.HasAttribute("defaultHeight")) {
|
||||
defaultHeight = element.GetDoubleAttribute("defaultHeight");
|
||||
}
|
||||
if (element.HasChild("defaultDepth") ||
|
||||
element.HasAttribute("defaultDepth")) {
|
||||
defaultDepth = element.GetDoubleAttribute("defaultDepth");
|
||||
}
|
||||
SetZOrder(element.GetIntAttribute("zOrder", 0, "plan"));
|
||||
SetOpacity(element.GetIntAttribute("opacity", 255));
|
||||
SetLayer(element.GetStringAttribute("layer"));
|
||||
@@ -74,45 +86,51 @@ void InitialInstance::UnserializeFrom(const SerializerElement& element) {
|
||||
if (persistentUuid.empty()) ResetPersistentUuid();
|
||||
|
||||
numberProperties.clear();
|
||||
const SerializerElement& numberPropertiesElement =
|
||||
element.GetChild("numberProperties", 0, "floatInfos");
|
||||
numberPropertiesElement.ConsiderAsArrayOf("property", "Info");
|
||||
for (std::size_t j = 0; j < numberPropertiesElement.GetChildrenCount(); ++j) {
|
||||
gd::String name =
|
||||
numberPropertiesElement.GetChild(j).GetStringAttribute("name");
|
||||
double value =
|
||||
numberPropertiesElement.GetChild(j).GetDoubleAttribute("value");
|
||||
if (element.HasChild("numberProperties", "floatInfos")) {
|
||||
const SerializerElement& numberPropertiesElement =
|
||||
element.GetChild("numberProperties", 0, "floatInfos");
|
||||
numberPropertiesElement.ConsiderAsArrayOf("property", "Info");
|
||||
for (std::size_t j = 0; j < numberPropertiesElement.GetChildrenCount(); ++j) {
|
||||
gd::String name =
|
||||
numberPropertiesElement.GetChild(j).GetStringAttribute("name");
|
||||
double value =
|
||||
numberPropertiesElement.GetChild(j).GetDoubleAttribute("value");
|
||||
|
||||
// Compatibility with GD <= 5.1.164
|
||||
if (name == "z") {
|
||||
SetZ(value);
|
||||
} else if (name == "rotationX") {
|
||||
SetRotationX(value);
|
||||
} else if (name == "rotationY") {
|
||||
SetRotationY(value);
|
||||
} else if (name == "depth") {
|
||||
SetHasCustomDepth(true);
|
||||
SetCustomDepth(value);
|
||||
}
|
||||
// end of compatibility code
|
||||
else {
|
||||
numberProperties[name] = value;
|
||||
// Compatibility with GD <= 5.1.164
|
||||
if (name == "z") {
|
||||
SetZ(value);
|
||||
} else if (name == "rotationX") {
|
||||
SetRotationX(value);
|
||||
} else if (name == "rotationY") {
|
||||
SetRotationY(value);
|
||||
} else if (name == "depth") {
|
||||
SetHasCustomDepth(true);
|
||||
SetCustomDepth(value);
|
||||
}
|
||||
// end of compatibility code
|
||||
else {
|
||||
numberProperties[name] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stringProperties.clear();
|
||||
const SerializerElement& stringPropElement =
|
||||
element.GetChild("stringProperties", 0, "stringInfos");
|
||||
stringPropElement.ConsiderAsArrayOf("property", "Info");
|
||||
for (std::size_t j = 0; j < stringPropElement.GetChildrenCount(); ++j) {
|
||||
gd::String name = stringPropElement.GetChild(j).GetStringAttribute("name");
|
||||
gd::String value =
|
||||
stringPropElement.GetChild(j).GetStringAttribute("value");
|
||||
stringProperties[name] = value;
|
||||
if (element.HasChild("stringProperties", "stringInfos")) {
|
||||
const SerializerElement& stringPropElement =
|
||||
element.GetChild("stringProperties", 0, "stringInfos");
|
||||
stringPropElement.ConsiderAsArrayOf("property", "Info");
|
||||
for (std::size_t j = 0; j < stringPropElement.GetChildrenCount(); ++j) {
|
||||
gd::String name = stringPropElement.GetChild(j).GetStringAttribute("name");
|
||||
gd::String value =
|
||||
stringPropElement.GetChild(j).GetStringAttribute("value");
|
||||
stringProperties[name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
GetVariables().UnserializeFrom(
|
||||
element.GetChild("initialVariables", 0, "InitialVariables"));
|
||||
if (element.HasChild("initialVariables", "InitialVariables")) {
|
||||
GetVariables().UnserializeFrom(
|
||||
element.GetChild("initialVariables", 0, "InitialVariables"));
|
||||
}
|
||||
}
|
||||
|
||||
void InitialInstance::SerializeTo(SerializerElement& element) const {
|
||||
@@ -133,6 +151,8 @@ void InitialInstance::SerializeTo(SerializerElement& element) const {
|
||||
element.SetAttribute("width", GetCustomWidth());
|
||||
element.SetAttribute("height", GetCustomHeight());
|
||||
if (HasCustomDepth()) element.SetAttribute("depth", GetCustomDepth());
|
||||
// defaultWidth, defaultHeight and defaultDepth are not serialized
|
||||
// because they are evaluated by InGameEditor.
|
||||
if (IsLocked()) element.SetAttribute("locked", IsLocked());
|
||||
if (IsSealed()) element.SetAttribute("sealed", IsSealed());
|
||||
if (ShouldKeepRatio()) element.SetAttribute("keepRatio", ShouldKeepRatio());
|
||||
|
@@ -219,6 +219,13 @@ class GD_CORE_API InitialInstance {
|
||||
double GetCustomDepth() const { return depth; }
|
||||
void SetCustomDepth(double depth_) { depth = depth_; }
|
||||
|
||||
double GetDefaultWidth() const { return defaultWidth; }
|
||||
double GetDefaultHeight() const { return defaultHeight; }
|
||||
double GetDefaultDepth() const { return defaultDepth; }
|
||||
void SetDefaultWidth(double width_) { defaultWidth = width_; }
|
||||
void SetDefaultHeight(double height_) { defaultHeight = height_; }
|
||||
void SetDefaultDepth(double depth_) { defaultDepth = depth_; }
|
||||
|
||||
/**
|
||||
* \brief Return true if the instance is locked and cannot be moved in the
|
||||
* IDE.
|
||||
@@ -366,7 +373,11 @@ class GD_CORE_API InitialInstance {
|
||||
*/
|
||||
InitialInstance& ResetPersistentUuid();
|
||||
|
||||
const gd::String& GetPersistentUuid() const { return persistentUuid; }
|
||||
/**
|
||||
* \brief Reset the persistent UUID used to recognize
|
||||
* the same initial instance between serialization.
|
||||
*/
|
||||
const gd::String& GetPersistentUuid() const { return persistentUuid; }
|
||||
///@}
|
||||
|
||||
private:
|
||||
@@ -395,6 +406,9 @@ class GD_CORE_API InitialInstance {
|
||||
double width; ///< Instance custom width
|
||||
double height; ///< Instance custom height
|
||||
double depth; ///< Instance custom depth
|
||||
double defaultWidth = 0; ///< Instance default width as reported by InGameEditor
|
||||
double defaultHeight = 0; ///< Instance default height as reported by InGameEditor
|
||||
double defaultDepth = 0; ///< Instance default depth as reported by InGameEditor
|
||||
gd::VariablesContainer initialVariables; ///< Instance specific variables
|
||||
bool locked; ///< True if the instance is locked
|
||||
bool sealed; ///< True if the instance is sealed
|
||||
|
@@ -23,6 +23,7 @@ Layer::Layer()
|
||||
camera3DNearPlaneDistance(3),
|
||||
camera3DFarPlaneDistance(10000),
|
||||
camera3DFieldOfView(45),
|
||||
camera2DPlaneMaxDrawingDistance(5000),
|
||||
ambientLightColorR(200),
|
||||
ambientLightColorG(200),
|
||||
ambientLightColorB(200) {}
|
||||
@@ -56,6 +57,8 @@ void Layer::SerializeTo(SerializerElement& element) const {
|
||||
element.SetAttribute("camera3DFarPlaneDistance",
|
||||
GetCamera3DFarPlaneDistance());
|
||||
element.SetAttribute("camera3DFieldOfView", GetCamera3DFieldOfView());
|
||||
element.SetAttribute("camera2DPlaneMaxDrawingDistance",
|
||||
GetCamera2DPlaneMaxDrawingDistance());
|
||||
|
||||
SerializerElement& camerasElement = element.AddChild("cameras");
|
||||
camerasElement.ConsiderAsArrayOf("camera");
|
||||
@@ -99,6 +102,8 @@ void Layer::UnserializeFrom(const SerializerElement& element) {
|
||||
"camera3DFarPlaneDistance", 10000, "threeDFarPlaneDistance"));
|
||||
SetCamera3DFieldOfView(element.GetDoubleAttribute(
|
||||
"camera3DFieldOfView", 45, "threeDFieldOfView"));
|
||||
SetCamera2DPlaneMaxDrawingDistance(element.GetDoubleAttribute(
|
||||
"camera2DPlaneMaxDrawingDistance", 5000));
|
||||
|
||||
cameras.clear();
|
||||
SerializerElement& camerasElement = element.GetChild("cameras");
|
||||
|
@@ -182,6 +182,8 @@ class GD_CORE_API Layer {
|
||||
}
|
||||
double GetCamera3DFieldOfView() const { return camera3DFieldOfView; }
|
||||
void SetCamera3DFieldOfView(double angle) { camera3DFieldOfView = angle; }
|
||||
double GetCamera2DPlaneMaxDrawingDistance() const { return camera2DPlaneMaxDrawingDistance; }
|
||||
void SetCamera2DPlaneMaxDrawingDistance(double distance) { camera2DPlaneMaxDrawingDistance = distance; }
|
||||
///@}
|
||||
|
||||
/** \name Cameras
|
||||
@@ -292,6 +294,7 @@ class GD_CORE_API Layer {
|
||||
double camera3DNearPlaneDistance; ///< 3D camera frustum near plan distance
|
||||
double camera3DFarPlaneDistance; ///< 3D camera frustum far plan distance
|
||||
double camera3DFieldOfView; ///< 3D camera field of view (fov) in degrees
|
||||
double camera2DPlaneMaxDrawingDistance; ///< Max drawing distance of the 2D plane when in the 3D world
|
||||
unsigned int ambientLightColorR; ///< Ambient light color Red component
|
||||
unsigned int ambientLightColorG; ///< Ambient light color Green component
|
||||
unsigned int ambientLightColorB; ///< Ambient light color Blue component
|
||||
|
@@ -730,6 +730,8 @@ void Project::UnserializeFrom(const SerializerElement& element) {
|
||||
SetPackageName(propElement.GetStringAttribute("packageName"));
|
||||
SetTemplateSlug(propElement.GetStringAttribute("templateSlug"));
|
||||
SetOrientation(propElement.GetStringAttribute("orientation", "default"));
|
||||
SetEffectsHiddenInEditor(
|
||||
propElement.GetBoolAttribute("areEffectsHiddenInEditor", false));
|
||||
SetFolderProject(propElement.GetBoolAttribute("folderProject"));
|
||||
SetLastCompilationDirectory(propElement
|
||||
.GetChild("latestCompilationDirectory",
|
||||
@@ -1109,6 +1111,10 @@ void Project::SerializeTo(SerializerElement& element) const {
|
||||
propElement.SetAttribute("packageName", packageName);
|
||||
propElement.SetAttribute("templateSlug", templateSlug);
|
||||
propElement.SetAttribute("orientation", orientation);
|
||||
if (areEffectsHiddenInEditor) {
|
||||
propElement.SetBoolAttribute("areEffectsHiddenInEditor",
|
||||
areEffectsHiddenInEditor);
|
||||
}
|
||||
platformSpecificAssets.SerializeTo(
|
||||
propElement.AddChild("platformSpecificAssets"));
|
||||
loadingScreen.SerializeTo(propElement.AddChild("loadingScreen"));
|
||||
@@ -1150,6 +1156,8 @@ void Project::SerializeTo(SerializerElement& element) const {
|
||||
// end of compatibility code
|
||||
|
||||
extensionProperties.SerializeTo(propElement.AddChild("extensionProperties"));
|
||||
|
||||
playableDevicesElement.AddChild("").SetStringValue("mobile");
|
||||
|
||||
SerializerElement& platformsElement = propElement.AddChild("platforms");
|
||||
platformsElement.ConsiderAsArrayOf("platform");
|
||||
@@ -1319,6 +1327,8 @@ void Project::Init(const gd::Project& game) {
|
||||
|
||||
sceneResourcesPreloading = game.sceneResourcesPreloading;
|
||||
sceneResourcesUnloading = game.sceneResourcesUnloading;
|
||||
|
||||
areEffectsHiddenInEditor = game.areEffectsHiddenInEditor;
|
||||
}
|
||||
|
||||
} // namespace gd
|
||||
|
@@ -506,6 +506,20 @@ class GD_CORE_API Project {
|
||||
*/
|
||||
void SetCurrentPlatform(const gd::String& platformName);
|
||||
|
||||
/**
|
||||
* Check if the effects are shown.
|
||||
*/
|
||||
bool AreEffectsHiddenInEditor() const { return areEffectsHiddenInEditor; }
|
||||
|
||||
/**
|
||||
* Define the project as playable on a mobile.
|
||||
* \param enable True When false effects are not shown and a default light is
|
||||
* used for 3D layers.
|
||||
*/
|
||||
void SetEffectsHiddenInEditor(bool enable = true) {
|
||||
areEffectsHiddenInEditor = enable;
|
||||
}
|
||||
|
||||
///@}
|
||||
|
||||
/** \name Factory method
|
||||
@@ -1165,6 +1179,9 @@ class GD_CORE_API Project {
|
||||
mutable unsigned int gdBuildVersion =
|
||||
0; ///< The GD build version used the last
|
||||
///< time the project was saved.
|
||||
bool areEffectsHiddenInEditor =
|
||||
false; ///< When false effects are not shown and a default light is used
|
||||
///< for 3D layers.
|
||||
};
|
||||
|
||||
} // namespace gd
|
||||
|
@@ -70,7 +70,9 @@ void PropertyDescriptor::UnserializeFrom(const SerializerElement& element) {
|
||||
currentValue = element.GetChild("value").GetStringValue();
|
||||
type = element.GetChild("type").GetStringValue();
|
||||
if (type == "Number") {
|
||||
gd::String unitName = element.GetChild("unit").GetStringValue();
|
||||
gd::String unitName = element.HasChild("unit")
|
||||
? element.GetChild("unit").GetStringValue()
|
||||
: "";
|
||||
measurementUnit =
|
||||
gd::MeasurementUnit::HasDefaultMeasurementUnitNamed(unitName)
|
||||
? measurementUnit =
|
||||
|
@@ -24,7 +24,7 @@ The rest of this page is an introduction to the main concepts of GDevelop archit
|
||||
|
||||
Extensions do have the same distinction between the "**IDE**" part and the "**Runtime**" part. For example, most extensions have:
|
||||
|
||||
- A file called [`JsExtension.js`(https://github.com/4ian/GDevelop/blob/master/Extensions/ExampleJsExtension/JsExtension.js)], which contains the _declaration_ of the extension for the **IDE**
|
||||
- A file called [`JsExtension.js`](https://github.com/4ian/GDevelop/blob/master/Extensions/ExampleJsExtension/JsExtension.js), which contains the _declaration_ of the extension for the **IDE**
|
||||
- One or more files implementing the feature for the game, in other words for **Runtime**. This can be a [Runtime Object](https://github.com/4ian/GDevelop/blob/master/Extensions/ExampleJsExtension/dummyruntimeobject.ts) or a [Runtime Behavior](https://github.com/4ian/GDevelop/blob/master/Extensions/ExampleJsExtension/dummyruntimebehavior.ts), [functions called by actions or conditions](https://github.com/4ian/GDevelop/blob/master/Extensions/ExampleJsExtension/examplejsextensiontools.ts) or by the game engine.
|
||||
|
||||
### "Runtime" and "IDE" difference using an example: the `gd::Variable` class
|
||||
|
@@ -97,6 +97,14 @@ namespace gdjs {
|
||||
oldObjectData: Object3DData,
|
||||
newObjectData: Object3DData
|
||||
): boolean {
|
||||
this.updateOriginalDimensionsFromObjectData(oldObjectData, newObjectData);
|
||||
return true;
|
||||
}
|
||||
|
||||
updateOriginalDimensionsFromObjectData(
|
||||
oldObjectData: Object3DData,
|
||||
newObjectData: Object3DData
|
||||
): void {
|
||||
// There is no need to check if they changed because events can't modify them.
|
||||
this._setOriginalWidth(
|
||||
getValidDimensionValue(newObjectData.content.width)
|
||||
@@ -107,12 +115,13 @@ namespace gdjs {
|
||||
this._setOriginalDepth(
|
||||
getValidDimensionValue(newObjectData.content.depth)
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(): Object3DNetworkSyncData {
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): Object3DNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
z: this.getZ(),
|
||||
d: this.getDepth(),
|
||||
rx: this.getRotationX(),
|
||||
@@ -123,8 +132,11 @@ namespace gdjs {
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(networkSyncData: Object3DNetworkSyncData) {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: Object3DNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
) {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
if (networkSyncData.z !== undefined) this.setZ(networkSyncData.z);
|
||||
if (networkSyncData.d !== undefined) this.setDepth(networkSyncData.d);
|
||||
if (networkSyncData.rx !== undefined)
|
||||
@@ -147,15 +159,9 @@ namespace gdjs {
|
||||
if (initialInstanceData.depth !== undefined) {
|
||||
this.setDepth(initialInstanceData.depth);
|
||||
}
|
||||
if (initialInstanceData.flippedX) {
|
||||
this.flipX(initialInstanceData.flippedX);
|
||||
}
|
||||
if (initialInstanceData.flippedY) {
|
||||
this.flipY(initialInstanceData.flippedY);
|
||||
}
|
||||
if (initialInstanceData.flippedZ) {
|
||||
this.flipZ(initialInstanceData.flippedZ);
|
||||
}
|
||||
this.flipX(!!initialInstanceData.flippedX);
|
||||
this.flipY(!!initialInstanceData.flippedY);
|
||||
this.flipZ(!!initialInstanceData.flippedZ);
|
||||
}
|
||||
|
||||
setX(x: float): void {
|
||||
@@ -322,6 +328,18 @@ namespace gdjs {
|
||||
this.setAngle(gdjs.toDegrees(mesh.rotation.z));
|
||||
}
|
||||
|
||||
override getOriginalWidth(): float {
|
||||
return this._originalWidth;
|
||||
}
|
||||
|
||||
override getOriginalHeight(): float {
|
||||
return this._originalHeight;
|
||||
}
|
||||
|
||||
getOriginalDepth(): float {
|
||||
return this._originalDepth;
|
||||
}
|
||||
|
||||
getWidth(): float {
|
||||
return this._width;
|
||||
}
|
||||
@@ -368,31 +386,6 @@ namespace gdjs {
|
||||
this.getRenderer().updateSize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the width of the object for a scale of 1.
|
||||
*
|
||||
* It can't be 0.
|
||||
*/
|
||||
_getOriginalWidth(): float {
|
||||
return this._originalWidth;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the height of the object for a scale of 1.
|
||||
*
|
||||
* It can't be 0.
|
||||
*/
|
||||
_getOriginalHeight(): float {
|
||||
return this._originalHeight;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the object size on the Z axis (called "depth") when the scale equals 1.
|
||||
*/
|
||||
_getOriginalDepth(): float {
|
||||
return this._originalDepth;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the width of the object for a scale of 1.
|
||||
*/
|
||||
|
@@ -11,6 +11,8 @@ namespace gdjs {
|
||||
this._object = runtimeObject;
|
||||
this._threeObject3D = threeObject3D;
|
||||
this._threeObject3D.rotation.order = 'ZYX';
|
||||
//@ts-ignore
|
||||
this._threeObject3D.gdjsRuntimeObject = runtimeObject;
|
||||
|
||||
instanceContainer
|
||||
.getLayer('')
|
||||
|
@@ -115,6 +115,12 @@ namespace gdjs {
|
||||
* Rotations around X and Y are not taken into account.
|
||||
*/
|
||||
getUnrotatedAABBMaxZ(): number;
|
||||
|
||||
/**
|
||||
* Return the depth of the object before any custom size is applied.
|
||||
* @return The depth of the object
|
||||
*/
|
||||
getOriginalDepth(): float;
|
||||
}
|
||||
|
||||
export interface Object3DDataContent {
|
||||
@@ -131,7 +137,11 @@ namespace gdjs {
|
||||
export namespace Base3DHandler {
|
||||
export const is3D = (
|
||||
object: gdjs.RuntimeObject
|
||||
): object is gdjs.RuntimeObject & gdjs.Base3DHandler => {
|
||||
): object is gdjs.RuntimeObject &
|
||||
gdjs.Base3DHandler &
|
||||
gdjs.Resizable &
|
||||
gdjs.Scalable &
|
||||
gdjs.Flippable => {
|
||||
//@ts-ignore We are checking if the methods are present.
|
||||
return object.getZ && object.setZ;
|
||||
};
|
||||
@@ -243,6 +253,10 @@ namespace gdjs {
|
||||
getUnrotatedAABBMaxZ(): number {
|
||||
return this.object.getUnrotatedAABBMaxZ();
|
||||
}
|
||||
|
||||
getOriginalDepth(): float {
|
||||
return this.object.getOriginalDepth();
|
||||
}
|
||||
}
|
||||
|
||||
gdjs.registerBehavior('Scene3D::Base3DBehavior', gdjs.Base3DBehavior);
|
||||
|
@@ -452,9 +452,11 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(): Cube3DObjectNetworkSyncData {
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): Cube3DObjectNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
mt: this._materialType,
|
||||
fo: this._facesOrientation,
|
||||
bfu: this._backFaceUpThroughWhichAxisRotation,
|
||||
@@ -466,9 +468,10 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: Cube3DObjectNetworkSyncData
|
||||
networkSyncData: Cube3DObjectNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
|
||||
if (networkSyncData.mt !== undefined) {
|
||||
this._materialType = networkSyncData.mt;
|
||||
|
@@ -1,12 +1,16 @@
|
||||
namespace gdjs {
|
||||
type CustomObject3DNetworkSyncDataType = CustomObjectNetworkSyncDataType & {
|
||||
type CustomObject3DNetworkSyncDataType = {
|
||||
z: float;
|
||||
d: float;
|
||||
rx: float;
|
||||
ry: float;
|
||||
ifz: boolean;
|
||||
ccz: float;
|
||||
};
|
||||
|
||||
type CustomObject3DNetworkSyncData = CustomObjectNetworkSyncData &
|
||||
CustomObject3DNetworkSyncDataType;
|
||||
|
||||
/**
|
||||
* Base class for 3D custom objects.
|
||||
*/
|
||||
@@ -74,32 +78,30 @@ namespace gdjs {
|
||||
if (initialInstanceData.depth !== undefined) {
|
||||
this.setDepth(initialInstanceData.depth);
|
||||
}
|
||||
if (initialInstanceData.flippedX) {
|
||||
this.flipX(initialInstanceData.flippedX);
|
||||
}
|
||||
if (initialInstanceData.flippedY) {
|
||||
this.flipY(initialInstanceData.flippedY);
|
||||
}
|
||||
if (initialInstanceData.flippedZ) {
|
||||
this.flipZ(initialInstanceData.flippedZ);
|
||||
}
|
||||
this.flipX(!!initialInstanceData.flippedX);
|
||||
this.flipY(!!initialInstanceData.flippedY);
|
||||
this.flipZ(!!initialInstanceData.flippedZ);
|
||||
}
|
||||
|
||||
getNetworkSyncData(): CustomObject3DNetworkSyncDataType {
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): CustomObject3DNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
z: this.getZ(),
|
||||
d: this.getDepth(),
|
||||
rx: this.getRotationX(),
|
||||
ry: this.getRotationY(),
|
||||
ifz: this.isFlippedZ(),
|
||||
ccz: this._customCenterZ,
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: CustomObject3DNetworkSyncDataType
|
||||
networkSyncData: CustomObject3DNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
if (networkSyncData.z !== undefined) this.setZ(networkSyncData.z);
|
||||
if (networkSyncData.d !== undefined) this.setDepth(networkSyncData.d);
|
||||
if (networkSyncData.rx !== undefined)
|
||||
@@ -107,6 +109,8 @@ namespace gdjs {
|
||||
if (networkSyncData.ry !== undefined)
|
||||
this.setRotationY(networkSyncData.ry);
|
||||
if (networkSyncData.ifz !== undefined) this.flipZ(networkSyncData.ifz);
|
||||
if (networkSyncData.ccz !== undefined)
|
||||
this._customCenterZ = networkSyncData.ccz;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -315,6 +319,10 @@ namespace gdjs {
|
||||
return this._maxZ - this._minZ;
|
||||
}
|
||||
|
||||
getOriginalDepth(): float {
|
||||
return this._instanceContainer._getInitialInnerAreaDepth();
|
||||
}
|
||||
|
||||
override _updateUntransformedHitBoxes(): void {
|
||||
super._updateUntransformedHitBoxes();
|
||||
|
||||
|
@@ -23,6 +23,8 @@ namespace gdjs {
|
||||
|
||||
this._threeGroup = new THREE.Group();
|
||||
this._threeGroup.rotation.order = 'ZYX';
|
||||
//@ts-ignore
|
||||
this._threeGroup.gdjsRuntimeObject = object;
|
||||
|
||||
const layer = parent.getLayer('');
|
||||
if (layer) {
|
||||
|
@@ -1901,6 +1901,11 @@ module.exports = {
|
||||
.getOrCreate('density')
|
||||
.setValue('0.0012')
|
||||
.setLabel(_('Density'))
|
||||
.setDescription(
|
||||
_(
|
||||
'Density of the fog. Usual values are between 0.0005 (far away) and 0.005 (very thick fog).'
|
||||
)
|
||||
)
|
||||
.setType('number');
|
||||
}
|
||||
{
|
||||
|
@@ -8,6 +8,7 @@ namespace gdjs {
|
||||
anis: Model3DAnimation[];
|
||||
ai: integer;
|
||||
ass: float;
|
||||
aet: float;
|
||||
ap: boolean;
|
||||
cfd: float;
|
||||
};
|
||||
@@ -152,6 +153,14 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
override updateOriginalDimensionsFromObjectData(
|
||||
oldObjectData: Object3DData,
|
||||
newObjectData: Object3DData
|
||||
): void {
|
||||
// Original dimensions must not be reset by `super.updateFromObjectData`.
|
||||
// `_updateModel` has a different logic to evaluate them using `keepAspectRatio`.
|
||||
}
|
||||
|
||||
updateFromObjectData(
|
||||
oldObjectData: Model3DObjectData,
|
||||
newObjectData: Model3DObjectData
|
||||
@@ -181,8 +190,14 @@ namespace gdjs {
|
||||
oldObjectData.content.keepAspectRatio !==
|
||||
newObjectData.content.keepAspectRatio ||
|
||||
oldObjectData.content.materialType !==
|
||||
newObjectData.content.materialType
|
||||
newObjectData.content.materialType ||
|
||||
oldObjectData.content.centerLocation !==
|
||||
newObjectData.content.centerLocation
|
||||
) {
|
||||
// The center is applied to the model by `_updateModel`.
|
||||
this._centerPoint = getPointForLocation(
|
||||
newObjectData.content.centerLocation
|
||||
);
|
||||
this._updateModel(newObjectData);
|
||||
}
|
||||
if (
|
||||
@@ -192,14 +207,7 @@ namespace gdjs {
|
||||
this._originPoint = getPointForLocation(
|
||||
newObjectData.content.originLocation
|
||||
);
|
||||
}
|
||||
if (
|
||||
oldObjectData.content.centerLocation !==
|
||||
newObjectData.content.centerLocation
|
||||
) {
|
||||
this._centerPoint = getPointForLocation(
|
||||
newObjectData.content.centerLocation
|
||||
);
|
||||
this._renderer.updatePosition();
|
||||
}
|
||||
if (
|
||||
oldObjectData.content.isCastingShadow !==
|
||||
@@ -216,24 +224,28 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(): Model3DObjectNetworkSyncData {
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): Model3DObjectNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
mt: this._materialType,
|
||||
op: this._originPoint,
|
||||
cp: this._centerPoint,
|
||||
anis: this._animations,
|
||||
ai: this._currentAnimationIndex,
|
||||
ass: this._animationSpeedScale,
|
||||
aet: this.getAnimationElapsedTime(),
|
||||
ap: this._animationPaused,
|
||||
cfd: this._crossfadeDuration,
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: Model3DObjectNetworkSyncData
|
||||
networkSyncData: Model3DObjectNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
|
||||
if (networkSyncData.mt !== undefined) {
|
||||
this._materialType = networkSyncData.mt;
|
||||
@@ -247,11 +259,14 @@ namespace gdjs {
|
||||
if (networkSyncData.anis !== undefined) {
|
||||
this._animations = networkSyncData.anis;
|
||||
}
|
||||
if (networkSyncData.ass !== undefined) {
|
||||
this.setAnimationSpeedScale(networkSyncData.ass);
|
||||
}
|
||||
if (networkSyncData.ai !== undefined) {
|
||||
this.setAnimationIndex(networkSyncData.ai);
|
||||
}
|
||||
if (networkSyncData.ass !== undefined) {
|
||||
this.setAnimationSpeedScale(networkSyncData.ass);
|
||||
if (networkSyncData.aet !== undefined) {
|
||||
this.setAnimationElapsedTime(networkSyncData.aet);
|
||||
}
|
||||
if (networkSyncData.ap !== undefined) {
|
||||
if (networkSyncData.ap !== this.isAnimationPaused()) {
|
||||
@@ -273,14 +288,17 @@ namespace gdjs {
|
||||
const rotationX = objectData.content.rotationX || 0;
|
||||
const rotationY = objectData.content.rotationY || 0;
|
||||
const rotationZ = objectData.content.rotationZ || 0;
|
||||
const width = objectData.content.width || 100;
|
||||
const height = objectData.content.height || 100;
|
||||
const depth = objectData.content.depth || 100;
|
||||
const keepAspectRatio = objectData.content.keepAspectRatio;
|
||||
this._renderer._updateModel(
|
||||
rotationX,
|
||||
rotationY,
|
||||
rotationZ,
|
||||
this._getOriginalWidth(),
|
||||
this._getOriginalHeight(),
|
||||
this._getOriginalDepth(),
|
||||
width,
|
||||
height,
|
||||
depth,
|
||||
keepAspectRatio
|
||||
);
|
||||
}
|
||||
|
@@ -233,6 +233,10 @@ namespace gdjs {
|
||||
this._object._setOriginalWidth(scaleRatio * modelWidth);
|
||||
this._object._setOriginalHeight(scaleRatio * modelHeight);
|
||||
this._object._setOriginalDepth(scaleRatio * modelDepth);
|
||||
} else {
|
||||
this._object._setOriginalWidth(originalWidth);
|
||||
this._object._setOriginalHeight(originalHeight);
|
||||
this._object._setOriginalDepth(originalDepth);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,6 +290,7 @@ namespace gdjs {
|
||||
this.get3DRendererObject().remove(this._threeObject);
|
||||
this.get3DRendererObject().add(threeObject);
|
||||
this._threeObject = threeObject;
|
||||
this.updatePosition();
|
||||
this._updateShadow();
|
||||
|
||||
// Start the current animation on the new 3D object.
|
||||
|
@@ -40,6 +40,19 @@ describe('gdjs.AnchorRuntimeBehavior', () => {
|
||||
objects: [],
|
||||
instances: [],
|
||||
usedResources: [],
|
||||
uiSettings: {
|
||||
grid: false,
|
||||
gridType: 'rectangular',
|
||||
gridWidth: 10,
|
||||
gridHeight: 10,
|
||||
gridDepth: 10,
|
||||
gridOffsetX: 0,
|
||||
gridOffsetY: 0,
|
||||
gridOffsetZ: 0,
|
||||
gridColor: 0,
|
||||
gridAlpha: 1,
|
||||
snap: false,
|
||||
},
|
||||
},
|
||||
usedExtensionsWithVariablesData: [],
|
||||
});
|
||||
|
@@ -145,9 +145,11 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
override getNetworkSyncData(): BBTextObjectNetworkSyncData {
|
||||
override getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): BBTextObjectNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
text: this._text,
|
||||
o: this._opacity,
|
||||
c: this._color,
|
||||
@@ -162,9 +164,10 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
override updateFromNetworkSyncData(
|
||||
networkSyncData: BBTextObjectNetworkSyncData
|
||||
networkSyncData: BBTextObjectNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
if (this._text !== undefined) {
|
||||
this.setBBText(networkSyncData.text);
|
||||
}
|
||||
|
@@ -155,9 +155,11 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
override getNetworkSyncData(): BitmapTextObjectNetworkSyncData {
|
||||
override getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): BitmapTextObjectNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
text: this._text,
|
||||
opa: this._opacity,
|
||||
tint: this._tint,
|
||||
@@ -172,9 +174,10 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
override updateFromNetworkSyncData(
|
||||
networkSyncData: BitmapTextObjectNetworkSyncData
|
||||
networkSyncData: BitmapTextObjectNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
if (this._text !== undefined) {
|
||||
this.setText(networkSyncData.text);
|
||||
}
|
||||
@@ -218,9 +221,11 @@ namespace gdjs {
|
||||
this.setWrappingWidth(initialInstanceData.width);
|
||||
this.setWrapping(true);
|
||||
}
|
||||
if (initialInstanceData.opacity !== undefined) {
|
||||
this.setOpacity(initialInstanceData.opacity);
|
||||
}
|
||||
this.setOpacity(
|
||||
initialInstanceData.opacity === undefined
|
||||
? 255
|
||||
: initialInstanceData.opacity
|
||||
);
|
||||
}
|
||||
|
||||
override onDestroyed(): void {
|
||||
|
@@ -21,7 +21,9 @@ module.exports = {
|
||||
.setExtensionInformation(
|
||||
'DebuggerTools',
|
||||
_('Debugger Tools'),
|
||||
_('Allow to interact with the editor debugger from the game.'),
|
||||
_(
|
||||
'Allow to interact with the editor debugger from the game (notably: enable 2D debug draw, log a message in the debugger console).'
|
||||
),
|
||||
'Arthur Pacaud (arthuro555), Aurélien Vivet (Bouh)',
|
||||
'MIT'
|
||||
)
|
||||
|
@@ -12,7 +12,8 @@ This project is released under the MIT License.
|
||||
#include "GDCore/Tools/Localization.h"
|
||||
|
||||
void DestroyOutsideBehavior::InitializeContent(gd::SerializerElement& content) {
|
||||
content.SetAttribute("extraBorder", 300);
|
||||
content.SetAttribute("extraBorder", 200);
|
||||
content.SetAttribute("unseenGraceDistance", 10000);
|
||||
}
|
||||
|
||||
#if defined(GD_IDE_ONLY)
|
||||
@@ -27,7 +28,15 @@ DestroyOutsideBehavior::GetProperties(
|
||||
.SetType("Number")
|
||||
.SetMeasurementUnit(gd::MeasurementUnit::GetPixel())
|
||||
.SetLabel(_("Deletion margin"))
|
||||
.SetDescription(_("Margin before deleting the object, in pixels"));
|
||||
.SetDescription(_("Margin before deleting the object, in pixels."));
|
||||
|
||||
properties["unseenGraceDistance"]
|
||||
.SetValue(gd::String::From(
|
||||
behaviorContent.GetDoubleAttribute("unseenGraceDistance", 0)))
|
||||
.SetType("Number")
|
||||
.SetMeasurementUnit(gd::MeasurementUnit::GetPixel())
|
||||
.SetLabel(_("Unseen object grace distance"))
|
||||
.SetDescription(_("If the object hasn't been visible yet, don't delete it until it travels this far beyond the screen (in pixels). Useful to avoid objects being deleted before they are visible when they spawn."));
|
||||
|
||||
return properties;
|
||||
}
|
||||
@@ -38,6 +47,8 @@ bool DestroyOutsideBehavior::UpdateProperty(
|
||||
const gd::String& value) {
|
||||
if (name == "extraBorder")
|
||||
behaviorContent.SetAttribute("extraBorder", value.To<double>());
|
||||
else if (name == "unseenGraceDistance")
|
||||
behaviorContent.SetAttribute("unseenGraceDistance", value.To<double>());
|
||||
else
|
||||
return false;
|
||||
|
||||
|
@@ -6,6 +6,7 @@ This project is released under the MIT License.
|
||||
*/
|
||||
|
||||
#include "DestroyOutsideBehavior.h"
|
||||
#include "GDCore/Extensions/Metadata/MultipleInstructionMetadata.h"
|
||||
#include "GDCore/Extensions/PlatformExtension.h"
|
||||
#include "GDCore/Project/BehaviorsSharedData.h"
|
||||
#include "GDCore/Tools/Localization.h"
|
||||
@@ -19,11 +20,10 @@ void DeclareDestroyOutsideBehaviorExtension(gd::PlatformExtension& extension) {
|
||||
"outside of the bounds of the 2D camera. Useful for 2D bullets or "
|
||||
"other short-lived objects. Don't use it for 3D objects in a "
|
||||
"FPS/TPS game or any game with a camera not being a top view "
|
||||
"(for 3D objects, prefer comparing "
|
||||
"the position, for example Z position to see if an object goes "
|
||||
"outside of the bound of the map). Be careful when using this "
|
||||
"behavior because if the object appears outside of the screen, it "
|
||||
"will be immediately removed."),
|
||||
"(for 3D objects, prefer comparing the position, for example Z "
|
||||
"position to see if an object goes outside of the bound of the "
|
||||
"map). If the object appears outside of the screen, it's not "
|
||||
"removed unless it goes beyond the unseen object grace distance."),
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetCategory("Game mechanic")
|
||||
@@ -44,34 +44,39 @@ void DeclareDestroyOutsideBehaviorExtension(gd::PlatformExtension& extension) {
|
||||
std::shared_ptr<gd::BehaviorsSharedData>())
|
||||
.SetQuickCustomizationVisibility(gd::QuickCustomization::Hidden);
|
||||
|
||||
aut.AddCondition("ExtraBorder",
|
||||
_("Additional border (extra distance before deletion)"),
|
||||
_("Compare the extra distance (in pixels) the object must "
|
||||
"travel beyond the screen before it gets deleted."),
|
||||
_("the additional border"),
|
||||
_("Destroy outside configuration"),
|
||||
"CppPlatform/Extensions/destroyoutsideicon24.png",
|
||||
"CppPlatform/Extensions/destroyoutsideicon16.png")
|
||||
aut.AddExpressionAndConditionAndAction(
|
||||
"number",
|
||||
"ExtraBorder",
|
||||
_("Additional border (extra distance before deletion)"),
|
||||
_("the extra distance (in pixels) the object must "
|
||||
"travel beyond the screen before it gets deleted"),
|
||||
_("the additional border"),
|
||||
_("Destroy outside configuration"),
|
||||
"CppPlatform/Extensions/destroyoutsideicon24.png")
|
||||
.AddParameter("object", _("Object"))
|
||||
.AddParameter("behavior", _("Behavior"), "DestroyOutside")
|
||||
.UseStandardRelationalOperatorParameters(
|
||||
"number", gd::ParameterOptions::MakeNewOptions())
|
||||
.MarkAsAdvanced()
|
||||
.SetFunctionName("GetExtraBorder");
|
||||
.UseStandardParameters("number", gd::ParameterOptions::MakeNewOptions())
|
||||
.MarkAsAdvanced();
|
||||
|
||||
aut.AddAction("ExtraBorder",
|
||||
_("Additional border (extra distance before deletion)"),
|
||||
_("Change the extra distance (in pixels) the object must "
|
||||
"travel beyond the screen before it gets deleted."),
|
||||
_("the additional border"),
|
||||
_("Destroy outside configuration"),
|
||||
"CppPlatform/Extensions/destroyoutsideicon24.png",
|
||||
"CppPlatform/Extensions/destroyoutsideicon16.png")
|
||||
// Deprecated:
|
||||
aut.AddDuplicatedAction("ExtraBorder", "DestroyOutside::SetExtraBorder")
|
||||
.SetHidden();
|
||||
aut.AddDuplicatedCondition("ExtraBorder", "DestroyOutside::ExtraBorder")
|
||||
.SetHidden();
|
||||
|
||||
aut.AddExpressionAndConditionAndAction(
|
||||
"number",
|
||||
"UnseenGraceDistance",
|
||||
_("Unseen object grace distance"),
|
||||
_("the grace distance (in pixels) before deleting the object if it "
|
||||
"has "
|
||||
"never been visible on the screen. Useful to avoid objects being "
|
||||
"deleted before they are visible when they spawn"),
|
||||
_("the unseen grace distance"),
|
||||
_("Destroy outside configuration"),
|
||||
"CppPlatform/Extensions/destroyoutsideicon24.png")
|
||||
.AddParameter("object", _("Object"))
|
||||
.AddParameter("behavior", _("Behavior"), "DestroyOutside")
|
||||
.UseStandardOperatorParameters("number",
|
||||
gd::ParameterOptions::MakeNewOptions())
|
||||
.MarkAsAdvanced()
|
||||
.SetFunctionName("SetExtraBorder")
|
||||
.SetGetter("GetExtraBorder");
|
||||
.UseStandardParameters("number", gd::ParameterOptions::MakeNewOptions())
|
||||
.MarkAsAdvanced();
|
||||
}
|
||||
|
@@ -5,11 +5,11 @@ Copyright (c) 2014-2016 Florian Rival (Florian.Rival@gmail.com)
|
||||
This project is released under the MIT License.
|
||||
*/
|
||||
#if defined(GD_IDE_ONLY)
|
||||
#include <iostream>
|
||||
|
||||
#include "GDCore/Extensions/PlatformExtension.h"
|
||||
#include "GDCore/Tools/Localization.h"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
void DeclareDestroyOutsideBehaviorExtension(gd::PlatformExtension& extension);
|
||||
|
||||
/**
|
||||
@@ -29,19 +29,36 @@ class DestroyOutsideBehaviorJsExtension : public gd::PlatformExtension {
|
||||
"Extensions/DestroyOutsideBehavior/"
|
||||
"destroyoutsideruntimebehavior.js");
|
||||
|
||||
GetAllExpressionsForBehavior(
|
||||
"DestroyOutsideBehavior::DestroyOutside")["ExtraBorder"]
|
||||
.SetFunctionName("getExtraBorder");
|
||||
GetAllConditionsForBehavior("DestroyOutsideBehavior::DestroyOutside")
|
||||
["DestroyOutsideBehavior::DestroyOutside::ExtraBorder"]
|
||||
.SetFunctionName("getExtraBorder");
|
||||
GetAllActionsForBehavior("DestroyOutsideBehavior::DestroyOutside")
|
||||
["DestroyOutsideBehavior::DestroyOutside::SetExtraBorder"]
|
||||
.SetFunctionName("setExtraBorder")
|
||||
.SetGetter("getExtraBorder");
|
||||
|
||||
// Deprecated:
|
||||
GetAllConditionsForBehavior("DestroyOutsideBehavior::DestroyOutside")
|
||||
["DestroyOutsideBehavior::ExtraBorder"]
|
||||
.SetFunctionName("getExtraBorder")
|
||||
.SetIncludeFile(
|
||||
"Extensions/DestroyOutsideBehavior/"
|
||||
"destroyoutsideruntimebehavior.js");
|
||||
.SetFunctionName("getExtraBorder");
|
||||
GetAllActionsForBehavior("DestroyOutsideBehavior::DestroyOutside")
|
||||
["DestroyOutsideBehavior::ExtraBorder"]
|
||||
.SetFunctionName("setExtraBorder")
|
||||
.SetGetter("getExtraBorder")
|
||||
.SetIncludeFile(
|
||||
"Extensions/DestroyOutsideBehavior/"
|
||||
"destroyoutsideruntimebehavior.js");
|
||||
.SetGetter("getExtraBorder");
|
||||
|
||||
GetAllExpressionsForBehavior(
|
||||
"DestroyOutsideBehavior::DestroyOutside")["UnseenGraceDistance"]
|
||||
.SetFunctionName("getUnseenGraceDistance");
|
||||
GetAllConditionsForBehavior("DestroyOutsideBehavior::DestroyOutside")
|
||||
["DestroyOutsideBehavior::DestroyOutside::UnseenGraceDistance"]
|
||||
.SetFunctionName("getUnseenGraceDistance");
|
||||
GetAllActionsForBehavior("DestroyOutsideBehavior::DestroyOutside")
|
||||
["DestroyOutsideBehavior::DestroyOutside::SetUnseenGraceDistance"]
|
||||
.SetFunctionName("setUnseenGraceDistance")
|
||||
.SetGetter("getUnseenGraceDistance");
|
||||
|
||||
GD_COMPLETE_EXTENSION_COMPILATION_INFORMATION();
|
||||
};
|
||||
|
@@ -8,7 +8,9 @@ namespace gdjs {
|
||||
* The DestroyOutsideRuntimeBehavior represents a behavior that destroys the object when it leaves the screen.
|
||||
*/
|
||||
export class DestroyOutsideRuntimeBehavior extends gdjs.RuntimeBehavior {
|
||||
_extraBorder: any;
|
||||
_extraBorder: float;
|
||||
_unseenGraceDistance: float;
|
||||
_hasBeenOnScreen: boolean;
|
||||
|
||||
constructor(
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
@@ -17,12 +19,20 @@ namespace gdjs {
|
||||
) {
|
||||
super(instanceContainer, behaviorData, owner);
|
||||
this._extraBorder = behaviorData.extraBorder || 0;
|
||||
this._unseenGraceDistance = behaviorData.unseenGraceDistance || 0;
|
||||
this._hasBeenOnScreen = false;
|
||||
}
|
||||
|
||||
updateFromBehaviorData(oldBehaviorData, newBehaviorData): boolean {
|
||||
if (oldBehaviorData.extraBorder !== newBehaviorData.extraBorder) {
|
||||
this._extraBorder = newBehaviorData.extraBorder;
|
||||
}
|
||||
if (
|
||||
oldBehaviorData.unseenGraceDistance !==
|
||||
newBehaviorData.unseenGraceDistance
|
||||
) {
|
||||
this._unseenGraceDistance = newBehaviorData.unseenGraceDistance;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -35,23 +45,47 @@ namespace gdjs {
|
||||
const ocy = this.owner.getDrawableY() + this.owner.getCenterY();
|
||||
const layer = instanceContainer.getLayer(this.owner.getLayer());
|
||||
const boundingCircleRadius = Math.sqrt(ow * ow + oh * oh) / 2.0;
|
||||
|
||||
const cameraLeft = layer.getCameraX() - layer.getCameraWidth() / 2;
|
||||
const cameraRight = layer.getCameraX() + layer.getCameraWidth() / 2;
|
||||
const cameraTop = layer.getCameraY() - layer.getCameraHeight() / 2;
|
||||
const cameraBottom = layer.getCameraY() + layer.getCameraHeight() / 2;
|
||||
|
||||
if (
|
||||
ocx + boundingCircleRadius + this._extraBorder <
|
||||
layer.getCameraX() - layer.getCameraWidth() / 2 ||
|
||||
ocx - boundingCircleRadius - this._extraBorder >
|
||||
layer.getCameraX() + layer.getCameraWidth() / 2 ||
|
||||
ocy + boundingCircleRadius + this._extraBorder <
|
||||
layer.getCameraY() - layer.getCameraHeight() / 2 ||
|
||||
ocy - boundingCircleRadius - this._extraBorder >
|
||||
layer.getCameraY() + layer.getCameraHeight() / 2
|
||||
ocx + boundingCircleRadius + this._extraBorder < cameraLeft ||
|
||||
ocx - boundingCircleRadius - this._extraBorder > cameraRight ||
|
||||
ocy + boundingCircleRadius + this._extraBorder < cameraTop ||
|
||||
ocy - boundingCircleRadius - this._extraBorder > cameraBottom
|
||||
) {
|
||||
//We are outside the camera area.
|
||||
this.owner.deleteFromScene();
|
||||
if (this._hasBeenOnScreen) {
|
||||
// Object is outside the camera area and object was previously seen inside it:
|
||||
// delete it now.
|
||||
this.owner.deleteFromScene();
|
||||
} else if (
|
||||
ocx + boundingCircleRadius + this._unseenGraceDistance < cameraLeft ||
|
||||
ocx - boundingCircleRadius - this._unseenGraceDistance >
|
||||
cameraRight ||
|
||||
ocy + boundingCircleRadius + this._unseenGraceDistance < cameraTop ||
|
||||
ocy - boundingCircleRadius - this._unseenGraceDistance > cameraBottom
|
||||
) {
|
||||
// Object is outside the camera area and also outside the grace distance:
|
||||
// force deletion.
|
||||
this.owner.deleteFromScene();
|
||||
} else {
|
||||
// Object is outside the camera area but inside the grace distance
|
||||
// and was never seen inside the camera area: don't delete it yet.
|
||||
}
|
||||
} else {
|
||||
this._hasBeenOnScreen = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set an additional border to the camera viewport as a buffer before the object gets destroyed.
|
||||
* Set the additional border outside the camera area.
|
||||
*
|
||||
* If the object goes beyond the camera area and this border, it will be deleted (unless it was
|
||||
* never seen inside the camera area and this border before, in which case it will be deleted
|
||||
* according to the grace distance).
|
||||
* @param val Border in pixels.
|
||||
*/
|
||||
setExtraBorder(val: number): void {
|
||||
@@ -59,12 +93,36 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the additional border of the camera viewport buffer which triggers the destruction of an object.
|
||||
* Get the additional border outside the camera area.
|
||||
* @return The additional border around the camera viewport in pixels
|
||||
*/
|
||||
getExtraBorder(): number {
|
||||
return this._extraBorder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the grace distance before an object is deleted if it's outside the camera area
|
||||
* and was never seen inside the camera area. Typically useful to avoid objects being deleted
|
||||
* before they are visible when they spawn.
|
||||
*/
|
||||
setUnseenGraceDistance(val: number): void {
|
||||
this._unseenGraceDistance = val;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the grace distance before an object is deleted if it's outside the camera area
|
||||
* and was never seen inside the camera area.
|
||||
*/
|
||||
getUnseenGraceDistance(): number {
|
||||
return this._unseenGraceDistance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this object has been visible on screen (precisely: inside the camera area *including* the extra border).
|
||||
*/
|
||||
hasBeenOnScreen(): boolean {
|
||||
return this._hasBeenOnScreen;
|
||||
}
|
||||
}
|
||||
gdjs.registerBehavior(
|
||||
'DestroyOutsideBehavior::DestroyOutside',
|
||||
|
@@ -29,6 +29,19 @@ describe('gdjs.DraggableRuntimeBehavior', function () {
|
||||
objects: [],
|
||||
instances: [],
|
||||
usedResources: [],
|
||||
uiSettings: {
|
||||
grid: false,
|
||||
gridType: 'rectangular',
|
||||
gridWidth: 10,
|
||||
gridHeight: 10,
|
||||
gridDepth: 10,
|
||||
gridOffsetX: 0,
|
||||
gridOffsetY: 0,
|
||||
gridOffsetZ: 0,
|
||||
gridColor: 0,
|
||||
gridAlpha: 1,
|
||||
snap: false,
|
||||
},
|
||||
},
|
||||
usedExtensionsWithVariablesData: [],
|
||||
});
|
||||
|
@@ -388,6 +388,9 @@ namespace gdjs {
|
||||
|
||||
return new gdjs.PromiseTask(
|
||||
(async () => {
|
||||
if (runtimeScene.getGame().isInGameEdition()) {
|
||||
return;
|
||||
}
|
||||
const scoreSavingState = (_scoreSavingStateByLeaderboard[
|
||||
leaderboardId
|
||||
] =
|
||||
@@ -423,6 +426,9 @@ namespace gdjs {
|
||||
) =>
|
||||
new gdjs.PromiseTask(
|
||||
(async () => {
|
||||
if (runtimeScene.getGame().isInGameEdition()) {
|
||||
return;
|
||||
}
|
||||
const playerId = gdjs.playerAuthentication.getUserId();
|
||||
const playerToken = gdjs.playerAuthentication.getUserToken();
|
||||
if (!playerId || !playerToken) {
|
||||
@@ -747,6 +753,9 @@ namespace gdjs {
|
||||
leaderboardId: string,
|
||||
displayLoader: boolean
|
||||
) {
|
||||
if (runtimeScene.getGame().isInGameEdition()) {
|
||||
return;
|
||||
}
|
||||
// First ensure we're not trying to display multiple times the same leaderboard (in which case
|
||||
// we "de-duplicate" the request to display it).
|
||||
if (leaderboardId === _requestedLeaderboardId) {
|
||||
|
@@ -87,16 +87,21 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(): LightNetworkSyncData {
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): LightNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
rad: this.getRadius(),
|
||||
col: this.getColor(),
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(networkSyncData: LightNetworkSyncData): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: LightNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
|
||||
if (networkSyncData.rad !== undefined) {
|
||||
this.setRadius(networkSyncData.rad);
|
||||
|
@@ -35,6 +35,19 @@ describe('gdjs.LinksManager', function () {
|
||||
stopSoundsOnStartup: false,
|
||||
title: '',
|
||||
usedResources: [],
|
||||
uiSettings: {
|
||||
grid: false,
|
||||
gridType: 'rectangular',
|
||||
gridWidth: 10,
|
||||
gridHeight: 10,
|
||||
gridDepth: 10,
|
||||
gridOffsetX: 0,
|
||||
gridOffsetY: 0,
|
||||
gridOffsetZ: 0,
|
||||
gridColor: 0,
|
||||
gridAlpha: 1,
|
||||
snap: false,
|
||||
},
|
||||
},
|
||||
usedExtensionsWithVariablesData: [],
|
||||
});
|
||||
|
@@ -729,7 +729,9 @@ namespace gdjs {
|
||||
behavior.playerNumber = ownerPlayerNumber;
|
||||
}
|
||||
|
||||
instance.updateFromNetworkSyncData(messageData);
|
||||
instance.updateFromNetworkSyncData(messageData, {
|
||||
clearInputs: false,
|
||||
});
|
||||
|
||||
setLastClockReceivedForInstanceOnScene({
|
||||
sceneNetworkId,
|
||||
@@ -1737,7 +1739,7 @@ namespace gdjs {
|
||||
return;
|
||||
}
|
||||
|
||||
runtimeScene.updateFromNetworkSyncData(messageData);
|
||||
runtimeScene.updateFromNetworkSyncData(messageData, {});
|
||||
} else {
|
||||
// If the game is not ready to receive game update messages, we need to save the data for later use.
|
||||
// This can happen when joining a game that is already running.
|
||||
@@ -1890,7 +1892,7 @@ namespace gdjs {
|
||||
const messageData = message.getData();
|
||||
const messageSender = message.getSender();
|
||||
if (gdjs.multiplayer.isReadyToSendOrReceiveGameUpdateMessages()) {
|
||||
runtimeScene.getGame().updateFromNetworkSyncData(messageData);
|
||||
runtimeScene.getGame().updateFromNetworkSyncData(messageData, {});
|
||||
} else {
|
||||
// If the game is not ready to receive game update messages, we need to save the data for later use.
|
||||
// This can happen when joining a game that is already running.
|
||||
@@ -1918,7 +1920,7 @@ namespace gdjs {
|
||||
// Reapply the game saved updates.
|
||||
lastReceivedGameSyncDataUpdates.getUpdates().forEach((messageData) => {
|
||||
debugLogger.info(`Reapplying saved update of game.`);
|
||||
runtimeScene.getGame().updateFromNetworkSyncData(messageData);
|
||||
runtimeScene.getGame().updateFromNetworkSyncData(messageData, {});
|
||||
});
|
||||
// Game updates are always applied properly, so we can clear them.
|
||||
lastReceivedGameSyncDataUpdates.clear();
|
||||
@@ -1937,7 +1939,7 @@ namespace gdjs {
|
||||
|
||||
debugLogger.info(`Reapplying saved update of scene ${sceneNetworkId}.`);
|
||||
|
||||
runtimeScene.updateFromNetworkSyncData(messageData);
|
||||
runtimeScene.updateFromNetworkSyncData(messageData, {});
|
||||
// We only remove the message if it was successfully applied, so it can be reapplied later,
|
||||
// in case we were not on the right scene.
|
||||
lastReceivedSceneSyncDataUpdates.remove(messageData);
|
||||
|
@@ -278,7 +278,7 @@ namespace gdjs {
|
||||
|
||||
const instanceNetworkId = this._getOrCreateInstanceNetworkId();
|
||||
const objectName = this.owner.getName();
|
||||
const objectNetworkSyncData = this.owner.getNetworkSyncData();
|
||||
const objectNetworkSyncData = this.owner.getNetworkSyncData({});
|
||||
|
||||
// this._logToConsoleWithThrottle(
|
||||
// `Synchronizing object ${this.owner.getName()} (instance ${
|
||||
@@ -448,7 +448,7 @@ namespace gdjs {
|
||||
objectOwner: this.playerNumber,
|
||||
objectName,
|
||||
instanceNetworkId,
|
||||
objectNetworkSyncData: this.owner.getNetworkSyncData(),
|
||||
objectNetworkSyncData: this.owner.getNetworkSyncData({}),
|
||||
sceneNetworkId,
|
||||
});
|
||||
this._sendDataToPeersWithIncreasedClock(
|
||||
@@ -598,7 +598,7 @@ namespace gdjs {
|
||||
debugLogger.info(
|
||||
'Sending update message to move the object immediately.'
|
||||
);
|
||||
const objectNetworkSyncData = this.owner.getNetworkSyncData();
|
||||
const objectNetworkSyncData = this.owner.getNetworkSyncData({});
|
||||
const {
|
||||
messageName: updateMessageName,
|
||||
messageData: updateMessageData,
|
||||
|
@@ -1841,6 +1841,9 @@ namespace gdjs {
|
||||
displayLoader: boolean,
|
||||
openLobbiesPageIfFailure: boolean
|
||||
) => {
|
||||
if (runtimeScene.getGame().isInGameEdition()) {
|
||||
return;
|
||||
}
|
||||
if (isQuickJoiningTooFast()) {
|
||||
return;
|
||||
}
|
||||
@@ -1860,6 +1863,9 @@ namespace gdjs {
|
||||
displayLoader: boolean,
|
||||
openLobbiesPageIfFailure: boolean
|
||||
) => {
|
||||
if (runtimeScene.getGame().isInGameEdition()) {
|
||||
return;
|
||||
}
|
||||
if (isQuickJoiningTooFast()) {
|
||||
return;
|
||||
}
|
||||
@@ -1893,6 +1899,9 @@ namespace gdjs {
|
||||
export const openLobbiesWindow = async (
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
) => {
|
||||
if (runtimeScene.getGame().isInGameEdition()) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
isLobbiesWindowOpen(runtimeScene) ||
|
||||
gdjs.playerAuthentication.isAuthenticationWindowOpen()
|
||||
|
@@ -53,6 +53,8 @@ namespace gdjs {
|
||||
|
||||
_renderer: gdjs.PanelSpriteRuntimeObjectRenderer;
|
||||
|
||||
_objectData: PanelSpriteObjectData;
|
||||
|
||||
/**
|
||||
* @param instanceContainer The container the object belongs to.
|
||||
* @param panelSpriteObjectData The initial properties of the object
|
||||
@@ -62,6 +64,7 @@ namespace gdjs {
|
||||
panelSpriteObjectData: PanelSpriteObjectData
|
||||
) {
|
||||
super(instanceContainer, panelSpriteObjectData);
|
||||
this._objectData = panelSpriteObjectData;
|
||||
this._rBorder = panelSpriteObjectData.rightMargin;
|
||||
this._lBorder = panelSpriteObjectData.leftMargin;
|
||||
this._tBorder = panelSpriteObjectData.topMargin;
|
||||
@@ -84,6 +87,7 @@ namespace gdjs {
|
||||
oldObjectData: PanelSpriteObjectData,
|
||||
newObjectData: PanelSpriteObjectData
|
||||
): boolean {
|
||||
this._objectData = newObjectData;
|
||||
if (oldObjectData.width !== newObjectData.width) {
|
||||
this.setWidth(newObjectData.width);
|
||||
}
|
||||
@@ -119,18 +123,21 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(): PanelSpriteNetworkSyncData {
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): PanelSpriteNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
op: this.getOpacity(),
|
||||
color: this.getColor(),
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: PanelSpriteNetworkSyncData
|
||||
networkSyncData: PanelSpriteNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
|
||||
// Texture is not synchronized, see if this is asked or not.
|
||||
|
||||
@@ -163,9 +170,11 @@ namespace gdjs {
|
||||
this.setWidth(initialInstanceData.width);
|
||||
this.setHeight(initialInstanceData.height);
|
||||
}
|
||||
if (initialInstanceData.opacity !== undefined) {
|
||||
this.setOpacity(initialInstanceData.opacity);
|
||||
}
|
||||
this.setOpacity(
|
||||
initialInstanceData.opacity === undefined
|
||||
? 255
|
||||
: initialInstanceData.opacity
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -244,6 +253,14 @@ namespace gdjs {
|
||||
this.setHeight(newHeight);
|
||||
}
|
||||
|
||||
override getOriginalWidth(): float {
|
||||
return this._objectData.width;
|
||||
}
|
||||
|
||||
override getOriginalHeight(): float {
|
||||
return this._objectData.height;
|
||||
}
|
||||
|
||||
setOpacity(opacity: float): void {
|
||||
if (opacity < 0) {
|
||||
opacity = 0;
|
||||
|
@@ -18,12 +18,15 @@ namespace gdjs {
|
||||
renderer: PIXI.Container;
|
||||
emitter: PIXI.particles.Emitter;
|
||||
started: boolean = false;
|
||||
helperGraphics: PIXI.Graphics | null = null;
|
||||
runtimeObject: gdjs.ParticleEmitterObject;
|
||||
|
||||
constructor(
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
runtimeObject: gdjs.RuntimeObject,
|
||||
runtimeObject: gdjs.ParticleEmitterObject,
|
||||
objectData: any
|
||||
) {
|
||||
this.runtimeObject = runtimeObject;
|
||||
const pixiRenderer = instanceContainer
|
||||
.getGame()
|
||||
.getRenderer()
|
||||
@@ -223,6 +226,44 @@ namespace gdjs {
|
||||
if (!this.started && wasEmitting) {
|
||||
this.started = true;
|
||||
}
|
||||
if (this.helperGraphics) {
|
||||
this.helperGraphics.clear();
|
||||
this.helperGraphics.position.x = this.runtimeObject.getX();
|
||||
this.helperGraphics.position.y = this.runtimeObject.getY();
|
||||
|
||||
const emitterAngle = gdjs.toRad(this.runtimeObject.getAngle());
|
||||
const sprayConeAngle = gdjs.toRad(
|
||||
this.runtimeObject.getConeSprayAngle()
|
||||
);
|
||||
const line1Angle = emitterAngle - sprayConeAngle / 2;
|
||||
const line2Angle = emitterAngle + sprayConeAngle / 2;
|
||||
const length = 64;
|
||||
|
||||
this.helperGraphics.beginFill(0, 0);
|
||||
this.helperGraphics.lineStyle(
|
||||
3,
|
||||
this.runtimeObject.getParticleColorEnd(),
|
||||
1
|
||||
);
|
||||
this.helperGraphics.moveTo(0, 0);
|
||||
this.helperGraphics.lineTo(
|
||||
Math.cos(line1Angle) * length,
|
||||
Math.sin(line1Angle) * length
|
||||
);
|
||||
this.helperGraphics.moveTo(0, 0);
|
||||
this.helperGraphics.lineTo(
|
||||
Math.cos(line2Angle) * length,
|
||||
Math.sin(line2Angle) * length
|
||||
);
|
||||
this.helperGraphics.endFill();
|
||||
|
||||
this.helperGraphics.lineStyle(0, 0x000000, 1);
|
||||
this.helperGraphics.beginFill(
|
||||
this.runtimeObject.getParticleColorStart()
|
||||
);
|
||||
this.helperGraphics.drawCircle(0, 0, 8);
|
||||
this.helperGraphics.endFill();
|
||||
}
|
||||
}
|
||||
|
||||
setPosition(x: number, y: number): void {
|
||||
@@ -443,6 +484,17 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
private static readonly frequencyMinimumValue = 0.0001;
|
||||
|
||||
setHelperVisible(visible: boolean) {
|
||||
if (visible && !this.helperGraphics) {
|
||||
this.helperGraphics = new PIXI.Graphics();
|
||||
this.renderer.addChild(this.helperGraphics);
|
||||
} else if (!visible && this.helperGraphics) {
|
||||
this.helperGraphics.removeFromParent();
|
||||
this.helperGraphics.destroy();
|
||||
this.helperGraphics = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// @ts-ignore - Register the class to let the engine use it.
|
||||
|
@@ -174,6 +174,10 @@ namespace gdjs {
|
||||
this,
|
||||
particleObjectData
|
||||
);
|
||||
if (instanceContainer.getGame().isInGameEdition()) {
|
||||
// TODO Disable the particles rendering
|
||||
this._renderer.setHelperVisible(true);
|
||||
}
|
||||
this.angleA = particleObjectData.emitterAngleA;
|
||||
this.angleB = particleObjectData.emitterAngleB;
|
||||
this.forceMin = particleObjectData.emitterForceMin;
|
||||
@@ -370,9 +374,11 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(): ParticleEmitterObjectNetworkSyncData {
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): ParticleEmitterObjectNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
prms: this.particleRotationMinSpeed,
|
||||
prmx: this.particleRotationMaxSpeed,
|
||||
mpc: this.maxParticlesCount,
|
||||
@@ -399,9 +405,10 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
syncData: ParticleEmitterObjectNetworkSyncData
|
||||
syncData: ParticleEmitterObjectNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(syncData);
|
||||
super.updateFromNetworkSyncData(syncData, options);
|
||||
if (syncData.x !== undefined) {
|
||||
this.setX(syncData.x);
|
||||
}
|
||||
@@ -799,6 +806,14 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
getParticleColorStart(): number {
|
||||
return this.color1;
|
||||
}
|
||||
|
||||
getParticleColorEnd(): number {
|
||||
return this.color2;
|
||||
}
|
||||
|
||||
getParticleRed1(): number {
|
||||
return gdjs.hexNumberToRGBArray(this.color1)[0];
|
||||
}
|
||||
|
@@ -6,7 +6,7 @@ namespace gdjs {
|
||||
const logger = new gdjs.Logger('Pathfinding behavior');
|
||||
|
||||
interface PathfindingNetworkSyncDataType {
|
||||
// Syncing the path should be enough to have a good prediction.
|
||||
// Syncing the path and its position on it should be enough to have a good prediction.
|
||||
path: FloatPoint[];
|
||||
pf: boolean;
|
||||
sp: number;
|
||||
@@ -15,6 +15,7 @@ namespace gdjs {
|
||||
tss: number;
|
||||
re: boolean;
|
||||
ma: number;
|
||||
dos: number;
|
||||
}
|
||||
|
||||
export interface PathfindingNetworkSyncData extends BehaviorNetworkSyncData {
|
||||
@@ -133,9 +134,11 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(): PathfindingNetworkSyncData {
|
||||
getNetworkSyncData(
|
||||
options: GetNetworkSyncDataOptions
|
||||
): PathfindingNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(options),
|
||||
props: {
|
||||
path: this._path,
|
||||
pf: this._pathFound,
|
||||
@@ -145,14 +148,16 @@ namespace gdjs {
|
||||
tss: this._totalSegmentDistance,
|
||||
re: this._reachedEnd,
|
||||
ma: this._movementAngle,
|
||||
dos: this._distanceOnSegment,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: PathfindingNetworkSyncData
|
||||
networkSyncData: PathfindingNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
const behaviorSpecificProps = networkSyncData.props;
|
||||
if (behaviorSpecificProps.path !== undefined) {
|
||||
this._path = behaviorSpecificProps.path;
|
||||
@@ -181,6 +186,9 @@ namespace gdjs {
|
||||
if (behaviorSpecificProps.ma !== undefined) {
|
||||
this._movementAngle = behaviorSpecificProps.ma;
|
||||
}
|
||||
if (behaviorSpecificProps.dos !== undefined) {
|
||||
this._distanceOnSegment = behaviorSpecificProps.dos;
|
||||
}
|
||||
}
|
||||
|
||||
setCellWidth(width: float): void {
|
||||
|
@@ -36,6 +36,19 @@ describe('gdjs.PathfindingRuntimeBehavior', function () {
|
||||
objects: [],
|
||||
instances: [],
|
||||
usedResources: [],
|
||||
uiSettings: {
|
||||
grid: false,
|
||||
gridType: 'rectangular',
|
||||
gridWidth: 10,
|
||||
gridHeight: 10,
|
||||
gridDepth: 10,
|
||||
gridOffsetX: 0,
|
||||
gridOffsetY: 0,
|
||||
gridOffsetZ: 0,
|
||||
gridColor: 0,
|
||||
gridAlpha: 1,
|
||||
snap: false,
|
||||
},
|
||||
},
|
||||
usedExtensionsWithVariablesData: [],
|
||||
});
|
||||
|
@@ -39,6 +39,19 @@ describe('gdjs.PathfindingRuntimeBehavior', function () {
|
||||
objects: [],
|
||||
instances: [],
|
||||
usedResources: [],
|
||||
uiSettings: {
|
||||
grid: false,
|
||||
gridType: 'rectangular',
|
||||
gridWidth: 10,
|
||||
gridHeight: 10,
|
||||
gridDepth: 10,
|
||||
gridOffsetX: 0,
|
||||
gridOffsetY: 0,
|
||||
gridOffsetZ: 0,
|
||||
gridColor: 0,
|
||||
gridAlpha: 1,
|
||||
snap: false,
|
||||
},
|
||||
},
|
||||
usedExtensionsWithVariablesData: [],
|
||||
});
|
||||
|
@@ -41,6 +41,19 @@ describe('gdjs.PathfindingRuntimeBehavior', function () {
|
||||
objects: [],
|
||||
instances: [],
|
||||
usedResources: [],
|
||||
uiSettings: {
|
||||
grid: false,
|
||||
gridType: 'rectangular',
|
||||
gridWidth: 10,
|
||||
gridHeight: 10,
|
||||
gridDepth: 10,
|
||||
gridOffsetX: 0,
|
||||
gridOffsetY: 0,
|
||||
gridOffsetZ: 0,
|
||||
gridColor: 0,
|
||||
gridAlpha: 1,
|
||||
snap: false,
|
||||
},
|
||||
},
|
||||
usedExtensionsWithVariablesData: [],
|
||||
});
|
||||
|
@@ -623,10 +623,46 @@ Zv();a.b2Manifold.e_faceA=$v();a.b2Manifold.e_faceB=aw();a.b2_staticBody=bw();a.
|
||||
})();
|
||||
|
||||
gdjs.registerAsynchronouslyLoadingLibraryPromise(initializeBox2D({locateFile: function(path, prefix) {
|
||||
return location.protocol === 'file:' ?
|
||||
// This is needed to run on Electron.
|
||||
prefix + "Extensions/Physics2Behavior/" + path :
|
||||
prefix + path;
|
||||
// Path should always be "Box2D_v2.3.1_min.wasm.wasm" (and if it's not, we should probably hardcode it).
|
||||
if (path !== 'Box2D_v2.3.1_min.wasm.wasm') {
|
||||
console.warn("'path' argument sent to locateFile in Box2D_v2.3.1_min.wasm.js is not the expected string 'Box2D_v2.3.1_min.wasm.wasm'. Loading may fail.")
|
||||
}
|
||||
|
||||
// Prefix is typically:
|
||||
// Games ("exported", standalone game):
|
||||
// - Web game: "https://games.gdevelop-app.com/[...]/Extensions/Physics2Behavior/"
|
||||
// - Cordova Android: "https://localhost/Extensions/Physics2Behavior/".
|
||||
// - Cordova iOS: "ionic://localhost/Extensions/Physics2Behavior/".
|
||||
// - Electron macOS: "/private/var/[...]/Contents/Resources/app.asar/app/" (notice the missing folder).
|
||||
// - Electron Windows: "C:\Users\[...]\AppData\Local\[...]\resources\app.asar\app/" (notice the missing folder).
|
||||
// Preview (in the editor):
|
||||
// - Web app preview (dev editor): "http://localhost:5002/Runtime/Extensions/Physics2Behavior/"
|
||||
// - Web app preview (production editor): "https://resources.gdevelop-app.com/[...]/Runtime/Extensions/Physics2Behavior/"
|
||||
// - Electron app preview (dev editor): "/var/[...]/preview/" (notice the missing folder).
|
||||
// - Electron app preview (production editor): "/var/[...]/preview/" (notice the missing folder).
|
||||
// In-game editor:
|
||||
// - Web app (dev editor): "http://localhost:5002/Runtime/Extensions/Physics2Behavior/"
|
||||
// - Web app (production editor): "https://resources.gdevelop-app.com/[...]/Runtime/Extensions/Physics2Behavior/"
|
||||
// - Electron app (dev editor): "file:///var/[...]/in-game-editor-preview/Extensions/Physics2Behavior/"
|
||||
// - Electron app (production editor): "file:///var/[...]/in-game-editor-preview/Extensions/Physics2Behavior/"
|
||||
|
||||
// If the prefix is a full URL, it's a full URL to the folder containing this JS file.
|
||||
// Sill consider the case where the folder could have been missing.
|
||||
let url;
|
||||
if (prefix.startsWith('http:') || prefix.startsWith('https:')) {
|
||||
url = prefix.endsWith('Extensions/Physics2Behavior/') ?
|
||||
prefix + path :
|
||||
prefix + 'Extensions/Physics2Behavior/' + path;
|
||||
} else {
|
||||
// Electron or Cordova iOS will fall in this case.
|
||||
// We can't use this simple solution for http/https because
|
||||
// on the web-app, the runtime is not necessarily hosted
|
||||
// on the same domain as where the game generated files are served (so "prefix" is needed).
|
||||
url = "Extensions/Physics2Behavior/" + path;
|
||||
}
|
||||
|
||||
console.info(`Box2D wasm file is being loaded from path "${path}" with prefix "${prefix}". Resolved URL: "${url}".`);
|
||||
return url;
|
||||
}}).then(box2d => {
|
||||
window.Box2D = box2d;
|
||||
}));
|
||||
|
@@ -499,7 +499,9 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(): Physics2NetworkSyncData {
|
||||
getNetworkSyncData(
|
||||
options: GetNetworkSyncDataOptions
|
||||
): Physics2NetworkSyncData {
|
||||
const bodyProps = this._body
|
||||
? {
|
||||
tpx: this._body.GetTransform().get_p().get_x(),
|
||||
@@ -520,7 +522,7 @@ namespace gdjs {
|
||||
aw: undefined,
|
||||
};
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(options),
|
||||
props: {
|
||||
...bodyProps,
|
||||
layers: this.layers,
|
||||
@@ -529,45 +531,13 @@ namespace gdjs {
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(networkSyncData: Physics2NetworkSyncData) {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: Physics2NetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
) {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
|
||||
const behaviorSpecificProps = networkSyncData.props;
|
||||
if (
|
||||
behaviorSpecificProps.tpx !== undefined &&
|
||||
behaviorSpecificProps.tpy !== undefined &&
|
||||
behaviorSpecificProps.tqa !== undefined
|
||||
) {
|
||||
if (this._body) {
|
||||
this._body.SetTransform(
|
||||
this.b2Vec2(behaviorSpecificProps.tpx, behaviorSpecificProps.tpy),
|
||||
behaviorSpecificProps.tqa
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
behaviorSpecificProps.lvx !== undefined &&
|
||||
behaviorSpecificProps.lvy !== undefined
|
||||
) {
|
||||
if (this._body) {
|
||||
this._body.SetLinearVelocity(
|
||||
this.b2Vec2(behaviorSpecificProps.lvx, behaviorSpecificProps.lvy)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (behaviorSpecificProps.av !== undefined) {
|
||||
if (this._body) {
|
||||
this._body.SetAngularVelocity(behaviorSpecificProps.av);
|
||||
}
|
||||
}
|
||||
|
||||
if (behaviorSpecificProps.aw !== undefined) {
|
||||
if (this._body) {
|
||||
this._body.SetAwake(behaviorSpecificProps.aw);
|
||||
}
|
||||
}
|
||||
|
||||
if (behaviorSpecificProps.layers !== undefined) {
|
||||
this.layers = behaviorSpecificProps.layers;
|
||||
@@ -576,6 +546,38 @@ namespace gdjs {
|
||||
if (behaviorSpecificProps.masks !== undefined) {
|
||||
this.masks = behaviorSpecificProps.masks;
|
||||
}
|
||||
|
||||
this.updateBodyFromObject();
|
||||
|
||||
if (!this._body) return;
|
||||
|
||||
if (
|
||||
behaviorSpecificProps.tpx !== undefined &&
|
||||
behaviorSpecificProps.tpy !== undefined &&
|
||||
behaviorSpecificProps.tqa !== undefined
|
||||
) {
|
||||
this._body.SetTransform(
|
||||
this.b2Vec2(behaviorSpecificProps.tpx, behaviorSpecificProps.tpy),
|
||||
behaviorSpecificProps.tqa
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
behaviorSpecificProps.lvx !== undefined &&
|
||||
behaviorSpecificProps.lvy !== undefined
|
||||
) {
|
||||
this._body.SetLinearVelocity(
|
||||
this.b2Vec2(behaviorSpecificProps.lvx, behaviorSpecificProps.lvy)
|
||||
);
|
||||
}
|
||||
|
||||
if (behaviorSpecificProps.av !== undefined) {
|
||||
this._body.SetAngularVelocity(behaviorSpecificProps.av);
|
||||
}
|
||||
|
||||
if (behaviorSpecificProps.aw !== undefined) {
|
||||
this._body.SetAwake(behaviorSpecificProps.aw);
|
||||
}
|
||||
}
|
||||
|
||||
onDeActivate() {
|
||||
|
@@ -495,7 +495,9 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
override getNetworkSyncData(): Physics3DNetworkSyncData {
|
||||
override getNetworkSyncData(
|
||||
options: GetNetworkSyncDataOptions
|
||||
): Physics3DNetworkSyncData {
|
||||
let bodyProps;
|
||||
if (this._body) {
|
||||
const position = this._body.GetPosition();
|
||||
@@ -537,7 +539,7 @@ namespace gdjs {
|
||||
};
|
||||
}
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(options),
|
||||
props: {
|
||||
...bodyProps,
|
||||
layers: this.layers,
|
||||
@@ -547,27 +549,40 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
override updateFromNetworkSyncData(
|
||||
networkSyncData: Physics3DNetworkSyncData
|
||||
networkSyncData: Physics3DNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
) {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
|
||||
const behaviorSpecificProps = networkSyncData.props;
|
||||
|
||||
if (behaviorSpecificProps.layers !== undefined) {
|
||||
this.layers = behaviorSpecificProps.layers;
|
||||
}
|
||||
if (behaviorSpecificProps.masks !== undefined) {
|
||||
this.masks = behaviorSpecificProps.masks;
|
||||
}
|
||||
|
||||
this._needToRecreateShape = true;
|
||||
this._needToRecreateBody = true;
|
||||
this.updateBodyFromObject();
|
||||
|
||||
if (!this._body) return;
|
||||
|
||||
if (
|
||||
behaviorSpecificProps.px !== undefined &&
|
||||
behaviorSpecificProps.py !== undefined &&
|
||||
behaviorSpecificProps.pz !== undefined
|
||||
) {
|
||||
if (this._body) {
|
||||
this._sharedData.bodyInterface.SetPosition(
|
||||
this._body.GetID(),
|
||||
this.getRVec3(
|
||||
behaviorSpecificProps.px,
|
||||
behaviorSpecificProps.py,
|
||||
behaviorSpecificProps.pz
|
||||
),
|
||||
Jolt.EActivation_DontActivate
|
||||
);
|
||||
}
|
||||
this._sharedData.bodyInterface.SetPosition(
|
||||
this._body.GetID(),
|
||||
this.getRVec3(
|
||||
behaviorSpecificProps.px,
|
||||
behaviorSpecificProps.py,
|
||||
behaviorSpecificProps.pz
|
||||
),
|
||||
Jolt.EActivation_DontActivate
|
||||
);
|
||||
}
|
||||
if (
|
||||
behaviorSpecificProps.rx !== undefined &&
|
||||
@@ -575,56 +590,44 @@ namespace gdjs {
|
||||
behaviorSpecificProps.rz !== undefined &&
|
||||
behaviorSpecificProps.rw !== undefined
|
||||
) {
|
||||
if (this._body) {
|
||||
this._sharedData.bodyInterface.SetRotation(
|
||||
this._body.GetID(),
|
||||
this.getQuat(
|
||||
behaviorSpecificProps.rx,
|
||||
behaviorSpecificProps.ry,
|
||||
behaviorSpecificProps.rz,
|
||||
behaviorSpecificProps.rw
|
||||
),
|
||||
Jolt.EActivation_DontActivate
|
||||
);
|
||||
}
|
||||
this._sharedData.bodyInterface.SetRotation(
|
||||
this._body.GetID(),
|
||||
this.getQuat(
|
||||
behaviorSpecificProps.rx,
|
||||
behaviorSpecificProps.ry,
|
||||
behaviorSpecificProps.rz,
|
||||
behaviorSpecificProps.rw
|
||||
),
|
||||
Jolt.EActivation_DontActivate
|
||||
);
|
||||
}
|
||||
if (
|
||||
behaviorSpecificProps.lvx !== undefined &&
|
||||
behaviorSpecificProps.lvy !== undefined &&
|
||||
behaviorSpecificProps.lvz !== undefined
|
||||
) {
|
||||
if (this._body) {
|
||||
this._sharedData.bodyInterface.SetLinearVelocity(
|
||||
this._body.GetID(),
|
||||
this.getVec3(
|
||||
behaviorSpecificProps.lvx,
|
||||
behaviorSpecificProps.lvy,
|
||||
behaviorSpecificProps.lvz
|
||||
)
|
||||
);
|
||||
}
|
||||
this._sharedData.bodyInterface.SetLinearVelocity(
|
||||
this._body.GetID(),
|
||||
this.getVec3(
|
||||
behaviorSpecificProps.lvx,
|
||||
behaviorSpecificProps.lvy,
|
||||
behaviorSpecificProps.lvz
|
||||
)
|
||||
);
|
||||
}
|
||||
if (
|
||||
behaviorSpecificProps.avx !== undefined &&
|
||||
behaviorSpecificProps.avy !== undefined &&
|
||||
behaviorSpecificProps.avz !== undefined
|
||||
) {
|
||||
if (this._body) {
|
||||
this._sharedData.bodyInterface.SetAngularVelocity(
|
||||
this._body.GetID(),
|
||||
this.getVec3(
|
||||
behaviorSpecificProps.avx,
|
||||
behaviorSpecificProps.avy,
|
||||
behaviorSpecificProps.avz
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
if (behaviorSpecificProps.layers !== undefined) {
|
||||
this.layers = behaviorSpecificProps.layers;
|
||||
}
|
||||
if (behaviorSpecificProps.masks !== undefined) {
|
||||
this.masks = behaviorSpecificProps.masks;
|
||||
this._sharedData.bodyInterface.SetAngularVelocity(
|
||||
this._body.GetID(),
|
||||
this.getVec3(
|
||||
behaviorSpecificProps.avx,
|
||||
behaviorSpecificProps.avy,
|
||||
behaviorSpecificProps.avz
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -921,31 +924,58 @@ namespace gdjs {
|
||||
this.updateBodyFromObject();
|
||||
}
|
||||
|
||||
recreateBody() {
|
||||
if (!this._body) {
|
||||
this._createBody();
|
||||
return;
|
||||
}
|
||||
|
||||
recreateBody(previousBodyData?: {
|
||||
linearVelocityX: float;
|
||||
linearVelocityY: float;
|
||||
linearVelocityZ: float;
|
||||
angularVelocityX: float;
|
||||
angularVelocityY: float;
|
||||
angularVelocityZ: float;
|
||||
}) {
|
||||
const bodyInterface = this._sharedData.bodyInterface;
|
||||
const linearVelocity = this._body.GetLinearVelocity();
|
||||
const linearVelocityX = linearVelocity.GetX();
|
||||
const linearVelocityY = linearVelocity.GetY();
|
||||
const linearVelocityZ = linearVelocity.GetZ();
|
||||
const angularVelocity = this._body.GetAngularVelocity();
|
||||
const angularVelocityX = angularVelocity.GetX();
|
||||
const angularVelocityY = angularVelocity.GetY();
|
||||
const angularVelocityZ = angularVelocity.GetZ();
|
||||
const linearVelocityX = previousBodyData
|
||||
? previousBodyData.linearVelocityX
|
||||
: this._body
|
||||
? this._body.GetLinearVelocity().GetX()
|
||||
: 0;
|
||||
const linearVelocityY = previousBodyData
|
||||
? previousBodyData.linearVelocityY
|
||||
: this._body
|
||||
? this._body.GetLinearVelocity().GetY()
|
||||
: 0;
|
||||
const linearVelocityZ = previousBodyData
|
||||
? previousBodyData.linearVelocityZ
|
||||
: this._body
|
||||
? this._body.GetLinearVelocity().GetZ()
|
||||
: 0;
|
||||
const angularVelocityX = previousBodyData
|
||||
? previousBodyData.angularVelocityX
|
||||
: this._body
|
||||
? this._body.GetAngularVelocity().GetX()
|
||||
: 0;
|
||||
const angularVelocityY = previousBodyData
|
||||
? previousBodyData.angularVelocityY
|
||||
: this._body
|
||||
? this._body.GetAngularVelocity().GetY()
|
||||
: 0;
|
||||
const angularVelocityZ = previousBodyData
|
||||
? previousBodyData.angularVelocityZ
|
||||
: this._body
|
||||
? this._body.GetAngularVelocity().GetZ()
|
||||
: 0;
|
||||
|
||||
this.bodyUpdater.destroyBody();
|
||||
this._contactsEndedThisFrame.length = 0;
|
||||
this._contactsStartedThisFrame.length = 0;
|
||||
this._currentContacts.length = 0;
|
||||
if (this._body) {
|
||||
this.bodyUpdater.destroyBody();
|
||||
this._contactsEndedThisFrame.length = 0;
|
||||
this._contactsStartedThisFrame.length = 0;
|
||||
this._currentContacts.length = 0;
|
||||
}
|
||||
|
||||
this._createBody();
|
||||
if (!this._body) {
|
||||
return;
|
||||
}
|
||||
|
||||
const bodyID = this._body.GetID();
|
||||
bodyInterface.SetLinearVelocity(
|
||||
bodyID,
|
||||
|
@@ -12,6 +12,7 @@ namespace gdjs {
|
||||
etm: float;
|
||||
esm: float;
|
||||
ei: float;
|
||||
es: float;
|
||||
}
|
||||
|
||||
export interface PhysicsCar3DNetworkSyncData extends BehaviorNetworkSyncData {
|
||||
@@ -96,7 +97,7 @@ namespace gdjs {
|
||||
// This is useful when the object is synchronized by an external source
|
||||
// like in a multiplayer game, and we want to be able to predict the
|
||||
// movement of the object, even if the inputs are not updated every frame.
|
||||
private _dontClearInputsBetweenFrames: boolean = false;
|
||||
private _clearInputsBetweenFrames: boolean = true;
|
||||
|
||||
constructor(
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
@@ -168,12 +169,37 @@ namespace gdjs {
|
||||
this._isHookedToPhysicsStep = true;
|
||||
}
|
||||
|
||||
// Destroy the body before switching the bodyUpdater,
|
||||
// to ensure the body of the previous bodyUpdater is not left alive.
|
||||
// (would be a memory leak and would create a phantom body in the physics world)
|
||||
// But transfer the linear and angular velocity to the new body,
|
||||
// so the body doesn't stop when it is recreated.
|
||||
let previousBodyData = {
|
||||
linearVelocityX: 0,
|
||||
linearVelocityY: 0,
|
||||
linearVelocityZ: 0,
|
||||
angularVelocityX: 0,
|
||||
angularVelocityY: 0,
|
||||
angularVelocityZ: 0,
|
||||
};
|
||||
if (behavior._body) {
|
||||
const linearVelocity = behavior._body.GetLinearVelocity();
|
||||
previousBodyData.linearVelocityX = linearVelocity.GetX();
|
||||
previousBodyData.linearVelocityY = linearVelocity.GetY();
|
||||
previousBodyData.linearVelocityZ = linearVelocity.GetZ();
|
||||
const angularVelocity = behavior._body.GetAngularVelocity();
|
||||
previousBodyData.angularVelocityX = angularVelocity.GetX();
|
||||
previousBodyData.angularVelocityY = angularVelocity.GetY();
|
||||
previousBodyData.angularVelocityZ = angularVelocity.GetZ();
|
||||
behavior.bodyUpdater.destroyBody();
|
||||
}
|
||||
|
||||
behavior.bodyUpdater =
|
||||
new gdjs.PhysicsCar3DRuntimeBehavior.VehicleBodyUpdater(
|
||||
this,
|
||||
behavior.bodyUpdater
|
||||
);
|
||||
behavior.recreateBody();
|
||||
behavior.recreateBody(previousBodyData);
|
||||
|
||||
return this._physics3D;
|
||||
}
|
||||
@@ -273,13 +299,15 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
override getNetworkSyncData(): PhysicsCar3DNetworkSyncData {
|
||||
override getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): PhysicsCar3DNetworkSyncData {
|
||||
// This method is called, so we are synchronizing this object.
|
||||
// Let's clear the inputs between frames as we control it.
|
||||
this._dontClearInputsBetweenFrames = false;
|
||||
this._clearInputsBetweenFrames = true;
|
||||
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
props: {
|
||||
lek: this._wasLeftKeyPressed,
|
||||
rik: this._wasRightKeyPressed,
|
||||
@@ -291,14 +319,16 @@ namespace gdjs {
|
||||
etm: this._engineTorqueMax,
|
||||
esm: this._engineSpeedMax,
|
||||
ei: this._engineInertia,
|
||||
es: this.getEngineSpeed(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
override updateFromNetworkSyncData(
|
||||
networkSyncData: PhysicsCar3DNetworkSyncData
|
||||
networkSyncData: PhysicsCar3DNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
) {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
|
||||
const behaviorSpecificProps = networkSyncData.props;
|
||||
this._hasPressedForwardKey = behaviorSpecificProps.upk;
|
||||
@@ -311,9 +341,15 @@ namespace gdjs {
|
||||
this._engineTorqueMax = behaviorSpecificProps.etm;
|
||||
this._engineSpeedMax = behaviorSpecificProps.esm;
|
||||
this._engineInertia = behaviorSpecificProps.ei;
|
||||
if (this._vehicleController) {
|
||||
this._vehicleController
|
||||
.GetEngine()
|
||||
.SetCurrentRPM(behaviorSpecificProps.es);
|
||||
}
|
||||
|
||||
// When the object is synchronized from the network, the inputs must not be cleared.
|
||||
this._dontClearInputsBetweenFrames = true;
|
||||
// When the object is synchronized from the network, the inputs must not be cleared,
|
||||
// except if asked specifically.
|
||||
this._clearInputsBetweenFrames = !!options.clearInputs;
|
||||
}
|
||||
|
||||
_getPhysicsPosition(result: Jolt.RVec3): Jolt.RVec3 {
|
||||
@@ -490,7 +526,7 @@ namespace gdjs {
|
||||
this._previousAcceleratorStickForce = this._acceleratorStickForce;
|
||||
this._previousSteeringStickForce = this._steeringStickForce;
|
||||
|
||||
if (!this._dontClearInputsBetweenFrames) {
|
||||
if (this._clearInputsBetweenFrames) {
|
||||
this._hasPressedForwardKey = false;
|
||||
this._hasPressedBackwardKey = false;
|
||||
this._hasPressedRightKey = false;
|
||||
|
@@ -2,11 +2,24 @@
|
||||
|
||||
namespace gdjs {
|
||||
interface PhysicsCharacter3DNetworkSyncDataType {
|
||||
sma: float;
|
||||
shm: float;
|
||||
grav: float;
|
||||
mfs: float;
|
||||
facc: float;
|
||||
fdec: float;
|
||||
fsm: float;
|
||||
sacc: float;
|
||||
sdec: float;
|
||||
ssm: float;
|
||||
jumpspeed: float;
|
||||
jumpsustime: float;
|
||||
sbpa: boolean;
|
||||
fwa: float;
|
||||
fws: float;
|
||||
sws: float;
|
||||
fs: float;
|
||||
js: float;
|
||||
cfs: float;
|
||||
cjs: float;
|
||||
cj: boolean;
|
||||
lek: boolean;
|
||||
rik: boolean;
|
||||
@@ -102,7 +115,7 @@ namespace gdjs {
|
||||
// This is useful when the object is synchronized by an external source
|
||||
// like in a multiplayer game, and we want to be able to predict the
|
||||
// movement of the object, even if the inputs are not updated every frame.
|
||||
private _dontClearInputsBetweenFrames: boolean = false;
|
||||
private _clearInputsBetweenFrames: boolean = true;
|
||||
|
||||
/**
|
||||
* A very small value compare to 1 pixel, yet very huge compare to rounding errors.
|
||||
@@ -207,10 +220,35 @@ namespace gdjs {
|
||||
this._isHookedToPhysicsStep = true;
|
||||
}
|
||||
|
||||
// Destroy the body before switching the bodyUpdater,
|
||||
// to ensure the body of the previous bodyUpdater is not left alive.
|
||||
// (would be a memory leak and would create a phantom body in the physics world)
|
||||
// But transfer the linear and angular velocity to the new body,
|
||||
// so the body doesn't stop when it is recreated.
|
||||
let previousBodyData = {
|
||||
linearVelocityX: 0,
|
||||
linearVelocityY: 0,
|
||||
linearVelocityZ: 0,
|
||||
angularVelocityX: 0,
|
||||
angularVelocityY: 0,
|
||||
angularVelocityZ: 0,
|
||||
};
|
||||
if (behavior._body) {
|
||||
const linearVelocity = behavior._body.GetLinearVelocity();
|
||||
previousBodyData.linearVelocityX = linearVelocity.GetX();
|
||||
previousBodyData.linearVelocityY = linearVelocity.GetY();
|
||||
previousBodyData.linearVelocityZ = linearVelocity.GetZ();
|
||||
const angularVelocity = behavior._body.GetAngularVelocity();
|
||||
previousBodyData.angularVelocityX = angularVelocity.GetX();
|
||||
previousBodyData.angularVelocityY = angularVelocity.GetY();
|
||||
previousBodyData.angularVelocityZ = angularVelocity.GetZ();
|
||||
behavior.bodyUpdater.destroyBody();
|
||||
}
|
||||
|
||||
behavior.bodyUpdater =
|
||||
new gdjs.PhysicsCharacter3DRuntimeBehavior.CharacterBodyUpdater(this);
|
||||
behavior.collisionChecker = this.collisionChecker;
|
||||
behavior.recreateBody();
|
||||
behavior.recreateBody(previousBodyData);
|
||||
|
||||
// Always begin in the direction of the object.
|
||||
this._forwardAngle = this.owner.getAngle();
|
||||
@@ -277,19 +315,34 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
override getNetworkSyncData(): PhysicsCharacter3DNetworkSyncData {
|
||||
override getNetworkSyncData(
|
||||
options: GetNetworkSyncDataOptions
|
||||
): PhysicsCharacter3DNetworkSyncData {
|
||||
// This method is called, so we are synchronizing this object.
|
||||
// Let's clear the inputs between frames as we control it.
|
||||
this._dontClearInputsBetweenFrames = false;
|
||||
this._clearInputsBetweenFrames = true;
|
||||
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(options),
|
||||
props: {
|
||||
sma: this._slopeMaxAngle,
|
||||
shm: this._stairHeightMax,
|
||||
grav: this._gravity,
|
||||
mfs: this._maxFallingSpeed,
|
||||
facc: this._forwardAcceleration,
|
||||
fdec: this._forwardDeceleration,
|
||||
fsm: this._forwardSpeedMax,
|
||||
sacc: this._sidewaysAcceleration,
|
||||
sdec: this._sidewaysDeceleration,
|
||||
ssm: this._sidewaysSpeedMax,
|
||||
jumpspeed: this._jumpSpeed,
|
||||
jumpsustime: this._jumpSustainTime,
|
||||
fwa: this._forwardAngle,
|
||||
sbpa: this._shouldBindObjectAndForwardAngle,
|
||||
fws: this._currentForwardSpeed,
|
||||
sws: this._currentSidewaysSpeed,
|
||||
fs: this._currentFallSpeed,
|
||||
js: this._currentJumpSpeed,
|
||||
cfs: this._currentFallSpeed,
|
||||
cjs: this._currentJumpSpeed,
|
||||
cj: this._canJump,
|
||||
lek: this._wasLeftKeyPressed,
|
||||
rik: this._wasRightKeyPressed,
|
||||
@@ -306,16 +359,30 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
override updateFromNetworkSyncData(
|
||||
networkSyncData: PhysicsCharacter3DNetworkSyncData
|
||||
networkSyncData: PhysicsCharacter3DNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
) {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
|
||||
const behaviorSpecificProps = networkSyncData.props;
|
||||
this._slopeMaxAngle = behaviorSpecificProps.sma;
|
||||
this._stairHeightMax = behaviorSpecificProps.shm;
|
||||
this._gravity = behaviorSpecificProps.grav;
|
||||
this._maxFallingSpeed = behaviorSpecificProps.mfs;
|
||||
this._forwardAcceleration = behaviorSpecificProps.facc;
|
||||
this._forwardDeceleration = behaviorSpecificProps.fdec;
|
||||
this._forwardSpeedMax = behaviorSpecificProps.fsm;
|
||||
this._sidewaysAcceleration = behaviorSpecificProps.sacc;
|
||||
this._sidewaysDeceleration = behaviorSpecificProps.sdec;
|
||||
this._sidewaysSpeedMax = behaviorSpecificProps.ssm;
|
||||
this._jumpSpeed = behaviorSpecificProps.jumpspeed;
|
||||
this._jumpSustainTime = behaviorSpecificProps.jumpsustime;
|
||||
this._forwardAngle = behaviorSpecificProps.fwa;
|
||||
this._shouldBindObjectAndForwardAngle = behaviorSpecificProps.sbpa;
|
||||
this._currentForwardSpeed = behaviorSpecificProps.fws;
|
||||
this._currentSidewaysSpeed = behaviorSpecificProps.sws;
|
||||
this._currentFallSpeed = behaviorSpecificProps.fs;
|
||||
this._currentJumpSpeed = behaviorSpecificProps.js;
|
||||
this._currentFallSpeed = behaviorSpecificProps.cfs;
|
||||
this._currentJumpSpeed = behaviorSpecificProps.cjs;
|
||||
this._canJump = behaviorSpecificProps.cj;
|
||||
this._hasPressedForwardKey = behaviorSpecificProps.upk;
|
||||
this._hasPressedBackwardKey = behaviorSpecificProps.dok;
|
||||
@@ -328,8 +395,8 @@ namespace gdjs {
|
||||
this._timeSinceCurrentJumpStart = behaviorSpecificProps.tscjs;
|
||||
this._jumpKeyHeldSinceJumpStart = behaviorSpecificProps.jkhsjs;
|
||||
|
||||
// When the object is synchronized from the network, the inputs must not be cleared.
|
||||
this._dontClearInputsBetweenFrames = true;
|
||||
// Clear user inputs between frames only if requested.
|
||||
this._clearInputsBetweenFrames = !!options.clearInputs;
|
||||
}
|
||||
|
||||
_getPhysicsPosition(result: Jolt.RVec3): Jolt.RVec3 {
|
||||
@@ -650,7 +717,7 @@ namespace gdjs {
|
||||
this._wasJumpKeyPressed = this._hasPressedJumpKey;
|
||||
this._wasStickUsed = this._hasUsedStick;
|
||||
|
||||
if (!this._dontClearInputsBetweenFrames) {
|
||||
if (this._clearInputsBetweenFrames) {
|
||||
this._hasPressedForwardKey = false;
|
||||
this._hasPressedBackwardKey = false;
|
||||
this._hasPressedRightKey = false;
|
||||
|
@@ -147,7 +147,7 @@ namespace gdjs {
|
||||
// This is useful when the object is synchronized by an external source
|
||||
// like in a multiplayer game, and we want to be able to predict the
|
||||
// movement of the object, even if the inputs are not updated every frame.
|
||||
_dontClearInputsBetweenFrames: boolean = false;
|
||||
private _clearInputsBetweenFrames: boolean = true;
|
||||
// This is useful when the object is synchronized over the network,
|
||||
// object is controlled by the network and we want to ensure the current player
|
||||
// cannot control it.
|
||||
@@ -227,14 +227,16 @@ namespace gdjs {
|
||||
this._state = this._falling;
|
||||
}
|
||||
|
||||
getNetworkSyncData(): PlatformerObjectNetworkSyncData {
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): PlatformerObjectNetworkSyncData {
|
||||
// This method is called, so we are synchronizing this object.
|
||||
// Let's clear the inputs between frames as we control it.
|
||||
this._dontClearInputsBetweenFrames = false;
|
||||
this._clearInputsBetweenFrames = true;
|
||||
this._ignoreDefaultControlsAsSyncedByNetwork = false;
|
||||
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
props: {
|
||||
cs: this._currentSpeed,
|
||||
|
||||
@@ -263,11 +265,52 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: PlatformerObjectNetworkSyncData
|
||||
networkSyncData: PlatformerObjectNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
) {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
|
||||
const behaviorSpecificProps = networkSyncData.props;
|
||||
|
||||
switch (behaviorSpecificProps.sn) {
|
||||
case 'Falling':
|
||||
if (behaviorSpecificProps.sn !== this._state.toString()) {
|
||||
this._setFalling();
|
||||
}
|
||||
this._falling.updateFromNetworkSyncData(behaviorSpecificProps.ssd);
|
||||
break;
|
||||
case 'OnFloor':
|
||||
// Let it handle automatically as we don't know which platform to land on.
|
||||
// @ts-ignore - we assume it's OnFloorStateNetworkSyncData
|
||||
this._onFloor.updateFromNetworkSyncData(behaviorSpecificProps.ssd);
|
||||
break;
|
||||
case 'Jumping':
|
||||
if (behaviorSpecificProps.sn !== this._state.toString()) {
|
||||
this._setJumping();
|
||||
}
|
||||
// @ts-ignore - we assume it's JumpingStateNetworkSyncData
|
||||
this._jumping.updateFromNetworkSyncData(behaviorSpecificProps.ssd);
|
||||
break;
|
||||
case 'GrabbingPlatform':
|
||||
// Let it handle automatically as we don't know which platform to grab.
|
||||
this._grabbingPlatform.updateFromNetworkSyncData(
|
||||
// @ts-ignore - we assume it's GrabbingPlatformStateNetworkSyncData
|
||||
behaviorSpecificProps.ssd
|
||||
);
|
||||
break;
|
||||
case 'OnLadder':
|
||||
if (behaviorSpecificProps.sn !== this._state.toString()) {
|
||||
this._setOnLadder();
|
||||
}
|
||||
this._onLadder.updateFromNetworkSyncData(behaviorSpecificProps.ssd);
|
||||
break;
|
||||
default:
|
||||
console.error(
|
||||
'Unknown state name: ' + behaviorSpecificProps.sn + '.'
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
if (behaviorSpecificProps.cs !== this._currentSpeed) {
|
||||
this._currentSpeed = behaviorSpecificProps.cs;
|
||||
}
|
||||
@@ -317,39 +360,10 @@ namespace gdjs {
|
||||
this._jumpKeyHeldSinceJumpStart = behaviorSpecificProps.jkhsjs;
|
||||
}
|
||||
|
||||
if (behaviorSpecificProps.sn !== this._state.toString()) {
|
||||
switch (behaviorSpecificProps.sn) {
|
||||
case 'Falling':
|
||||
this._setFalling();
|
||||
break;
|
||||
case 'OnFloor':
|
||||
// Let it handle automatically as we don't know which platform to land on.
|
||||
break;
|
||||
case 'Jumping':
|
||||
this._setJumping();
|
||||
break;
|
||||
case 'GrabbingPlatform':
|
||||
// Let it handle automatically as we don't know which platform to grab.
|
||||
break;
|
||||
case 'OnLadder':
|
||||
this._setOnLadder();
|
||||
break;
|
||||
default:
|
||||
console.error(
|
||||
'Unknown state name: ' + behaviorSpecificProps.sn + '.'
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (behaviorSpecificProps.sn === this._state.toString()) {
|
||||
this._state.updateFromNetworkSyncData(behaviorSpecificProps.ssd);
|
||||
}
|
||||
|
||||
// When the object is synchronized from the network, the inputs must not be cleared.
|
||||
this._dontClearInputsBetweenFrames = true;
|
||||
// Clear user inputs between frames only if requested.
|
||||
this._clearInputsBetweenFrames = !!options.clearInputs;
|
||||
// And we are not using the default controls.
|
||||
this._ignoreDefaultControlsAsSyncedByNetwork = true;
|
||||
this._ignoreDefaultControlsAsSyncedByNetwork = !options.keepControl;
|
||||
}
|
||||
|
||||
updateFromBehaviorData(oldBehaviorData, newBehaviorData): boolean {
|
||||
@@ -545,8 +559,9 @@ namespace gdjs {
|
||||
this._wasJumpKeyPressed = this._jumpKey;
|
||||
this._wasReleasePlatformKeyPressed = this._releasePlatformKey;
|
||||
this._wasReleaseLadderKeyPressed = this._releaseLadderKey;
|
||||
|
||||
//4) Do not forget to reset pressed keys
|
||||
if (!this._dontClearInputsBetweenFrames) {
|
||||
if (this._clearInputsBetweenFrames) {
|
||||
// Reset the keys only if the inputs are not supposed to survive between frames.
|
||||
// (Most of the time, except if this object is synchronized by an external source)
|
||||
this._leftKey = false;
|
||||
|
@@ -157,6 +157,57 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
trackChangesAndUpdateManagerIfNeeded() {
|
||||
if (!this.activated() && this._registeredInManager) {
|
||||
this._manager.removePlatform(this);
|
||||
this._registeredInManager = false;
|
||||
} else {
|
||||
if (this.activated() && !this._registeredInManager) {
|
||||
this._manager.addPlatform(this);
|
||||
this._registeredInManager = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
this._oldX !== this.owner.getX() ||
|
||||
this._oldY !== this.owner.getY() ||
|
||||
this._oldWidth !== this.owner.getWidth() ||
|
||||
this._oldHeight !== this.owner.getHeight() ||
|
||||
this._oldAngle !== this.owner.getAngle()
|
||||
) {
|
||||
if (this._registeredInManager) {
|
||||
this._manager.removePlatform(this);
|
||||
this._manager.addPlatform(this);
|
||||
}
|
||||
this._oldX = this.owner.getX();
|
||||
this._oldY = this.owner.getY();
|
||||
this._oldWidth = this.owner.getWidth();
|
||||
this._oldHeight = this.owner.getHeight();
|
||||
this._oldAngle = this.owner.getAngle();
|
||||
}
|
||||
}
|
||||
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): BehaviorNetworkSyncData {
|
||||
return super.getNetworkSyncData(syncOptions);
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: BehaviorNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
|
||||
this.trackChangesAndUpdateManagerIfNeeded();
|
||||
}
|
||||
|
||||
onCreated(): void {
|
||||
// Register it right away if activated,
|
||||
// so it can be used by platformer objects in that same frame.
|
||||
this.trackChangesAndUpdateManagerIfNeeded();
|
||||
}
|
||||
|
||||
onDestroy() {
|
||||
if (this._manager && this._registeredInManager) {
|
||||
this._manager.removePlatform(this);
|
||||
@@ -175,34 +226,7 @@ namespace gdjs {
|
||||
}*/
|
||||
|
||||
//Make sure the platform is or is not in the platforms manager.
|
||||
if (!this.activated() && this._registeredInManager) {
|
||||
this._manager.removePlatform(this);
|
||||
this._registeredInManager = false;
|
||||
} else {
|
||||
if (this.activated() && !this._registeredInManager) {
|
||||
this._manager.addPlatform(this);
|
||||
this._registeredInManager = true;
|
||||
}
|
||||
}
|
||||
|
||||
//Track changes in size or position
|
||||
if (
|
||||
this._oldX !== this.owner.getX() ||
|
||||
this._oldY !== this.owner.getY() ||
|
||||
this._oldWidth !== this.owner.getWidth() ||
|
||||
this._oldHeight !== this.owner.getHeight() ||
|
||||
this._oldAngle !== this.owner.getAngle()
|
||||
) {
|
||||
if (this._registeredInManager) {
|
||||
this._manager.removePlatform(this);
|
||||
this._manager.addPlatform(this);
|
||||
}
|
||||
this._oldX = this.owner.getX();
|
||||
this._oldY = this.owner.getY();
|
||||
this._oldWidth = this.owner.getWidth();
|
||||
this._oldHeight = this.owner.getHeight();
|
||||
this._oldAngle = this.owner.getAngle();
|
||||
}
|
||||
this.trackChangesAndUpdateManagerIfNeeded();
|
||||
}
|
||||
|
||||
doStepPostEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {}
|
||||
|
@@ -647,6 +647,9 @@ namespace gdjs {
|
||||
export const displayAuthenticationBanner = function (
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
) {
|
||||
if (runtimeScene.getGame().isInGameEdition()) {
|
||||
return;
|
||||
}
|
||||
if (_authenticationBanner) {
|
||||
// Banner already displayed, ensure it's visible.
|
||||
_authenticationBanner.style.opacity = '1';
|
||||
@@ -1042,6 +1045,10 @@ namespace gdjs {
|
||||
): gdjs.PromiseTask<{ status: 'logged' | 'errored' | 'dismissed' }> =>
|
||||
new gdjs.PromiseTask(
|
||||
new Promise((resolve) => {
|
||||
if (runtimeScene.getGame().isInGameEdition()) {
|
||||
resolve({ status: 'dismissed' });
|
||||
}
|
||||
|
||||
// Create the authentication container for the player to wait.
|
||||
const domElementContainer = runtimeScene
|
||||
.getGame()
|
||||
|
@@ -37,6 +37,24 @@ namespace gdjs {
|
||||
|
||||
export type ShapePainterObjectData = ObjectData & ShapePainterObjectDataType;
|
||||
|
||||
type ShapePainterNetworkSyncDataType = {
|
||||
cbf: boolean; // clearBetweenFrames
|
||||
aa: Antialiasing; // antialiasing
|
||||
ac: boolean; // absoluteCoordinates
|
||||
fc: integer; // fillColor
|
||||
oc: integer; // outlineColor
|
||||
os: float; // outlineSize
|
||||
fo: float; // fillOpacity
|
||||
oo: float; // outlineOpacity
|
||||
scaleX: number;
|
||||
scaleY: number;
|
||||
ifx: boolean; // isFlippedX
|
||||
ify: boolean; // isFlippedY
|
||||
};
|
||||
|
||||
export type ShapePainterNetworkSyncData = ObjectNetworkSyncData &
|
||||
ShapePainterNetworkSyncDataType;
|
||||
|
||||
/**
|
||||
* The ShapePainterRuntimeObject allows to draw graphics shapes on screen.
|
||||
*/
|
||||
@@ -191,17 +209,77 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): ShapePainterNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
cbf: this._clearBetweenFrames,
|
||||
aa: this._antialiasing,
|
||||
ac: this._useAbsoluteCoordinates,
|
||||
fc: this._fillColor,
|
||||
oc: this._outlineColor,
|
||||
os: this._outlineSize,
|
||||
fo: this._fillOpacity,
|
||||
oo: this._outlineOpacity,
|
||||
scaleX: this.getScaleX(),
|
||||
scaleY: this.getScaleY(),
|
||||
ifx: this._flippedX,
|
||||
ify: this._flippedY,
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: ShapePainterNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
|
||||
if (networkSyncData.cbf !== undefined) {
|
||||
this._clearBetweenFrames = networkSyncData.cbf;
|
||||
}
|
||||
if (networkSyncData.aa !== undefined) {
|
||||
this.setAntialiasing(networkSyncData.aa);
|
||||
}
|
||||
if (networkSyncData.ac !== undefined) {
|
||||
this.setCoordinatesRelative(!networkSyncData.ac);
|
||||
}
|
||||
if (networkSyncData.fc !== undefined) {
|
||||
this._fillColor = networkSyncData.fc;
|
||||
}
|
||||
if (networkSyncData.oc !== undefined) {
|
||||
this._outlineColor = networkSyncData.oc;
|
||||
}
|
||||
if (networkSyncData.os !== undefined) {
|
||||
this.setOutlineSize(networkSyncData.os);
|
||||
}
|
||||
if (networkSyncData.fo !== undefined) {
|
||||
this.setFillOpacity(networkSyncData.fo);
|
||||
}
|
||||
if (networkSyncData.oo !== undefined) {
|
||||
this.setOutlineOpacity(networkSyncData.oo);
|
||||
}
|
||||
if (networkSyncData.scaleX !== undefined) {
|
||||
this.setScaleX(networkSyncData.scaleX);
|
||||
}
|
||||
if (networkSyncData.scaleY !== undefined) {
|
||||
this.setScaleY(networkSyncData.scaleY);
|
||||
}
|
||||
if (networkSyncData.ifx !== undefined) {
|
||||
this.flipX(networkSyncData.ifx);
|
||||
}
|
||||
if (networkSyncData.ify !== undefined) {
|
||||
this.flipY(networkSyncData.ify);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the extra parameters that could be set for an instance.
|
||||
* @param initialInstanceData The extra parameters
|
||||
*/
|
||||
extraInitializationFromInitialInstance(initialInstanceData: InstanceData) {
|
||||
if (initialInstanceData.flippedX) {
|
||||
this.flipX(initialInstanceData.flippedX);
|
||||
}
|
||||
if (initialInstanceData.flippedY) {
|
||||
this.flipY(initialInstanceData.flippedY);
|
||||
}
|
||||
this.flipX(!!initialInstanceData.flippedX);
|
||||
this.flipY(!!initialInstanceData.flippedY);
|
||||
}
|
||||
|
||||
stepBehaviorsPreEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
|
@@ -50,6 +50,19 @@ describe('gdjs.ShapePainterRuntimeObject (using a PixiJS RuntimeGame with assets
|
||||
instances: [],
|
||||
variables: [],
|
||||
usedResources: [],
|
||||
uiSettings: {
|
||||
grid: false,
|
||||
gridType: 'rectangular',
|
||||
gridWidth: 10,
|
||||
gridHeight: 10,
|
||||
gridDepth: 10,
|
||||
gridOffsetX: 0,
|
||||
gridOffsetY: 0,
|
||||
gridOffsetZ: 0,
|
||||
gridColor: 0,
|
||||
gridAlpha: 1,
|
||||
snap: false,
|
||||
},
|
||||
},
|
||||
usedExtensionsWithVariablesData: [],
|
||||
});
|
||||
|
488
Extensions/SaveState/JsExtension.js
Normal file
488
Extensions/SaveState/JsExtension.js
Normal file
@@ -0,0 +1,488 @@
|
||||
//@ts-check
|
||||
/// <reference path="../JsExtensionTypes.d.ts" />
|
||||
/**
|
||||
* This is a declaration of an extension for GDevelop 5.
|
||||
*
|
||||
* ℹ️ Changes in this file are watched and automatically imported if the editor
|
||||
* is running. You can also manually run `node import-GDJS-Runtime.js` (in newIDE/app/scripts).
|
||||
*
|
||||
* The file must be named "JsExtension.js", otherwise GDevelop won't load it.
|
||||
* ⚠️ If you make a change and the extension is not loaded, open the developer console
|
||||
* and search for any errors.
|
||||
*
|
||||
* More information on https://github.com/4ian/GDevelop/blob/master/newIDE/README-extensions.md
|
||||
*/
|
||||
|
||||
/** @type {ExtensionModule} */
|
||||
module.exports = {
|
||||
createExtension: function (_, gd) {
|
||||
const extension = new gd.PlatformExtension();
|
||||
extension
|
||||
.setExtensionInformation(
|
||||
'SaveState',
|
||||
_('Save State (experimental)'),
|
||||
_(
|
||||
'Allows to save and load the full state of a game, usually on the device storage. A Save State, by default, contains the full state of the game (objects, variables, sounds, music, effects etc.). Using the "Save Configuration" behavior, you can customize which objects should not be saved in a Save State. You can also use the "Change the save configuration of a variable" action to change the save configuration of a variable. Finally, both objects, variables and scene/game data can be given a profile name: in this case, when saving or loading with one or more profile names specified, only the object/variables/data belonging to one of the specified profiles will be saved or loaded.'
|
||||
),
|
||||
'Neyl Mahfouf',
|
||||
'Open source (MIT License)'
|
||||
)
|
||||
.setExtensionHelpPath('/all-features/save-state')
|
||||
.setCategory('Game mechanic')
|
||||
.addInstructionOrExpressionGroupMetadata(_('Save State (experimental)'))
|
||||
.setIcon('res/actions/saveDown.svg');
|
||||
|
||||
extension
|
||||
.addAction(
|
||||
'CreateGameSaveStateInVariable',
|
||||
_('Save game to a variable'),
|
||||
_(
|
||||
'Create a Save State and save it to a variable. This is for advanced usage, prefer to use "Save game to device storage" in most cases.'
|
||||
),
|
||||
_('Save game in variable _PARAM1_ (profile(s): _PARAM2_)'),
|
||||
_('Save'),
|
||||
'res/actions/saveDown.svg',
|
||||
'res/actions/saveDown.svg'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter('variable', _('Variable to store the save to'), '', false)
|
||||
.addParameter('string', _('Profile(s) to save'), '', true)
|
||||
.setDefaultValue('"default"')
|
||||
.setParameterLongDescription(
|
||||
_(
|
||||
'Comma-separated list of profile names that must be saved. Only objects tagged with at least one of these profiles will be saved. If no profile names are specified, all objects will be saved (unless they have a "Save Configuration" behavior set to "Do not save").'
|
||||
)
|
||||
)
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/SaveState/SaveStateTools.js')
|
||||
.addIncludeFile(
|
||||
'Extensions/SaveState/SaveConfigurationRuntimeBehavior.js'
|
||||
)
|
||||
.setFunctionName('gdjs.saveState.createGameSaveStateInVariable');
|
||||
|
||||
extension
|
||||
.addAction(
|
||||
'CreateGameSaveStateInStorage',
|
||||
_('Save game to device storage'),
|
||||
_('Create a Save State and save it to device storage.'),
|
||||
_('Save game to device storage named _PARAM1_ (profile(s): _PARAM2_)'),
|
||||
_('Save'),
|
||||
'res/actions/saveDown.svg',
|
||||
'res/actions/saveDown.svg'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter('string', _('Storage key to save to'), '', false)
|
||||
.addParameter('string', _('Profile(s) to save'), '', true)
|
||||
.setDefaultValue('"default"')
|
||||
.setParameterLongDescription(
|
||||
_(
|
||||
'Comma-separated list of profile names that must be saved. Only objects tagged with at least one of these profiles will be saved. If no profile names are specified, all objects will be saved (unless they have a "Save Configuration" behavior set to "Do not save").'
|
||||
)
|
||||
)
|
||||
.setDefaultValue('no')
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/SaveState/SaveStateTools.js')
|
||||
.addIncludeFile(
|
||||
'Extensions/SaveState/SaveConfigurationRuntimeBehavior.js'
|
||||
)
|
||||
.setFunctionName('gdjs.saveState.createGameSaveStateInStorage');
|
||||
|
||||
extension
|
||||
.addAction(
|
||||
'RestoreGameSaveStateFromVariable',
|
||||
_('Load game from variable'),
|
||||
_(
|
||||
'Restore the game from a Save State stored in the specified variable. This is for advanced usage, prefer to use "Load game from device storage" in most cases.'
|
||||
),
|
||||
_(
|
||||
'Load game from variable _PARAM1_ (profile(s): _PARAM2_, stop and restart all the scenes currently played: _PARAM3_)'
|
||||
),
|
||||
_('Load'),
|
||||
'res/actions/saveUp.svg',
|
||||
'res/actions/saveUp.svg'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter('variable', _('Variable to load the game from'), '', false)
|
||||
.addParameter('string', _('Profile(s) to load'), '', true)
|
||||
.setDefaultValue('"default"')
|
||||
.setParameterLongDescription(
|
||||
_(
|
||||
'Comma-separated list of profile names that must be loaded. Only objects tagged with at least one of these profiles will be loaded - others will be left alone. If no profile names are specified, all objects will be loaded (unless they have a "Save Configuration" behavior set to "Do not save").'
|
||||
)
|
||||
)
|
||||
.addParameter(
|
||||
'yesorno',
|
||||
_('Stop and restart all the scenes currently played?'),
|
||||
'',
|
||||
true
|
||||
)
|
||||
.setDefaultValue('no')
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/SaveState/SaveStateTools.js')
|
||||
.addIncludeFile(
|
||||
'Extensions/SaveState/SaveConfigurationRuntimeBehavior.js'
|
||||
)
|
||||
.setFunctionName('gdjs.saveState.restoreGameSaveStateFromVariable');
|
||||
|
||||
extension
|
||||
.addAction(
|
||||
'RestoreGameSaveStateFromStorage',
|
||||
_('Load game from device storage'),
|
||||
_('Restore the game from a Save State stored on the device.'),
|
||||
_(
|
||||
'Load game from device storage named _PARAM1_ (profile(s): _PARAM2_, stop and restart all the scenes currently played: _PARAM3_)'
|
||||
),
|
||||
_('Load'),
|
||||
'res/actions/saveUp.svg',
|
||||
'res/actions/saveUp.svg'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter(
|
||||
'string',
|
||||
_('Storage name to load the game from'),
|
||||
'',
|
||||
false
|
||||
)
|
||||
.addParameter('string', _('Profile(s) to load'), '', true)
|
||||
.setDefaultValue('"default"')
|
||||
.setParameterLongDescription(
|
||||
_(
|
||||
'Comma-separated list of profile names that must be loaded. Only objects tagged with at least one of these profiles will be loaded - others will be left alone. If no profile names are specified, all objects will be loaded.'
|
||||
)
|
||||
)
|
||||
.addParameter(
|
||||
'yesorno',
|
||||
_('Stop and restart all the scenes currently played?'),
|
||||
'',
|
||||
true
|
||||
)
|
||||
.setDefaultValue('no')
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/SaveState/SaveStateTools.js')
|
||||
.addIncludeFile(
|
||||
'Extensions/SaveState/SaveConfigurationRuntimeBehavior.js'
|
||||
)
|
||||
.setFunctionName('gdjs.saveState.restoreGameSaveStateFromStorage');
|
||||
|
||||
extension
|
||||
.addExpressionAndCondition(
|
||||
'number',
|
||||
'TimeSinceLastSave',
|
||||
_('Time since last save'),
|
||||
_(
|
||||
'Time since the last save, in seconds. Returns -1 if no save happened, and a positive number otherwise.'
|
||||
),
|
||||
_('Time since the last save'),
|
||||
'',
|
||||
'res/actions/saveDown.svg'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.useStandardParameters('number', gd.ParameterOptions.makeNewOptions())
|
||||
.setIncludeFile('Extensions/SaveState/SaveStateTools.js')
|
||||
.addIncludeFile(
|
||||
'Extensions/SaveState/SaveConfigurationRuntimeBehavior.js'
|
||||
)
|
||||
.setFunctionName('gdjs.saveState.getSecondsSinceLastSave')
|
||||
.setGetter('gdjs.saveState.getSecondsSinceLastSave');
|
||||
|
||||
extension
|
||||
.addExpressionAndCondition(
|
||||
'number',
|
||||
'TimeSinceLastLoad',
|
||||
_('Time since last load'),
|
||||
_(
|
||||
'Time since the last load, in seconds. Returns -1 if no load happened, and a positive number otherwise.'
|
||||
),
|
||||
_('Time since the last load'),
|
||||
'',
|
||||
'res/actions/saveDown.svg'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.useStandardParameters('number', gd.ParameterOptions.makeNewOptions())
|
||||
.setIncludeFile('Extensions/SaveState/SaveStateTools.js')
|
||||
.addIncludeFile(
|
||||
'Extensions/SaveState/SaveConfigurationRuntimeBehavior.js'
|
||||
)
|
||||
.setFunctionName('gdjs.saveState.getSecondsSinceLastLoad')
|
||||
.setGetter('gdjs.saveState.getSecondsSinceLastLoad');
|
||||
|
||||
extension
|
||||
.addCondition(
|
||||
'SaveJustSucceeded',
|
||||
_('Save just succeeded'),
|
||||
_('The last save attempt just succeeded.'),
|
||||
_('Save just succeeded'),
|
||||
_('Save'),
|
||||
'res/actions/saveDown.svg',
|
||||
'res/actions/saveDown.svg'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/SaveState/SaveStateTools.js')
|
||||
.addIncludeFile(
|
||||
'Extensions/SaveState/SaveConfigurationRuntimeBehavior.js'
|
||||
)
|
||||
.setFunctionName('gdjs.saveState.hasSaveJustSucceeded');
|
||||
|
||||
extension
|
||||
.addCondition(
|
||||
'SaveJustFailed',
|
||||
_('Save just failed'),
|
||||
_('The last save attempt just failed.'),
|
||||
_('Save just failed'),
|
||||
_('Save'),
|
||||
'res/actions/saveDown.svg',
|
||||
'res/actions/saveDown.svg'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/SaveState/SaveStateTools.js')
|
||||
.addIncludeFile(
|
||||
'Extensions/SaveState/SaveConfigurationRuntimeBehavior.js'
|
||||
)
|
||||
.setFunctionName('gdjs.saveState.hasSaveJustFailed');
|
||||
|
||||
extension
|
||||
.addCondition(
|
||||
'LoadJustSucceeded',
|
||||
_('Load just succeeded'),
|
||||
_('The last load attempt just succeeded.'),
|
||||
_('Load just succeeded'),
|
||||
_('Load'),
|
||||
'res/actions/saveUp.svg',
|
||||
'res/actions/saveUp.svg'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/SaveState/SaveStateTools.js')
|
||||
.addIncludeFile(
|
||||
'Extensions/SaveState/SaveConfigurationRuntimeBehavior.js'
|
||||
)
|
||||
.setFunctionName('gdjs.saveState.hasLoadJustSucceeded');
|
||||
|
||||
extension
|
||||
.addCondition(
|
||||
'LoadJustFailed',
|
||||
_('Load just failed'),
|
||||
_('The last load attempt just failed.'),
|
||||
_('Load just failed'),
|
||||
_('Load'),
|
||||
'res/actions/saveUp.svg',
|
||||
'res/actions/saveUp.svg'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/SaveState/SaveStateTools.js')
|
||||
.addIncludeFile(
|
||||
'Extensions/SaveState/SaveConfigurationRuntimeBehavior.js'
|
||||
)
|
||||
.setFunctionName('gdjs.saveState.hasLoadJustFailed');
|
||||
|
||||
extension
|
||||
.addAction(
|
||||
'SetVariableSaveConfiguration',
|
||||
_('Change the save configuration of a variable'),
|
||||
_(
|
||||
'Set if a scene or global variable should be saved in the default save state. Also allow to specify one or more profiles in which the variable should be saved.'
|
||||
),
|
||||
_(
|
||||
'Change save configuration of _PARAM1_: save it in the default save states: _PARAM2_ and in profiles: _PARAM3_'
|
||||
),
|
||||
_('Advanced configuration'),
|
||||
'res/actions/saveDown.svg',
|
||||
'res/actions/saveDown.svg'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter(
|
||||
'variable',
|
||||
_('Variable for which configuration should be changed'),
|
||||
'',
|
||||
false
|
||||
)
|
||||
.addParameter('yesorno', _('Persist in default save states'), '', false)
|
||||
.setDefaultValue('yes')
|
||||
.addParameter(
|
||||
'string',
|
||||
_('Profiles in which the variable should be saved'),
|
||||
'',
|
||||
true
|
||||
)
|
||||
.setDefaultValue('')
|
||||
.setParameterLongDescription(
|
||||
_(
|
||||
'Comma-separated list of profile names in which the variable will be saved. When a save state is created with one or more profile names specified, the variable will be saved only if it matches one of these profiles.'
|
||||
)
|
||||
)
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/SaveState/SaveStateTools.js')
|
||||
.addIncludeFile(
|
||||
'Extensions/SaveState/SaveConfigurationRuntimeBehavior.js'
|
||||
)
|
||||
.setFunctionName('gdjs.saveState.setVariableSaveConfiguration');
|
||||
|
||||
extension
|
||||
.addAction(
|
||||
'SetGameDataSaveConfiguration',
|
||||
_('Change the save configuration of the global game data'),
|
||||
_(
|
||||
'Set if the global game data (audio & global variables) should be saved in the default save state. Also allow to specify one or more profiles in which the global game data should be saved.'
|
||||
),
|
||||
_(
|
||||
'Change save configuration of global game data: save them in the default save states: _PARAM1_ and in profiles: _PARAM2_'
|
||||
),
|
||||
_('Advanced configuration'),
|
||||
'res/actions/saveDown.svg',
|
||||
'res/actions/saveDown.svg'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter('yesorno', _('Persist in default save states'), '', false)
|
||||
.setDefaultValue('yes')
|
||||
.addParameter(
|
||||
'string',
|
||||
_('Profiles in which the global game data should be saved'),
|
||||
'',
|
||||
true
|
||||
)
|
||||
.setDefaultValue('')
|
||||
.setParameterLongDescription(
|
||||
_(
|
||||
'Comma-separated list of profile names in which the global game data will be saved. When a save state is created with one or more profile names specified, the global game data will be saved only if it matches one of these profiles.'
|
||||
)
|
||||
)
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/SaveState/SaveStateTools.js')
|
||||
.addIncludeFile(
|
||||
'Extensions/SaveState/SaveConfigurationRuntimeBehavior.js'
|
||||
)
|
||||
.setFunctionName('gdjs.saveState.setGameDataSaveConfiguration');
|
||||
|
||||
extension
|
||||
.addAction(
|
||||
'SetSceneDataSaveConfiguration',
|
||||
_('Change the save configuration of a scene data'),
|
||||
_(
|
||||
'Set if the data of the specified scene (scene variables, timers, trigger once, wait actions, layers, etc.) should be saved in the default save state. Also allow to specify one or more profiles in which the scene data should be saved. Note: objects are always saved separately from the scene data (use the "Save Configuration" behavior to customize the configuration of objects).'
|
||||
),
|
||||
_(
|
||||
'Change save configuration of scene _PARAM1_: save it in the default save states: _PARAM2_ and in profiles: _PARAM3_'
|
||||
),
|
||||
_('Advanced configuration'),
|
||||
'res/actions/saveDown.svg',
|
||||
'res/actions/saveDown.svg'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter(
|
||||
'sceneName',
|
||||
_('Scene name for which configuration should be changed'),
|
||||
'',
|
||||
false
|
||||
)
|
||||
.addParameter('yesorno', _('Persist in default save states'), '', false)
|
||||
.setDefaultValue('yes')
|
||||
.addParameter(
|
||||
'string',
|
||||
_('Profiles in which the scene data should be saved'),
|
||||
'',
|
||||
true
|
||||
)
|
||||
.setDefaultValue('')
|
||||
.setParameterLongDescription(
|
||||
_(
|
||||
'Comma-separated list of profile names in which the scene data will be saved. When a save state is created with one or more profile names specified, the scene data will be saved only if it matches one of these profiles.'
|
||||
)
|
||||
)
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/SaveState/SaveStateTools.js')
|
||||
.addIncludeFile(
|
||||
'Extensions/SaveState/SaveConfigurationRuntimeBehavior.js'
|
||||
)
|
||||
.setFunctionName('gdjs.saveState.setSceneDataSaveConfiguration');
|
||||
|
||||
// Save Configuration behavior
|
||||
const saveConfigurationBehavior = new gd.BehaviorJsImplementation();
|
||||
|
||||
saveConfigurationBehavior.updateProperty = function (
|
||||
behaviorContent,
|
||||
propertyName,
|
||||
newValue
|
||||
) {
|
||||
if (propertyName === 'defaultProfilePersistence') {
|
||||
behaviorContent
|
||||
.getChild('defaultProfilePersistence')
|
||||
.setStringValue(newValue);
|
||||
return true;
|
||||
}
|
||||
if (propertyName === 'persistedInProfiles') {
|
||||
behaviorContent
|
||||
.getChild('persistedInProfiles')
|
||||
.setStringValue(newValue);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
saveConfigurationBehavior.getProperties = function (behaviorContent) {
|
||||
const behaviorProperties = new gd.MapStringPropertyDescriptor();
|
||||
|
||||
behaviorProperties
|
||||
.getOrCreate('defaultProfilePersistence')
|
||||
.setValue(
|
||||
behaviorContent.getChild('defaultProfilePersistence').getStringValue()
|
||||
)
|
||||
.setType('Choice')
|
||||
.setLabel(_('Persistence mode'))
|
||||
.addChoice('Persisted', _('Include in save states (default)'))
|
||||
.addChoice('DoNotSave', _('Do not save'));
|
||||
|
||||
behaviorProperties
|
||||
.getOrCreate('persistedInProfiles')
|
||||
.setValue(
|
||||
behaviorContent.getChild('persistedInProfiles').getStringValue()
|
||||
)
|
||||
.setType('String')
|
||||
.setLabel(_('Save profile names'))
|
||||
.setDescription(
|
||||
_(
|
||||
'Comma-separated list of profile names in which the object is saved. When a save state is created with one or more profile names specified, the object will be saved only if it matches one of these profiles.'
|
||||
)
|
||||
)
|
||||
.setAdvanced(true);
|
||||
|
||||
return behaviorProperties;
|
||||
};
|
||||
|
||||
saveConfigurationBehavior.initializeContent = function (behaviorContent) {
|
||||
behaviorContent
|
||||
.addChild('defaultProfilePersistence')
|
||||
.setStringValue('Persisted');
|
||||
behaviorContent.addChild('persistedInProfiles').setStringValue('');
|
||||
};
|
||||
|
||||
const sharedData = new gd.BehaviorsSharedData();
|
||||
|
||||
extension
|
||||
.addBehavior(
|
||||
'SaveConfiguration',
|
||||
_('Save state configuration'),
|
||||
'SaveConfiguration',
|
||||
_('Allow the customize how the object is persisted in a save state.'),
|
||||
'',
|
||||
'res/actions/saveUp.svg',
|
||||
'SaveConfiguration',
|
||||
// @ts-ignore - TODO: Fix type being a BehaviorJsImplementation instead of an Behavior
|
||||
saveConfigurationBehavior,
|
||||
sharedData
|
||||
)
|
||||
.setQuickCustomizationVisibility(gd.QuickCustomization.Hidden)
|
||||
.setIncludeFile('Extensions/SaveState/SaveStateTools.js')
|
||||
.addIncludeFile(
|
||||
'Extensions/SaveState/SaveConfigurationRuntimeBehavior.js'
|
||||
);
|
||||
|
||||
return extension;
|
||||
},
|
||||
runExtensionSanityTests: function (gd, extension) {
|
||||
return [];
|
||||
},
|
||||
};
|
32
Extensions/SaveState/SaveConfigurationRuntimeBehavior.ts
Normal file
32
Extensions/SaveState/SaveConfigurationRuntimeBehavior.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
namespace gdjs {
|
||||
// const logger = new gdjs.Logger('Save State');
|
||||
|
||||
export class SaveConfigurationRuntimeBehavior extends gdjs.RuntimeBehavior {
|
||||
private readonly _defaultProfilePersistence: 'Persisted' | 'DoNotSave' =
|
||||
'Persisted';
|
||||
private readonly _persistedInProfiles = '';
|
||||
|
||||
constructor(
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
behaviorData: any,
|
||||
owner: RuntimeObject
|
||||
) {
|
||||
super(instanceContainer, behaviorData, owner);
|
||||
this._defaultProfilePersistence =
|
||||
behaviorData.defaultProfilePersistence || 'Persisted';
|
||||
this._persistedInProfiles = behaviorData.persistedInProfiles || '';
|
||||
}
|
||||
|
||||
getDefaultProfilePersistence() {
|
||||
return this._defaultProfilePersistence;
|
||||
}
|
||||
|
||||
getPersistedInProfiles() {
|
||||
return this._persistedInProfiles;
|
||||
}
|
||||
}
|
||||
gdjs.registerBehavior(
|
||||
'SaveState::SaveConfiguration',
|
||||
gdjs.SaveConfigurationRuntimeBehavior
|
||||
);
|
||||
}
|
696
Extensions/SaveState/SaveStateTools.ts
Normal file
696
Extensions/SaveState/SaveStateTools.ts
Normal file
@@ -0,0 +1,696 @@
|
||||
namespace gdjs {
|
||||
const logger = new gdjs.Logger('Save State');
|
||||
const debugLogger = new gdjs.Logger('Save State - Debug');
|
||||
// Comment this to see message logs and ease debugging:
|
||||
gdjs.Logger.getDefaultConsoleLoggerOutput().discardGroup(
|
||||
'Save State - Debug'
|
||||
);
|
||||
|
||||
type ArbitrarySaveConfiguration = {
|
||||
defaultProfilePersistence: 'Persisted' | 'DoNotSave';
|
||||
persistedInProfiles: Set<string>;
|
||||
};
|
||||
|
||||
export type RestoreRequestOptions = {
|
||||
profileNames: string[];
|
||||
clearSceneStack: boolean;
|
||||
|
||||
fromStorageName?: string;
|
||||
fromVariable?: gdjs.Variable;
|
||||
};
|
||||
|
||||
export namespace saveState {
|
||||
export const getIndexedDbDatabaseName = () => {
|
||||
const gameId = gdjs.projectData.properties.projectUuid;
|
||||
return `gdevelop-game-${gameId}`;
|
||||
};
|
||||
export const getIndexedDbObjectStore = () => {
|
||||
return `game-saves`;
|
||||
};
|
||||
export const getIndexedDbStorageKey = (key: string) => {
|
||||
return `save-${key}`;
|
||||
};
|
||||
|
||||
const variablesSaveConfiguration: WeakMap<
|
||||
Variable,
|
||||
ArbitrarySaveConfiguration
|
||||
> = new WeakMap();
|
||||
const runtimeSceneDataSaveConfiguration: WeakMap<
|
||||
RuntimeGame,
|
||||
Record<string, ArbitrarySaveConfiguration>
|
||||
> = new WeakMap();
|
||||
const runtimeGameDataSaveConfiguration: WeakMap<
|
||||
RuntimeGame,
|
||||
ArbitrarySaveConfiguration
|
||||
> = new WeakMap();
|
||||
|
||||
export const setVariableSaveConfiguration = (
|
||||
_: gdjs.RuntimeScene,
|
||||
variable: gdjs.Variable,
|
||||
persistInDefaultProfile: boolean,
|
||||
persistedInProfilesAsString: string
|
||||
) => {
|
||||
variablesSaveConfiguration.set(variable, {
|
||||
defaultProfilePersistence: persistInDefaultProfile
|
||||
? 'Persisted'
|
||||
: 'DoNotSave',
|
||||
persistedInProfiles: new Set(
|
||||
parseCommaSeparatedProfileNames(persistedInProfilesAsString)
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
export const setSceneDataSaveConfiguration = (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
sceneName: string,
|
||||
persistInDefaultProfile: boolean,
|
||||
persistedInProfilesAsString: string
|
||||
) => {
|
||||
const runtimeSceneDataSaveConfigurations =
|
||||
runtimeSceneDataSaveConfiguration.get(runtimeScene.getGame()) || {};
|
||||
|
||||
runtimeSceneDataSaveConfiguration.set(runtimeScene.getGame(), {
|
||||
...runtimeSceneDataSaveConfigurations,
|
||||
[sceneName]: {
|
||||
defaultProfilePersistence: persistInDefaultProfile
|
||||
? 'Persisted'
|
||||
: 'DoNotSave',
|
||||
persistedInProfiles: new Set(
|
||||
parseCommaSeparatedProfileNames(persistedInProfilesAsString)
|
||||
),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const setGameDataSaveConfiguration = (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
persistInDefaultProfile: boolean,
|
||||
persistedInProfilesAsString: string
|
||||
) => {
|
||||
runtimeGameDataSaveConfiguration.set(runtimeScene.getGame(), {
|
||||
defaultProfilePersistence: persistInDefaultProfile
|
||||
? 'Persisted'
|
||||
: 'DoNotSave',
|
||||
persistedInProfiles: new Set(
|
||||
parseCommaSeparatedProfileNames(persistedInProfilesAsString)
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const checkIfIsPersistedInProfiles = (
|
||||
profileNames: string[],
|
||||
configuration: ArbitrarySaveConfiguration | null | undefined
|
||||
) => {
|
||||
if (profileNames.includes('default')) {
|
||||
if (
|
||||
!configuration ||
|
||||
configuration.defaultProfilePersistence === 'Persisted'
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (configuration) {
|
||||
for (const profileName of profileNames) {
|
||||
if (configuration.persistedInProfiles.has(profileName)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
const makeIsVariableExcludedFromSaveState =
|
||||
(profileNames: string[]) => (variable: gdjs.Variable) => {
|
||||
const saveConfiguration = variablesSaveConfiguration.get(variable);
|
||||
return !checkIfIsPersistedInProfiles(
|
||||
profileNames,
|
||||
saveConfiguration || null
|
||||
);
|
||||
};
|
||||
|
||||
let lastSaveTime: number | null = null;
|
||||
let lastLoadTime: number | null = null;
|
||||
let saveJustSucceeded: boolean = false;
|
||||
let saveJustFailed: boolean = false;
|
||||
let loadJustSucceeded: boolean = false;
|
||||
let loadJustFailed: boolean = false;
|
||||
|
||||
let restoreRequestOptions: RestoreRequestOptions | null = null;
|
||||
|
||||
export const getSecondsSinceLastSave = (_: RuntimeScene): number => {
|
||||
if (!lastSaveTime) return -1;
|
||||
return Math.floor((Date.now() - lastSaveTime) / 1000);
|
||||
};
|
||||
export const getSecondsSinceLastLoad = (_: RuntimeScene): number => {
|
||||
if (!lastLoadTime) return -1;
|
||||
return Math.floor((Date.now() - lastLoadTime) / 1000);
|
||||
};
|
||||
export const hasSaveJustSucceeded = (_: RuntimeScene) => {
|
||||
return saveJustSucceeded;
|
||||
};
|
||||
export const hasLoadJustSucceeded = (_: RuntimeScene) => {
|
||||
return loadJustSucceeded;
|
||||
};
|
||||
export const hasSaveJustFailed = (_: RuntimeScene) => {
|
||||
return saveJustFailed;
|
||||
};
|
||||
export const hasLoadJustFailed = (_: RuntimeScene) => {
|
||||
return loadJustFailed;
|
||||
};
|
||||
export const markSaveJustSucceeded = (_: RuntimeScene) => {
|
||||
saveJustSucceeded = true;
|
||||
lastSaveTime = Date.now();
|
||||
};
|
||||
export const markLoadJustSucceeded = (_: RuntimeScene) => {
|
||||
loadJustSucceeded = true;
|
||||
lastLoadTime = Date.now();
|
||||
};
|
||||
export const markSaveJustFailed = (_: RuntimeScene) => {
|
||||
saveJustFailed = true;
|
||||
};
|
||||
export const markLoadJustFailed = (_: RuntimeScene) => {
|
||||
loadJustFailed = true;
|
||||
};
|
||||
|
||||
// Ensure that the condition "save/load just succeeded/failed" are valid only for one frame.
|
||||
gdjs.registerRuntimeScenePostEventsCallback(() => {
|
||||
saveJustSucceeded = false;
|
||||
saveJustFailed = false;
|
||||
loadJustSucceeded = false;
|
||||
loadJustFailed = false;
|
||||
});
|
||||
|
||||
gdjs.registerRuntimeScenePostEventsCallback(
|
||||
(runtimeScene: gdjs.RuntimeScene) => {
|
||||
checkAndRestoreGameSaveStateAtEndOfFrame(runtimeScene);
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Create a Save State from the given game.
|
||||
*
|
||||
* Only objects, variables etc... tagged with at least one of the profiles
|
||||
* given in `options.profileNames` will be saved.
|
||||
*/
|
||||
export const createGameSaveState = (
|
||||
runtimeGame: RuntimeGame,
|
||||
options: {
|
||||
profileNames: string[];
|
||||
}
|
||||
) => {
|
||||
const { profileNames } = options;
|
||||
|
||||
const getNetworkSyncOptions: GetNetworkSyncDataOptions = {
|
||||
syncObjectIdentifiers: true,
|
||||
shouldExcludeVariableFromData:
|
||||
makeIsVariableExcludedFromSaveState(profileNames),
|
||||
syncAllBehaviors: true,
|
||||
syncGameVariables: true,
|
||||
syncSceneTimers: true,
|
||||
syncOnceTriggers: true,
|
||||
syncSounds: true,
|
||||
syncTweens: true,
|
||||
syncLayers: true,
|
||||
syncAsyncTasks: true,
|
||||
syncSceneVisualProps: true,
|
||||
syncFullTileMaps: true,
|
||||
};
|
||||
|
||||
const shouldPersistGameData = checkIfIsPersistedInProfiles(
|
||||
options.profileNames,
|
||||
runtimeGameDataSaveConfiguration.get(runtimeGame)
|
||||
);
|
||||
|
||||
const gameSaveState: GameSaveState = {
|
||||
// Always persist some game data, but limit it to just the scene stack
|
||||
// if asked to not persist the game data.
|
||||
gameNetworkSyncData: runtimeGame.getNetworkSyncData({
|
||||
...getNetworkSyncOptions,
|
||||
syncGameVariables: shouldPersistGameData,
|
||||
syncSounds: shouldPersistGameData,
|
||||
}),
|
||||
layoutNetworkSyncDatas: [],
|
||||
};
|
||||
|
||||
const scenes = runtimeGame.getSceneStack().getAllScenes();
|
||||
scenes.forEach((runtimeScene, index) => {
|
||||
gameSaveState.layoutNetworkSyncDatas[index] = {
|
||||
sceneData: {} as LayoutNetworkSyncData,
|
||||
objectDatas: {},
|
||||
};
|
||||
|
||||
// First collect all object sync data, as they may generate unique
|
||||
// identifiers like their networkId.
|
||||
for (const object of runtimeScene.getAdhocListOfAllInstances()) {
|
||||
// By default, an object which has no SaveConfiguration behavior is like
|
||||
// it has the default profile persistence set to "Persisted".
|
||||
let shouldPersist = profileNames.includes('default');
|
||||
|
||||
// @ts-ignore - access to `_behaviors` is an exceptional case for the SaveConfiguration behavior.
|
||||
for (const behavior of object._behaviors) {
|
||||
if (behavior instanceof gdjs.SaveConfigurationRuntimeBehavior) {
|
||||
// This object has a SaveConfiguration behavior. Check if the configuration is set to
|
||||
// persist it in one of the given profiles.
|
||||
if (
|
||||
(profileNames.includes('default') &&
|
||||
behavior.getDefaultProfilePersistence() === 'Persisted') ||
|
||||
profileNames.some((profileName) =>
|
||||
// TODO: avoid do it for every single object instance?
|
||||
behavior
|
||||
.getPersistedInProfiles()
|
||||
.split(',')
|
||||
.map((profileName) => profileName.trim())
|
||||
.includes(profileName)
|
||||
)
|
||||
) {
|
||||
shouldPersist = true;
|
||||
} else {
|
||||
shouldPersist = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldPersist) {
|
||||
const objectSyncData = object.getNetworkSyncData(
|
||||
getNetworkSyncOptions
|
||||
);
|
||||
gameSaveState.layoutNetworkSyncDatas[index].objectDatas[object.id] =
|
||||
objectSyncData;
|
||||
}
|
||||
}
|
||||
|
||||
// Collect scene data after the objects:
|
||||
const shouldPersistSceneData = checkIfIsPersistedInProfiles(
|
||||
options.profileNames,
|
||||
(runtimeSceneDataSaveConfiguration.get(runtimeGame) || {})[
|
||||
runtimeScene.getName()
|
||||
]
|
||||
);
|
||||
if (shouldPersistSceneData) {
|
||||
const sceneData = runtimeScene.getNetworkSyncData(
|
||||
getNetworkSyncOptions
|
||||
);
|
||||
if (sceneData) {
|
||||
gameSaveState.layoutNetworkSyncDatas[index].sceneData = sceneData;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return gameSaveState;
|
||||
};
|
||||
|
||||
export const createGameSaveStateInVariable = async function (
|
||||
runtimeScene: RuntimeScene,
|
||||
variable: gdjs.Variable,
|
||||
commaSeparatedProfileNames: string
|
||||
) {
|
||||
try {
|
||||
const gameSaveState = createGameSaveState(runtimeScene.getGame(), {
|
||||
profileNames: parseCommaSeparatedProfileNamesOrDefault(
|
||||
commaSeparatedProfileNames
|
||||
),
|
||||
});
|
||||
variable.fromJSObject(gameSaveState);
|
||||
markSaveJustSucceeded(runtimeScene);
|
||||
} catch (error) {
|
||||
logger.error('Error saving to variable:', error);
|
||||
markSaveJustFailed(runtimeScene);
|
||||
}
|
||||
};
|
||||
|
||||
export const createGameSaveStateInStorage = async function (
|
||||
runtimeScene: RuntimeScene,
|
||||
storageKey: string,
|
||||
commaSeparatedProfileNames: string
|
||||
) {
|
||||
try {
|
||||
const gameSaveState = createGameSaveState(runtimeScene.getGame(), {
|
||||
profileNames: parseCommaSeparatedProfileNamesOrDefault(
|
||||
commaSeparatedProfileNames
|
||||
),
|
||||
});
|
||||
await gdjs.indexedDb.saveToIndexedDB(
|
||||
getIndexedDbDatabaseName(),
|
||||
getIndexedDbObjectStore(),
|
||||
getIndexedDbStorageKey(storageKey),
|
||||
gameSaveState
|
||||
);
|
||||
markSaveJustSucceeded(runtimeScene);
|
||||
} catch (error) {
|
||||
logger.error('Error saving to IndexedDB:', error);
|
||||
markSaveJustFailed(runtimeScene);
|
||||
}
|
||||
};
|
||||
|
||||
const checkAndRestoreGameSaveStateAtEndOfFrame = function (
|
||||
runtimeScene: RuntimeScene
|
||||
) {
|
||||
const runtimeGame = runtimeScene.getGame();
|
||||
|
||||
if (!restoreRequestOptions) return;
|
||||
const { fromVariable, fromStorageName, profileNames, clearSceneStack } =
|
||||
restoreRequestOptions;
|
||||
|
||||
// Reset it so we don't load it twice.
|
||||
restoreRequestOptions = null;
|
||||
|
||||
if (fromVariable) {
|
||||
const saveState = fromVariable.toJSObject();
|
||||
|
||||
try {
|
||||
restoreGameSaveState(runtimeGame, saveState, {
|
||||
profileNames,
|
||||
clearSceneStack,
|
||||
});
|
||||
markLoadJustSucceeded(runtimeScene);
|
||||
} catch (error) {
|
||||
logger.error('Error loading from variable:', error);
|
||||
markLoadJustFailed(runtimeScene);
|
||||
}
|
||||
} else if (fromStorageName) {
|
||||
gdjs.indexedDb
|
||||
.loadFromIndexedDB(
|
||||
getIndexedDbDatabaseName(),
|
||||
getIndexedDbObjectStore(),
|
||||
getIndexedDbStorageKey(fromStorageName)
|
||||
)
|
||||
.then((jsonData) => {
|
||||
const saveState = jsonData as GameSaveState;
|
||||
restoreGameSaveState(runtimeGame, saveState, {
|
||||
profileNames,
|
||||
clearSceneStack,
|
||||
});
|
||||
markLoadJustSucceeded(runtimeScene);
|
||||
})
|
||||
.catch((error) => {
|
||||
logger.error('Error loading from IndexedDB:', error);
|
||||
markLoadJustFailed(runtimeScene);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const getInstanceFromNetworkId = ({
|
||||
runtimeScene,
|
||||
objectName,
|
||||
networkId,
|
||||
}: {
|
||||
runtimeScene: gdjs.RuntimeScene;
|
||||
objectName: string;
|
||||
networkId: string;
|
||||
}): gdjs.RuntimeObject | null => {
|
||||
const instances = runtimeScene.getInstancesOf(objectName);
|
||||
if (!instances) {
|
||||
// object does not exist in the scene, cannot find the instance.
|
||||
return null;
|
||||
}
|
||||
let instance =
|
||||
instances.find((instance) => instance.networkId === networkId) || null;
|
||||
|
||||
// Check if there is already an instance with the given network ID.
|
||||
if (instance) {
|
||||
debugLogger.info(
|
||||
`Found instance ${networkId}, will use it for restoring.`
|
||||
);
|
||||
return instance;
|
||||
}
|
||||
|
||||
// Instance not found - it must have been deleted. Create it now.
|
||||
debugLogger.info(
|
||||
`Instance ${networkId} not found, creating instance ${objectName}.`
|
||||
);
|
||||
const newInstance = runtimeScene.createObject(objectName);
|
||||
if (!newInstance) {
|
||||
// Object does not exist in the scene, cannot create the instance.
|
||||
return null;
|
||||
}
|
||||
|
||||
newInstance.networkId = networkId;
|
||||
return newInstance;
|
||||
};
|
||||
|
||||
/**
|
||||
* Restore the game using the given Save State.
|
||||
*
|
||||
* `options.profileNames` is the list of profiles to restore: only objects, variables etc... tagged with at least
|
||||
* one of these profiles will be restored (or recreated if they don't exist, or deleted if not in the save state).
|
||||
* Others will be left untouched.
|
||||
*
|
||||
* If `options.clearSceneStack` is true, all the scenes will be unloaded and re-created
|
||||
* (meaning all instances will be re-created, variables will go back to their initial values, etc...).
|
||||
* Otherwise, the existing scenes will be updated (or unloaded or created if the save state has different scenes).
|
||||
*/
|
||||
export const restoreGameSaveState = (
|
||||
runtimeGame: RuntimeGame,
|
||||
saveState: GameSaveState,
|
||||
options: {
|
||||
profileNames: string[];
|
||||
clearSceneStack: boolean;
|
||||
}
|
||||
): void => {
|
||||
const getObjectNamesToRestoreForRuntimeScene = (
|
||||
runtimeScene: RuntimeScene
|
||||
): Set<string> => {
|
||||
const allObjectData = [];
|
||||
runtimeScene._objects.values(allObjectData);
|
||||
return getObjectNamesIncludedInProfiles(
|
||||
allObjectData,
|
||||
options.profileNames
|
||||
);
|
||||
};
|
||||
|
||||
const updateFromNetworkSyncDataOptions: UpdateFromNetworkSyncDataOptions =
|
||||
{
|
||||
clearSceneStack:
|
||||
options.clearSceneStack === undefined
|
||||
? true
|
||||
: options.clearSceneStack,
|
||||
getExcludedObjectNames: getObjectNamesToRestoreForRuntimeScene,
|
||||
preventSoundsStoppingOnStartup: true,
|
||||
clearInputs: true,
|
||||
keepControl: true,
|
||||
ignoreVariableOwnership: true,
|
||||
shouldExcludeVariableFromUpdate: makeIsVariableExcludedFromSaveState(
|
||||
options.profileNames
|
||||
),
|
||||
};
|
||||
|
||||
// First update the game, which will update the variables,
|
||||
// and set the scene stack to update when ready.
|
||||
if (saveState.gameNetworkSyncData) {
|
||||
const shouldRestoreGameData = checkIfIsPersistedInProfiles(
|
||||
options.profileNames,
|
||||
runtimeGameDataSaveConfiguration.get(runtimeGame)
|
||||
);
|
||||
|
||||
runtimeGame.updateFromNetworkSyncData(
|
||||
shouldRestoreGameData
|
||||
? saveState.gameNetworkSyncData
|
||||
: {
|
||||
// Disable game data restoration if asked to, but
|
||||
// still always keep `ss` (scene stack) restoration as it's always needed.
|
||||
ss: saveState.gameNetworkSyncData.ss,
|
||||
},
|
||||
updateFromNetworkSyncDataOptions
|
||||
);
|
||||
}
|
||||
|
||||
// Apply the scene stack updates, as we are at the end of a frame,
|
||||
// we can safely do it.
|
||||
const sceneStack = runtimeGame.getSceneStack();
|
||||
sceneStack.applyUpdateFromNetworkSyncDataIfAny(
|
||||
updateFromNetworkSyncDataOptions
|
||||
);
|
||||
|
||||
// Then get all scenes, which we assume will be the expected ones
|
||||
// after the load has been done, so we can update them,
|
||||
// and create their objects.
|
||||
const runtimeScenes = sceneStack.getAllScenes();
|
||||
runtimeScenes.forEach((runtimeScene, index) => {
|
||||
const layoutSyncData = saveState.layoutNetworkSyncDatas[index];
|
||||
if (!layoutSyncData) return;
|
||||
|
||||
// List names of objects that must be restored
|
||||
// (and only them - instances of others will be left alone).
|
||||
const objectNamesToRestore =
|
||||
getObjectNamesToRestoreForRuntimeScene(runtimeScene);
|
||||
|
||||
// Create objects first, so they are available for the scene update,
|
||||
// especially so that they have a networkId defined.
|
||||
const allLoadedNetworkIds = new Set<string>();
|
||||
const objectDatas = layoutSyncData.objectDatas;
|
||||
for (const id in objectDatas) {
|
||||
const objectNetworkSyncData = objectDatas[id];
|
||||
const objectName = objectNetworkSyncData.n;
|
||||
if (!objectName) {
|
||||
logger.warn('Tried to recreate an object without a name.');
|
||||
continue;
|
||||
}
|
||||
if (!objectNamesToRestore.has(objectName)) {
|
||||
// Object is in the save state, but not in the profiles to restore, don't restore it.
|
||||
continue;
|
||||
}
|
||||
|
||||
// Object is both in the save state and in the profiles to restore, restore it.
|
||||
// Either find the existing instance with the same networkId, or create a new one.
|
||||
const networkId = objectNetworkSyncData.networkId || '';
|
||||
allLoadedNetworkIds.add(networkId);
|
||||
|
||||
const object = getInstanceFromNetworkId({
|
||||
runtimeScene,
|
||||
objectName: objectName,
|
||||
networkId,
|
||||
});
|
||||
if (object) {
|
||||
object.updateFromNetworkSyncData(
|
||||
objectNetworkSyncData,
|
||||
updateFromNetworkSyncDataOptions
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Clean instances of objects that are not in the profiles to restore but not in the save state
|
||||
// (i.e: those who don't have a networkId, or it's not in the save state: they must not exist).
|
||||
for (const objectName of objectNamesToRestore) {
|
||||
// /!\ Clone the instances to avoid it being modified while iterating through them.
|
||||
const objects = [...runtimeScene.getInstancesOf(objectName)];
|
||||
for (const object of objects) {
|
||||
// This is an object instance that is part of the object that are being restored,
|
||||
// but it has not network id (created after the save state was created) or the network
|
||||
// id is not in the save state: it's not part of the save state and must be deleted.
|
||||
if (
|
||||
!object.networkId ||
|
||||
!allLoadedNetworkIds.has(object.networkId)
|
||||
) {
|
||||
object.deleteFromScene();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update the rest of the scene last.
|
||||
if (
|
||||
checkIfIsPersistedInProfiles(
|
||||
options.profileNames,
|
||||
(runtimeSceneDataSaveConfiguration.get(runtimeGame) || {})[
|
||||
runtimeScene.getName()
|
||||
]
|
||||
)
|
||||
) {
|
||||
runtimeScene.updateFromNetworkSyncData(
|
||||
layoutSyncData.sceneData,
|
||||
updateFromNetworkSyncDataOptions
|
||||
);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const parseCommaSeparatedProfileNames = (
|
||||
commaSeparatedProfileNames: string
|
||||
): string[] | null => {
|
||||
if (!commaSeparatedProfileNames) return null;
|
||||
|
||||
return commaSeparatedProfileNames
|
||||
.split(',')
|
||||
.map((profileName) => profileName.trim());
|
||||
};
|
||||
|
||||
const parseCommaSeparatedProfileNamesOrDefault = (
|
||||
commaSeparatedProfileNames: string
|
||||
): string[] => {
|
||||
return (
|
||||
parseCommaSeparatedProfileNames(commaSeparatedProfileNames) || [
|
||||
'default',
|
||||
]
|
||||
);
|
||||
};
|
||||
|
||||
export const restoreGameSaveStateFromVariable = async function (
|
||||
_: gdjs.RuntimeScene,
|
||||
variable: gdjs.Variable,
|
||||
commaSeparatedProfileNames: string,
|
||||
clearSceneStack: boolean
|
||||
) {
|
||||
// The information is saved, so that the restore can be done
|
||||
// at the end of the frame,
|
||||
// and avoid possible conflicts with running events.
|
||||
restoreRequestOptions = {
|
||||
fromVariable: variable,
|
||||
profileNames: parseCommaSeparatedProfileNamesOrDefault(
|
||||
commaSeparatedProfileNames
|
||||
),
|
||||
clearSceneStack,
|
||||
};
|
||||
};
|
||||
|
||||
export const restoreGameSaveStateFromStorage = async function (
|
||||
_: gdjs.RuntimeScene,
|
||||
storageName: string,
|
||||
commaSeparatedProfileNames: string,
|
||||
clearSceneStack: boolean
|
||||
) {
|
||||
// The information is saved, so that the restore can be done
|
||||
// at the end of the frame,
|
||||
// and avoid possible conflicts with running events.
|
||||
restoreRequestOptions = {
|
||||
fromStorageName: storageName,
|
||||
profileNames: parseCommaSeparatedProfileNamesOrDefault(
|
||||
commaSeparatedProfileNames
|
||||
),
|
||||
clearSceneStack,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Compute, by looking at the "static" object data (i.e: in the Project Data),
|
||||
* the name of objects which must be restored, based on the given profiles.
|
||||
*/
|
||||
const getObjectNamesIncludedInProfiles = (
|
||||
allObjectData: ObjectData[],
|
||||
profileNames: string[]
|
||||
): Set<string> => {
|
||||
const objectNames = new Set<string>();
|
||||
for (const objectData of allObjectData) {
|
||||
// By default, an object which has no SaveConfiguration behavior is like
|
||||
// it has the default profile persistence set to "Persisted".
|
||||
let includedInProfiles = profileNames.includes('default');
|
||||
|
||||
for (const behaviorData of objectData.behaviors) {
|
||||
if (behaviorData.type !== 'SaveState::SaveConfiguration') continue;
|
||||
|
||||
const defaultProfilePersistence =
|
||||
behaviorData.defaultProfilePersistence === 'Persisted'
|
||||
? 'Persisted'
|
||||
: 'DoNotSave';
|
||||
const persistedInProfiles =
|
||||
typeof behaviorData.persistedInProfiles === 'string'
|
||||
? behaviorData.persistedInProfiles
|
||||
.split(',')
|
||||
.map((profileName: string) => profileName.trim())
|
||||
: [];
|
||||
|
||||
// This object has a SaveConfiguration behavior. Check if the configuration is set to
|
||||
// persist it in one of the given profiles.
|
||||
includedInProfiles = false;
|
||||
|
||||
if (
|
||||
(profileNames.includes('default') &&
|
||||
defaultProfilePersistence === 'Persisted') ||
|
||||
profileNames.some((profileName) =>
|
||||
persistedInProfiles.includes(profileName)
|
||||
)
|
||||
) {
|
||||
// This object must be persisted in one of the given profile.
|
||||
includedInProfiles = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (includedInProfiles) {
|
||||
objectNames.add(objectData.name);
|
||||
}
|
||||
}
|
||||
|
||||
return objectNames;
|
||||
};
|
||||
}
|
||||
}
|
1224
Extensions/SaveState/tests/SaveState.spec.js
Normal file
1224
Extensions/SaveState/tests/SaveState.spec.js
Normal file
File diff suppressed because it is too large
Load Diff
@@ -203,13 +203,17 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
unloadResource(resourceData: ResourceData): void {
|
||||
const loadedSpineAtlas = this._loadedSpineAtlases.get(resourceData);
|
||||
const loadedSpineAtlas = this._loadedSpineAtlases.getFromName(
|
||||
resourceData.name
|
||||
);
|
||||
if (loadedSpineAtlas) {
|
||||
loadedSpineAtlas.dispose();
|
||||
this._loadedSpineAtlases.delete(resourceData);
|
||||
}
|
||||
|
||||
const loadingSpineAtlas = this._loadingSpineAtlases.get(resourceData);
|
||||
const loadingSpineAtlas = this._loadingSpineAtlases.getFromName(
|
||||
resourceData.name
|
||||
);
|
||||
if (loadingSpineAtlas) {
|
||||
loadingSpineAtlas.then((atl) => atl.dispose());
|
||||
this._loadingSpineAtlases.delete(resourceData);
|
||||
|
@@ -53,6 +53,8 @@ namespace gdjs {
|
||||
|
||||
readonly spineResourceName: string;
|
||||
|
||||
static isHitBoxesUpdateDisabled = false;
|
||||
|
||||
/**
|
||||
* @param instanceContainer The container the object belongs to.
|
||||
* @param objectData The object data used to initialize the object
|
||||
@@ -74,6 +76,10 @@ namespace gdjs {
|
||||
this.setAnimationIndex(0);
|
||||
this._renderer.updateAnimation(0);
|
||||
|
||||
if (SpineRuntimeObject.isHitBoxesUpdateDisabled) {
|
||||
this.hitBoxes.length = 0;
|
||||
}
|
||||
|
||||
// *ALWAYS* call `this.onCreated()` at the very end of your object constructor.
|
||||
this.onCreated();
|
||||
}
|
||||
@@ -111,9 +117,11 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(): SpineNetworkSyncData {
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): SpineNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
opa: this._opacity,
|
||||
scaX: this.getScaleX(),
|
||||
scaY: this.getScaleY(),
|
||||
@@ -127,8 +135,11 @@ namespace gdjs {
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(syncData: SpineNetworkSyncData): void {
|
||||
super.updateFromNetworkSyncData(syncData);
|
||||
updateFromNetworkSyncData(
|
||||
syncData: SpineNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(syncData, options);
|
||||
|
||||
if (syncData.opa !== undefined && syncData.opa !== this._opacity) {
|
||||
this.setOpacity(syncData.opa);
|
||||
@@ -183,6 +194,14 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
updateHitBoxes(): void {
|
||||
if (SpineRuntimeObject.isHitBoxesUpdateDisabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
super.updateHitBoxes();
|
||||
}
|
||||
|
||||
extraInitializationFromInitialInstance(
|
||||
initialInstanceData: InstanceData
|
||||
): void {
|
||||
@@ -199,15 +218,13 @@ namespace gdjs {
|
||||
this.setSize(initialInstanceData.width, initialInstanceData.height);
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
if (initialInstanceData.opacity !== undefined) {
|
||||
this.setOpacity(initialInstanceData.opacity);
|
||||
}
|
||||
if (initialInstanceData.flippedX) {
|
||||
this.flipX(initialInstanceData.flippedX);
|
||||
}
|
||||
if (initialInstanceData.flippedY) {
|
||||
this.flipY(initialInstanceData.flippedY);
|
||||
}
|
||||
this.setOpacity(
|
||||
initialInstanceData.opacity === undefined
|
||||
? 255
|
||||
: initialInstanceData.opacity
|
||||
);
|
||||
this.flipX(!!initialInstanceData.flippedX);
|
||||
this.flipY(!!initialInstanceData.flippedY);
|
||||
}
|
||||
|
||||
getDrawableX(): number {
|
||||
|
@@ -61,6 +61,19 @@ describe('gdjs.TextInputRuntimeObject (using a PixiJS RuntimeGame with DOM eleme
|
||||
instances: [],
|
||||
variables: [],
|
||||
usedResources: [],
|
||||
uiSettings: {
|
||||
grid: false,
|
||||
gridType: 'rectangular',
|
||||
gridWidth: 10,
|
||||
gridHeight: 10,
|
||||
gridDepth: 10,
|
||||
gridOffsetX: 0,
|
||||
gridOffsetY: 0,
|
||||
gridOffsetZ: 0,
|
||||
gridColor: 0,
|
||||
gridAlpha: 1,
|
||||
snap: false,
|
||||
},
|
||||
},
|
||||
usedExtensionsWithVariablesData: [],
|
||||
});
|
||||
|
@@ -141,7 +141,9 @@ namespace gdjs {
|
||||
);
|
||||
this._borderOpacity = objectData.content.borderOpacity;
|
||||
this._borderWidth = objectData.content.borderWidth;
|
||||
this._disabled = objectData.content.disabled;
|
||||
this._disabled = instanceContainer.getGame().isInGameEdition()
|
||||
? true
|
||||
: objectData.content.disabled;
|
||||
this._readOnly = objectData.content.readOnly;
|
||||
this._spellCheck =
|
||||
objectData.content.spellCheck !== undefined
|
||||
@@ -267,9 +269,11 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(): TextInputNetworkSyncData {
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): TextInputNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
opa: this.getOpacity(),
|
||||
txt: this.getText(),
|
||||
frn: this.getFontResourceName(),
|
||||
@@ -288,8 +292,11 @@ namespace gdjs {
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(syncData: TextInputNetworkSyncData): void {
|
||||
super.updateFromNetworkSyncData(syncData);
|
||||
updateFromNetworkSyncData(
|
||||
syncData: TextInputNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(syncData, options);
|
||||
|
||||
if (syncData.opa !== undefined) this.setOpacity(syncData.opa);
|
||||
if (syncData.txt !== undefined) this.setText(syncData.txt);
|
||||
@@ -329,9 +336,11 @@ namespace gdjs {
|
||||
this.setHeight(initialInstanceData.height);
|
||||
this._renderer.updatePadding();
|
||||
}
|
||||
if (initialInstanceData.opacity !== undefined) {
|
||||
this.setOpacity(initialInstanceData.opacity);
|
||||
}
|
||||
this.setOpacity(
|
||||
initialInstanceData.opacity === undefined
|
||||
? 255
|
||||
: initialInstanceData.opacity
|
||||
);
|
||||
}
|
||||
|
||||
onScenePaused(runtimeScene: gdjs.RuntimeScene): void {
|
||||
@@ -561,6 +570,9 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
setDisabled(value: boolean) {
|
||||
if (this.getInstanceContainer().getGame().isInGameEdition()) {
|
||||
return;
|
||||
}
|
||||
this._disabled = value;
|
||||
this._renderer.updateDisabled();
|
||||
}
|
||||
|
@@ -52,6 +52,7 @@ namespace gdjs {
|
||||
c: number[];
|
||||
scale: number;
|
||||
ta: string;
|
||||
vta: string;
|
||||
wrap: boolean;
|
||||
wrapw: float;
|
||||
oena: boolean;
|
||||
@@ -179,9 +180,6 @@ namespace gdjs {
|
||||
if (oldContent.text !== newContent.text) {
|
||||
this.setText(newContent.text);
|
||||
}
|
||||
if (oldContent.underlined !== newContent.underlined) {
|
||||
return false;
|
||||
}
|
||||
if (oldContent.textAlignment !== newContent.textAlignment) {
|
||||
this.setTextAlignment(newContent.textAlignment);
|
||||
}
|
||||
@@ -220,12 +218,18 @@ namespace gdjs {
|
||||
if ((oldContent.lineHeight || 0) !== (newContent.lineHeight || 0)) {
|
||||
this.setLineHeight(newContent.lineHeight || 0);
|
||||
}
|
||||
if (oldContent.underlined !== newContent.underlined) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
override getNetworkSyncData(): TextObjectNetworkSyncData {
|
||||
override getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): TextObjectNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
str: this._str,
|
||||
o: this.opacity,
|
||||
cs: this._characterSize,
|
||||
@@ -236,6 +240,7 @@ namespace gdjs {
|
||||
c: this._color,
|
||||
scale: this.getScale(),
|
||||
ta: this._textAlign,
|
||||
vta: this._verticalTextAlignment,
|
||||
wrap: this._wrapping,
|
||||
wrapw: this._wrappingWidth,
|
||||
oena: this._isOutlineEnabled,
|
||||
@@ -253,9 +258,10 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
override updateFromNetworkSyncData(
|
||||
networkSyncData: TextObjectNetworkSyncData
|
||||
networkSyncData: TextObjectNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
if (networkSyncData.str !== undefined) {
|
||||
this.setText(networkSyncData.str);
|
||||
}
|
||||
@@ -286,8 +292,8 @@ namespace gdjs {
|
||||
if (networkSyncData.ta !== undefined) {
|
||||
this.setTextAlignment(networkSyncData.ta);
|
||||
}
|
||||
if (networkSyncData.ta !== undefined) {
|
||||
this.setVerticalTextAlignment(networkSyncData.ta);
|
||||
if (networkSyncData.vta !== undefined) {
|
||||
this.setVerticalTextAlignment(networkSyncData.vta);
|
||||
}
|
||||
if (networkSyncData.wrap !== undefined) {
|
||||
this.setWrapping(networkSyncData.wrap);
|
||||
@@ -334,7 +340,9 @@ namespace gdjs {
|
||||
return this._renderer.getRendererObject();
|
||||
}
|
||||
|
||||
override update(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
override updatePreRender(
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): void {
|
||||
this._renderer.ensureUpToDate();
|
||||
}
|
||||
|
||||
@@ -352,9 +360,11 @@ namespace gdjs {
|
||||
} else {
|
||||
this.setWrapping(false);
|
||||
}
|
||||
if (initialInstanceData.opacity !== undefined) {
|
||||
this.setOpacity(initialInstanceData.opacity);
|
||||
}
|
||||
this.setOpacity(
|
||||
initialInstanceData.opacity === undefined
|
||||
? 255
|
||||
: initialInstanceData.opacity
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@@ -9,7 +9,7 @@ import {
|
||||
* A tile map model.
|
||||
*
|
||||
* Tile map files are parsed into this model by {@link TiledTileMapLoader} or {@link LDtkTileMapLoader}.
|
||||
* This model is used for rending ({@link TileMapRuntimeObjectPixiRenderer})
|
||||
* This model is used for rendering ({@link TileMapRuntimeObjectPixiRenderer})
|
||||
* and hitboxes handling ({@link TransformedCollisionTileMap}).
|
||||
* This allows to support new file format with only a new parser.
|
||||
*/
|
||||
@@ -71,7 +71,7 @@ export declare class EditableTileMap {
|
||||
tileSetRowCount: number;
|
||||
}
|
||||
): EditableTileMap;
|
||||
toJSObject(): Object;
|
||||
toJSObject(): EditableTileMapAsJsObject;
|
||||
/**
|
||||
* @returns The tile map width in pixels.
|
||||
*/
|
||||
@@ -205,7 +205,7 @@ declare abstract class AbstractEditableLayer {
|
||||
*/
|
||||
constructor(tileMap: EditableTileMap, id: integer);
|
||||
setVisible(visible: boolean): void;
|
||||
toJSObject(): Object;
|
||||
toJSObject(): EditableTileMapLayerAsJsObject;
|
||||
/**
|
||||
* @returns true if the layer is visible.
|
||||
*/
|
||||
@@ -284,7 +284,7 @@ export declare class EditableTileMapLayer extends AbstractEditableLayer {
|
||||
tileMap: EditableTileMap,
|
||||
isTileIdValid: (tileId: number) => boolean
|
||||
): EditableTileMapLayer;
|
||||
toJSObject(): Object;
|
||||
toJSObject(): EditableTileMapLayerAsJsObject;
|
||||
/**
|
||||
* The opacity (between 0-1) of the layer
|
||||
*/
|
||||
|
@@ -2,7 +2,6 @@
|
||||
namespace gdjs {
|
||||
export type SimpleTileMapObjectDataType = {
|
||||
content: {
|
||||
opacity: number;
|
||||
atlasImage: string;
|
||||
rowCount: number;
|
||||
columnCount: number;
|
||||
@@ -16,8 +15,7 @@ namespace gdjs {
|
||||
|
||||
export type SimpleTileMapNetworkSyncDataType = {
|
||||
op: number;
|
||||
ai: string;
|
||||
// TODO: Support tilemap synchronization. Find an efficient way to send tiles changes.
|
||||
tm?: TileMapHelper.EditableTileMapAsJsObject;
|
||||
};
|
||||
|
||||
export type SimpleTileMapNetworkSyncData = ObjectNetworkSyncData &
|
||||
@@ -38,6 +36,7 @@ namespace gdjs {
|
||||
_opacity: float = 255;
|
||||
_atlasImage: string;
|
||||
_tileMapManager: gdjs.TileMap.TileMapRuntimeManager;
|
||||
_tileMap: TileMapHelper.EditableTileMap | null = null;
|
||||
_renderer: gdjs.TileMapRuntimeObjectPixiRenderer;
|
||||
readonly _rowCount: number;
|
||||
readonly _columnCount: number;
|
||||
@@ -62,7 +61,6 @@ namespace gdjs {
|
||||
objectData: SimpleTileMapObjectDataType
|
||||
) {
|
||||
super(instanceContainer, objectData);
|
||||
this._opacity = objectData.content.opacity;
|
||||
this._atlasImage = objectData.content.atlasImage;
|
||||
this._rowCount = objectData.content.rowCount;
|
||||
this._columnCount = objectData.content.columnCount;
|
||||
@@ -87,16 +85,19 @@ namespace gdjs {
|
||||
instanceContainer
|
||||
);
|
||||
|
||||
this._loadInitialTileMap((tileMap: TileMapHelper.EditableTileMap) => {
|
||||
this._renderer.updatePosition();
|
||||
this._loadTileMap(
|
||||
this._initialTileMapAsJsObject,
|
||||
(tileMap: TileMapHelper.EditableTileMap) => {
|
||||
this._renderer.updatePosition();
|
||||
|
||||
this._collisionTileMap = new gdjs.TileMap.TransformedCollisionTileMap(
|
||||
tileMap,
|
||||
this._hitBoxTag
|
||||
);
|
||||
this._collisionTileMap = new gdjs.TileMap.TransformedCollisionTileMap(
|
||||
tileMap,
|
||||
this._hitBoxTag
|
||||
);
|
||||
|
||||
this.updateTransformation();
|
||||
});
|
||||
this.updateTransformation();
|
||||
}
|
||||
);
|
||||
|
||||
// *ALWAYS* call `this.onCreated()` at the very end of your object constructor.
|
||||
this.onCreated();
|
||||
@@ -139,8 +140,8 @@ namespace gdjs {
|
||||
);
|
||||
if (!shouldContinue) return;
|
||||
if (this._collisionTileMap) {
|
||||
const tileMap = this._renderer.getTileMap();
|
||||
if (tileMap) this._collisionTileMap.updateFromTileMap(tileMap);
|
||||
if (this._tileMap)
|
||||
this._collisionTileMap.updateFromTileMap(this._tileMap);
|
||||
}
|
||||
this._isTileMapDirty = false;
|
||||
}
|
||||
@@ -150,9 +151,6 @@ namespace gdjs {
|
||||
oldObjectData: SimpleTileMapObjectData,
|
||||
newObjectData: SimpleTileMapObjectData
|
||||
): boolean {
|
||||
if (oldObjectData.content.opacity !== newObjectData.content.opacity) {
|
||||
this.setOpacity(newObjectData.content.opacity);
|
||||
}
|
||||
if (
|
||||
oldObjectData.content.atlasImage !== newObjectData.content.atlasImage
|
||||
) {
|
||||
@@ -163,27 +161,58 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(): SimpleTileMapNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): SimpleTileMapNetworkSyncData {
|
||||
const syncData: SimpleTileMapNetworkSyncData = {
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
op: this._opacity,
|
||||
ai: this._atlasImage,
|
||||
};
|
||||
if (this._tileMap && syncOptions.syncFullTileMaps) {
|
||||
const currentTileMapAsJsObject = this._tileMap.toJSObject();
|
||||
syncData.tm = currentTileMapAsJsObject;
|
||||
}
|
||||
|
||||
return syncData;
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: SimpleTileMapNetworkSyncData
|
||||
networkSyncData: SimpleTileMapNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
|
||||
if (
|
||||
networkSyncData.op !== undefined &&
|
||||
networkSyncData.op !== this._opacity
|
||||
) {
|
||||
this.setOpacity(networkSyncData.op);
|
||||
}
|
||||
if (networkSyncData.ai !== undefined) {
|
||||
// TODO: support changing the atlas texture
|
||||
if (networkSyncData.tm !== undefined) {
|
||||
this._loadTileMap(
|
||||
networkSyncData.tm,
|
||||
(tileMap: TileMapHelper.EditableTileMap) => {
|
||||
if (networkSyncData.w !== undefined) {
|
||||
this.setWidth(networkSyncData.w);
|
||||
}
|
||||
if (networkSyncData.h !== undefined) {
|
||||
this.setHeight(networkSyncData.h);
|
||||
}
|
||||
if (networkSyncData.op !== undefined) {
|
||||
this.setOpacity(networkSyncData.op);
|
||||
}
|
||||
|
||||
// 4. Update position (calculations based on renderer's dimensions).
|
||||
this._renderer.updatePosition();
|
||||
|
||||
if (this._collisionTileMap) {
|
||||
// If collision tile map is already defined, only update it.
|
||||
this._collisionTileMap.updateFromTileMap(tileMap);
|
||||
} else {
|
||||
this._collisionTileMap =
|
||||
new gdjs.TileMap.TransformedCollisionTileMap(
|
||||
tileMap,
|
||||
this._hitBoxTag
|
||||
);
|
||||
}
|
||||
|
||||
this.updateTransformation();
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,39 +228,45 @@ namespace gdjs {
|
||||
|
||||
// 2. Update the renderer so that it updates the tilemap object
|
||||
// (used for width and position calculations).
|
||||
this._loadInitialTileMap((tileMap: TileMapHelper.EditableTileMap) => {
|
||||
// 3. Set custom dimensions & opacity if applicable.
|
||||
if (initialInstanceData.customSize) {
|
||||
this.setWidth(initialInstanceData.width);
|
||||
this.setHeight(initialInstanceData.height);
|
||||
}
|
||||
if (initialInstanceData.opacity !== undefined) {
|
||||
this.setOpacity(initialInstanceData.opacity);
|
||||
}
|
||||
|
||||
// 4. Update position (calculations based on renderer's dimensions).
|
||||
this._renderer.updatePosition();
|
||||
|
||||
if (this._collisionTileMap) {
|
||||
// If collision tile map is already defined, there's a good chance it means
|
||||
// extraInitializationFromInitialInstance is called when hot reloading the
|
||||
// scene so the collision is tile map is updated instead of being re-created.
|
||||
this._collisionTileMap.updateFromTileMap(tileMap);
|
||||
} else {
|
||||
this._collisionTileMap = new gdjs.TileMap.TransformedCollisionTileMap(
|
||||
tileMap,
|
||||
this._hitBoxTag
|
||||
this._loadTileMap(
|
||||
this._initialTileMapAsJsObject,
|
||||
(tileMap: TileMapHelper.EditableTileMap) => {
|
||||
// 3. Set custom dimensions & opacity if applicable.
|
||||
if (initialInstanceData.customSize) {
|
||||
this.setWidth(initialInstanceData.width);
|
||||
this.setHeight(initialInstanceData.height);
|
||||
}
|
||||
this.setOpacity(
|
||||
initialInstanceData.opacity === undefined
|
||||
? 255
|
||||
: initialInstanceData.opacity
|
||||
);
|
||||
}
|
||||
|
||||
this.updateTransformation();
|
||||
});
|
||||
// 4. Update position (calculations based on renderer's dimensions).
|
||||
this._renderer.updatePosition();
|
||||
|
||||
if (this._collisionTileMap) {
|
||||
// If collision tile map is already defined, there's a good chance it means
|
||||
// extraInitializationFromInitialInstance is called when hot reloading the
|
||||
// scene so the collision is tile map is updated instead of being re-created.
|
||||
this._collisionTileMap.updateFromTileMap(tileMap);
|
||||
} else {
|
||||
this._collisionTileMap =
|
||||
new gdjs.TileMap.TransformedCollisionTileMap(
|
||||
tileMap,
|
||||
this._hitBoxTag
|
||||
);
|
||||
}
|
||||
|
||||
this.updateTransformation();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private _loadInitialTileMap(
|
||||
private _loadTileMap(
|
||||
tileMapAsJsObject: TileMapHelper.EditableTileMapAsJsObject,
|
||||
tileMapLoadingCallback: (tileMap: TileMapHelper.EditableTileMap) => void
|
||||
): void {
|
||||
if (!this._initialTileMapAsJsObject) return;
|
||||
if (this._columnCount <= 0 || this._rowCount <= 0) {
|
||||
console.error(
|
||||
`Tilemap object ${this.name} is not configured properly.`
|
||||
@@ -240,7 +275,7 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
this._tileMapManager.getOrLoadSimpleTileMap(
|
||||
this._initialTileMapAsJsObject,
|
||||
tileMapAsJsObject,
|
||||
this.name,
|
||||
this._tileSize,
|
||||
this._columnCount,
|
||||
@@ -284,7 +319,8 @@ namespace gdjs {
|
||||
// getOrLoadTextureCache already log warns and errors.
|
||||
return;
|
||||
}
|
||||
this._renderer.updatePixiTileMap(tileMap, textureCache);
|
||||
this._tileMap = tileMap;
|
||||
this._renderer.refreshPixiTileMap(textureCache);
|
||||
tileMapLoadingCallback(tileMap);
|
||||
},
|
||||
(error) => {
|
||||
@@ -415,6 +451,14 @@ namespace gdjs {
|
||||
return this._renderer.getHeight();
|
||||
}
|
||||
|
||||
override getOriginalWidth(): float {
|
||||
return this.getTileMapWidth();
|
||||
}
|
||||
|
||||
override getOriginalHeight(): float {
|
||||
return this.getTileMapHeight();
|
||||
}
|
||||
|
||||
getScaleX(): float {
|
||||
return this._renderer.getScaleX();
|
||||
}
|
||||
@@ -640,7 +684,7 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
getTileAtGridCoordinates(columnIndex: integer, rowIndex: integer): integer {
|
||||
return this._renderer.getTileId(columnIndex, rowIndex, 0);
|
||||
return this.getTileId(columnIndex, rowIndex, 0);
|
||||
}
|
||||
|
||||
setTileAtPosition(tileId: number, x: float, y: float) {
|
||||
@@ -654,11 +698,10 @@ namespace gdjs {
|
||||
columnIndex: integer,
|
||||
rowIndex: integer
|
||||
) {
|
||||
const tileMap = this._renderer._tileMap;
|
||||
if (!tileMap) {
|
||||
if (!this._tileMap) {
|
||||
return;
|
||||
}
|
||||
const layer = tileMap.getTileLayer(this._layerIndex);
|
||||
const layer = this._tileMap.getTileLayer(this._layerIndex);
|
||||
if (!layer) {
|
||||
return;
|
||||
}
|
||||
@@ -670,8 +713,8 @@ namespace gdjs {
|
||||
|
||||
if (this._collisionTileMap) {
|
||||
const oldTileDefinition =
|
||||
oldTileId !== undefined && tileMap.getTileDefinition(oldTileId);
|
||||
const newTileDefinition = tileMap.getTileDefinition(tileId);
|
||||
oldTileId !== undefined && this._tileMap.getTileDefinition(oldTileId);
|
||||
const newTileDefinition = this._tileMap.getTileDefinition(tileId);
|
||||
const hadFullHitBox =
|
||||
!!oldTileDefinition &&
|
||||
oldTileDefinition.hasFullHitBox(this._hitBoxTag);
|
||||
@@ -707,7 +750,7 @@ namespace gdjs {
|
||||
rowIndex: integer,
|
||||
flip: boolean
|
||||
) {
|
||||
this._renderer.flipTileOnY(columnIndex, rowIndex, 0, flip);
|
||||
this.flipTileOnY(columnIndex, rowIndex, 0, flip);
|
||||
this._isTileMapDirty = true;
|
||||
// No need to invalidate hit boxes since at the moment, collision mask
|
||||
// cannot be configured on each tile.
|
||||
@@ -718,7 +761,7 @@ namespace gdjs {
|
||||
rowIndex: integer,
|
||||
flip: boolean
|
||||
) {
|
||||
this._renderer.flipTileOnX(columnIndex, rowIndex, 0, flip);
|
||||
this.flipTileOnX(columnIndex, rowIndex, 0, flip);
|
||||
this._isTileMapDirty = true;
|
||||
// No need to invalidate hit boxes since at the moment, collision mask
|
||||
// cannot be configured on each tile.
|
||||
@@ -728,22 +771,22 @@ namespace gdjs {
|
||||
const [columnIndex, rowIndex] =
|
||||
this.getGridCoordinatesFromSceneCoordinates(x, y);
|
||||
|
||||
return this._renderer.isTileFlippedOnX(columnIndex, rowIndex, 0);
|
||||
return this.isTileFlippedOnX(columnIndex, rowIndex, 0);
|
||||
}
|
||||
|
||||
isTileFlippedOnXAtGridCoordinates(columnIndex: integer, rowIndex: integer) {
|
||||
return this._renderer.isTileFlippedOnX(columnIndex, rowIndex, 0);
|
||||
return this.isTileFlippedOnX(columnIndex, rowIndex, 0);
|
||||
}
|
||||
|
||||
isTileFlippedOnYAtPosition(x: float, y: float) {
|
||||
const [columnIndex, rowIndex] =
|
||||
this.getGridCoordinatesFromSceneCoordinates(x, y);
|
||||
|
||||
return this._renderer.isTileFlippedOnY(columnIndex, rowIndex, 0);
|
||||
return this.isTileFlippedOnY(columnIndex, rowIndex, 0);
|
||||
}
|
||||
|
||||
isTileFlippedOnYAtGridCoordinates(columnIndex: integer, rowIndex: integer) {
|
||||
return this._renderer.isTileFlippedOnY(columnIndex, rowIndex, 0);
|
||||
return this.isTileFlippedOnY(columnIndex, rowIndex, 0);
|
||||
}
|
||||
|
||||
removeTileAtPosition(x: float, y: float) {
|
||||
@@ -753,11 +796,10 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
removeTileAtGridCoordinates(columnIndex: integer, rowIndex: integer) {
|
||||
const tileMap = this._renderer._tileMap;
|
||||
if (!tileMap) {
|
||||
if (!this._tileMap) {
|
||||
return;
|
||||
}
|
||||
const layer = tileMap.getTileLayer(this._layerIndex);
|
||||
const layer = this._tileMap.getTileLayer(this._layerIndex);
|
||||
if (!layer) {
|
||||
return;
|
||||
}
|
||||
@@ -779,24 +821,28 @@ namespace gdjs {
|
||||
|
||||
setGridRowCount(targetRowCount: integer) {
|
||||
if (targetRowCount <= 0) return;
|
||||
this._renderer.setGridRowCount(targetRowCount);
|
||||
if (!this._tileMap) return;
|
||||
this._tileMap.setDimensionY(targetRowCount);
|
||||
this._isTileMapDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
setGridColumnCount(targetColumnCount: integer) {
|
||||
if (targetColumnCount <= 0) return;
|
||||
this._renderer.setGridColumnCount(targetColumnCount);
|
||||
if (!this._tileMap) return;
|
||||
this._tileMap.setDimensionX(targetColumnCount);
|
||||
this._isTileMapDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
getGridRowCount(): integer {
|
||||
return this._renderer.getGridRowCount();
|
||||
if (!this._tileMap) return 0;
|
||||
return this._tileMap.getDimensionY();
|
||||
}
|
||||
|
||||
getGridColumnCount(): integer {
|
||||
return this._renderer.getGridColumnCount();
|
||||
if (!this._tileMap) return 0;
|
||||
return this._tileMap.getDimensionX();
|
||||
}
|
||||
|
||||
getTilesetColumnCount(): integer {
|
||||
@@ -806,6 +852,73 @@ namespace gdjs {
|
||||
getTilesetRowCount(): integer {
|
||||
return this._rowCount;
|
||||
}
|
||||
|
||||
getTileMap(): TileMapHelper.EditableTileMap | null {
|
||||
return this._tileMap;
|
||||
}
|
||||
|
||||
getTileMapWidth() {
|
||||
const tileMap = this._tileMap;
|
||||
return tileMap ? tileMap.getWidth() : 20;
|
||||
}
|
||||
|
||||
getTileMapHeight() {
|
||||
const tileMap = this._tileMap;
|
||||
return tileMap ? tileMap.getHeight() : 20;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param x The layer column.
|
||||
* @param y The layer row.
|
||||
* @param layerIndex The layer index.
|
||||
* @returns The tile's id.
|
||||
*/
|
||||
getTileId(x: integer, y: integer, layerIndex: integer): integer {
|
||||
if (!this._tileMap) return -1;
|
||||
return this._tileMap.getTileId(x, y, layerIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param x The layer column.
|
||||
* @param y The layer row.
|
||||
* @param layerIndex The layer index.
|
||||
* @param flip true if the tile should be flipped.
|
||||
*/
|
||||
flipTileOnY(x: integer, y: integer, layerIndex: integer, flip: boolean) {
|
||||
if (!this._tileMap) return;
|
||||
this._tileMap.flipTileOnY(x, y, layerIndex, flip);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param x The layer column.
|
||||
* @param y The layer row.
|
||||
* @param layerIndex The layer index.
|
||||
* @param flip true if the tile should be flipped.
|
||||
*/
|
||||
flipTileOnX(x: integer, y: integer, layerIndex: integer, flip: boolean) {
|
||||
if (!this._tileMap) return;
|
||||
this._tileMap.flipTileOnX(x, y, layerIndex, flip);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param x The layer column.
|
||||
* @param y The layer row.
|
||||
* @param layerIndex The layer index.
|
||||
*/
|
||||
isTileFlippedOnX(x: integer, y: integer, layerIndex: integer): boolean {
|
||||
if (!this._tileMap) return false;
|
||||
return this._tileMap.isTileFlippedOnX(x, y, layerIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param x The layer column.
|
||||
* @param y The layer row.
|
||||
* @param layerIndex The layer index.
|
||||
*/
|
||||
isTileFlippedOnY(x: integer, y: integer, layerIndex: integer): boolean {
|
||||
if (!this._tileMap) return false;
|
||||
return this._tileMap.isTileFlippedOnY(x, y, layerIndex);
|
||||
}
|
||||
}
|
||||
gdjs.registerObject(
|
||||
'TileMap::SimpleTileMap',
|
||||
|
@@ -57,6 +57,19 @@ describe('gdjs.TileMapCollisionMaskRuntimeObject', function () {
|
||||
objects: [],
|
||||
instances: [],
|
||||
usedResources: [],
|
||||
uiSettings: {
|
||||
grid: false,
|
||||
gridType: 'rectangular',
|
||||
gridWidth: 10,
|
||||
gridHeight: 10,
|
||||
gridDepth: 10,
|
||||
gridOffsetX: 0,
|
||||
gridOffsetY: 0,
|
||||
gridOffsetZ: 0,
|
||||
gridColor: 0,
|
||||
gridAlpha: 1,
|
||||
snap: false,
|
||||
},
|
||||
},
|
||||
usedExtensionsWithVariablesData: [],
|
||||
});
|
||||
|
@@ -189,9 +189,11 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(): TilemapCollisionMaskNetworkSyncData {
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): TilemapCollisionMaskNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
tmjf: this.getTilemapJsonFile(),
|
||||
tsjf: this.getTilesetJsonFile(),
|
||||
dm: this.getDebugMode(),
|
||||
@@ -204,9 +206,10 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: TilemapCollisionMaskNetworkSyncData
|
||||
networkSyncData: TilemapCollisionMaskNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
|
||||
if (networkSyncData.tmjf !== undefined) {
|
||||
this.setTilemapJsonFile(networkSyncData.tmjf);
|
||||
|
@@ -10,8 +10,6 @@ namespace gdjs {
|
||||
private _object:
|
||||
| gdjs.TileMapRuntimeObject
|
||||
| gdjs.SimpleTileMapRuntimeObject;
|
||||
// TODO Move this attribute in the object as it's a model.
|
||||
_tileMap: TileMapHelper.EditableTileMap | null = null;
|
||||
|
||||
private _pixiObject: PIXI.tilemap.CompositeTilemap;
|
||||
|
||||
@@ -51,40 +49,9 @@ namespace gdjs {
|
||||
this._pixiObject.tileAnim[0] += 1;
|
||||
}
|
||||
|
||||
updatePixiTileMap(
|
||||
tileMap: TileMapHelper.EditableTileMap,
|
||||
textureCache: TileMapHelper.TileTextureCache
|
||||
) {
|
||||
this._tileMap = tileMap;
|
||||
TileMapHelper.PixiTileMapHelper.updatePixiTileMap(
|
||||
this._pixiObject,
|
||||
tileMap,
|
||||
textureCache,
|
||||
// @ts-ignore
|
||||
this._object._displayMode,
|
||||
this._object._layerIndex
|
||||
);
|
||||
}
|
||||
|
||||
refreshPixiTileMap(textureCache: TileMapHelper.TileTextureCache) {
|
||||
if (!this._tileMap) return;
|
||||
TileMapHelper.PixiTileMapHelper.updatePixiTileMap(
|
||||
this._pixiObject,
|
||||
this._tileMap,
|
||||
textureCache,
|
||||
// @ts-ignore
|
||||
this._object._displayMode,
|
||||
this._object._layerIndex
|
||||
);
|
||||
}
|
||||
|
||||
getTileMap(): TileMapHelper.EditableTileMap | null {
|
||||
return this._tileMap;
|
||||
}
|
||||
|
||||
updatePosition(): void {
|
||||
this._pixiObject.pivot.x = this.getTileMapWidth() / 2;
|
||||
this._pixiObject.pivot.y = this.getTileMapHeight() / 2;
|
||||
this._pixiObject.pivot.x = this._object.getTileMapWidth() / 2;
|
||||
this._pixiObject.pivot.y = this._object.getTileMapHeight() / 2;
|
||||
this._pixiObject.position.x = this._object.x + this.getWidth() / 2;
|
||||
this._pixiObject.position.y = this._object.y + this.getHeight() / 2;
|
||||
}
|
||||
@@ -98,7 +65,7 @@ namespace gdjs {
|
||||
// opacity. Setting alpha on each layer tile might not be useful as
|
||||
// each layer would be separately transparent instead of the whole tilemap.
|
||||
this._pixiObject.alpha = this._object._opacity / 255;
|
||||
const tileMap = this._tileMap;
|
||||
const tileMap = this._object.getTileMap();
|
||||
if (!tileMap) return;
|
||||
for (const layer of tileMap.getLayers()) {
|
||||
if (
|
||||
@@ -114,44 +81,34 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
getTileMapWidth() {
|
||||
const tileMap = this._tileMap;
|
||||
return tileMap ? tileMap.getWidth() : 20;
|
||||
}
|
||||
|
||||
getTileMapHeight() {
|
||||
const tileMap = this._tileMap;
|
||||
return tileMap ? tileMap.getHeight() : 20;
|
||||
}
|
||||
|
||||
setWidth(width: float): void {
|
||||
this._pixiObject.scale.x = width / this.getTileMapWidth();
|
||||
this._pixiObject.scale.x = width / this._object.getTileMapWidth();
|
||||
this._pixiObject.position.x = this._object.x + width / 2;
|
||||
}
|
||||
|
||||
setHeight(height: float): void {
|
||||
this._pixiObject.scale.y = height / this.getTileMapHeight();
|
||||
this._pixiObject.scale.y = height / this._object.getTileMapHeight();
|
||||
this._pixiObject.position.y = this._object.y + height / 2;
|
||||
}
|
||||
|
||||
setScaleX(scaleX: float): void {
|
||||
this._pixiObject.scale.x = scaleX;
|
||||
const width = scaleX * this.getTileMapWidth();
|
||||
const width = scaleX * this._object.getTileMapWidth();
|
||||
this._pixiObject.position.x = this._object.x + width / 2;
|
||||
}
|
||||
|
||||
setScaleY(scaleY: float): void {
|
||||
this._pixiObject.scale.y = scaleY;
|
||||
const height = scaleY * this.getTileMapHeight();
|
||||
const height = scaleY * this._object.getTileMapHeight();
|
||||
this._pixiObject.position.y = this._object.y + height / 2;
|
||||
}
|
||||
|
||||
getWidth(): float {
|
||||
return this.getTileMapWidth() * this._pixiObject.scale.x;
|
||||
return this._object.getTileMapWidth() * this._pixiObject.scale.x;
|
||||
}
|
||||
|
||||
getHeight(): float {
|
||||
return this.getTileMapHeight() * this._pixiObject.scale.y;
|
||||
return this._object.getTileMapHeight() * this._pixiObject.scale.y;
|
||||
}
|
||||
|
||||
getScaleX(): float {
|
||||
@@ -162,91 +119,17 @@ namespace gdjs {
|
||||
return this._pixiObject.scale.y;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param x The layer column.
|
||||
* @param y The layer row.
|
||||
* @param layerIndex The layer index.
|
||||
* @returns The tile's id.
|
||||
*/
|
||||
getTileId(x: integer, y: integer, layerIndex: integer): integer {
|
||||
const tileMap = this._tileMap;
|
||||
if (!tileMap) return -1;
|
||||
return tileMap.getTileId(x, y, layerIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param x The layer column.
|
||||
* @param y The layer row.
|
||||
* @param layerIndex The layer index.
|
||||
* @param flip true if the tile should be flipped.
|
||||
*/
|
||||
flipTileOnY(x: integer, y: integer, layerIndex: integer, flip: boolean) {
|
||||
const tileMap = this._tileMap;
|
||||
refreshPixiTileMap(textureCache: TileMapHelper.TileTextureCache) {
|
||||
const tileMap = this._object.getTileMap();
|
||||
if (!tileMap) return;
|
||||
tileMap.flipTileOnY(x, y, layerIndex, flip);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param x The layer column.
|
||||
* @param y The layer row.
|
||||
* @param layerIndex The layer index.
|
||||
* @param flip true if the tile should be flipped.
|
||||
*/
|
||||
flipTileOnX(x: integer, y: integer, layerIndex: integer, flip: boolean) {
|
||||
const tileMap = this._tileMap;
|
||||
if (!tileMap) return;
|
||||
tileMap.flipTileOnX(x, y, layerIndex, flip);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param x The layer column.
|
||||
* @param y The layer row.
|
||||
* @param layerIndex The layer index.
|
||||
*/
|
||||
isTileFlippedOnX(x: integer, y: integer, layerIndex: integer): boolean {
|
||||
const tileMap = this._tileMap;
|
||||
if (!tileMap) return false;
|
||||
return tileMap.isTileFlippedOnX(x, y, layerIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param x The layer column.
|
||||
* @param y The layer row.
|
||||
* @param layerIndex The layer index.
|
||||
*/
|
||||
isTileFlippedOnY(x: integer, y: integer, layerIndex: integer): boolean {
|
||||
const tileMap = this._tileMap;
|
||||
if (!tileMap) return false;
|
||||
return tileMap.isTileFlippedOnY(x, y, layerIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param targetRowCount The number of rows to have.
|
||||
*/
|
||||
setGridRowCount(targetRowCount: integer) {
|
||||
const tileMap = this._tileMap;
|
||||
if (!tileMap) return;
|
||||
return tileMap.setDimensionY(targetRowCount);
|
||||
}
|
||||
/**
|
||||
* @param targetColumnCount The number of rows to have.
|
||||
*/
|
||||
setGridColumnCount(targetColumnCount: integer) {
|
||||
const tileMap = this._tileMap;
|
||||
if (!tileMap) return;
|
||||
return tileMap.setDimensionX(targetColumnCount);
|
||||
}
|
||||
|
||||
getGridRowCount(): integer {
|
||||
const tileMap = this._tileMap;
|
||||
if (!tileMap) return 0;
|
||||
return tileMap.getDimensionY();
|
||||
}
|
||||
|
||||
getGridColumnCount(): integer {
|
||||
const tileMap = this._tileMap;
|
||||
if (!tileMap) return 0;
|
||||
return tileMap.getDimensionX();
|
||||
TileMapHelper.PixiTileMapHelper.updatePixiTileMap(
|
||||
this._pixiObject,
|
||||
tileMap,
|
||||
textureCache,
|
||||
// @ts-ignore
|
||||
this._displayMode,
|
||||
this._object._layerIndex
|
||||
);
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
|
@@ -2,7 +2,6 @@
|
||||
namespace gdjs {
|
||||
export type TilemapObjectDataType = {
|
||||
content: {
|
||||
opacity: number;
|
||||
tilemapJsonFile: string;
|
||||
tilesetJsonFile: string;
|
||||
tilemapAtlasImage: string;
|
||||
@@ -38,7 +37,7 @@ namespace gdjs {
|
||||
implements gdjs.Resizable, gdjs.Scalable, gdjs.OpacityHandler
|
||||
{
|
||||
_frameElapsedTime: float = 0;
|
||||
_opacity: float;
|
||||
_opacity: float = 255;
|
||||
_tilemapJsonFile: string;
|
||||
_tilesetJsonFile: string;
|
||||
_tilemapAtlasImage: string;
|
||||
@@ -48,11 +47,14 @@ namespace gdjs {
|
||||
_animationSpeedScale: number;
|
||||
_animationFps: number;
|
||||
_tileMapManager: gdjs.TileMap.TileMapRuntimeManager;
|
||||
_tileMap: TileMapHelper.EditableTileMap | null = null;
|
||||
_renderer: gdjs.TileMapRuntimeObjectPixiRenderer;
|
||||
|
||||
constructor(instanceContainer: gdjs.RuntimeInstanceContainer, objectData) {
|
||||
constructor(
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
objectData: TilemapObjectData
|
||||
) {
|
||||
super(instanceContainer, objectData);
|
||||
this._opacity = objectData.content.opacity;
|
||||
this._tilemapJsonFile = objectData.content.tilemapJsonFile;
|
||||
this._tilesetJsonFile = objectData.content.tilesetJsonFile;
|
||||
this._tilemapAtlasImage = objectData.content.tilemapAtlasImage;
|
||||
@@ -93,9 +95,6 @@ namespace gdjs {
|
||||
oldObjectData: TilemapObjectData,
|
||||
newObjectData: TilemapObjectData
|
||||
): boolean {
|
||||
if (oldObjectData.content.opacity !== newObjectData.content.opacity) {
|
||||
this.setOpacity(newObjectData.content.opacity);
|
||||
}
|
||||
if (
|
||||
oldObjectData.content.tilemapJsonFile !==
|
||||
newObjectData.content.tilemapJsonFile
|
||||
@@ -145,9 +144,11 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(): TilemapNetworkSyncData {
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): TilemapNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
op: this._opacity,
|
||||
tmjf: this._tilemapJsonFile,
|
||||
tsjf: this._tilesetJsonFile,
|
||||
@@ -159,8 +160,11 @@ namespace gdjs {
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(networkSyncData: TilemapNetworkSyncData): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: TilemapNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
|
||||
if (networkSyncData.op !== undefined) {
|
||||
this.setOpacity(networkSyncData.op);
|
||||
@@ -193,9 +197,11 @@ namespace gdjs {
|
||||
this.setWidth(initialInstanceData.width);
|
||||
this.setHeight(initialInstanceData.height);
|
||||
}
|
||||
if (initialInstanceData.opacity !== undefined) {
|
||||
this.setOpacity(initialInstanceData.opacity);
|
||||
}
|
||||
this.setOpacity(
|
||||
initialInstanceData.opacity === undefined
|
||||
? 255
|
||||
: initialInstanceData.opacity
|
||||
);
|
||||
}
|
||||
|
||||
private _updateTileMap(): void {
|
||||
@@ -230,7 +236,9 @@ namespace gdjs {
|
||||
// getOrLoadTextureCache already log warns and errors.
|
||||
return;
|
||||
}
|
||||
this._renderer.updatePixiTileMap(tileMap, textureCache);
|
||||
this._tileMap = tileMap;
|
||||
this._renderer.refreshPixiTileMap(textureCache);
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -337,6 +345,14 @@ namespace gdjs {
|
||||
this.setHeight(newHeight);
|
||||
}
|
||||
|
||||
override getOriginalWidth(): float {
|
||||
return this.getTileMapWidth();
|
||||
}
|
||||
|
||||
override getOriginalHeight(): float {
|
||||
return this.getTileMapHeight();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the scale of the object (or the geometric mean of the X and Y scale in case they are different).
|
||||
*
|
||||
@@ -427,6 +443,73 @@ namespace gdjs {
|
||||
getScaleY(): float {
|
||||
return this._renderer.getScaleY();
|
||||
}
|
||||
|
||||
getTileMap(): TileMapHelper.EditableTileMap | null {
|
||||
return this._tileMap;
|
||||
}
|
||||
|
||||
getTileMapWidth() {
|
||||
const tileMap = this._tileMap;
|
||||
return tileMap ? tileMap.getWidth() : 20;
|
||||
}
|
||||
|
||||
getTileMapHeight() {
|
||||
const tileMap = this._tileMap;
|
||||
return tileMap ? tileMap.getHeight() : 20;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param x The layer column.
|
||||
* @param y The layer row.
|
||||
* @param layerIndex The layer index.
|
||||
* @returns The tile's id.
|
||||
*/
|
||||
getTileId(x: integer, y: integer, layerIndex: integer): integer {
|
||||
if (!this._tileMap) return -1;
|
||||
return this._tileMap.getTileId(x, y, layerIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param x The layer column.
|
||||
* @param y The layer row.
|
||||
* @param layerIndex The layer index.
|
||||
* @param flip true if the tile should be flipped.
|
||||
*/
|
||||
flipTileOnY(x: integer, y: integer, layerIndex: integer, flip: boolean) {
|
||||
if (!this._tileMap) return;
|
||||
this._tileMap.flipTileOnY(x, y, layerIndex, flip);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param x The layer column.
|
||||
* @param y The layer row.
|
||||
* @param layerIndex The layer index.
|
||||
* @param flip true if the tile should be flipped.
|
||||
*/
|
||||
flipTileOnX(x: integer, y: integer, layerIndex: integer, flip: boolean) {
|
||||
if (!this._tileMap) return;
|
||||
this._tileMap.flipTileOnX(x, y, layerIndex, flip);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param x The layer column.
|
||||
* @param y The layer row.
|
||||
* @param layerIndex The layer index.
|
||||
*/
|
||||
isTileFlippedOnX(x: integer, y: integer, layerIndex: integer): boolean {
|
||||
if (!this._tileMap) return false;
|
||||
return this._tileMap.isTileFlippedOnX(x, y, layerIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param x The layer column.
|
||||
* @param y The layer row.
|
||||
* @param layerIndex The layer index.
|
||||
*/
|
||||
isTileFlippedOnY(x: integer, y: integer, layerIndex: integer): boolean {
|
||||
if (!this._tileMap) return false;
|
||||
return this._tileMap.isTileFlippedOnY(x, y, layerIndex);
|
||||
}
|
||||
}
|
||||
gdjs.registerObject('TileMap::TileMap', gdjs.TileMapRuntimeObject);
|
||||
}
|
||||
|
@@ -42,6 +42,8 @@ namespace gdjs {
|
||||
|
||||
_renderer: gdjs.TiledSpriteRuntimeObjectRenderer;
|
||||
|
||||
_objectData: TiledSpriteObjectData;
|
||||
|
||||
/**
|
||||
* @param instanceContainer The container the object belongs to.
|
||||
* @param tiledSpriteObjectData The initial properties of the object
|
||||
@@ -51,6 +53,7 @@ namespace gdjs {
|
||||
tiledSpriteObjectData: TiledSpriteObjectData
|
||||
) {
|
||||
super(instanceContainer, tiledSpriteObjectData);
|
||||
this._objectData = tiledSpriteObjectData;
|
||||
this._renderer = new gdjs.TiledSpriteRuntimeObjectRenderer(
|
||||
this,
|
||||
instanceContainer,
|
||||
@@ -66,6 +69,7 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
updateFromObjectData(oldObjectData, newObjectData): boolean {
|
||||
this._objectData = newObjectData;
|
||||
if (oldObjectData.texture !== newObjectData.texture) {
|
||||
this.setTexture(newObjectData.texture, this.getRuntimeScene());
|
||||
}
|
||||
@@ -78,9 +82,11 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(): TiledSpriteNetworkSyncData {
|
||||
getNetworkSyncData(
|
||||
syncOptons: GetNetworkSyncDataOptions
|
||||
): TiledSpriteNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptons),
|
||||
xo: this.getXOffset(),
|
||||
yo: this.getYOffset(),
|
||||
op: this.getOpacity(),
|
||||
@@ -89,9 +95,10 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: TiledSpriteNetworkSyncData
|
||||
networkSyncData: TiledSpriteNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
|
||||
// Texture is not synchronized, see if this is asked or not.
|
||||
|
||||
@@ -126,9 +133,11 @@ namespace gdjs {
|
||||
this.setWidth(initialInstanceData.width);
|
||||
this.setHeight(initialInstanceData.height);
|
||||
}
|
||||
if (initialInstanceData.opacity !== undefined) {
|
||||
this.setOpacity(initialInstanceData.opacity);
|
||||
}
|
||||
this.setOpacity(
|
||||
initialInstanceData.opacity === undefined
|
||||
? 255
|
||||
: initialInstanceData.opacity
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -220,6 +229,14 @@ namespace gdjs {
|
||||
this.setHeight(height);
|
||||
}
|
||||
|
||||
override getOriginalWidth(): float {
|
||||
return this._objectData.width;
|
||||
}
|
||||
|
||||
override getOriginalHeight(): float {
|
||||
return this._objectData.height;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the offset on the X-axis when displaying the image of the Tiled Sprite object.
|
||||
* @param xOffset The new offset on the X-axis.
|
||||
|
@@ -34,6 +34,19 @@ describe('gdjs.TopDownMovementRuntimeBehavior', function () {
|
||||
objects: [],
|
||||
instances: [],
|
||||
usedResources: [],
|
||||
uiSettings: {
|
||||
grid: false,
|
||||
gridType: 'rectangular',
|
||||
gridWidth: 10,
|
||||
gridHeight: 10,
|
||||
gridDepth: 10,
|
||||
gridOffsetX: 0,
|
||||
gridOffsetY: 0,
|
||||
gridOffsetZ: 0,
|
||||
gridColor: 0,
|
||||
gridAlpha: 1,
|
||||
snap: false,
|
||||
},
|
||||
},
|
||||
usedExtensionsWithVariablesData: [],
|
||||
});
|
||||
|
@@ -63,7 +63,7 @@ namespace gdjs {
|
||||
// This is useful when the object is synchronized by an external source
|
||||
// like in a multiplayer game, and we want to be able to predict the
|
||||
// movement of the object, even if the inputs are not updated every frame.
|
||||
_dontClearInputsBetweenFrames: boolean = false;
|
||||
private _clearInputsBetweenFrames: boolean = true;
|
||||
// This is useful when the object is synchronized over the network,
|
||||
// object is controlled by the network and we want to ensure the current player
|
||||
// cannot control it.
|
||||
@@ -109,14 +109,16 @@ namespace gdjs {
|
||||
: behaviorData.useLegacyTurnBack;
|
||||
}
|
||||
|
||||
getNetworkSyncData(): TopDownMovementNetworkSyncData {
|
||||
getNetworkSyncData(
|
||||
options: GetNetworkSyncDataOptions
|
||||
): TopDownMovementNetworkSyncData {
|
||||
// This method is called, so we are synchronizing this object.
|
||||
// Let's clear the inputs between frames as we control it.
|
||||
this._dontClearInputsBetweenFrames = false;
|
||||
this._clearInputsBetweenFrames = true;
|
||||
this._ignoreDefaultControlsAsSyncedByNetwork = false;
|
||||
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(options),
|
||||
props: {
|
||||
a: this._angle,
|
||||
xv: this._xVelocity,
|
||||
@@ -134,9 +136,10 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: TopDownMovementNetworkSyncData
|
||||
networkSyncData: TopDownMovementNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
|
||||
const behaviorSpecificProps = networkSyncData.props;
|
||||
if (behaviorSpecificProps.a !== undefined) {
|
||||
@@ -173,10 +176,10 @@ namespace gdjs {
|
||||
this._stickForce = behaviorSpecificProps.sf;
|
||||
}
|
||||
|
||||
// When the object is synchronized from the network, the inputs must not be cleared.
|
||||
this._dontClearInputsBetweenFrames = true;
|
||||
// And we are not using the default controls.
|
||||
this._ignoreDefaultControlsAsSyncedByNetwork = true;
|
||||
// Clear user inputs between frames only if requested.
|
||||
this._clearInputsBetweenFrames = !!options.clearInputs;
|
||||
// And ignore default controls if not asked otherwise.
|
||||
this._ignoreDefaultControlsAsSyncedByNetwork = !options.keepControl;
|
||||
}
|
||||
|
||||
updateFromBehaviorData(oldBehaviorData, newBehaviorData): boolean {
|
||||
@@ -581,7 +584,7 @@ namespace gdjs {
|
||||
this._wasRightKeyPressed = this._rightKey;
|
||||
this._wasUpKeyPressed = this._upKey;
|
||||
this._wasDownKeyPressed = this._downKey;
|
||||
if (!this._dontClearInputsBetweenFrames) {
|
||||
if (this._clearInputsBetweenFrames) {
|
||||
this._leftKey = false;
|
||||
this._rightKey = false;
|
||||
this._upKey = false;
|
||||
|
File diff suppressed because it is too large
Load Diff
@@ -4,6 +4,15 @@ Copyright (c) 2010-2023 Florian Rival (Florian.Rival@gmail.com)
|
||||
*/
|
||||
namespace gdjs {
|
||||
const logger = new gdjs.Logger('Tween');
|
||||
|
||||
interface TweenBehaviorNetworkSyncDataType {
|
||||
tweenManager: TweenManagerNetworkSyncData;
|
||||
}
|
||||
export interface TweenBehaviorNetworkSyncData
|
||||
extends BehaviorNetworkSyncData {
|
||||
props: TweenBehaviorNetworkSyncDataType;
|
||||
}
|
||||
|
||||
interface IColorable extends gdjs.RuntimeObject {
|
||||
setColor(color: string): void;
|
||||
getColor(): string;
|
||||
@@ -59,6 +68,305 @@ namespace gdjs {
|
||||
const exponentialInterpolation =
|
||||
gdjs.evtTools.common.exponentialInterpolation;
|
||||
|
||||
const tweenObjectValueSetter = () => {};
|
||||
const getTweenVariableSetter = (variable: gdjs.Variable) => {
|
||||
return (value: float) => variable.setNumber(value);
|
||||
};
|
||||
const getTweenObjectPositionXSetter = (object: gdjs.RuntimeObject) => {
|
||||
return (value: float) => object.setX(value);
|
||||
};
|
||||
const getTweenObjectPositionYSetter = (object: gdjs.RuntimeObject) => {
|
||||
return (value: float) => object.setY(value);
|
||||
};
|
||||
const getTweenObjectPositionZSetter = (object: gdjs.RuntimeObject) => {
|
||||
if (!is3D(object)) return () => {};
|
||||
return (value: float) => object.setZ(value);
|
||||
};
|
||||
const getTweenObjectPositionSetter = (object: gdjs.RuntimeObject) => {
|
||||
return ([x, y]: float[]) => object.setPosition(x, y);
|
||||
};
|
||||
const getTweenObjectAngleSetter = (object: gdjs.RuntimeObject) => {
|
||||
return (value: float) => object.setAngle(value);
|
||||
};
|
||||
const getTweenObjectWidthSetter = (object: gdjs.RuntimeObject) => {
|
||||
return (value: float) => object.setWidth(value);
|
||||
};
|
||||
const getTweenObjectHeightSetter = (object: gdjs.RuntimeObject) => {
|
||||
return (value: float) => object.setHeight(value);
|
||||
};
|
||||
const getTweenObjectRotationXSetter = (
|
||||
object: gdjs.RuntimeObject & gdjs.Base3DHandler
|
||||
) => {
|
||||
return (value: float) => object.setRotationX(value);
|
||||
};
|
||||
const getTweenObjectRotationYSetter = (
|
||||
object: gdjs.RuntimeObject & gdjs.Base3DHandler
|
||||
) => {
|
||||
return (value: float) => object.setRotationY(value);
|
||||
};
|
||||
const getTweenObjectDepthSetter = (
|
||||
object: gdjs.RuntimeObject & gdjs.Base3DHandler
|
||||
) => {
|
||||
return (value: float) => object.setDepth(value);
|
||||
};
|
||||
const getTweenObjectScaleXYSetter = (
|
||||
object: gdjs.RuntimeObject & gdjs.Scalable,
|
||||
scaleFromCenterOfObject: boolean
|
||||
) => {
|
||||
return scaleFromCenterOfObject
|
||||
? ([scaleX, scaleY]: float[]) => {
|
||||
const oldX = object.getCenterXInScene();
|
||||
const oldY = object.getCenterYInScene();
|
||||
object.setScaleX(scaleX);
|
||||
object.setScaleY(scaleY);
|
||||
object.setCenterPositionInScene(oldX, oldY);
|
||||
}
|
||||
: ([scaleX, scaleY]: float[]) => {
|
||||
object.setScaleX(scaleX);
|
||||
object.setScaleY(scaleY);
|
||||
};
|
||||
};
|
||||
const getTweenObjectScaleSetter = (
|
||||
object: gdjs.RuntimeObject & gdjs.Scalable,
|
||||
object3d: (gdjs.RuntimeObject & gdjs.Base3DHandler) | null,
|
||||
scaleFromCenterOfObject: boolean
|
||||
) => {
|
||||
return scaleFromCenterOfObject
|
||||
? (scale: float) => {
|
||||
const oldX = object.getCenterXInScene();
|
||||
const oldY = object.getCenterYInScene();
|
||||
const oldZ = object3d ? object3d.getCenterZInScene() : 0;
|
||||
object.setScale(scale);
|
||||
object.setCenterXInScene(oldX);
|
||||
object.setCenterYInScene(oldY);
|
||||
if (object3d) {
|
||||
object3d.setCenterZInScene(oldZ);
|
||||
}
|
||||
}
|
||||
: (scale: float) => object.setScale(scale);
|
||||
};
|
||||
const getTweenObjectScaleXSetter = (
|
||||
object: gdjs.RuntimeObject & gdjs.Scalable,
|
||||
scaleFromCenterOfObject: boolean
|
||||
) => {
|
||||
return scaleFromCenterOfObject
|
||||
? (scaleX: float) => {
|
||||
const oldX = object.getCenterXInScene();
|
||||
object.setScaleX(scaleX);
|
||||
object.setCenterXInScene(oldX);
|
||||
}
|
||||
: (scaleX: float) => object.setScaleX(scaleX);
|
||||
};
|
||||
const getTweenObjectScaleYSetter = (
|
||||
object: gdjs.RuntimeObject & gdjs.Scalable,
|
||||
scaleFromCenterOfObject: boolean
|
||||
) => {
|
||||
return scaleFromCenterOfObject
|
||||
? (scaleY: float) => {
|
||||
const oldY = object.getCenterYInScene();
|
||||
object.setScaleY(scaleY);
|
||||
object.setCenterYInScene(oldY);
|
||||
}
|
||||
: (scaleY: float) => object.setScaleY(scaleY);
|
||||
};
|
||||
const getTweenObjectOpacitySetter = (
|
||||
object: gdjs.RuntimeObject & gdjs.OpacityHandler
|
||||
) => {
|
||||
return (value: float) => object.setOpacity(value);
|
||||
};
|
||||
const getTweenObjectCharacterSizeSetter = (object: ICharacterScalable) => {
|
||||
return (value: float) => object.setCharacterSize(value);
|
||||
};
|
||||
const getTweenObjectNumberEffectPropertySetter = (
|
||||
effect: PixiFiltersTools.Filter,
|
||||
propertyName: string
|
||||
) => {
|
||||
return (value: float) => {
|
||||
effect.updateDoubleParameter(propertyName, value);
|
||||
};
|
||||
};
|
||||
const getTweenObjectColorEffectPropertySetter = (
|
||||
effect: PixiFiltersTools.Filter,
|
||||
propertyName: string
|
||||
) => {
|
||||
return ([hue, saturation, lightness]: number[]) => {
|
||||
const rgbFromHslColor = gdjs.evtTools.tween.hslToRgb(
|
||||
hue,
|
||||
saturation,
|
||||
lightness
|
||||
);
|
||||
effect.updateColorParameter(
|
||||
propertyName,
|
||||
gdjs.rgbToHexNumber(
|
||||
rgbFromHslColor[0],
|
||||
rgbFromHslColor[1],
|
||||
rgbFromHslColor[2]
|
||||
)
|
||||
);
|
||||
};
|
||||
};
|
||||
const getTweenObjectColorSetter = (
|
||||
object: IColorable,
|
||||
useHSLColorTransition: boolean
|
||||
) => {
|
||||
if (useHSLColorTransition) {
|
||||
return ([hue, saturation, lightness]: number[]) => {
|
||||
const rgbFromHslColor = gdjs.evtTools.tween.hslToRgb(
|
||||
hue,
|
||||
saturation,
|
||||
lightness
|
||||
);
|
||||
object.setColor(
|
||||
Math.floor(rgbFromHslColor[0]) +
|
||||
';' +
|
||||
Math.floor(rgbFromHslColor[1]) +
|
||||
';' +
|
||||
Math.floor(rgbFromHslColor[2])
|
||||
);
|
||||
};
|
||||
} else {
|
||||
return ([red, green, blue]: number[]) => {
|
||||
object.setColor(
|
||||
Math.floor(red) + ';' + Math.floor(green) + ';' + Math.floor(blue)
|
||||
);
|
||||
};
|
||||
}
|
||||
};
|
||||
const getTweenObjectColorHSLSetter = (object: IColorable) => {
|
||||
return ([hue, saturation, lightness]: number[]) => {
|
||||
const rgbFromHslColor = gdjs.evtTools.tween.hslToRgb(
|
||||
hue,
|
||||
saturation,
|
||||
lightness
|
||||
);
|
||||
|
||||
object.setColor(
|
||||
Math.floor(rgbFromHslColor[0]) +
|
||||
';' +
|
||||
Math.floor(rgbFromHslColor[1]) +
|
||||
';' +
|
||||
Math.floor(rgbFromHslColor[2])
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
const tweenSetterFactory =
|
||||
(object: RuntimeObject) =>
|
||||
(tweenInformation: TweenInformationNetworkSyncData) => {
|
||||
const type = tweenInformation.type;
|
||||
const variablePath = tweenInformation.variablePath;
|
||||
const effectName = tweenInformation.effectName;
|
||||
const propertyName = tweenInformation.propertyName;
|
||||
const scaleFromCenterOfObject =
|
||||
!!tweenInformation.scaleFromCenterOfObject;
|
||||
const useHSLColorTransition = !!tweenInformation.useHSLColorTransition;
|
||||
if (type === 'objectValue') {
|
||||
return tweenObjectValueSetter;
|
||||
}
|
||||
if (type === 'variable' && variablePath) {
|
||||
const variable = object
|
||||
.getVariables()
|
||||
.getVariableFromPath(variablePath);
|
||||
if (!variable) return () => {};
|
||||
return getTweenVariableSetter(variable);
|
||||
}
|
||||
if (type === 'positionX') {
|
||||
return getTweenObjectPositionXSetter(object);
|
||||
}
|
||||
if (type === 'positionY') {
|
||||
return getTweenObjectPositionYSetter(object);
|
||||
}
|
||||
if (type === 'position') {
|
||||
return getTweenObjectPositionSetter(object);
|
||||
}
|
||||
if (type === 'positionZ') {
|
||||
return getTweenObjectPositionZSetter(object);
|
||||
}
|
||||
if (type === 'width') {
|
||||
return getTweenObjectWidthSetter(object);
|
||||
}
|
||||
if (type === 'height') {
|
||||
return getTweenObjectHeightSetter(object);
|
||||
}
|
||||
if (type === 'depth') {
|
||||
if (!is3D(object)) return () => {};
|
||||
return getTweenObjectDepthSetter(object);
|
||||
}
|
||||
if (type === 'angle') {
|
||||
return getTweenObjectAngleSetter(object);
|
||||
}
|
||||
if (type === 'rotationX') {
|
||||
if (!is3D(object)) return () => {};
|
||||
return getTweenObjectRotationXSetter(object);
|
||||
}
|
||||
if (type === 'rotationY') {
|
||||
if (!is3D(object)) return () => {};
|
||||
return getTweenObjectRotationYSetter(object);
|
||||
}
|
||||
if (type === 'scale') {
|
||||
if (!isScalable(object)) return () => {};
|
||||
|
||||
const object3d = is3D(object) ? object : null;
|
||||
return getTweenObjectScaleSetter(
|
||||
object,
|
||||
object3d,
|
||||
scaleFromCenterOfObject
|
||||
);
|
||||
}
|
||||
if (type === 'scaleXY') {
|
||||
if (!isScalable(object)) return () => {};
|
||||
return getTweenObjectScaleXYSetter(object, scaleFromCenterOfObject);
|
||||
}
|
||||
if (type === 'scaleX') {
|
||||
if (!isScalable(object)) return () => {};
|
||||
return getTweenObjectScaleXSetter(object, scaleFromCenterOfObject);
|
||||
}
|
||||
if (type === 'scaleY') {
|
||||
if (!isScalable(object)) return () => {};
|
||||
return getTweenObjectScaleYSetter(object, scaleFromCenterOfObject);
|
||||
}
|
||||
if (type === 'opacity') {
|
||||
if (!isOpaque(object)) return () => {};
|
||||
return getTweenObjectOpacitySetter(object);
|
||||
}
|
||||
if (type === 'characterSize') {
|
||||
if (!isCharacterScalable(object)) return () => {};
|
||||
return getTweenObjectCharacterSizeSetter(object);
|
||||
}
|
||||
if (type === 'numberEffectProperty' && effectName && propertyName) {
|
||||
const effect = object.getRendererEffects()[effectName];
|
||||
if (!effect) {
|
||||
logger.error(
|
||||
`The object "${object.name}" doesn't have any effect called "${effectName}"`
|
||||
);
|
||||
}
|
||||
return getTweenObjectNumberEffectPropertySetter(effect, propertyName);
|
||||
}
|
||||
if (type === 'colorEffectProperty' && effectName && propertyName) {
|
||||
const effect = object.getRendererEffects()[effectName];
|
||||
if (!effect) {
|
||||
logger.error(
|
||||
`The object "${object.name}" doesn't have any effect called "${effectName}"`
|
||||
);
|
||||
}
|
||||
|
||||
return getTweenObjectColorEffectPropertySetter(effect, propertyName);
|
||||
}
|
||||
|
||||
if (type === 'objectColor') {
|
||||
if (!isColorable(object)) return () => {};
|
||||
|
||||
return getTweenObjectColorSetter(object, useHSLColorTransition);
|
||||
}
|
||||
if (type === 'objectColorHSL') {
|
||||
if (!isColorable(object)) return () => {};
|
||||
|
||||
return getTweenObjectColorHSLSetter(object);
|
||||
}
|
||||
|
||||
return () => {};
|
||||
};
|
||||
|
||||
export class TweenRuntimeBehavior extends gdjs.RuntimeBehavior {
|
||||
private _tweens = new gdjs.evtTools.tween.TweenManager();
|
||||
private _isActive: boolean = true;
|
||||
@@ -84,6 +392,43 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): TweenBehaviorNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
props: {
|
||||
tweenManager: this._tweens.getNetworkSyncData(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: TweenBehaviorNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
|
||||
if (networkSyncData.props.tweenManager) {
|
||||
this._tweens.updateFromNetworkSyncData(
|
||||
networkSyncData.props.tweenManager,
|
||||
(tweenInformationNetworkSyncData) => {
|
||||
return this.owner;
|
||||
},
|
||||
(tweenInformationNetworkSyncData) => {
|
||||
return tweenSetterFactory(this.owner)(
|
||||
tweenInformationNetworkSyncData
|
||||
);
|
||||
},
|
||||
(tweenInformationNetworkSyncData) => {
|
||||
return tweenInformationNetworkSyncData.destroyObjectWhenFinished
|
||||
? () => this._deleteFromScene()
|
||||
: null;
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
doStepPreEvents(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
this._tweens.step();
|
||||
}
|
||||
@@ -126,7 +471,12 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
fromValue,
|
||||
toValue,
|
||||
(value: float) => variable.setNumber(value),
|
||||
getTweenVariableSetter(variable),
|
||||
{
|
||||
type: 'variable',
|
||||
variable,
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -208,7 +558,12 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
variable.getValue() as number,
|
||||
toValue,
|
||||
(value: float) => variable.setNumber(value),
|
||||
getTweenVariableSetter(variable),
|
||||
{
|
||||
type: 'variable',
|
||||
variable,
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -243,7 +598,11 @@ namespace gdjs {
|
||||
: linearInterpolation,
|
||||
fromValue,
|
||||
toValue,
|
||||
(value: float) => {},
|
||||
tweenObjectValueSetter,
|
||||
{
|
||||
type: 'objectValue',
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -322,7 +681,11 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
[this.owner.getX(), this.owner.getY()],
|
||||
[toX, toY],
|
||||
([x, y]) => this.owner.setPosition(x, y),
|
||||
getTweenObjectPositionSetter(this.owner),
|
||||
{
|
||||
type: 'position',
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -394,7 +757,11 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
this.owner.getX(),
|
||||
toX,
|
||||
(value: float) => this.owner.setX(value),
|
||||
getTweenObjectPositionXSetter(this.owner),
|
||||
{
|
||||
type: 'positionX',
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -466,7 +833,11 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
this.owner.getY(),
|
||||
toY,
|
||||
(value: float) => this.owner.setY(value),
|
||||
getTweenObjectPositionYSetter(this.owner),
|
||||
{
|
||||
type: 'positionY',
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -543,7 +914,11 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
owner.getZ(),
|
||||
toZ,
|
||||
(value: float) => owner.setZ(value),
|
||||
getTweenObjectPositionZSetter(owner),
|
||||
{
|
||||
type: 'positionZ',
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -615,7 +990,11 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
this.owner.getAngle(),
|
||||
toAngle,
|
||||
(value: float) => this.owner.setAngle(value),
|
||||
getTweenObjectAngleSetter(this.owner),
|
||||
{
|
||||
type: 'angle',
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -648,7 +1027,11 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
owner.getRotationX(),
|
||||
toAngle,
|
||||
(value: float) => owner.setRotationX(value),
|
||||
getTweenObjectRotationXSetter(owner),
|
||||
{
|
||||
type: 'rotationX',
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -681,7 +1064,11 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
owner.getRotationY(),
|
||||
toAngle,
|
||||
(value: float) => owner.setRotationY(value),
|
||||
getTweenObjectRotationYSetter(owner),
|
||||
{
|
||||
type: 'rotationY',
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -769,19 +1156,6 @@ namespace gdjs {
|
||||
if (toScaleX < 0) toScaleX = 0;
|
||||
if (toScaleY < 0) toScaleY = 0;
|
||||
|
||||
const setValue = scaleFromCenterOfObject
|
||||
? ([scaleX, scaleY]: float[]) => {
|
||||
const oldX = owner.getCenterXInScene();
|
||||
const oldY = owner.getCenterYInScene();
|
||||
owner.setScaleX(scaleX);
|
||||
owner.setScaleY(scaleY);
|
||||
owner.setCenterPositionInScene(oldX, oldY);
|
||||
}
|
||||
: ([scaleX, scaleY]: float[]) => {
|
||||
owner.setScaleX(scaleX);
|
||||
owner.setScaleY(scaleY);
|
||||
};
|
||||
|
||||
this._tweens.addMultiTween(
|
||||
identifier,
|
||||
timeSource,
|
||||
@@ -790,7 +1164,11 @@ namespace gdjs {
|
||||
interpolation,
|
||||
[owner.getScaleX(), owner.getScaleY()],
|
||||
[toScaleX, toScaleY],
|
||||
setValue,
|
||||
getTweenObjectScaleXYSetter(owner, scaleFromCenterOfObject),
|
||||
{
|
||||
type: 'scaleXY',
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -830,20 +1208,6 @@ namespace gdjs {
|
||||
// when the 3D extension is not used.
|
||||
const owner3d = is3D(owner) ? owner : null;
|
||||
|
||||
const setValue = scaleFromCenterOfObject
|
||||
? (scale: float) => {
|
||||
const oldX = owner.getCenterXInScene();
|
||||
const oldY = owner.getCenterYInScene();
|
||||
const oldZ = owner3d ? owner3d.getCenterZInScene() : 0;
|
||||
owner.setScale(scale);
|
||||
owner.setCenterXInScene(oldX);
|
||||
owner.setCenterYInScene(oldY);
|
||||
if (owner3d) {
|
||||
owner3d.setCenterZInScene(oldZ);
|
||||
}
|
||||
}
|
||||
: (scale: float) => owner.setScale(scale);
|
||||
|
||||
this._tweens.addSimpleTween(
|
||||
identifier,
|
||||
this.owner,
|
||||
@@ -852,7 +1216,12 @@ namespace gdjs {
|
||||
exponentialInterpolation,
|
||||
owner.getScale(),
|
||||
toScale,
|
||||
setValue,
|
||||
getTweenObjectScaleSetter(owner, owner3d, scaleFromCenterOfObject),
|
||||
{
|
||||
type: 'scale',
|
||||
scaleFromCenterOfObject,
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -929,14 +1298,6 @@ namespace gdjs {
|
||||
const owner = this.owner;
|
||||
if (!isScalable(owner)) return;
|
||||
|
||||
const setValue = scaleFromCenterOfObject
|
||||
? (scaleX: float) => {
|
||||
const oldX = owner.getCenterXInScene();
|
||||
owner.setScaleX(scaleX);
|
||||
owner.setCenterXInScene(oldX);
|
||||
}
|
||||
: (scaleX: float) => owner.setScaleX(scaleX);
|
||||
|
||||
this._tweens.addSimpleTween(
|
||||
identifier,
|
||||
timeSource,
|
||||
@@ -945,7 +1306,12 @@ namespace gdjs {
|
||||
interpolation,
|
||||
owner.getScaleX(),
|
||||
toScaleX,
|
||||
setValue,
|
||||
getTweenObjectScaleXSetter(owner, scaleFromCenterOfObject),
|
||||
{
|
||||
type: 'scaleX',
|
||||
scaleFromCenterOfObject,
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -1022,14 +1388,6 @@ namespace gdjs {
|
||||
const owner = this.owner;
|
||||
if (!isScalable(owner)) return;
|
||||
|
||||
const setValue = scaleFromCenterOfObject
|
||||
? (scaleY: float) => {
|
||||
const oldY = owner.getCenterYInScene();
|
||||
owner.setScaleY(scaleY);
|
||||
owner.setCenterYInScene(oldY);
|
||||
}
|
||||
: (scaleY: float) => owner.setScaleY(scaleY);
|
||||
|
||||
this._tweens.addSimpleTween(
|
||||
identifier,
|
||||
timeSource,
|
||||
@@ -1038,7 +1396,12 @@ namespace gdjs {
|
||||
interpolation,
|
||||
owner.getScaleY(),
|
||||
toScaleY,
|
||||
setValue,
|
||||
getTweenObjectScaleYSetter(owner, scaleFromCenterOfObject),
|
||||
{
|
||||
type: 'scaleY',
|
||||
scaleFromCenterOfObject,
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -1113,7 +1476,11 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
owner.getOpacity(),
|
||||
toOpacity,
|
||||
(value: float) => owner.setOpacity(value),
|
||||
getTweenObjectOpacitySetter(owner),
|
||||
{
|
||||
type: 'opacity',
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -1153,10 +1520,12 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
effect ? effect.getDoubleParameter(propertyName) : 0,
|
||||
toValue,
|
||||
(value: float) => {
|
||||
if (effect) {
|
||||
effect.updateDoubleParameter(propertyName, value);
|
||||
}
|
||||
getTweenObjectNumberEffectPropertySetter(effect, propertyName),
|
||||
{
|
||||
type: 'numberEffectProperty',
|
||||
effectName,
|
||||
propertyName,
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
@@ -1210,22 +1579,12 @@ namespace gdjs {
|
||||
rgbToColor[1],
|
||||
rgbToColor[2]
|
||||
),
|
||||
([hue, saturation, lightness]) => {
|
||||
if (effect) {
|
||||
const rgbFromHslColor = gdjs.evtTools.tween.hslToRgb(
|
||||
hue,
|
||||
saturation,
|
||||
lightness
|
||||
);
|
||||
effect.updateColorParameter(
|
||||
propertyName,
|
||||
gdjs.rgbToHexNumber(
|
||||
rgbFromHslColor[0],
|
||||
rgbFromHslColor[1],
|
||||
rgbFromHslColor[2]
|
||||
)
|
||||
);
|
||||
}
|
||||
getTweenObjectColorEffectPropertySetter(effect, propertyName),
|
||||
{
|
||||
type: 'colorEffectProperty',
|
||||
effectName,
|
||||
propertyName,
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
@@ -1305,43 +1664,20 @@ namespace gdjs {
|
||||
const rgbFromColor: float[] = gdjs.rgbOrHexToRGBColor(owner.getColor());
|
||||
const rgbToColor: float[] = gdjs.rgbOrHexToRGBColor(toColorStr);
|
||||
|
||||
let initialValue;
|
||||
let targetedValue;
|
||||
let setValue;
|
||||
if (useHSLColorTransition) {
|
||||
initialValue = gdjs.evtTools.tween.rgbToHsl(
|
||||
rgbFromColor[0],
|
||||
rgbFromColor[1],
|
||||
rgbFromColor[2]
|
||||
);
|
||||
targetedValue = gdjs.evtTools.tween.rgbToHsl(
|
||||
rgbToColor[0],
|
||||
rgbToColor[1],
|
||||
rgbToColor[2]
|
||||
);
|
||||
setValue = ([hue, saturation, lightness]) => {
|
||||
const rgbFromHslColor = gdjs.evtTools.tween.hslToRgb(
|
||||
hue,
|
||||
saturation,
|
||||
lightness
|
||||
);
|
||||
owner.setColor(
|
||||
Math.round(rgbFromHslColor[0]) +
|
||||
';' +
|
||||
Math.round(rgbFromHslColor[1]) +
|
||||
';' +
|
||||
Math.round(rgbFromHslColor[2])
|
||||
);
|
||||
};
|
||||
} else {
|
||||
initialValue = rgbFromColor;
|
||||
targetedValue = rgbToColor;
|
||||
setValue = ([red, green, blue]) => {
|
||||
owner.setColor(
|
||||
Math.floor(red) + ';' + Math.floor(green) + ';' + Math.floor(blue)
|
||||
);
|
||||
};
|
||||
}
|
||||
const initialValue = useHSLColorTransition
|
||||
? gdjs.evtTools.tween.rgbToHsl(
|
||||
rgbFromColor[0],
|
||||
rgbFromColor[1],
|
||||
rgbFromColor[2]
|
||||
)
|
||||
: rgbFromColor;
|
||||
const targetedValue = useHSLColorTransition
|
||||
? gdjs.evtTools.tween.rgbToHsl(
|
||||
rgbToColor[0],
|
||||
rgbToColor[1],
|
||||
rgbToColor[2]
|
||||
)
|
||||
: rgbToColor;
|
||||
|
||||
this._tweens.addMultiTween(
|
||||
identifier,
|
||||
@@ -1351,7 +1687,12 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
initialValue,
|
||||
targetedValue,
|
||||
setValue,
|
||||
getTweenObjectColorSetter(owner, useHSLColorTransition),
|
||||
{
|
||||
type: 'objectColor',
|
||||
useHSLColorTransition,
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -1462,25 +1803,13 @@ namespace gdjs {
|
||||
duration,
|
||||
easing,
|
||||
linearInterpolation,
|
||||
|
||||
hslFromColor,
|
||||
[toH, toS, toL],
|
||||
([hue, saturation, lightness]) => {
|
||||
const rgbFromHslColor = gdjs.evtTools.tween.hslToRgb(
|
||||
hue,
|
||||
saturation,
|
||||
lightness
|
||||
);
|
||||
|
||||
owner.setColor(
|
||||
Math.round(rgbFromHslColor[0]) +
|
||||
';' +
|
||||
Math.round(rgbFromHslColor[1]) +
|
||||
';' +
|
||||
Math.round(rgbFromHslColor[2])
|
||||
);
|
||||
getTweenObjectColorHSLSetter(owner),
|
||||
{
|
||||
type: 'objectColorHSL',
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -1558,7 +1887,11 @@ namespace gdjs {
|
||||
interpolation,
|
||||
owner.getCharacterSize(),
|
||||
toSize,
|
||||
(value: float) => owner.setCharacterSize(value),
|
||||
getTweenObjectCharacterSizeSetter(owner),
|
||||
{
|
||||
type: 'characterSize',
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -1630,7 +1963,11 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
this.owner.getWidth(),
|
||||
toWidth,
|
||||
(value: float) => this.owner.setWidth(value),
|
||||
getTweenObjectWidthSetter(this.owner),
|
||||
{
|
||||
type: 'width',
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -1702,7 +2039,11 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
this.owner.getHeight(),
|
||||
toHeight,
|
||||
(value: float) => this.owner.setHeight(value),
|
||||
getTweenObjectHeightSetter(this.owner),
|
||||
{
|
||||
type: 'height',
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
@@ -1779,7 +2120,11 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
owner.getDepth(),
|
||||
toDepth,
|
||||
(value: float) => owner.setDepth(value),
|
||||
getTweenObjectDepthSetter(owner),
|
||||
{
|
||||
type: 'depth',
|
||||
destroyObjectWhenFinished,
|
||||
},
|
||||
destroyObjectWhenFinished ? () => this._deleteFromScene() : null
|
||||
);
|
||||
}
|
||||
|
@@ -10,6 +10,127 @@ namespace gdjs {
|
||||
export namespace tween {
|
||||
const logger = new gdjs.Logger('Tween');
|
||||
|
||||
const getTweenVariableSetter = (variable: gdjs.Variable) => {
|
||||
return (value: float) => variable.setNumber(value);
|
||||
};
|
||||
const tweenLayoutValueSetter = (value: float) => {};
|
||||
const tweenLayerValueSetter = (value: float) => {};
|
||||
const getTweenLayerCameraPositionSetter = (layer: gdjs.RuntimeLayer) => {
|
||||
return ([x, y]: Array<float>) => {
|
||||
layer.setCameraX(x);
|
||||
layer.setCameraY(y);
|
||||
};
|
||||
};
|
||||
const getTweenLayerCameraRotationSetter = (layer: gdjs.RuntimeLayer) => {
|
||||
return (value: float) => layer.setCameraRotation(value);
|
||||
};
|
||||
const getTweenLayerCameraZoomSetter = (layer: gdjs.RuntimeLayer) => {
|
||||
return (value: float) => layer.setCameraZoom(value);
|
||||
};
|
||||
const getTweenNumberEffectPropertySetter = (
|
||||
effect: PixiFiltersTools.Filter,
|
||||
propertyName: string
|
||||
) => {
|
||||
return (value: float) => {
|
||||
if (effect) {
|
||||
effect.updateDoubleParameter(propertyName, value);
|
||||
}
|
||||
};
|
||||
};
|
||||
const getTweenColorEffectPropertySetter = (
|
||||
effect: PixiFiltersTools.Filter,
|
||||
propertyName: string
|
||||
) => {
|
||||
return ([hue, saturation, lightness]: Array<float>) => {
|
||||
if (effect) {
|
||||
const rgbFromHslColor = gdjs.evtTools.tween.hslToRgb(
|
||||
hue,
|
||||
saturation,
|
||||
lightness
|
||||
);
|
||||
effect.updateColorParameter(
|
||||
propertyName,
|
||||
gdjs.rgbToHexNumber(
|
||||
rgbFromHslColor[0],
|
||||
rgbFromHslColor[1],
|
||||
rgbFromHslColor[2]
|
||||
)
|
||||
);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// Factory to get the tween setter based on type and options
|
||||
export const tweenSetterFactory =
|
||||
(runtimeScene: RuntimeScene) =>
|
||||
(tweenInformation: TweenInformationNetworkSyncData) => {
|
||||
const type = tweenInformation.type;
|
||||
const layerName = tweenInformation.layerName;
|
||||
const variablePath = tweenInformation.variablePath;
|
||||
const effectName = tweenInformation.effectName;
|
||||
const propertyName = tweenInformation.propertyName;
|
||||
|
||||
if (type === 'variable' && variablePath) {
|
||||
const variable = runtimeScene
|
||||
.getVariables()
|
||||
.getVariableFromPath(variablePath);
|
||||
if (!variable) {
|
||||
return () => {};
|
||||
}
|
||||
return getTweenVariableSetter(variable);
|
||||
}
|
||||
if (type === 'cameraZoom' && layerName !== undefined) {
|
||||
const layer = runtimeScene.getLayer(layerName);
|
||||
return getTweenLayerCameraZoomSetter(layer);
|
||||
}
|
||||
if (type === 'cameraRotation' && layerName !== undefined) {
|
||||
const layer = runtimeScene.getLayer(layerName);
|
||||
return getTweenLayerCameraRotationSetter(layer);
|
||||
}
|
||||
if (type === 'cameraPosition' && layerName !== undefined) {
|
||||
const layer = runtimeScene.getLayer(layerName);
|
||||
return getTweenLayerCameraPositionSetter(layer);
|
||||
}
|
||||
if (
|
||||
type === 'colorEffectProperty' &&
|
||||
layerName !== undefined &&
|
||||
effectName &&
|
||||
propertyName
|
||||
) {
|
||||
const layer = runtimeScene.getLayer(layerName);
|
||||
const effect = layer.getRendererEffects()[effectName];
|
||||
if (!effect) {
|
||||
logger.error(
|
||||
`The layer "${layerName}" doesn't have any effect called "${effectName}"`
|
||||
);
|
||||
}
|
||||
|
||||
return getTweenColorEffectPropertySetter(effect, propertyName);
|
||||
}
|
||||
if (
|
||||
type === 'numberEffectProperty' &&
|
||||
layerName !== undefined &&
|
||||
effectName &&
|
||||
propertyName
|
||||
) {
|
||||
const layer = runtimeScene.getLayer(layerName);
|
||||
const effect = layer.getRendererEffects()[effectName];
|
||||
if (!effect) {
|
||||
logger.error(
|
||||
`The layer "${layerName}" doesn't have any effect called "${effectName}"`
|
||||
);
|
||||
}
|
||||
return getTweenNumberEffectPropertySetter(effect, propertyName);
|
||||
}
|
||||
if (type === 'layoutValue') {
|
||||
return tweenLayoutValueSetter;
|
||||
}
|
||||
if (type === 'layerValue') {
|
||||
return tweenLayerValueSetter;
|
||||
}
|
||||
return () => {};
|
||||
};
|
||||
|
||||
export const getTweensMap = (runtimeScene: RuntimeScene) =>
|
||||
runtimeScene._tweens ||
|
||||
(runtimeScene._tweens = new gdjs.evtTools.tween.TweenManager());
|
||||
@@ -20,6 +141,44 @@ namespace gdjs {
|
||||
gdjs.evtTools.tween.getTweensMap(runtimeScene).step();
|
||||
});
|
||||
|
||||
gdjs.registerRuntimeSceneGetSyncDataCallback(
|
||||
function (runtimeScene, currentLayoutSyncData, syncOptions) {
|
||||
if (!syncOptions.syncTweens) return;
|
||||
const tweensNetworkSyncData = gdjs.evtTools.tween
|
||||
.getTweensMap(runtimeScene)
|
||||
.getNetworkSyncData();
|
||||
|
||||
currentLayoutSyncData.tween = tweensNetworkSyncData;
|
||||
}
|
||||
);
|
||||
|
||||
gdjs.registerRuntimeSceneUpdateFromSyncDataCallback(
|
||||
function (runtimeScene, receivedSyncData, syncOptions) {
|
||||
if (!receivedSyncData.tween) return;
|
||||
|
||||
gdjs.evtTools.tween
|
||||
.getTweensMap(runtimeScene)
|
||||
.updateFromNetworkSyncData(
|
||||
receivedSyncData.tween,
|
||||
(tweenInformationNetworkSyncData) => {
|
||||
if (tweenInformationNetworkSyncData.layerName !== undefined) {
|
||||
return runtimeScene.getLayer(
|
||||
tweenInformationNetworkSyncData.layerName
|
||||
);
|
||||
}
|
||||
return runtimeScene;
|
||||
},
|
||||
(tweenInformationNetworkSyncData) => {
|
||||
return gdjs.evtTools.tween.tweenSetterFactory(runtimeScene)(
|
||||
tweenInformationNetworkSyncData
|
||||
);
|
||||
},
|
||||
// No onFinish for scene tweens.
|
||||
() => null
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
export const sceneTweenExists = (
|
||||
runtimeScene: RuntimeScene,
|
||||
id: string
|
||||
@@ -130,7 +289,10 @@ namespace gdjs {
|
||||
: linearInterpolation,
|
||||
fromValue,
|
||||
toValue,
|
||||
(value: float) => {}
|
||||
tweenLayoutValueSetter,
|
||||
{
|
||||
type: 'layoutValue',
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
@@ -167,7 +329,11 @@ namespace gdjs {
|
||||
: linearInterpolation,
|
||||
fromValue,
|
||||
toValue,
|
||||
(value: float) => {}
|
||||
tweenLayerValueSetter,
|
||||
{
|
||||
type: 'layerValue',
|
||||
layerName,
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
@@ -197,7 +363,11 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
from,
|
||||
to,
|
||||
(value: float) => variable.setNumber(value)
|
||||
getTweenVariableSetter(variable),
|
||||
{
|
||||
type: 'variable',
|
||||
variable,
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
@@ -250,7 +420,11 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
variable.getValue() as number,
|
||||
toValue,
|
||||
(value: float) => variable.setNumber(value)
|
||||
getTweenVariableSetter(variable),
|
||||
{
|
||||
type: 'variable',
|
||||
variable,
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
@@ -329,9 +503,10 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
[layer.getCameraX(), layer.getCameraY()],
|
||||
[toX, toY],
|
||||
([x, y]) => {
|
||||
layer.setCameraX(x);
|
||||
layer.setCameraY(y);
|
||||
getTweenLayerCameraPositionSetter(layer),
|
||||
{
|
||||
type: 'cameraPosition',
|
||||
layerName,
|
||||
}
|
||||
);
|
||||
};
|
||||
@@ -408,7 +583,11 @@ namespace gdjs {
|
||||
interpolation,
|
||||
layer.getCameraZoom(),
|
||||
toZoom,
|
||||
(value: float) => layer.setCameraZoom(value)
|
||||
getTweenLayerCameraZoomSetter(layer),
|
||||
{
|
||||
type: 'cameraZoom',
|
||||
layerName,
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
@@ -478,7 +657,11 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
layer.getCameraRotation(),
|
||||
toRotation,
|
||||
(value: float) => layer.setCameraRotation(value)
|
||||
getTweenLayerCameraRotationSetter(layer),
|
||||
{
|
||||
type: 'cameraRotation',
|
||||
layerName,
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
@@ -518,10 +701,12 @@ namespace gdjs {
|
||||
linearInterpolation,
|
||||
effect ? effect.getDoubleParameter(propertyName) : 0,
|
||||
toValue,
|
||||
(value: float) => {
|
||||
if (effect) {
|
||||
effect.updateDoubleParameter(propertyName, value);
|
||||
}
|
||||
getTweenNumberEffectPropertySetter(effect, propertyName),
|
||||
{
|
||||
type: 'numberEffectProperty',
|
||||
layerName,
|
||||
effectName,
|
||||
propertyName,
|
||||
}
|
||||
);
|
||||
};
|
||||
@@ -575,22 +760,12 @@ namespace gdjs {
|
||||
rgbToColor[1],
|
||||
rgbToColor[2]
|
||||
),
|
||||
([hue, saturation, lightness]) => {
|
||||
if (effect) {
|
||||
const rgbFromHslColor = gdjs.evtTools.tween.hslToRgb(
|
||||
hue,
|
||||
saturation,
|
||||
lightness
|
||||
);
|
||||
effect.updateColorParameter(
|
||||
propertyName,
|
||||
gdjs.rgbToHexNumber(
|
||||
rgbFromHslColor[0],
|
||||
rgbFromHslColor[1],
|
||||
rgbFromHslColor[2]
|
||||
)
|
||||
);
|
||||
}
|
||||
getTweenColorEffectPropertySetter(effect, propertyName),
|
||||
{
|
||||
type: 'colorEffectProperty',
|
||||
layerName,
|
||||
effectName,
|
||||
propertyName,
|
||||
}
|
||||
);
|
||||
};
|
||||
|
@@ -16,7 +16,7 @@ namespace gdjs {
|
||||
|
||||
export type VideoObjectData = ObjectData & VideoObjectDataType;
|
||||
|
||||
export type VideoNetworkSyncDataType = {
|
||||
export type VideoObjectNetworkSyncDataType = {
|
||||
op: float;
|
||||
// We don't sync volume, as it's probably a user setting?
|
||||
pla: boolean;
|
||||
@@ -25,8 +25,8 @@ namespace gdjs {
|
||||
ps: number;
|
||||
};
|
||||
|
||||
export type VideoNetworkSyncData = ObjectNetworkSyncData &
|
||||
VideoNetworkSyncDataType;
|
||||
export type VideoObjectNetworkSyncData = ObjectNetworkSyncData &
|
||||
VideoObjectNetworkSyncDataType;
|
||||
|
||||
/**
|
||||
* An object displaying a video on screen.
|
||||
@@ -99,9 +99,11 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(): VideoNetworkSyncData {
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): VideoObjectNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
op: this._opacity,
|
||||
pla: this.isPlayed(),
|
||||
loop: this.isLooped(),
|
||||
@@ -110,8 +112,11 @@ namespace gdjs {
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(syncData: VideoNetworkSyncData): void {
|
||||
super.updateFromNetworkSyncData(syncData);
|
||||
updateFromNetworkSyncData(
|
||||
syncData: VideoObjectNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(syncData, options);
|
||||
|
||||
if (this._opacity !== undefined && this._opacity && syncData.op) {
|
||||
this.setOpacity(syncData.op);
|
||||
@@ -146,9 +151,11 @@ namespace gdjs {
|
||||
this.setWidth(initialInstanceData.width);
|
||||
this.setHeight(initialInstanceData.height);
|
||||
}
|
||||
if (initialInstanceData.opacity !== undefined) {
|
||||
this.setOpacity(initialInstanceData.opacity);
|
||||
}
|
||||
this.setOpacity(
|
||||
initialInstanceData.opacity === undefined
|
||||
? 255
|
||||
: initialInstanceData.opacity
|
||||
);
|
||||
}
|
||||
|
||||
onDestroyed(): void {
|
||||
|
@@ -214,16 +214,16 @@ CODE_NAMESPACE.RUNTIME_BEHAVIOR_CLASSNAME = class RUNTIME_BEHAVIOR_CLASSNAME ext
|
||||
}
|
||||
|
||||
// Network sync:
|
||||
getNetworkSyncData() {
|
||||
getNetworkSyncData(syncOptions) {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
props: {
|
||||
GET_NETWORK_SYNC_DATA_CODE
|
||||
}
|
||||
};
|
||||
}
|
||||
updateFromNetworkSyncData(networkSyncData) {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
updateFromNetworkSyncData(networkSyncData, options) {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
UPDATE_FROM_NETWORK_SYNC_DATA_CODE
|
||||
}
|
||||
|
||||
|
@@ -74,10 +74,15 @@ gd::String EventsCodeGenerator::GenerateEventsListCompleteFunctionCode(
|
||||
codeGenerator.GetCodeNamespace() + ".localVariables = [];\n";
|
||||
}
|
||||
|
||||
gd::String idToCallbackMapCode;
|
||||
idToCallbackMapCode +=
|
||||
codeGenerator.GetCodeNamespace() + ".idToCallbackMap = new Map();\n";
|
||||
|
||||
gd::String output =
|
||||
// clang-format off
|
||||
codeGenerator.GetCodeNamespace() + " = {};\n" +
|
||||
localVariablesInitializationCode +
|
||||
idToCallbackMapCode +
|
||||
globalDeclarations +
|
||||
globalObjectLists + "\n\n" +
|
||||
codeGenerator.GetCustomCodeOutsideMain() + "\n\n" +
|
||||
@@ -135,8 +140,11 @@ gd::String EventsCodeGenerator::GenerateEventsFunctionCode(
|
||||
gd::VariablesContainer::SourceType::Parameters);
|
||||
auto projectScopedContainers = gd::ProjectScopedContainers::
|
||||
MakeNewProjectScopedContainersForFreeEventsFunction(
|
||||
project, eventsFunctionsExtension, eventsFunction,
|
||||
parameterObjectsAndGroups, parameterVariablesContainer);
|
||||
project,
|
||||
eventsFunctionsExtension,
|
||||
eventsFunction,
|
||||
parameterObjectsAndGroups,
|
||||
parameterVariablesContainer);
|
||||
|
||||
EventsCodeGenerator codeGenerator(projectScopedContainers);
|
||||
codeGenerator.SetCodeNamespace(codeNamespace);
|
||||
@@ -148,16 +156,21 @@ gd::String EventsCodeGenerator::GenerateEventsFunctionCode(
|
||||
// Generate the code setting up the context of the function.
|
||||
gd::String fullPreludeCode = "let scopeInstanceContainer = null;\n" +
|
||||
codeGenerator.GenerateFreeEventsFunctionContext(
|
||||
eventsFunctionsExtension, eventsFunction,
|
||||
eventsFunctionsExtension,
|
||||
eventsFunction,
|
||||
"runtimeScene.getOnceTriggers()");
|
||||
|
||||
gd::String output = GenerateEventsListCompleteFunctionCode(
|
||||
codeGenerator, codeGenerator.GetCodeNamespaceAccessor() + "func",
|
||||
codeGenerator,
|
||||
codeGenerator.GetCodeNamespaceAccessor() + "func",
|
||||
codeGenerator.GenerateEventsFunctionParameterDeclarationsList(
|
||||
eventsFunction.GetParametersForEvents(
|
||||
eventsFunctionsExtension.GetEventsFunctions()),
|
||||
0, true),
|
||||
fullPreludeCode, eventsFunction.GetEvents(), "",
|
||||
0,
|
||||
true),
|
||||
fullPreludeCode,
|
||||
eventsFunction.GetEvents(),
|
||||
"",
|
||||
codeGenerator.GenerateEventsFunctionReturn(eventsFunction));
|
||||
|
||||
// TODO: the editor should pass the diagnostic report and display it to the
|
||||
@@ -193,9 +206,13 @@ gd::String EventsCodeGenerator::GenerateBehaviorEventsFunctionCode(
|
||||
gd::VariablesContainer::SourceType::Properties);
|
||||
auto projectScopedContainers = gd::ProjectScopedContainers::
|
||||
MakeNewProjectScopedContainersForBehaviorEventsFunction(
|
||||
project, eventsFunctionsExtension, eventsBasedBehavior,
|
||||
eventsFunction, parameterObjectsContainers,
|
||||
parameterVariablesContainer, propertyVariablesContainer);
|
||||
project,
|
||||
eventsFunctionsExtension,
|
||||
eventsBasedBehavior,
|
||||
eventsFunction,
|
||||
parameterObjectsContainers,
|
||||
parameterVariablesContainer,
|
||||
propertyVariablesContainer);
|
||||
|
||||
EventsCodeGenerator codeGenerator(projectScopedContainers);
|
||||
codeGenerator.SetCodeNamespace(codeNamespace);
|
||||
@@ -209,8 +226,9 @@ gd::String EventsCodeGenerator::GenerateBehaviorEventsFunctionCode(
|
||||
preludeCode + "\n" + "var that = this;\n" +
|
||||
// runtimeScene is supposed to be always accessible, read
|
||||
// it from the behavior.
|
||||
// TODO: this should be renamed to "instanceContainer" and have the code generation
|
||||
// adapted for this (rely less on `gdjs.RuntimeScene`, and more on `RuntimeInstanceContainer`).
|
||||
// TODO: this should be renamed to "instanceContainer" and have the code
|
||||
// generation adapted for this (rely less on `gdjs.RuntimeScene`, and more
|
||||
// on `RuntimeInstanceContainer`).
|
||||
"var runtimeScene = this._runtimeScene;\n" +
|
||||
"let scopeInstanceContainer = null;\n" +
|
||||
// By convention of Behavior Events Function, the object is accessible
|
||||
@@ -279,8 +297,12 @@ gd::String EventsCodeGenerator::GenerateObjectEventsFunctionCode(
|
||||
gd::VariablesContainer::SourceType::Properties);
|
||||
auto projectScopedContainers = gd::ProjectScopedContainers::
|
||||
MakeNewProjectScopedContainersForObjectEventsFunction(
|
||||
project, eventsFunctionsExtension, eventsBasedObject, eventsFunction,
|
||||
parameterObjectsContainers, parameterVariablesContainer,
|
||||
project,
|
||||
eventsFunctionsExtension,
|
||||
eventsBasedObject,
|
||||
eventsFunction,
|
||||
parameterObjectsContainers,
|
||||
parameterVariablesContainer,
|
||||
propertyVariablesContainer);
|
||||
|
||||
EventsCodeGenerator codeGenerator(projectScopedContainers);
|
||||
@@ -295,8 +317,9 @@ gd::String EventsCodeGenerator::GenerateObjectEventsFunctionCode(
|
||||
preludeCode + "\n" + "var that = this;\n" +
|
||||
// runtimeScene is supposed to be always accessible, read
|
||||
// it from the object.
|
||||
// TODO: this should be renamed to "instanceContainer" and have the code generation
|
||||
// adapted for this (rely less on `gdjs.RuntimeScene`, and more on `RuntimeInstanceContainer`).
|
||||
// TODO: this should be renamed to "instanceContainer" and have the code
|
||||
// generation adapted for this (rely less on `gdjs.RuntimeScene`, and more
|
||||
// on `RuntimeInstanceContainer`).
|
||||
"var runtimeScene = this._instanceContainer;\n" +
|
||||
"let scopeInstanceContainer = this._instanceContainer;\n" +
|
||||
// By convention of Object Events Function, the object is accessible
|
||||
@@ -388,13 +411,14 @@ gd::String EventsCodeGenerator::GenerateFreeEventsFunctionContext(
|
||||
gd::String objectsGettersMap;
|
||||
gd::String objectArraysMap;
|
||||
gd::String behaviorNamesMap;
|
||||
return GenerateEventsFunctionContext(eventsFunctionsExtension,
|
||||
eventsFunctionsExtension.GetEventsFunctions(),
|
||||
eventsFunction,
|
||||
onceTriggersVariable,
|
||||
objectsGettersMap,
|
||||
objectArraysMap,
|
||||
behaviorNamesMap);
|
||||
return GenerateEventsFunctionContext(
|
||||
eventsFunctionsExtension,
|
||||
eventsFunctionsExtension.GetEventsFunctions(),
|
||||
eventsFunction,
|
||||
onceTriggersVariable,
|
||||
objectsGettersMap,
|
||||
objectArraysMap,
|
||||
behaviorNamesMap);
|
||||
}
|
||||
|
||||
gd::String EventsCodeGenerator::GenerateBehaviorEventsFunctionContext(
|
||||
@@ -929,7 +953,8 @@ gd::String EventsCodeGenerator::GenerateObjectAction(
|
||||
const std::vector<gd::String>& arguments,
|
||||
const gd::InstructionMetadata& instrInfos,
|
||||
gd::EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName) {
|
||||
const gd::String& optionalAsyncCallbackName,
|
||||
const gd::String& optionalAsyncCallbackId) {
|
||||
gd::String actionCode;
|
||||
|
||||
// Prepare call
|
||||
@@ -978,10 +1003,11 @@ gd::String EventsCodeGenerator::GenerateObjectAction(
|
||||
actionCode += " " + call + ";\n";
|
||||
actionCode += "}\n";
|
||||
|
||||
if (!optionalAsyncCallbackName.empty()) {
|
||||
if (!optionalAsyncCallbackName.empty() && !optionalAsyncCallbackId.empty()) {
|
||||
actionCode +=
|
||||
"runtimeScene.getAsyncTasksManager().addTask(asyncTaskGroup, " +
|
||||
optionalAsyncCallbackName + ")\n}";
|
||||
optionalAsyncCallbackName + ", " + optionalAsyncCallbackId +
|
||||
", asyncObjectsList)\n}";
|
||||
}
|
||||
|
||||
return actionCode;
|
||||
@@ -995,7 +1021,8 @@ gd::String EventsCodeGenerator::GenerateBehaviorAction(
|
||||
const std::vector<gd::String>& arguments,
|
||||
const gd::InstructionMetadata& instrInfos,
|
||||
gd::EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName) {
|
||||
const gd::String& optionalAsyncCallbackName,
|
||||
const gd::String& optionalAsyncCallbackId) {
|
||||
gd::String actionCode;
|
||||
|
||||
// Prepare call
|
||||
@@ -1055,10 +1082,12 @@ gd::String EventsCodeGenerator::GenerateBehaviorAction(
|
||||
actionCode += " " + call + ";\n";
|
||||
actionCode += "}\n";
|
||||
|
||||
if (!optionalAsyncCallbackName.empty()) {
|
||||
if (!optionalAsyncCallbackName.empty() &&
|
||||
!optionalAsyncCallbackId.empty()) {
|
||||
actionCode +=
|
||||
"runtimeScene.getAsyncTasksManager().addTask(asyncTaskGroup, " +
|
||||
optionalAsyncCallbackName + ");\n };";
|
||||
optionalAsyncCallbackName + ", " + optionalAsyncCallbackId +
|
||||
", asyncObjectsList);\n };";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1377,17 +1406,16 @@ gd::String EventsCodeGenerator::GenerateGetVariable(
|
||||
scope == VARIABLE_OR_PROPERTY_OR_PARAMETER) {
|
||||
const auto variablesContainersList =
|
||||
GetProjectScopedContainers().GetVariablesContainersList();
|
||||
const auto &variablesContainer =
|
||||
const auto& variablesContainer =
|
||||
scope == VARIABLE_OR_PROPERTY_OR_PARAMETER
|
||||
? variablesContainersList.GetVariablesContainerFromVariableOrPropertyOrParameterName(
|
||||
variableName)
|
||||
? variablesContainersList
|
||||
.GetVariablesContainerFromVariableOrPropertyOrParameterName(
|
||||
variableName)
|
||||
: scope == VARIABLE_OR_PROPERTY
|
||||
? variablesContainersList
|
||||
.GetVariablesContainerFromVariableOrPropertyName(
|
||||
variableName)
|
||||
: variablesContainersList
|
||||
.GetVariablesContainerFromVariableNameOnly(
|
||||
variableName);
|
||||
.GetVariablesContainerFromVariableOrPropertyName(variableName)
|
||||
: variablesContainersList.GetVariablesContainerFromVariableNameOnly(
|
||||
variableName);
|
||||
const auto sourceType = variablesContainer.GetSourceType();
|
||||
if (sourceType == gd::VariablesContainer::SourceType::Scene) {
|
||||
variables = &variablesContainer;
|
||||
@@ -1410,48 +1438,50 @@ gd::String EventsCodeGenerator::GenerateGetVariable(
|
||||
gd::VariablesContainer::SourceType::ExtensionScene) {
|
||||
variables = &variablesContainer;
|
||||
output = "eventsFunctionContext.sceneVariablesForExtension";
|
||||
} else if (sourceType ==
|
||||
gd::VariablesContainer::SourceType::Properties) {
|
||||
} else if (sourceType == gd::VariablesContainer::SourceType::Properties) {
|
||||
if (hasChild) {
|
||||
// Properties with children are not supported.
|
||||
return "gdjs.VariablesContainer.badVariablesContainer";
|
||||
}
|
||||
const auto &propertiesContainersList =
|
||||
const auto& propertiesContainersList =
|
||||
GetProjectScopedContainers().GetPropertiesContainersList();
|
||||
const auto &propertiesContainerAndProperty =
|
||||
const auto& propertiesContainerAndProperty =
|
||||
propertiesContainersList.Get(variableName);
|
||||
return GeneratePropertyGetterWithoutCasting(
|
||||
propertiesContainerAndProperty.first,
|
||||
propertiesContainerAndProperty.second);
|
||||
} else if (sourceType ==
|
||||
gd::VariablesContainer::SourceType::Parameters) {
|
||||
} else if (sourceType == gd::VariablesContainer::SourceType::Parameters) {
|
||||
if (hasChild) {
|
||||
// Parameters with children are not supported.
|
||||
return "gdjs.VariablesContainer.badVariablesContainer";
|
||||
}
|
||||
const auto ¶metersVectorsList =
|
||||
const auto& parametersVectorsList =
|
||||
GetProjectScopedContainers().GetParametersVectorsList();
|
||||
const auto ¶meter =
|
||||
const auto& parameter =
|
||||
gd::ParameterMetadataTools::Get(parametersVectorsList, variableName);
|
||||
return GenerateParameterGetterWithoutCasting(parameter);
|
||||
}
|
||||
} else if (scope == LAYOUT_VARIABLE) {
|
||||
output = "runtimeScene.getScene().getVariables()";
|
||||
|
||||
const auto *legacySceneVariables = GetProjectScopedContainers().GetLegacySceneVariables();
|
||||
const auto* legacySceneVariables =
|
||||
GetProjectScopedContainers().GetLegacySceneVariables();
|
||||
if (HasProjectAndLayout()) {
|
||||
variables = &GetLayout().GetVariables();
|
||||
} else if (legacySceneVariables && legacySceneVariables->Has(variableName)) {
|
||||
} else if (legacySceneVariables &&
|
||||
legacySceneVariables->Has(variableName)) {
|
||||
variables = legacySceneVariables;
|
||||
output = "eventsFunctionContext.sceneVariablesForExtension";
|
||||
}
|
||||
} else if (scope == PROJECT_VARIABLE) {
|
||||
output = "runtimeScene.getGame().getVariables()";
|
||||
|
||||
const auto *legacyGlobalVariables = GetProjectScopedContainers().GetLegacyGlobalVariables();
|
||||
const auto* legacyGlobalVariables =
|
||||
GetProjectScopedContainers().GetLegacyGlobalVariables();
|
||||
if (HasProjectAndLayout()) {
|
||||
variables = &GetProject().GetVariables();
|
||||
} else if (legacyGlobalVariables && legacyGlobalVariables->Has(variableName)) {
|
||||
} else if (legacyGlobalVariables &&
|
||||
legacyGlobalVariables->Has(variableName)) {
|
||||
variables = legacyGlobalVariables;
|
||||
output = "eventsFunctionContext.globalVariablesForExtension";
|
||||
}
|
||||
@@ -1543,9 +1573,9 @@ gd::String EventsCodeGenerator::GenerateProfilerSectionEnd(
|
||||
}
|
||||
|
||||
gd::String EventsCodeGenerator::GeneratePropertySetterWithoutCasting(
|
||||
const gd::PropertiesContainer &propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor &property,
|
||||
const gd::String &operandCode) {
|
||||
const gd::PropertiesContainer& propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor& property,
|
||||
const gd::String& operandCode) {
|
||||
bool isLocalProperty =
|
||||
projectScopedContainers.GetPropertiesContainersList()
|
||||
.GetBottomMostPropertiesContainer() == &propertiesContainer;
|
||||
@@ -1571,8 +1601,8 @@ gd::String EventsCodeGenerator::GeneratePropertySetterWithoutCasting(
|
||||
}
|
||||
|
||||
gd::String EventsCodeGenerator::GeneratePropertyGetterWithoutCasting(
|
||||
const gd::PropertiesContainer &propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor &property) {
|
||||
const gd::PropertiesContainer& propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor& property) {
|
||||
bool isLocalProperty =
|
||||
projectScopedContainers.GetPropertiesContainersList()
|
||||
.GetBottomMostPropertiesContainer() == &propertiesContainer;
|
||||
@@ -1639,7 +1669,7 @@ gd::String EventsCodeGenerator::GeneratePropertyGetter(
|
||||
}
|
||||
|
||||
gd::String EventsCodeGenerator::GenerateParameterGetterWithoutCasting(
|
||||
const gd::ParameterMetadata ¶meter) {
|
||||
const gd::ParameterMetadata& parameter) {
|
||||
return "eventsFunctionContext.getArgument(" +
|
||||
ConvertToStringExplicit(parameter.GetName()) + ")";
|
||||
}
|
||||
|
@@ -59,7 +59,8 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
* Generate JavaScript for executing events of an events based function.
|
||||
*
|
||||
* \param project Project used.
|
||||
* \param eventsFunctionsExtension The container of the compiled event function.
|
||||
* \param eventsFunctionsExtension The container of the compiled event
|
||||
* function.
|
||||
* \param eventsFunction The events function to be compiled.
|
||||
* \param codeNamespace Where to store the context used by the function.
|
||||
* \param includeFiles Will be filled with the necessary include files.
|
||||
@@ -96,7 +97,7 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
*/
|
||||
static gd::String GenerateBehaviorEventsFunctionCode(
|
||||
gd::Project& project,
|
||||
const gd::EventsFunctionsExtension& eventsFunctionsExtension,
|
||||
const gd::EventsFunctionsExtension& eventsFunctionsExtension,
|
||||
const gd::EventsBasedBehavior& eventsBasedBehavior,
|
||||
const gd::EventsFunction& eventsFunction,
|
||||
const gd::String& codeNamespace,
|
||||
@@ -111,7 +112,8 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
* function.
|
||||
*
|
||||
* \param project Project used.
|
||||
* \param eventsBasedObject The object that contains the function to be compiled.
|
||||
* \param eventsBasedObject The object that contains the function to be
|
||||
* compiled.
|
||||
* \param eventsFunction The events function to be compiled.
|
||||
* \param codeNamespace Where to store the context used by the function.
|
||||
* \param fullyQualifiedFunctionName The function name with its namespace.
|
||||
@@ -129,7 +131,7 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
*/
|
||||
static gd::String GenerateObjectEventsFunctionCode(
|
||||
gd::Project& project,
|
||||
const gd::EventsFunctionsExtension& eventsFunctionsExtension,
|
||||
const gd::EventsFunctionsExtension& eventsFunctionsExtension,
|
||||
const gd::EventsBasedObject& eventsBasedObject,
|
||||
const gd::EventsFunction& eventsFunction,
|
||||
const gd::String& codeNamespace,
|
||||
@@ -152,7 +154,8 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
* \return Code
|
||||
*/
|
||||
virtual gd::String GenerateEventsListCode(
|
||||
gd::EventsList& events, gd::EventsCodeGenerationContext& context) override;
|
||||
gd::EventsList& events,
|
||||
gd::EventsCodeGenerationContext& context) override;
|
||||
|
||||
/**
|
||||
* Generate code for executing a condition list
|
||||
@@ -194,7 +197,8 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
* \brief Get the full name for accessing to a list of objects
|
||||
*/
|
||||
virtual gd::String GetObjectListName(
|
||||
const gd::String& name, const gd::EventsCodeGenerationContext& context) override;
|
||||
const gd::String& name,
|
||||
const gd::EventsCodeGenerationContext& context) override;
|
||||
|
||||
/**
|
||||
* \brief Get the namespace to be used to store code generated
|
||||
@@ -226,9 +230,9 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
};
|
||||
|
||||
virtual gd::String GeneratePropertySetterWithoutCasting(
|
||||
const gd::PropertiesContainer &propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor &property,
|
||||
const gd::String &operandCode) override;
|
||||
const gd::PropertiesContainer& propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor& property,
|
||||
const gd::String& operandCode) override;
|
||||
|
||||
protected:
|
||||
virtual gd::String GenerateParameterCodes(
|
||||
@@ -289,7 +293,8 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
const std::vector<gd::String>& arguments,
|
||||
const gd::InstructionMetadata& instrInfos,
|
||||
gd::EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName = "") override;
|
||||
const gd::String& optionalAsyncCallbackName = "",
|
||||
const gd::String& optionalAsyncCallbackId = "") override;
|
||||
|
||||
virtual gd::String GenerateBehaviorAction(
|
||||
const gd::String& objectName,
|
||||
@@ -299,7 +304,8 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
const std::vector<gd::String>& arguments,
|
||||
const gd::InstructionMetadata& instrInfos,
|
||||
gd::EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName = "") override;
|
||||
const gd::String& optionalAsyncCallbackName = "",
|
||||
const gd::String& optionalAsyncCallbackId = "") override;
|
||||
|
||||
virtual gd::String GenerateGetBehaviorNameCode(
|
||||
const gd::String& behaviorName) override;
|
||||
@@ -320,9 +326,9 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
gd::String expressionCode) override {
|
||||
// This uses `getChild` which allows to access a child
|
||||
// with a number (an index, for an array) or a string (for a structure).
|
||||
// This could be optimised, if the type of the accessed variable AND the type of the index is known,
|
||||
// so that `getChildAt` (for an array, with an index) or `getChildNamed` (for a structure, with a name)
|
||||
// is used instead.
|
||||
// This could be optimised, if the type of the accessed variable AND the
|
||||
// type of the index is known, so that `getChildAt` (for an array, with an
|
||||
// index) or `getChildNamed` (for a structure, with a name) is used instead.
|
||||
return ".getChild(" + expressionCode + ")";
|
||||
};
|
||||
|
||||
@@ -330,29 +336,33 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
return "gdjs.VariablesContainer.badVariable";
|
||||
}
|
||||
|
||||
virtual gd::String GeneratePropertyGetter(const gd::PropertiesContainer& propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor& property,
|
||||
const gd::String& type,
|
||||
gd::EventsCodeGenerationContext& context) override;
|
||||
virtual gd::String GeneratePropertyGetter(
|
||||
const gd::PropertiesContainer& propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor& property,
|
||||
const gd::String& type,
|
||||
gd::EventsCodeGenerationContext& context) override;
|
||||
|
||||
virtual gd::String GeneratePropertyGetterWithoutCasting(
|
||||
const gd::PropertiesContainer &propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor &property) override;
|
||||
const gd::PropertiesContainer& propertiesContainer,
|
||||
const gd::NamedPropertyDescriptor& property) override;
|
||||
|
||||
virtual gd::String GenerateParameterGetter(const gd::ParameterMetadata& parameter,
|
||||
const gd::String& type,
|
||||
gd::EventsCodeGenerationContext& context) override;
|
||||
virtual gd::String GenerateParameterGetter(
|
||||
const gd::ParameterMetadata& parameter,
|
||||
const gd::String& type,
|
||||
gd::EventsCodeGenerationContext& context) override;
|
||||
|
||||
virtual gd::String GenerateParameterGetterWithoutCasting(
|
||||
const gd::ParameterMetadata ¶meter) override;
|
||||
const gd::ParameterMetadata& parameter) override;
|
||||
|
||||
virtual gd::String GenerateBadObject() override { return "null"; }
|
||||
|
||||
virtual gd::String GenerateObject(const gd::String& objectName,
|
||||
const gd::String& type,
|
||||
gd::EventsCodeGenerationContext& context) override;
|
||||
virtual gd::String GenerateObject(
|
||||
const gd::String& objectName,
|
||||
const gd::String& type,
|
||||
gd::EventsCodeGenerationContext& context) override;
|
||||
|
||||
virtual gd::String GenerateNegatedPredicate(const gd::String& predicate) const override {
|
||||
virtual gd::String GenerateNegatedPredicate(
|
||||
const gd::String& predicate) const override {
|
||||
return "!(" + predicate + ")";
|
||||
};
|
||||
|
||||
@@ -362,13 +372,15 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
virtual gd::String GenerateAllInstancesGetterCode(
|
||||
const gd::String& objectName, gd::EventsCodeGenerationContext& context);
|
||||
|
||||
virtual gd::String GenerateProfilerSectionBegin(const gd::String& section) override;
|
||||
virtual gd::String GenerateProfilerSectionEnd(const gd::String& section) override;
|
||||
virtual gd::String GenerateProfilerSectionBegin(
|
||||
const gd::String& section) override;
|
||||
virtual gd::String GenerateProfilerSectionEnd(
|
||||
const gd::String& section) override;
|
||||
|
||||
virtual gd::String GenerateRelationalOperation(
|
||||
const gd::String& relationalOperator,
|
||||
const gd::String& lhs,
|
||||
const gd::String& rhs) override;
|
||||
const gd::String& relationalOperator,
|
||||
const gd::String& lhs,
|
||||
const gd::String& rhs) override;
|
||||
|
||||
private:
|
||||
static gd::String GenerateEventsListCompleteFunctionCode(
|
||||
@@ -415,8 +427,8 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
* arguments from the rest of the events.
|
||||
*/
|
||||
gd::String GenerateFreeEventsFunctionContext(
|
||||
const gd::EventsFunctionsExtension &eventsFunctionsExtension,
|
||||
const gd::EventsFunction &eventsFunction,
|
||||
const gd::EventsFunctionsExtension& eventsFunctionsExtension,
|
||||
const gd::EventsFunction& eventsFunction,
|
||||
const gd::String& onceTriggersVariable);
|
||||
|
||||
/**
|
||||
@@ -425,9 +437,9 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
* arguments from the rest of the events.
|
||||
*/
|
||||
gd::String GenerateBehaviorEventsFunctionContext(
|
||||
const gd::EventsFunctionsExtension &eventsFunctionsExtension,
|
||||
const gd::EventsFunctionsExtension& eventsFunctionsExtension,
|
||||
const gd::EventsBasedBehavior& eventsBasedBehavior,
|
||||
const gd::EventsFunction &eventsFunction,
|
||||
const gd::EventsFunction& eventsFunction,
|
||||
const gd::String& onceTriggersVariable,
|
||||
const gd::String& thisObjectName,
|
||||
const gd::String& thisBehaviorName);
|
||||
@@ -438,9 +450,9 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
* arguments from the rest of the events.
|
||||
*/
|
||||
gd::String GenerateObjectEventsFunctionContext(
|
||||
const gd::EventsFunctionsExtension &eventsFunctionsExtension,
|
||||
const gd::EventsFunctionsExtension& eventsFunctionsExtension,
|
||||
const gd::EventsBasedObject& eventsBasedObject,
|
||||
const gd::EventsFunction &eventsFunction,
|
||||
const gd::EventsFunction& eventsFunction,
|
||||
const gd::String& onceTriggersVariable,
|
||||
const gd::String& thisObjectName);
|
||||
|
||||
@@ -455,7 +467,8 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
/**
|
||||
* \brief Construct a code generator for the specified containers.
|
||||
*/
|
||||
EventsCodeGenerator(const gd::ProjectScopedContainers& projectScopedContainers);
|
||||
EventsCodeGenerator(
|
||||
const gd::ProjectScopedContainers& projectScopedContainers);
|
||||
virtual ~EventsCodeGenerator();
|
||||
|
||||
gd::String codeNamespace; ///< Optional namespace for the generated code,
|
||||
@@ -467,16 +480,16 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
* to provides access objects, object creation and access to arguments from
|
||||
* the rest of the events.
|
||||
*/
|
||||
gd::String GenerateEventsFunctionContext(
|
||||
const gd::EventsFunctionsExtension &eventsFunctionsExtension,
|
||||
const gd::EventsFunctionsContainer &eventsFunctionsContainer,
|
||||
const gd::EventsFunction &eventsFunction,
|
||||
const gd::String &onceTriggersVariable,
|
||||
gd::String &objectsGettersMap,
|
||||
gd::String &objectArraysMap,
|
||||
gd::String &behaviorNamesMap,
|
||||
const gd::String &thisObjectName = "",
|
||||
const gd::String &thisBehaviorName = "");
|
||||
gd::String GenerateEventsFunctionContext(
|
||||
const gd::EventsFunctionsExtension& eventsFunctionsExtension,
|
||||
const gd::EventsFunctionsContainer& eventsFunctionsContainer,
|
||||
const gd::EventsFunction& eventsFunction,
|
||||
const gd::String& onceTriggersVariable,
|
||||
gd::String& objectsGettersMap,
|
||||
gd::String& objectArraysMap,
|
||||
gd::String& behaviorNamesMap,
|
||||
const gd::String& thisObjectName = "",
|
||||
const gd::String& thisBehaviorName = "");
|
||||
};
|
||||
|
||||
} // namespace gdjs
|
||||
|
@@ -22,9 +22,11 @@ AsyncExtension::AsyncExtension() {
|
||||
gd::AsyncEvent &event = dynamic_cast<gd::AsyncEvent &>(event_);
|
||||
|
||||
// Generate callback code
|
||||
const auto callbackDescriptor = codeGenerator.GenerateCallback(
|
||||
const auto callbackId =
|
||||
gd::String::From(codeGenerator.GenerateSingleUsageUniqueIdFor(
|
||||
event.GetInstruction().GetOriginalInstruction().lock().get())),
|
||||
event.GetInstruction().GetOriginalInstruction().lock().get()));
|
||||
const auto callbackDescriptor = codeGenerator.GenerateCallback(
|
||||
callbackId,
|
||||
parentContext,
|
||||
event.GetActions(),
|
||||
event.HasSubEvents() ? &event.GetSubEvents() : nullptr);
|
||||
@@ -33,10 +35,6 @@ AsyncExtension::AsyncExtension() {
|
||||
"(runtimeScene) => (" + callbackDescriptor.functionName + "(" +
|
||||
callbackDescriptor.argumentsList + "))";
|
||||
|
||||
// Generate the action and store the generated task.
|
||||
const gd::String asyncActionCode = codeGenerator.GenerateActionCode(
|
||||
event.GetInstruction(), parentContext, callbackCallCode);
|
||||
|
||||
// Generate code to backup the objects lists.
|
||||
// Do it after generating the code of the action so that it uses the
|
||||
// same object list as used in the action.
|
||||
@@ -70,6 +68,13 @@ AsyncExtension::AsyncExtension() {
|
||||
", obj);\n";
|
||||
}
|
||||
|
||||
// Generate the action and store the generated task.
|
||||
const gd::String asyncActionCode =
|
||||
codeGenerator.GenerateActionCode(event.GetInstruction(),
|
||||
parentContext,
|
||||
callbackCallCode,
|
||||
callbackId);
|
||||
|
||||
return "{\n" + parentAsyncObjectsListGetter + "{\n" +
|
||||
asyncContextBuilder + asyncActionCode + "}\n" + "}\n";
|
||||
});
|
||||
|
@@ -53,6 +53,7 @@ BaseObjectExtension::BaseObjectExtension() {
|
||||
"runtimeobject.js");
|
||||
objectActions["RotateTowardAngle"].SetFunctionName("rotateTowardAngle");
|
||||
objectActions["RotateTowardPosition"].SetFunctionName("rotateTowardPosition");
|
||||
objectActions["RotateTowardObject"].SetFunctionName("rotateTowardObject");
|
||||
objectActions["ChangeLayer"].SetFunctionName("setLayer");
|
||||
objectConditions["Layer"].SetFunctionName("isOnLayer");
|
||||
objectActions["ChangePlan"]
|
||||
@@ -229,6 +230,8 @@ BaseObjectExtension::BaseObjectExtension() {
|
||||
"gdjs.evtTools.object.pickRandomObject");
|
||||
GetAllConditions()["AjoutHasard"].SetFunctionName(
|
||||
"gdjs.evtTools.object.pickRandomObject");
|
||||
GetAllActions()["PickNearest"].SetFunctionName(
|
||||
"gdjs.evtTools.object.pickNearestObject");
|
||||
GetAllConditions()["PickNearest"].SetFunctionName(
|
||||
"gdjs.evtTools.object.pickNearestObject");
|
||||
|
||||
|
@@ -18,6 +18,9 @@
|
||||
#include "GDCore/IDE/Project/ProjectResourcesCopier.h"
|
||||
#include "GDCore/IDE/Project/SceneResourcesFinder.h"
|
||||
#include "GDCore/IDE/ProjectStripper.h"
|
||||
#include "GDCore/Project/EventsBasedObject.h"
|
||||
#include "GDCore/Project/EventsBasedObjectVariant.h"
|
||||
#include "GDCore/Project/EventsFunctionsExtension.h"
|
||||
#include "GDCore/Project/ExternalEvents.h"
|
||||
#include "GDCore/Project/ExternalLayout.h"
|
||||
#include "GDCore/Project/Layout.h"
|
||||
@@ -47,7 +50,7 @@ Exporter::~Exporter() {}
|
||||
bool Exporter::ExportProjectForPixiPreview(
|
||||
const PreviewExportOptions &options) {
|
||||
ExporterHelper helper(fs, gdjsRoot, codeOutputDir);
|
||||
return helper.ExportProjectForPixiPreview(options);
|
||||
return helper.ExportProjectForPixiPreview(options, includesFiles);
|
||||
}
|
||||
|
||||
bool Exporter::ExportWholePixiProject(const ExportOptions &options) {
|
||||
@@ -80,7 +83,7 @@ bool Exporter::ExportWholePixiProject(const ExportOptions &options) {
|
||||
|
||||
// Prepare the export directory
|
||||
fs.MkDir(exportDir);
|
||||
std::vector<gd::String> includesFiles;
|
||||
includesFiles.clear();
|
||||
std::vector<gd::String> resourcesFiles;
|
||||
|
||||
// Export the resources (before generating events as some resources
|
||||
@@ -98,6 +101,7 @@ bool Exporter::ExportWholePixiProject(const ExportOptions &options) {
|
||||
helper.AddLibsInclude(
|
||||
/*pixiRenderers=*/true,
|
||||
usedExtensionsResult.Has3DObjects(),
|
||||
/*isInGameEditor=*/false,
|
||||
/*includeWebsocketDebuggerClient=*/false,
|
||||
/*includeWindowMessageDebuggerClient=*/false,
|
||||
/*includeMinimalDebuggerClient=*/false,
|
||||
@@ -120,7 +124,7 @@ bool Exporter::ExportWholePixiProject(const ExportOptions &options) {
|
||||
helper.ExportEffectIncludes(exportedProject, includesFiles);
|
||||
|
||||
// Export events
|
||||
if (!helper.ExportEventsCode(exportedProject,
|
||||
if (!helper.ExportScenesEventsCode(exportedProject,
|
||||
codeOutputDir,
|
||||
includesFiles,
|
||||
wholeProjectDiagnosticReport,
|
||||
@@ -130,29 +134,10 @@ bool Exporter::ExportWholePixiProject(const ExportOptions &options) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto projectUsedResources =
|
||||
gd::SceneResourcesFinder::FindProjectResources(exportedProject);
|
||||
std::unordered_map<gd::String, std::set<gd::String>> scenesUsedResources;
|
||||
for (std::size_t layoutIndex = 0;
|
||||
layoutIndex < exportedProject.GetLayoutsCount();
|
||||
layoutIndex++) {
|
||||
auto &layout = exportedProject.GetLayout(layoutIndex);
|
||||
scenesUsedResources[layout.GetName()] =
|
||||
gd::SceneResourcesFinder::FindSceneResources(exportedProject, layout);
|
||||
}
|
||||
|
||||
// Strip the project (*after* generating events as the events may use
|
||||
// stripped things like objects groups...)...
|
||||
gd::ProjectStripper::StripProjectForExport(exportedProject);
|
||||
|
||||
//...and export it
|
||||
gd::SerializerElement noRuntimeGameOptions;
|
||||
helper.ExportProjectData(fs,
|
||||
exportedProject,
|
||||
codeOutputDir + "/data.js",
|
||||
noRuntimeGameOptions,
|
||||
projectUsedResources,
|
||||
scenesUsedResources);
|
||||
helper.ExportProjectData(fs, exportedProject, codeOutputDir + "/data.js",
|
||||
noRuntimeGameOptions);
|
||||
includesFiles.push_back(codeOutputDir + "/data.js");
|
||||
|
||||
helper.ExportIncludesAndLibs(includesFiles, exportDir, false);
|
||||
@@ -215,4 +200,18 @@ bool Exporter::ExportWholePixiProject(const ExportOptions &options) {
|
||||
return true;
|
||||
}
|
||||
|
||||
void Exporter::SerializeProjectData(const gd::Project &project,
|
||||
const PreviewExportOptions &options,
|
||||
gd::SerializerElement &projectDataElement) {
|
||||
ExporterHelper::SerializeProjectData(fs, project, options,
|
||||
projectDataElement);
|
||||
}
|
||||
|
||||
void Exporter::SerializeRuntimeGameOptions(
|
||||
const PreviewExportOptions &options,
|
||||
gd::SerializerElement &runtimeGameOptionsElement) {
|
||||
ExporterHelper::SerializeRuntimeGameOptions(
|
||||
fs, gdjsRoot, options, includesFiles, runtimeGameOptionsElement);
|
||||
}
|
||||
|
||||
} // namespace gdjs
|
||||
|
@@ -16,6 +16,7 @@ class Project;
|
||||
class Layout;
|
||||
class ExternalLayout;
|
||||
class AbstractFileSystem;
|
||||
class SerializerElement;
|
||||
} // namespace gd
|
||||
namespace gdjs {
|
||||
struct PreviewExportOptions;
|
||||
@@ -64,7 +65,33 @@ class Exporter {
|
||||
codeOutputDir = codeOutputDir_;
|
||||
}
|
||||
|
||||
private:
|
||||
/**
|
||||
* \brief Serialize a project without its events to JSON
|
||||
*
|
||||
* \param project The project to be exported
|
||||
* \param options The content of the extra configuration
|
||||
* \param projectDataElement The element where the project data is serialized
|
||||
*/
|
||||
void SerializeProjectData(const gd::Project &project,
|
||||
const PreviewExportOptions &options,
|
||||
gd::SerializerElement &projectDataElement);
|
||||
|
||||
/**
|
||||
* \brief Serialize the content of the extra configuration to store
|
||||
* in gdjs.runtimeGameOptions to JSON
|
||||
*
|
||||
* \warning `ExportProjectForPixiPreview` must be called first to serialize
|
||||
* the list of scripts files.
|
||||
*
|
||||
* \param options The content of the extra configuration
|
||||
* \param runtimeGameOptionsElement The element where the game options are
|
||||
* serialized
|
||||
*/
|
||||
void
|
||||
SerializeRuntimeGameOptions(const PreviewExportOptions &options,
|
||||
gd::SerializerElement &runtimeGameOptionsElement);
|
||||
|
||||
private:
|
||||
gd::AbstractFileSystem&
|
||||
fs; ///< The abstract file system to be used for exportation.
|
||||
gd::String lastError; ///< The last error that occurred.
|
||||
@@ -72,6 +99,8 @@ class Exporter {
|
||||
gdjsRoot; ///< The root directory of GDJS, used to copy runtime files.
|
||||
gd::String codeOutputDir; ///< The directory where JS code is outputted. Will
|
||||
///< be then copied to the final output directory.
|
||||
std::vector<gd::String>
|
||||
includesFiles; ///< The list of scripts files - useful for hot-reloading
|
||||
};
|
||||
|
||||
} // namespace gdjs
|
||||
|
@@ -28,10 +28,13 @@
|
||||
#include "GDCore/IDE/Events/UsedExtensionsFinder.h"
|
||||
#include "GDCore/IDE/ExportedDependencyResolver.h"
|
||||
#include "GDCore/IDE/Project/ProjectResourcesCopier.h"
|
||||
#include "GDCore/IDE/Project/ResourcesMergingHelper.h"
|
||||
#include "GDCore/IDE/Project/SceneResourcesFinder.h"
|
||||
#include "GDCore/IDE/ProjectStripper.h"
|
||||
#include "GDCore/IDE/ResourceExposer.h"
|
||||
#include "GDCore/IDE/SceneNameMangler.h"
|
||||
#include "GDCore/Project/EventsBasedObject.h"
|
||||
#include "GDCore/Project/EventsBasedObjectVariant.h"
|
||||
#include "GDCore/Project/EventsFunctionsExtension.h"
|
||||
#include "GDCore/Project/ExternalEvents.h"
|
||||
#include "GDCore/Project/ExternalLayout.h"
|
||||
@@ -58,7 +61,6 @@ double GetTimeSpent(double previousTime) { return GetTimeNow() - previousTime; }
|
||||
double LogTimeSpent(const gd::String &name, double previousTime) {
|
||||
gd::LogStatus(name + " took " + gd::String::From(GetTimeSpent(previousTime)) +
|
||||
"ms");
|
||||
std::cout << std::endl;
|
||||
return GetTimeNow();
|
||||
}
|
||||
} // namespace
|
||||
@@ -104,128 +106,297 @@ ExporterHelper::ExporterHelper(gd::AbstractFileSystem &fileSystem,
|
||||
: fs(fileSystem), gdjsRoot(gdjsRoot_), codeOutputDir(codeOutputDir_) {};
|
||||
|
||||
bool ExporterHelper::ExportProjectForPixiPreview(
|
||||
const PreviewExportOptions &options) {
|
||||
const PreviewExportOptions &options,
|
||||
std::vector<gd::String> &includesFiles) {
|
||||
|
||||
if (options.isInGameEdition && !options.shouldReloadProjectData &&
|
||||
!options.shouldReloadLibraries && !options.shouldGenerateScenesEventsCode) {
|
||||
gd::LogStatus("Skip project export entirely");
|
||||
return "";
|
||||
}
|
||||
|
||||
double previousTime = GetTimeNow();
|
||||
fs.MkDir(options.exportPath);
|
||||
fs.ClearDir(options.exportPath);
|
||||
std::vector<gd::String> includesFiles;
|
||||
if (options.shouldClearExportFolder) {
|
||||
fs.ClearDir(options.exportPath);
|
||||
}
|
||||
includesFiles.clear();
|
||||
std::vector<gd::String> resourcesFiles;
|
||||
|
||||
// TODO Try to remove side effects to avoid the copy
|
||||
// that destroys the AST in cache.
|
||||
gd::Project exportedProject = options.project;
|
||||
const gd::Project &immutableProject = exportedProject;
|
||||
const gd::Project &immutableProject = options.project;
|
||||
previousTime = LogTimeSpent("Project cloning", previousTime);
|
||||
|
||||
if (options.fullLoadingScreen) {
|
||||
// Use project properties fallback to set empty properties
|
||||
if (exportedProject.GetAuthorIds().empty() &&
|
||||
!options.fallbackAuthorId.empty()) {
|
||||
exportedProject.GetAuthorIds().push_back(options.fallbackAuthorId);
|
||||
}
|
||||
if (exportedProject.GetAuthorUsernames().empty() &&
|
||||
!options.fallbackAuthorUsername.empty()) {
|
||||
exportedProject.GetAuthorUsernames().push_back(
|
||||
options.fallbackAuthorUsername);
|
||||
if (options.isInGameEdition) {
|
||||
if (options.shouldReloadProjectData || options.shouldGenerateScenesEventsCode) {
|
||||
auto projectDirectory = fs.DirNameFrom(exportedProject.GetProjectFile());
|
||||
gd::ResourcesMergingHelper resourcesMergingHelper(
|
||||
exportedProject.GetResourcesManager(), fs);
|
||||
resourcesMergingHelper.SetBaseDirectory(projectDirectory);
|
||||
resourcesMergingHelper.SetShouldUseOriginalAbsoluteFilenames();
|
||||
gd::ResourceExposer::ExposeWholeProjectResources(exportedProject,
|
||||
resourcesMergingHelper);
|
||||
|
||||
previousTime = LogTimeSpent("Resource path resolving", previousTime);
|
||||
}
|
||||
gd::LogStatus("Resource export is skipped");
|
||||
} else {
|
||||
// Most of the time, we skip the logo and minimum duration so that
|
||||
// the preview start as soon as possible.
|
||||
exportedProject.GetLoadingScreen()
|
||||
.ShowGDevelopLogoDuringLoadingScreen(false)
|
||||
.SetMinDuration(0);
|
||||
exportedProject.GetWatermark().ShowGDevelopWatermark(false);
|
||||
// Export resources (*before* generating events as some resources filenames
|
||||
// may be updated)
|
||||
ExportResources(fs, exportedProject, options.exportPath);
|
||||
|
||||
previousTime = LogTimeSpent("Resource export", previousTime);
|
||||
}
|
||||
|
||||
// Export resources (*before* generating events as some resources filenames
|
||||
// may be updated)
|
||||
ExportResources(fs, exportedProject, options.exportPath);
|
||||
|
||||
previousTime = LogTimeSpent("Resource export", previousTime);
|
||||
|
||||
// Compatibility with GD <= 5.0-beta56
|
||||
// Stay compatible with text objects declaring their font as just a filename
|
||||
// without a font resource - by manually adding these resources.
|
||||
AddDeprecatedFontFilesToFontResources(
|
||||
fs, exportedProject.GetResourcesManager(), options.exportPath);
|
||||
// end of compatibility code
|
||||
|
||||
auto usedExtensionsResult =
|
||||
gd::UsedExtensionsFinder::ScanProject(exportedProject);
|
||||
|
||||
// Export engine libraries
|
||||
AddLibsInclude(/*pixiRenderers=*/true,
|
||||
usedExtensionsResult.Has3DObjects(),
|
||||
/*includeWebsocketDebuggerClient=*/
|
||||
!options.websocketDebuggerServerAddress.empty(),
|
||||
/*includeWindowMessageDebuggerClient=*/
|
||||
options.useWindowMessageDebuggerClient,
|
||||
/*includeMinimalDebuggerClient=*/
|
||||
options.useMinimalDebuggerClient,
|
||||
/*includeCaptureManager=*/
|
||||
!options.captureOptions.IsEmpty(),
|
||||
/*includeInAppTutorialMessage*/
|
||||
!options.inAppTutorialMessageInPreview.empty(),
|
||||
immutableProject.GetLoadingScreen().GetGDevelopLogoStyle(),
|
||||
includesFiles);
|
||||
|
||||
// Export files for free function, object and behaviors
|
||||
for (const auto &includeFile : usedExtensionsResult.GetUsedIncludeFiles()) {
|
||||
InsertUnique(includesFiles, includeFile);
|
||||
}
|
||||
for (const auto &requiredFile : usedExtensionsResult.GetUsedRequiredFiles()) {
|
||||
InsertUnique(resourcesFiles, requiredFile);
|
||||
if (options.shouldReloadProjectData || options.shouldGenerateScenesEventsCode) {
|
||||
// Compatibility with GD <= 5.0-beta56
|
||||
// Stay compatible with text objects declaring their font as just a filename
|
||||
// without a font resource - by manually adding these resources.
|
||||
AddDeprecatedFontFilesToFontResources(
|
||||
fs, exportedProject.GetResourcesManager(), options.exportPath);
|
||||
// end of compatibility code
|
||||
}
|
||||
|
||||
// Export effects (after engine libraries as they auto-register themselves to
|
||||
// the engine)
|
||||
ExportEffectIncludes(exportedProject, includesFiles);
|
||||
std::vector<gd::SourceFileMetadata> noUsedSourceFiles;
|
||||
std::vector<gd::SourceFileMetadata> &usedSourceFiles = noUsedSourceFiles;
|
||||
if (options.shouldReloadLibraries) {
|
||||
auto usedExtensionsResult =
|
||||
gd::UsedExtensionsFinder::ScanProject(exportedProject);
|
||||
usedSourceFiles = usedExtensionsResult.GetUsedSourceFiles();
|
||||
|
||||
previousTime = LogTimeSpent("Include files export", previousTime);
|
||||
// Export engine libraries
|
||||
AddLibsInclude(/*pixiRenderers=*/true,
|
||||
/*pixiInThreeRenderers=*/
|
||||
usedExtensionsResult.Has3DObjects(),
|
||||
/*isInGameEdition=*/
|
||||
options.isInGameEdition,
|
||||
/*includeWebsocketDebuggerClient=*/
|
||||
!options.websocketDebuggerServerAddress.empty(),
|
||||
/*includeWindowMessageDebuggerClient=*/
|
||||
options.useWindowMessageDebuggerClient,
|
||||
/*includeMinimalDebuggerClient=*/
|
||||
options.useMinimalDebuggerClient,
|
||||
/*includeCaptureManager=*/
|
||||
!options.captureOptions.IsEmpty(),
|
||||
/*includeInAppTutorialMessage*/
|
||||
!options.inAppTutorialMessageInPreview.empty(),
|
||||
immutableProject.GetLoadingScreen().GetGDevelopLogoStyle(),
|
||||
includesFiles);
|
||||
|
||||
if (!options.projectDataOnlyExport) {
|
||||
// Export files for free function, object and behaviors
|
||||
for (const auto &includeFile : usedExtensionsResult.GetUsedIncludeFiles()) {
|
||||
InsertUnique(includesFiles, includeFile);
|
||||
}
|
||||
for (const auto &requiredFile : usedExtensionsResult.GetUsedRequiredFiles()) {
|
||||
InsertUnique(resourcesFiles, requiredFile);
|
||||
}
|
||||
if (options.isInGameEdition) {
|
||||
// TODO Scan the objects and events of event-based objects
|
||||
// (it could be an alternative method ScanProjectAndEventsBasedObjects in
|
||||
// UsedExtensionsFinder).
|
||||
// This is already done by UsedExtensionsFinder, but maybe it shouldn't.
|
||||
|
||||
// Export all event-based objects because they can be edited even if they
|
||||
// are not used yet.
|
||||
for (std::size_t e = 0;
|
||||
e < exportedProject.GetEventsFunctionsExtensionsCount(); e++) {
|
||||
auto &eventsFunctionsExtension =
|
||||
exportedProject.GetEventsFunctionsExtension(e);
|
||||
|
||||
for (auto &&eventsBasedObjectUniquePtr :
|
||||
eventsFunctionsExtension.GetEventsBasedObjects()
|
||||
.GetInternalVector()) {
|
||||
auto eventsBasedObject = eventsBasedObjectUniquePtr.get();
|
||||
|
||||
auto metadata = gd::MetadataProvider::GetExtensionAndObjectMetadata(
|
||||
exportedProject.GetCurrentPlatform(),
|
||||
gd::PlatformExtension::GetObjectFullType(
|
||||
eventsFunctionsExtension.GetName(),
|
||||
eventsBasedObject->GetName()));
|
||||
for (auto &&includeFile : metadata.GetMetadata().includeFiles) {
|
||||
InsertUnique(includesFiles, includeFile);
|
||||
}
|
||||
for (auto &behaviorType :
|
||||
metadata.GetMetadata().GetDefaultBehaviors()) {
|
||||
auto behaviorMetadata =
|
||||
gd::MetadataProvider::GetExtensionAndBehaviorMetadata(
|
||||
exportedProject.GetCurrentPlatform(), behaviorType);
|
||||
for (auto &&includeFile :
|
||||
behaviorMetadata.GetMetadata().includeFiles) {
|
||||
InsertUnique(includesFiles, includeFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Export effects (after engine libraries as they auto-register themselves to
|
||||
// the engine)
|
||||
ExportEffectIncludes(exportedProject, includesFiles);
|
||||
|
||||
previousTime = LogTimeSpent("Include files export", previousTime);
|
||||
}
|
||||
else {
|
||||
gd::LogStatus("Include files export is skipped");
|
||||
}
|
||||
|
||||
if (options.shouldGenerateScenesEventsCode) {
|
||||
gd::WholeProjectDiagnosticReport &wholeProjectDiagnosticReport =
|
||||
options.project.GetWholeProjectDiagnosticReport();
|
||||
wholeProjectDiagnosticReport.Clear();
|
||||
|
||||
// Generate events code
|
||||
if (!ExportEventsCode(immutableProject,
|
||||
if (!ExportScenesEventsCode(immutableProject,
|
||||
codeOutputDir,
|
||||
includesFiles,
|
||||
wholeProjectDiagnosticReport,
|
||||
true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
previousTime = LogTimeSpent("Events code export", previousTime);
|
||||
}
|
||||
|
||||
auto projectUsedResources =
|
||||
gd::SceneResourcesFinder::FindProjectResources(exportedProject);
|
||||
std::unordered_map<gd::String, std::set<gd::String>> scenesUsedResources;
|
||||
for (std::size_t layoutIndex = 0;
|
||||
layoutIndex < exportedProject.GetLayoutsCount();
|
||||
layoutIndex++) {
|
||||
auto &layout = exportedProject.GetLayout(layoutIndex);
|
||||
scenesUsedResources[layout.GetName()] =
|
||||
gd::SceneResourcesFinder::FindSceneResources(exportedProject, layout);
|
||||
else {
|
||||
gd::LogStatus("Events code export is skipped");
|
||||
}
|
||||
|
||||
// Strip the project (*after* generating events as the events may use stripped
|
||||
// things (objects groups...))
|
||||
gd::ProjectStripper::StripProjectForExport(exportedProject);
|
||||
exportedProject.SetFirstLayout(options.layoutName);
|
||||
if (options.shouldReloadProjectData) {
|
||||
|
||||
if (options.fullLoadingScreen) {
|
||||
// Use project properties fallback to set empty properties
|
||||
if (exportedProject.GetAuthorIds().empty() &&
|
||||
!options.fallbackAuthorId.empty()) {
|
||||
exportedProject.GetAuthorIds().push_back(options.fallbackAuthorId);
|
||||
}
|
||||
if (exportedProject.GetAuthorUsernames().empty() &&
|
||||
!options.fallbackAuthorUsername.empty()) {
|
||||
exportedProject.GetAuthorUsernames().push_back(
|
||||
options.fallbackAuthorUsername);
|
||||
}
|
||||
} else {
|
||||
// Most of the time, we skip the logo and minimum duration so that
|
||||
// the preview start as soon as possible.
|
||||
exportedProject.GetLoadingScreen()
|
||||
.ShowGDevelopLogoDuringLoadingScreen(false)
|
||||
.SetMinDuration(0);
|
||||
exportedProject.GetWatermark().ShowGDevelopWatermark(false);
|
||||
}
|
||||
|
||||
previousTime = LogTimeSpent("Data stripping", previousTime);
|
||||
gd::SerializerElement runtimeGameOptions;
|
||||
ExporterHelper::SerializeRuntimeGameOptions(fs, gdjsRoot, options,
|
||||
includesFiles, runtimeGameOptions);
|
||||
ExportProjectData(fs,
|
||||
exportedProject,
|
||||
codeOutputDir + "/data.js",
|
||||
runtimeGameOptions);
|
||||
includesFiles.push_back(codeOutputDir + "/data.js");
|
||||
|
||||
previousTime = LogTimeSpent("Project data export", previousTime);
|
||||
}
|
||||
else {
|
||||
gd::LogStatus("Project data export is skipped");
|
||||
}
|
||||
|
||||
if (options.shouldReloadLibraries) {
|
||||
// Copy all the dependencies and their source maps
|
||||
ExportIncludesAndLibs(includesFiles, options.exportPath, true);
|
||||
ExportIncludesAndLibs(resourcesFiles, options.exportPath, true);
|
||||
|
||||
// TODO Build a full includesFiles list without actually doing export or
|
||||
// generation.
|
||||
if (options.shouldGenerateScenesEventsCode) {
|
||||
// Create the index file
|
||||
if (!ExportIndexFile(exportedProject, gdjsRoot + "/Runtime/index.html",
|
||||
options.exportPath, includesFiles, usedSourceFiles,
|
||||
options.nonRuntimeScriptsCacheBurst,
|
||||
"gdjs.runtimeGameOptions")) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
previousTime = LogTimeSpent("Include and libs export", previousTime);
|
||||
} else {
|
||||
gd::LogStatus("Include and libs export is skipped");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
gd::String ExporterHelper::ExportProjectData(
|
||||
gd::AbstractFileSystem &fs, gd::Project &project, gd::String filename,
|
||||
const gd::SerializerElement &runtimeGameOptions) {
|
||||
fs.MkDir(fs.DirNameFrom(filename));
|
||||
|
||||
gd::SerializerElement projectDataElement;
|
||||
ExporterHelper::StriptAndSerializeProjectData(project, projectDataElement);
|
||||
|
||||
// Save the project to JSON
|
||||
gd::String output =
|
||||
"gdjs.projectData = " + gd::Serializer::ToJSON(projectDataElement) +
|
||||
";\ngdjs.runtimeGameOptions = " + gd::Serializer::ToJSON(runtimeGameOptions) +
|
||||
";\n";
|
||||
|
||||
if (!fs.WriteToFile(filename, output))
|
||||
return "Unable to write " + filename;
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
void ExporterHelper::SerializeRuntimeGameOptions(
|
||||
gd::AbstractFileSystem &fs, const gd::String &gdjsRoot,
|
||||
const PreviewExportOptions &options,
|
||||
std::vector<gd::String> &includesFiles,
|
||||
gd::SerializerElement &runtimeGameOptions) {
|
||||
// Create the setup options passed to the gdjs.RuntimeGame
|
||||
gd::SerializerElement runtimeGameOptions;
|
||||
runtimeGameOptions.AddChild("isPreview").SetBoolValue(true);
|
||||
if (!options.externalLayoutName.empty()) {
|
||||
runtimeGameOptions.AddChild("injectExternalLayout")
|
||||
.SetValue(options.externalLayoutName);
|
||||
|
||||
auto &initialRuntimeGameStatus =
|
||||
runtimeGameOptions.AddChild("initialRuntimeGameStatus");
|
||||
initialRuntimeGameStatus.AddChild("sceneName")
|
||||
.SetStringValue(options.layoutName);
|
||||
if (options.isInGameEdition) {
|
||||
initialRuntimeGameStatus.AddChild("isInGameEdition").SetBoolValue(true);
|
||||
initialRuntimeGameStatus.AddChild("editorId").SetValue(options.editorId);
|
||||
if (!options.editorCamera3DCameraMode.empty()) {
|
||||
auto &editorCamera3D =
|
||||
initialRuntimeGameStatus.AddChild("editorCamera3D");
|
||||
editorCamera3D.AddChild("cameraMode").SetStringValue(
|
||||
options.editorCamera3DCameraMode);
|
||||
editorCamera3D.AddChild("positionX")
|
||||
.SetDoubleValue(options.editorCamera3DPositionX);
|
||||
editorCamera3D.AddChild("positionY")
|
||||
.SetDoubleValue(options.editorCamera3DPositionY);
|
||||
editorCamera3D.AddChild("positionZ")
|
||||
.SetDoubleValue(options.editorCamera3DPositionZ);
|
||||
editorCamera3D.AddChild("rotationAngle")
|
||||
.SetDoubleValue(options.editorCamera3DRotationAngle);
|
||||
editorCamera3D.AddChild("elevationAngle")
|
||||
.SetDoubleValue(options.editorCamera3DElevationAngle);
|
||||
editorCamera3D.AddChild("distance")
|
||||
.SetDoubleValue(options.editorCamera3DDistance);
|
||||
}
|
||||
}
|
||||
runtimeGameOptions.AddChild("projectDataOnlyExport")
|
||||
.SetBoolValue(options.projectDataOnlyExport);
|
||||
if (!options.externalLayoutName.empty()) {
|
||||
initialRuntimeGameStatus.AddChild("injectedExternalLayoutName")
|
||||
.SetValue(options.externalLayoutName);
|
||||
|
||||
if (options.isInGameEdition) {
|
||||
initialRuntimeGameStatus.AddChild("skipCreatingInstancesFromScene")
|
||||
.SetBoolValue(true);
|
||||
}
|
||||
}
|
||||
if (!options.eventsBasedObjectType.empty()) {
|
||||
initialRuntimeGameStatus.AddChild("eventsBasedObjectType")
|
||||
.SetValue(options.eventsBasedObjectType);
|
||||
initialRuntimeGameStatus.AddChild("eventsBasedObjectVariantName")
|
||||
.SetValue(options.eventsBasedObjectVariantName);
|
||||
}
|
||||
|
||||
runtimeGameOptions.AddChild("shouldReloadLibraries")
|
||||
.SetBoolValue(options.shouldReloadLibraries);
|
||||
runtimeGameOptions.AddChild("shouldGenerateScenesEventsCode")
|
||||
.SetBoolValue(options.shouldGenerateScenesEventsCode);
|
||||
|
||||
runtimeGameOptions.AddChild("nativeMobileApp")
|
||||
.SetBoolValue(options.nativeMobileApp);
|
||||
runtimeGameOptions.AddChild("websocketDebuggerServerAddress")
|
||||
@@ -297,71 +468,93 @@ bool ExporterHelper::ExportProjectForPixiPreview(
|
||||
|
||||
for (const auto &includeFile : includesFiles) {
|
||||
auto hashIt = options.includeFileHashes.find(includeFile);
|
||||
gd::String scriptSrc = GetExportedIncludeFilename(includeFile);
|
||||
gd::String scriptSrc = GetExportedIncludeFilename(fs, gdjsRoot, includeFile);
|
||||
scriptFilesElement.AddChild("scriptFile")
|
||||
.SetStringAttribute("path", scriptSrc)
|
||||
.SetIntAttribute(
|
||||
"hash",
|
||||
hashIt != options.includeFileHashes.end() ? hashIt->second : 0);
|
||||
}
|
||||
|
||||
// Export the project
|
||||
ExportProjectData(fs,
|
||||
exportedProject,
|
||||
codeOutputDir + "/data.js",
|
||||
runtimeGameOptions,
|
||||
projectUsedResources,
|
||||
scenesUsedResources);
|
||||
includesFiles.push_back(codeOutputDir + "/data.js");
|
||||
|
||||
previousTime = LogTimeSpent("Project data export", previousTime);
|
||||
|
||||
// Copy all the dependencies and their source maps
|
||||
ExportIncludesAndLibs(includesFiles, options.exportPath, true);
|
||||
ExportIncludesAndLibs(resourcesFiles, options.exportPath, true);
|
||||
|
||||
// Create the index file
|
||||
if (!ExportIndexFile(exportedProject,
|
||||
gdjsRoot + "/Runtime/index.html",
|
||||
options.exportPath,
|
||||
includesFiles,
|
||||
usedExtensionsResult.GetUsedSourceFiles(),
|
||||
options.nonRuntimeScriptsCacheBurst,
|
||||
"gdjs.runtimeGameOptions"))
|
||||
return false;
|
||||
|
||||
previousTime = LogTimeSpent("Include and libs export", previousTime);
|
||||
return true;
|
||||
}
|
||||
|
||||
gd::String ExporterHelper::ExportProjectData(
|
||||
gd::AbstractFileSystem &fs,
|
||||
gd::Project &project,
|
||||
gd::String filename,
|
||||
const gd::SerializerElement &runtimeGameOptions,
|
||||
std::set<gd::String> &projectUsedResources,
|
||||
std::unordered_map<gd::String, std::set<gd::String>> &scenesUsedResources) {
|
||||
fs.MkDir(fs.DirNameFrom(filename));
|
||||
void ExporterHelper::SerializeProjectData(gd::AbstractFileSystem &fs,
|
||||
const gd::Project &project,
|
||||
const PreviewExportOptions &options,
|
||||
gd::SerializerElement &rootElement) {
|
||||
gd::Project clonedProject = project;
|
||||
|
||||
// Replace all resource file paths with the one used in exported projects.
|
||||
auto projectDirectory = fs.DirNameFrom(project.GetProjectFile());
|
||||
gd::ResourcesMergingHelper resourcesMergingHelper(
|
||||
clonedProject.GetResourcesManager(), fs);
|
||||
resourcesMergingHelper.SetBaseDirectory(projectDirectory);
|
||||
if (options.isInGameEdition) {
|
||||
resourcesMergingHelper.SetShouldUseOriginalAbsoluteFilenames();
|
||||
} else {
|
||||
resourcesMergingHelper.PreserveDirectoriesStructure(false);
|
||||
resourcesMergingHelper.PreserveAbsoluteFilenames(false);
|
||||
}
|
||||
gd::ResourceExposer::ExposeWholeProjectResources(clonedProject,
|
||||
resourcesMergingHelper);
|
||||
|
||||
ExporterHelper::StriptAndSerializeProjectData(clonedProject, rootElement);
|
||||
}
|
||||
|
||||
void ExporterHelper::StriptAndSerializeProjectData(
|
||||
gd::Project &project, gd::SerializerElement &rootElement) {
|
||||
auto projectUsedResources =
|
||||
gd::SceneResourcesFinder::FindProjectResources(project);
|
||||
std::unordered_map<gd::String, std::set<gd::String>> scenesUsedResources;
|
||||
for (std::size_t layoutIndex = 0;
|
||||
layoutIndex < project.GetLayoutsCount(); layoutIndex++) {
|
||||
auto &layout = project.GetLayout(layoutIndex);
|
||||
scenesUsedResources[layout.GetName()] =
|
||||
gd::SceneResourcesFinder::FindSceneResources(project, layout);
|
||||
}
|
||||
std::unordered_map<gd::String, std::set<gd::String>>
|
||||
eventsBasedObjectVariantsUsedResources;
|
||||
for (std::size_t extensionIndex = 0;
|
||||
extensionIndex < project.GetEventsFunctionsExtensionsCount();
|
||||
extensionIndex++) {
|
||||
auto &eventsFunctionsExtension =
|
||||
project.GetEventsFunctionsExtension(extensionIndex);
|
||||
for (auto &&eventsBasedObject :
|
||||
eventsFunctionsExtension.GetEventsBasedObjects().GetInternalVector()) {
|
||||
|
||||
auto eventsBasedObjectType = gd::PlatformExtension::GetObjectFullType(
|
||||
eventsFunctionsExtension.GetName(), eventsBasedObject->GetName());
|
||||
eventsBasedObjectVariantsUsedResources[eventsBasedObjectType] =
|
||||
gd::SceneResourcesFinder::FindEventsBasedObjectVariantResources(
|
||||
project, eventsBasedObject->GetDefaultVariant());
|
||||
|
||||
for (auto &&eventsBasedObjectVariant :
|
||||
eventsBasedObject->GetVariants().GetInternalVector()) {
|
||||
|
||||
auto variantType = gd::PlatformExtension::GetVariantFullType(
|
||||
eventsFunctionsExtension.GetName(), eventsBasedObject->GetName(),
|
||||
eventsBasedObjectVariant->GetName());
|
||||
eventsBasedObjectVariantsUsedResources[variantType] =
|
||||
gd::SceneResourcesFinder::FindEventsBasedObjectVariantResources(
|
||||
project, *eventsBasedObjectVariant);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Strip the project (*after* generating events as the events may use stripped
|
||||
// things (objects groups...))
|
||||
gd::ProjectStripper::StripProjectForExport(project);
|
||||
|
||||
// Save the project to JSON
|
||||
gd::SerializerElement rootElement;
|
||||
project.SerializeTo(rootElement);
|
||||
SerializeUsedResources(
|
||||
rootElement, projectUsedResources, scenesUsedResources);
|
||||
gd::String output =
|
||||
"gdjs.projectData = " + gd::Serializer::ToJSON(rootElement) + ";\n" +
|
||||
"gdjs.runtimeGameOptions = " +
|
||||
gd::Serializer::ToJSON(runtimeGameOptions) + ";\n";
|
||||
|
||||
if (!fs.WriteToFile(filename, output)) return "Unable to write " + filename;
|
||||
|
||||
return "";
|
||||
SerializeUsedResources(rootElement, projectUsedResources, scenesUsedResources,
|
||||
eventsBasedObjectVariantsUsedResources);
|
||||
}
|
||||
|
||||
void ExporterHelper::SerializeUsedResources(
|
||||
gd::SerializerElement &rootElement,
|
||||
std::set<gd::String> &projectUsedResources,
|
||||
std::unordered_map<gd::String, std::set<gd::String>> &scenesUsedResources) {
|
||||
std::unordered_map<gd::String, std::set<gd::String>> &scenesUsedResources,
|
||||
std::unordered_map<gd::String, std::set<gd::String>>
|
||||
&eventsBasedObjectVariantsUsedResources) {
|
||||
auto serializeUsedResources =
|
||||
[](gd::SerializerElement &element,
|
||||
std::set<gd::String> &usedResources) -> void {
|
||||
@@ -385,6 +578,41 @@ void ExporterHelper::SerializeUsedResources(
|
||||
auto &layoutUsedResources = scenesUsedResources[layoutName];
|
||||
serializeUsedResources(layoutElement, layoutUsedResources);
|
||||
}
|
||||
|
||||
auto &extensionsElement = rootElement.GetChild("eventsFunctionsExtensions");
|
||||
for (std::size_t extensionIndex = 0;
|
||||
extensionIndex < extensionsElement.GetChildrenCount();
|
||||
extensionIndex++) {
|
||||
auto &extensionElement = extensionsElement.GetChild(extensionIndex);
|
||||
const auto extensionName = extensionElement.GetStringAttribute("name");
|
||||
|
||||
auto &objectsElement = extensionElement.GetChild("eventsBasedObjects");
|
||||
|
||||
for (std::size_t objectIndex = 0;
|
||||
objectIndex < objectsElement.GetChildrenCount(); objectIndex++) {
|
||||
auto &objectElement = objectsElement.GetChild(objectIndex);
|
||||
const auto objectName = objectElement.GetStringAttribute("name");
|
||||
|
||||
auto eventsBasedObjectType =
|
||||
gd::PlatformExtension::GetObjectFullType(extensionName, objectName);
|
||||
auto &objectUsedResources =
|
||||
eventsBasedObjectVariantsUsedResources[eventsBasedObjectType];
|
||||
serializeUsedResources(objectElement, objectUsedResources);
|
||||
|
||||
auto &variantsElement = objectElement.GetChild("variants");
|
||||
for (std::size_t variantIndex = 0;
|
||||
variantIndex < variantsElement.GetChildrenCount(); variantIndex++) {
|
||||
auto &variantElement = variantsElement.GetChild(variantIndex);
|
||||
const auto variantName = variantElement.GetStringAttribute("name");
|
||||
|
||||
auto variantType = gd::PlatformExtension::GetVariantFullType(
|
||||
extensionName, objectName, variantName);
|
||||
auto &variantUsedResources =
|
||||
eventsBasedObjectVariantsUsedResources[variantType];
|
||||
serializeUsedResources(variantElement, variantUsedResources);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool ExporterHelper::ExportIndexFile(
|
||||
@@ -775,7 +1003,7 @@ bool ExporterHelper::CompleteIndexFile(
|
||||
gd::String codeFilesIncludes;
|
||||
for (auto &include : includesFiles) {
|
||||
gd::String scriptSrc =
|
||||
GetExportedIncludeFilename(include, nonRuntimeScriptsCacheBurst);
|
||||
GetExportedIncludeFilename(fs, gdjsRoot, include, nonRuntimeScriptsCacheBurst);
|
||||
|
||||
// Sanity check if the file exists - if not skip it to avoid
|
||||
// including it in the list of scripts.
|
||||
@@ -801,6 +1029,7 @@ bool ExporterHelper::CompleteIndexFile(
|
||||
|
||||
void ExporterHelper::AddLibsInclude(bool pixiRenderers,
|
||||
bool pixiInThreeRenderers,
|
||||
bool isInGameEdition,
|
||||
bool includeWebsocketDebuggerClient,
|
||||
bool includeWindowMessageDebuggerClient,
|
||||
bool includeMinimalDebuggerClient,
|
||||
@@ -844,6 +1073,7 @@ void ExporterHelper::AddLibsInclude(bool pixiRenderers,
|
||||
InsertUnique(includesFiles, "CustomRuntimeObjectInstanceContainer.js");
|
||||
InsertUnique(includesFiles, "CustomRuntimeObject.js");
|
||||
InsertUnique(includesFiles, "CustomRuntimeObject2D.js");
|
||||
InsertUnique(includesFiles, "indexeddb.js");
|
||||
|
||||
// Common includes for events only.
|
||||
InsertUnique(includesFiles, "events-tools/commontools.js");
|
||||
@@ -877,6 +1107,7 @@ void ExporterHelper::AddLibsInclude(bool pixiRenderers,
|
||||
InsertUnique(includesFiles, "debugger-client/hot-reloader.js");
|
||||
InsertUnique(includesFiles, "debugger-client/abstract-debugger-client.js");
|
||||
InsertUnique(includesFiles, "debugger-client/InGameDebugger.js");
|
||||
InsertUnique(includesFiles, "InGameEditor/InGameEditor.js");
|
||||
}
|
||||
if (includeWebsocketDebuggerClient) {
|
||||
InsertUnique(includesFiles, "debugger-client/websocket-debugger-client.js");
|
||||
@@ -889,14 +1120,16 @@ void ExporterHelper::AddLibsInclude(bool pixiRenderers,
|
||||
InsertUnique(includesFiles, "debugger-client/minimal-debugger-client.js");
|
||||
}
|
||||
|
||||
if (pixiInThreeRenderers) {
|
||||
if (pixiInThreeRenderers || isInGameEdition) {
|
||||
InsertUnique(includesFiles, "pixi-renderers/three.js");
|
||||
InsertUnique(includesFiles, "pixi-renderers/ThreeAddons.js");
|
||||
InsertUnique(includesFiles, "pixi-renderers/draco/gltf/draco_decoder.wasm");
|
||||
InsertUnique(includesFiles,
|
||||
"pixi-renderers/draco/gltf/draco_wasm_wrapper.js");
|
||||
// Extensions in JS may use it.
|
||||
InsertUnique(includesFiles, "Extensions/3D/Scene3DTools.js");
|
||||
}
|
||||
if (pixiRenderers) {
|
||||
if (pixiRenderers || isInGameEdition) {
|
||||
InsertUnique(includesFiles, "pixi-renderers/pixi.js");
|
||||
InsertUnique(includesFiles, "pixi-renderers/pixi-filters-tools.js");
|
||||
InsertUnique(includesFiles, "pixi-renderers/runtimegame-pixi-renderer.js");
|
||||
@@ -920,7 +1153,12 @@ void ExporterHelper::AddLibsInclude(bool pixiRenderers,
|
||||
includesFiles,
|
||||
"fontfaceobserver-font-manager/fontfaceobserver-font-manager.js");
|
||||
}
|
||||
if (pixiInThreeRenderers) {
|
||||
if (isInGameEdition) {
|
||||
// `InGameEditor` uses the `is3D` function.
|
||||
InsertUnique(includesFiles, "Extensions/3D/Base3DBehavior.js");
|
||||
InsertUnique(includesFiles, "Extensions/3D/HemisphereLight.js");
|
||||
}
|
||||
if (pixiInThreeRenderers || isInGameEdition) {
|
||||
InsertUnique(includesFiles, "Extensions/3D/A_RuntimeObject3D.js");
|
||||
InsertUnique(includesFiles, "Extensions/3D/A_RuntimeObject3DRenderer.js");
|
||||
InsertUnique(includesFiles, "Extensions/3D/CustomRuntimeObject3D.js");
|
||||
@@ -958,7 +1196,7 @@ bool ExporterHelper::ExportEffectIncludes(
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ExporterHelper::ExportEventsCode(
|
||||
bool ExporterHelper::ExportScenesEventsCode(
|
||||
const gd::Project &project,
|
||||
gd::String outputDir,
|
||||
std::vector<gd::String> &includesFiles,
|
||||
@@ -994,6 +1232,7 @@ bool ExporterHelper::ExportEventsCode(
|
||||
}
|
||||
|
||||
gd::String ExporterHelper::GetExportedIncludeFilename(
|
||||
gd::AbstractFileSystem &fs, const gd::String &gdjsRoot,
|
||||
const gd::String &include, unsigned int nonRuntimeScriptsCacheBurst) {
|
||||
auto addSearchParameterToUrl = [](const gd::String &url,
|
||||
const gd::String &urlEncodedParameterName,
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user