mirror of
https://github.com/4ian/GDevelop.git
synced 2025-10-15 10:19:04 +00:00
Compare commits
1 Commits
a05b0cd0ef
...
fix/subscr
Author | SHA1 | Date | |
---|---|---|---|
![]() |
59c48d52f7 |
@@ -42,19 +42,15 @@ 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 "";
|
||||
}
|
||||
@@ -91,23 +87,20 @@ 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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -131,8 +124,7 @@ 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;
|
||||
@@ -203,8 +195,7 @@ 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;
|
||||
@@ -257,8 +248,7 @@ 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;
|
||||
@@ -333,97 +323,83 @@ 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);
|
||||
}
|
||||
|
||||
gd::EventsCodeGenerator::CheckBehaviorParameters(condition, instrInfos);
|
||||
// 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. */";
|
||||
}
|
||||
}
|
||||
}
|
||||
bool isAnyBehaviorMissing =
|
||||
gd::EventsCodeGenerator::CheckBehaviorParameters(condition, instrInfos);
|
||||
if (isAnyBehaviorMissing) {
|
||||
return "/* Missing behavior - skipped. */";
|
||||
}
|
||||
|
||||
if (instrInfos.IsObjectInstruction()) {
|
||||
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) {
|
||||
@@ -435,14 +411,15 @@ 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();
|
||||
}
|
||||
@@ -511,50 +488,31 @@ gd::String EventsCodeGenerator::GenerateConditionsListCode(
|
||||
return outputCode;
|
||||
}
|
||||
|
||||
bool EventsCodeGenerator::CheckBehaviorParameters(
|
||||
const gd::Instruction& instruction,
|
||||
const gd::InstructionMetadata& instrInfos) {
|
||||
bool isAnyBehaviorMissing = false;
|
||||
gd::ParameterMetadataTools::IterateOverParametersWithIndex(
|
||||
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) {
|
||||
void EventsCodeGenerator::CheckBehaviorParameters(
|
||||
const gd::Instruction &instruction,
|
||||
const gd::InstructionMetadata &instrInfos) {
|
||||
gd::ParameterMetadataTools::IterateOverParameters(
|
||||
instruction.GetParameters(), instrInfos.parameters,
|
||||
[this](const gd::ParameterMetadata ¶meterMetadata,
|
||||
const gd::Expression ¶meterValue,
|
||||
const gd::String &lastObjectName) {
|
||||
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 =
|
||||
instrInfos.GetParameter(lastObjectIndex);
|
||||
// Event functions crash if some objects in a group are missing
|
||||
// the required behaviors, since they lose reference to the original
|
||||
// objects. Missing behaviors are considered "fatal" only for
|
||||
// ObjectList parameters, in order to minimize side effects on
|
||||
// built-in functions.
|
||||
if (objectParameterMetadata.GetType() == "objectList") {
|
||||
isAnyBehaviorMissing = true;
|
||||
}
|
||||
gd::ProjectDiagnostic projectDiagnostic(
|
||||
gd::ProjectDiagnostic::ErrorType::MissingBehavior,
|
||||
"",
|
||||
actualBehaviorType,
|
||||
expectedBehaviorType,
|
||||
lastObjectName);
|
||||
gd::ProjectDiagnostic::ErrorType::MissingBehavior, "",
|
||||
actualBehaviorType, expectedBehaviorType, lastObjectName);
|
||||
if (diagnosticReport) diagnosticReport->Add(projectDiagnostic);
|
||||
}
|
||||
}
|
||||
});
|
||||
return isAnyBehaviorMissing;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -563,8 +521,7 @@ bool EventsCodeGenerator::CheckBehaviorParameters(
|
||||
gd::String EventsCodeGenerator::GenerateActionCode(
|
||||
gd::Instruction& action,
|
||||
EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName,
|
||||
const gd::String& optionalAsyncCallbackId) {
|
||||
const gd::String& optionalAsyncCallbackName) {
|
||||
gd::String actionCode;
|
||||
|
||||
const gd::InstructionMetadata& instrInfos =
|
||||
@@ -589,51 +546,39 @@ 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);
|
||||
}
|
||||
|
||||
gd::EventsCodeGenerator::CheckBehaviorParameters(action, instrInfos);
|
||||
// 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. */";
|
||||
}
|
||||
}
|
||||
}
|
||||
bool isAnyBehaviorMissing =
|
||||
gd::EventsCodeGenerator::CheckBehaviorParameters(action, instrInfos);
|
||||
if (isAnyBehaviorMissing) {
|
||||
return "/* Missing behavior - skipped. */";
|
||||
}
|
||||
|
||||
// Call free function first if available
|
||||
if (instrInfos.IsObjectInstruction()) {
|
||||
@@ -641,46 +586,43 @@ 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,
|
||||
optionalAsyncCallbackId);
|
||||
// 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);
|
||||
|
||||
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);
|
||||
@@ -692,15 +634,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,
|
||||
optionalAsyncCallbackId);
|
||||
actionCode +=
|
||||
GenerateBehaviorAction(realObjects[i],
|
||||
behaviorName,
|
||||
autoInfo,
|
||||
functionCallName,
|
||||
arguments,
|
||||
instrInfos,
|
||||
context,
|
||||
optionalAsyncCallbackName);
|
||||
|
||||
context.SetNoCurrentObject();
|
||||
}
|
||||
@@ -712,8 +654,7 @@ gd::String EventsCodeGenerator::GenerateActionCode(
|
||||
arguments,
|
||||
instrInfos,
|
||||
context,
|
||||
optionalAsyncCallbackName,
|
||||
optionalAsyncCallbackId);
|
||||
optionalAsyncCallbackName);
|
||||
}
|
||||
|
||||
return actionCode;
|
||||
@@ -726,8 +667,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());
|
||||
|
||||
@@ -738,12 +679,8 @@ gd::String EventsCodeGenerator::GenerateAnyOrSceneVariableGetter(
|
||||
: "scenevar";
|
||||
|
||||
return gd::ExpressionCodeGenerator::GenerateExpressionCode(
|
||||
*this,
|
||||
context,
|
||||
variableParameterType,
|
||||
variableExpression.GetPlainString(),
|
||||
"",
|
||||
"AllowUndeclaredVariable");
|
||||
*this, context, variableParameterType,
|
||||
variableExpression.GetPlainString(), "", "AllowUndeclaredVariable");
|
||||
}
|
||||
|
||||
const EventsCodeGenerator::CallbackDescriptor
|
||||
@@ -790,11 +727,6 @@ 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
|
||||
@@ -837,7 +769,7 @@ gd::String EventsCodeGenerator::GenerateActionsListCode(
|
||||
} else {
|
||||
outputCode += actionCode;
|
||||
}
|
||||
outputCode += "}\n";
|
||||
outputCode += "}";
|
||||
}
|
||||
|
||||
return outputCode;
|
||||
@@ -854,28 +786,13 @@ 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.
|
||||
@@ -910,8 +827,7 @@ 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") {
|
||||
@@ -1061,8 +977,7 @@ 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
|
||||
@@ -1187,7 +1102,7 @@ gd::String EventsCodeGenerator::GenerateFreeCondition(
|
||||
instrInfos.codeExtraInformation.functionCallName);
|
||||
} else {
|
||||
predicate = instrInfos.codeExtraInformation.functionCallName + "(" +
|
||||
GenerateArgumentsList(arguments, 0) + ")";
|
||||
GenerateArgumentsList(arguments, 0) + ")";
|
||||
}
|
||||
|
||||
// Add logical not if needed
|
||||
@@ -1231,7 +1146,7 @@ gd::String EventsCodeGenerator::GenerateObjectCondition(
|
||||
instrInfos, arguments, objectFunctionCallNamePart, 1);
|
||||
} else {
|
||||
predicate = objectFunctionCallNamePart + "(" +
|
||||
GenerateArgumentsList(arguments, 1) + ")";
|
||||
GenerateArgumentsList(arguments, 1) + ")";
|
||||
}
|
||||
if (conditionInverted) predicate = GenerateNegatedPredicate(predicate);
|
||||
|
||||
@@ -1263,20 +1178,18 @@ 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& optionalAsyncCallbackId) {
|
||||
const gd::String& optionalAsyncCallbackName) {
|
||||
// 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)) {
|
||||
@@ -1289,19 +1202,23 @@ gd::String EventsCodeGenerator::GenerateFreeAction(
|
||||
instrInfos.codeExtraInformation.optionalAssociatedInstruction);
|
||||
else if (instrInfos.codeExtraInformation.accessType ==
|
||||
gd::InstructionMetadata::ExtraInformation::Mutators)
|
||||
call = GenerateMutatorCall(instrInfos, arguments, functionCallName);
|
||||
else
|
||||
call =
|
||||
GenerateCompoundOperatorCall(instrInfos, arguments, functionCallName);
|
||||
GenerateMutatorCall(instrInfos,
|
||||
arguments,
|
||||
functionCallName);
|
||||
else
|
||||
call = GenerateCompoundOperatorCall(
|
||||
instrInfos,
|
||||
arguments,
|
||||
functionCallName);
|
||||
} else {
|
||||
call = functionCallName + "(" + GenerateArgumentsList(arguments) + ")";
|
||||
call = functionCallName + "(" +
|
||||
GenerateArgumentsList(arguments) + ")";
|
||||
}
|
||||
|
||||
if (!optionalAsyncCallbackName.empty() && !optionalAsyncCallbackId.empty()) {
|
||||
if (!optionalAsyncCallbackName.empty())
|
||||
call = "runtimeScene.getAsyncTasksManager().addTask(" + call + ", " +
|
||||
optionalAsyncCallbackName + ", " + optionalAsyncCallbackId +
|
||||
", asyncObjectsList)";
|
||||
}
|
||||
optionalAsyncCallbackName + ")";
|
||||
|
||||
return call + ";\n";
|
||||
}
|
||||
@@ -1313,8 +1230,7 @@ gd::String EventsCodeGenerator::GenerateObjectAction(
|
||||
const std::vector<gd::String>& arguments,
|
||||
const gd::InstructionMetadata& instrInfos,
|
||||
gd::EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName,
|
||||
const gd::String& optionalAsyncCallbackId) {
|
||||
const gd::String& optionalAsyncCallbackName) {
|
||||
// Create call
|
||||
gd::String call;
|
||||
if ((instrInfos.codeExtraInformation.type == "number" ||
|
||||
@@ -1355,8 +1271,7 @@ gd::String EventsCodeGenerator::GenerateBehaviorAction(
|
||||
const std::vector<gd::String>& arguments,
|
||||
const gd::InstructionMetadata& instrInfos,
|
||||
gd::EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName,
|
||||
const gd::String& optionalAsyncCallbackId) {
|
||||
const gd::String& optionalAsyncCallbackName) {
|
||||
// Create call
|
||||
gd::String call;
|
||||
if ((instrInfos.codeExtraInformation.type == "number" ||
|
||||
@@ -1371,13 +1286,17 @@ 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 + "\"" +
|
||||
@@ -1432,47 +1351,42 @@ 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& parameter) {
|
||||
return "getParameter" + parameter.GetName() + "()";
|
||||
}
|
||||
const gd::ParameterMetadata ¶meter) {
|
||||
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),
|
||||
@@ -1481,7 +1395,7 @@ EventsCodeGenerator::EventsCodeGenerator(const gd::Project& project_,
|
||||
maxCustomConditionsDepth(0),
|
||||
maxConditionsListsSize(0),
|
||||
eventsListNextUniqueId(0),
|
||||
diagnosticReport(nullptr) {};
|
||||
diagnosticReport(nullptr){};
|
||||
|
||||
EventsCodeGenerator::EventsCodeGenerator(
|
||||
const gd::Platform& platform_,
|
||||
@@ -1496,6 +1410,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,8 +160,7 @@ class GD_CORE_API EventsCodeGenerator {
|
||||
gd::String GenerateActionCode(
|
||||
gd::Instruction& action,
|
||||
EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName = "",
|
||||
const gd::String& optionalAsyncCallbackId = "");
|
||||
const gd::String& optionalAsyncCallbackName = "");
|
||||
|
||||
struct CallbackDescriptor {
|
||||
CallbackDescriptor(const gd::String functionName_,
|
||||
@@ -169,7 +168,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.
|
||||
*/
|
||||
@@ -339,9 +338,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() {
|
||||
@@ -388,7 +387,9 @@ 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
|
||||
@@ -512,16 +513,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);
|
||||
|
||||
@@ -642,16 +643,16 @@ class GD_CORE_API EventsCodeGenerator {
|
||||
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& parameter);
|
||||
virtual gd::String
|
||||
GenerateParameterGetterWithoutCasting(const gd::ParameterMetadata ¶meter);
|
||||
|
||||
/**
|
||||
* \brief Generate the code to reference an object which is
|
||||
@@ -768,8 +769,7 @@ class GD_CORE_API EventsCodeGenerator {
|
||||
const std::vector<gd::String>& arguments,
|
||||
const gd::InstructionMetadata& instrInfos,
|
||||
gd::EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName = "",
|
||||
const gd::String& optionalAsyncCallbackId = "");
|
||||
const gd::String& optionalAsyncCallbackName = "");
|
||||
|
||||
virtual gd::String GenerateObjectAction(
|
||||
const gd::String& objectName,
|
||||
@@ -778,8 +778,7 @@ class GD_CORE_API EventsCodeGenerator {
|
||||
const std::vector<gd::String>& arguments,
|
||||
const gd::InstructionMetadata& instrInfos,
|
||||
gd::EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName = "",
|
||||
const gd::String& optionalAsyncCallbackId = "");
|
||||
const gd::String& optionalAsyncCallbackName = "");
|
||||
|
||||
virtual gd::String GenerateBehaviorAction(
|
||||
const gd::String& objectName,
|
||||
@@ -789,8 +788,7 @@ class GD_CORE_API EventsCodeGenerator {
|
||||
const std::vector<gd::String>& arguments,
|
||||
const gd::InstructionMetadata& instrInfos,
|
||||
gd::EventsCodeGenerationContext& context,
|
||||
const gd::String& optionalAsyncCallbackName = "",
|
||||
const gd::String& optionalAsyncCallbackId = "");
|
||||
const gd::String& optionalAsyncCallbackName = "");
|
||||
|
||||
gd::String GenerateRelationalOperatorCall(
|
||||
const gd::InstructionMetadata& instrInfos,
|
||||
@@ -839,8 +837,9 @@ class GD_CORE_API EventsCodeGenerator {
|
||||
virtual gd::String GenerateGetBehaviorNameCode(
|
||||
const gd::String& behaviorName);
|
||||
|
||||
bool CheckBehaviorParameters(const gd::Instruction& instruction,
|
||||
const gd::InstructionMetadata& instrInfos);
|
||||
void CheckBehaviorParameters(
|
||||
const gd::Instruction &instruction,
|
||||
const gd::InstructionMetadata &instrInfos);
|
||||
|
||||
const gd::Platform& platform; ///< The platform being used.
|
||||
|
||||
@@ -877,3 +876,4 @@ class GD_CORE_API EventsCodeGenerator {
|
||||
};
|
||||
|
||||
} // namespace gd
|
||||
|
||||
|
@@ -293,25 +293,6 @@ 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"),
|
||||
@@ -1636,7 +1617,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
|
||||
extension
|
||||
.AddAction("AjoutObjConcern",
|
||||
_("Pick all object instances"),
|
||||
_("Pick all 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 "
|
||||
@@ -1650,34 +1631,20 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
.MarkAsAdvanced();
|
||||
|
||||
extension
|
||||
.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")
|
||||
.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")
|
||||
.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",
|
||||
@@ -1727,12 +1694,11 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
extension
|
||||
.AddCondition(
|
||||
"AjoutObjConcern",
|
||||
_("Pick all object instances"),
|
||||
_("Pick all instances of the specified object(s). When you "
|
||||
"pick all instances, "
|
||||
_("Pick all objects"),
|
||||
_("Pick all the specified objects. When you pick all objects, "
|
||||
"the next conditions and actions of this event work on all "
|
||||
"of them."),
|
||||
_("Pick all instances of _PARAM1_"),
|
||||
_("Pick all _PARAM1_ objects"),
|
||||
_("Objects"),
|
||||
"res/conditions/add24.png",
|
||||
"res/conditions/add.png")
|
||||
@@ -1741,15 +1707,16 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
.MarkAsAdvanced();
|
||||
|
||||
extension
|
||||
.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")
|
||||
.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")
|
||||
.AddCodeOnlyParameter("objectsContext", "")
|
||||
.AddParameter("objectList", _("Object"))
|
||||
.MarkAsSimple();
|
||||
@@ -1758,9 +1725,9 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
.AddCondition(
|
||||
"PickNearest",
|
||||
_("Pick nearest object"),
|
||||
_("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 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 _PARAM0_ that is nearest to _PARAM1_;_PARAM2_"),
|
||||
_("Objects"),
|
||||
"res/conditions/distance24.png",
|
||||
|
@@ -18,21 +18,21 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsAnimatableExtension(
|
||||
gd::PlatformExtension& extension) {
|
||||
extension
|
||||
.SetExtensionInformation("AnimatableCapability",
|
||||
_("Objects with animations"),
|
||||
_("Actions and conditions for objects having animations (sprite, 3D models...)."),
|
||||
_("Animatable capability"),
|
||||
_("Animate objects."),
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetExtensionHelpPath("/objects");
|
||||
extension.AddInstructionOrExpressionGroupMetadata(_("Objects with animations"))
|
||||
extension.AddInstructionOrExpressionGroupMetadata(_("Animatable capability"))
|
||||
.SetIcon("res/actions/animation24.png");
|
||||
extension.AddInstructionOrExpressionGroupMetadata(_("Animations and images"))
|
||||
.SetIcon("res/actions/animation24.png");
|
||||
|
||||
gd::BehaviorMetadata& aut = extension.AddBehavior(
|
||||
"AnimatableBehavior",
|
||||
_("Objects with animations"),
|
||||
_("Animatable capability"),
|
||||
"Animation",
|
||||
_("Actions and conditions for objects having animations (sprite, 3D models...).."),
|
||||
_("Animate objects."),
|
||||
"",
|
||||
"res/actions/animation24.png",
|
||||
"AnimatableBehavior",
|
||||
|
@@ -18,8 +18,8 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsEffectExtension(
|
||||
gd::PlatformExtension& extension) {
|
||||
extension
|
||||
.SetExtensionInformation("EffectCapability",
|
||||
_("Objects with effects"),
|
||||
_("Actions/conditions to enable/disable and change parameters of visual effects applied on objects."),
|
||||
_("Effect capability"),
|
||||
_("Apply visual effects to objects."),
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetExtensionHelpPath("/objects");
|
||||
@@ -28,9 +28,9 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsEffectExtension(
|
||||
|
||||
gd::BehaviorMetadata& aut = extension.AddBehavior(
|
||||
"EffectBehavior",
|
||||
_("Objects with effects"),
|
||||
_("Effect capability"),
|
||||
"Effect",
|
||||
_("Actions/conditions to enable/disable and change parameters of visual effects applied on objects."),
|
||||
_("Apply visual effects to objects."),
|
||||
"",
|
||||
"res/actions/effect_black.svg",
|
||||
"EffectBehavior",
|
||||
|
@@ -18,8 +18,8 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsFlippableExtension(
|
||||
gd::PlatformExtension& extension) {
|
||||
extension
|
||||
.SetExtensionInformation("FlippableCapability",
|
||||
_("Flippable objects"),
|
||||
_("Actions/conditions for objects which can be flipped horizontally or vertically."),
|
||||
_("Flippable capability"),
|
||||
_("Flip objects."),
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetExtensionHelpPath("/objects");
|
||||
@@ -28,9 +28,9 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsFlippableExtension(
|
||||
|
||||
gd::BehaviorMetadata& aut = extension.AddBehavior(
|
||||
"FlippableBehavior",
|
||||
_("Flippable objects"),
|
||||
_("Flippable capability"),
|
||||
"Flippable",
|
||||
_("Actions/conditions for objects which can be flipped horizontally or vertically."),
|
||||
_("Flip objects."),
|
||||
"",
|
||||
"res/actions/flipX24.png",
|
||||
"FlippableBehavior",
|
||||
|
@@ -18,30 +18,27 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsOpacityExtension(
|
||||
gd::PlatformExtension& extension) {
|
||||
extension
|
||||
.SetExtensionInformation("OpacityCapability",
|
||||
_("Objects with opacity"),
|
||||
_("Action/condition/expression to change or "
|
||||
"check the opacity of an object (0-255)."),
|
||||
_("Opacity capability"),
|
||||
_("Change the object opacity."),
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetExtensionHelpPath("/objects");
|
||||
extension.AddInstructionOrExpressionGroupMetadata(_("Objects with opacity"))
|
||||
extension.AddInstructionOrExpressionGroupMetadata(_("Opacity capability"))
|
||||
.SetIcon("res/actions/opacity24.png");
|
||||
extension.AddInstructionOrExpressionGroupMetadata(_("Visibility"))
|
||||
.SetIcon("res/actions/opacity24.png");
|
||||
|
||||
gd::BehaviorMetadata& aut =
|
||||
extension
|
||||
.AddBehavior("OpacityBehavior",
|
||||
_("Objects with opacity"),
|
||||
"Opacity",
|
||||
_("Action/condition/expression to change or check the "
|
||||
"opacity of an object (0-255)."),
|
||||
"",
|
||||
"res/actions/opacity24.png",
|
||||
"OpacityBehavior",
|
||||
std::make_shared<gd::Behavior>(),
|
||||
std::make_shared<gd::BehaviorsSharedData>())
|
||||
.SetHidden();
|
||||
gd::BehaviorMetadata& aut = extension.AddBehavior(
|
||||
"OpacityBehavior",
|
||||
_("Opacity capability"),
|
||||
"Opacity",
|
||||
_("Change the object opacity."),
|
||||
"",
|
||||
"res/actions/opacity24.png",
|
||||
"OpacityBehavior",
|
||||
std::make_shared<gd::Behavior>(),
|
||||
std::make_shared<gd::BehaviorsSharedData>())
|
||||
.SetHidden();
|
||||
|
||||
aut.AddExpressionAndConditionAndAction(
|
||||
"number",
|
||||
@@ -55,9 +52,8 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsOpacityExtension(
|
||||
.AddParameter("object", _("Object"))
|
||||
.AddParameter("behavior", _("Behavior"), "OpacityBehavior")
|
||||
.UseStandardParameters(
|
||||
"number",
|
||||
gd::ParameterOptions::MakeNewOptions().SetDescription(
|
||||
_("Opacity (0-255)")))
|
||||
"number", gd::ParameterOptions::MakeNewOptions().SetDescription(
|
||||
_("Opacity (0-255)")))
|
||||
.SetFunctionName("setOpacity")
|
||||
.SetGetter("getOpacity");
|
||||
aut.GetAllExpressions()["Value"].SetGroup("");
|
||||
|
@@ -16,13 +16,11 @@ namespace gd {
|
||||
void GD_CORE_API BuiltinExtensionsImplementer::ImplementsResizableExtension(
|
||||
gd::PlatformExtension &extension) {
|
||||
extension
|
||||
.SetExtensionInformation(
|
||||
"ResizableCapability",
|
||||
_("Resizable objects"),
|
||||
_("Change or compare the size (width/height) of an object which can "
|
||||
"be resized (i.e: most objects)."),
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetExtensionInformation("ResizableCapability",
|
||||
_("Resizable capability"),
|
||||
_("Change the object dimensions."),
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetExtensionHelpPath("/objects");
|
||||
extension.AddInstructionOrExpressionGroupMetadata(_("Size")).SetIcon(
|
||||
"res/actions/scale24_black.png");
|
||||
@@ -30,10 +28,9 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsResizableExtension(
|
||||
gd::BehaviorMetadata &aut =
|
||||
extension
|
||||
.AddBehavior("ResizableBehavior",
|
||||
_("Resizable objects"),
|
||||
_("Resizable capability"),
|
||||
"Resizable",
|
||||
_("Change or compare the size (width/height) of an "
|
||||
"object which can be resized (i.e: most objects)."),
|
||||
_("Change the object dimensions."),
|
||||
"",
|
||||
"res/actions/scale24_black.png",
|
||||
"ResizableBehavior",
|
||||
|
@@ -18,30 +18,27 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsScalableExtension(
|
||||
gd::PlatformExtension& extension) {
|
||||
extension
|
||||
.SetExtensionInformation("ScalableCapability",
|
||||
_("Scalable objects"),
|
||||
_("Actions/conditions/expression to change or "
|
||||
"check the scale of an object (default: 1)."),
|
||||
_("Scalable capability"),
|
||||
_("Change the object scale."),
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetExtensionHelpPath("/objects");
|
||||
extension.AddInstructionOrExpressionGroupMetadata(_("Scalable objects"))
|
||||
extension.AddInstructionOrExpressionGroupMetadata(_("Scalable capability"))
|
||||
.SetIcon("res/actions/scale24_black.png");
|
||||
extension.AddInstructionOrExpressionGroupMetadata(_("Size"))
|
||||
.SetIcon("res/actions/scale24_black.png");
|
||||
extension.AddInstructionOrExpressionGroupMetadata(_("Size")).SetIcon(
|
||||
"res/actions/scale24_black.png");
|
||||
|
||||
gd::BehaviorMetadata& aut =
|
||||
extension
|
||||
.AddBehavior("ScalableBehavior",
|
||||
_("Scalable objects"),
|
||||
"Scale",
|
||||
_("Actions/conditions/expression to change or check the "
|
||||
"scale of an object (default: 1)."),
|
||||
"",
|
||||
"res/actions/scale24_black.png",
|
||||
"ResizableBehavior",
|
||||
std::make_shared<gd::Behavior>(),
|
||||
std::make_shared<gd::BehaviorsSharedData>())
|
||||
.SetHidden();
|
||||
gd::BehaviorMetadata& aut = extension.AddBehavior(
|
||||
"ScalableBehavior",
|
||||
_("Scalable capability"),
|
||||
"Scale",
|
||||
_("Change the object scale."),
|
||||
"",
|
||||
"res/actions/scale24_black.png",
|
||||
"ResizableBehavior",
|
||||
std::make_shared<gd::Behavior>(),
|
||||
std::make_shared<gd::BehaviorsSharedData>())
|
||||
.SetHidden();
|
||||
|
||||
aut.AddExpressionAndConditionAndAction(
|
||||
"number",
|
||||
|
@@ -18,17 +18,17 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsTextContainerExtension(
|
||||
gd::PlatformExtension& extension) {
|
||||
extension
|
||||
.SetExtensionInformation("TextContainerCapability",
|
||||
_("Objects containing a text"),
|
||||
_("Text capability"),
|
||||
_("Allows an object to contain a text, usually shown on screen, that can be modified."),
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetExtensionHelpPath("/objects");
|
||||
extension.AddInstructionOrExpressionGroupMetadata(_("Objects containing a text"))
|
||||
extension.AddInstructionOrExpressionGroupMetadata(_("Text capability"))
|
||||
.SetIcon("res/conditions/text24_black.png");
|
||||
|
||||
gd::BehaviorMetadata& aut = extension.AddBehavior(
|
||||
"TextContainerBehavior",
|
||||
_("Objects containing a text"),
|
||||
_("Text capability"),
|
||||
"Text",
|
||||
_("Allows an object to contain a text, usually shown on screen, that can be modified."),
|
||||
"",
|
||||
|
@@ -16,9 +16,7 @@ BuiltinExtensionsImplementer::ImplementsCommonConversionsExtension(
|
||||
.SetExtensionInformation(
|
||||
"BuiltinCommonConversions",
|
||||
_("Conversion"),
|
||||
"Expressions to convert numbers to string, strings to numbers, "
|
||||
"angles (degrees from/to radians) and a GDevelop variable to/from a "
|
||||
"JSON string.",
|
||||
"Expressions to convert number, texts and quantities.",
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetExtensionHelpPath("/all-features/common-conversions");
|
||||
@@ -43,7 +41,7 @@ BuiltinExtensionsImplementer::ImplementsCommonConversionsExtension(
|
||||
|
||||
extension
|
||||
.AddStrExpression("LargeNumberToString",
|
||||
_("Number > Text (without scientific notation)"),
|
||||
_("Number > Text ( without scientific notation )"),
|
||||
_("Convert the result of the expression to text, "
|
||||
"without using the scientific notation"),
|
||||
"",
|
||||
@@ -74,8 +72,7 @@ BuiltinExtensionsImplementer::ImplementsCommonConversionsExtension(
|
||||
_("Convert a variable to JSON"),
|
||||
_("JSON"),
|
||||
"res/conditions/toujours24_black.png")
|
||||
.AddParameter("variable",
|
||||
_("The variable to be stringified"),
|
||||
.AddParameter("variable", _("The variable to be stringified"),
|
||||
"AllowUndeclaredVariable");
|
||||
|
||||
// Deprecated
|
||||
|
@@ -42,17 +42,13 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsFileExtension(
|
||||
extension
|
||||
.AddAction(
|
||||
"LoadFile",
|
||||
_("Manually preload a storage in memory"),
|
||||
_("Forces the specified storage to be loaded and kept in "
|
||||
"memory, allowing faster reads/writes. "
|
||||
"However, it requires manual management: if you use this "
|
||||
"action, you *must* also unload the storage manually when "
|
||||
"it's no longer needed to ensure data is persisted.\n\n"
|
||||
"Unless you have a specific performance need, avoid using this "
|
||||
"action. The system already handles loading/unloading "
|
||||
"automatically."),
|
||||
_("Load data storage _PARAM0_ in memory"),
|
||||
_("Advanced"),
|
||||
_("Load a storage in memory"),
|
||||
_("This action loads the specified storage in memory, so you can "
|
||||
"write and read it.\nYou can open and write without using this "
|
||||
"action, but it will be slower.\nIf you use this action, do not "
|
||||
"forget to unload the storage from memory."),
|
||||
_("Load storage _PARAM0_ in memory"),
|
||||
"",
|
||||
"res/actions/fichier24.png",
|
||||
"res/actions/fichier.png")
|
||||
.AddParameter("string", _("Storage name"))
|
||||
@@ -60,11 +56,11 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsFileExtension(
|
||||
|
||||
extension
|
||||
.AddAction("UnloadFile",
|
||||
_("Manually unload and persist a storage"),
|
||||
_("Close the specified storage previously loaded "
|
||||
_("Close a storage"),
|
||||
_("This action closes the structured data previously loaded "
|
||||
"in memory, saving all changes made."),
|
||||
_("Unload and persist data storage _PARAM0_"),
|
||||
_("Advanced"),
|
||||
_("Close structured data _PARAM0_"),
|
||||
"",
|
||||
"res/actions/fichier24.png",
|
||||
"res/actions/fichier.png")
|
||||
.AddParameter("string", _("Storage name"))
|
||||
|
@@ -15,11 +15,10 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsKeyboardExtension(
|
||||
.SetExtensionInformation(
|
||||
"BuiltinKeyboard",
|
||||
_("Keyboard"),
|
||||
_("Conditions to check keys pressed on a keyboard. Note that this "
|
||||
_("Allows your game to respond to keyboard input. Note that this "
|
||||
"does not work with on-screen keyboard on touch devices: use "
|
||||
"instead mouse/touch conditions when making a game for "
|
||||
"mobile/touchscreen devices or when making a new game from "
|
||||
"scratch."),
|
||||
"instead conditions related to touch when making a game for "
|
||||
"mobile/touchscreen devices."),
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetExtensionHelpPath("/all-features/keyboard")
|
||||
@@ -52,25 +51,10 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsKeyboardExtension(
|
||||
.SetHidden();
|
||||
|
||||
extension
|
||||
.AddCondition(
|
||||
"KeyFromTextPressed",
|
||||
_("Key pressed"),
|
||||
_("Check if a key is pressed. This stays true as long as "
|
||||
"the key is held down. To check if a key was pressed during "
|
||||
"the frame, use \"Key just pressed\" instead."),
|
||||
_("_PARAM1_ key is pressed"),
|
||||
"",
|
||||
"res/conditions/keyboard24.png",
|
||||
"res/conditions/keyboard.png")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("keyboardKey", _("Key to check"))
|
||||
.MarkAsSimple();
|
||||
|
||||
extension
|
||||
.AddCondition("KeyFromTextJustPressed",
|
||||
_("Key just pressed"),
|
||||
_("Check if a key was just pressed."),
|
||||
_("_PARAM1_ key was just pressed"),
|
||||
.AddCondition("KeyFromTextPressed",
|
||||
_("Key pressed"),
|
||||
_("Check if a key is pressed"),
|
||||
_("_PARAM1_ key is pressed"),
|
||||
"",
|
||||
"res/conditions/keyboard24.png",
|
||||
"res/conditions/keyboard.png")
|
||||
@@ -81,7 +65,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsKeyboardExtension(
|
||||
extension
|
||||
.AddCondition("KeyFromTextReleased",
|
||||
_("Key released"),
|
||||
_("Check if a key was just released."),
|
||||
_("Check if a key was just released"),
|
||||
_("_PARAM1_ key is released"),
|
||||
"",
|
||||
"res/conditions/keyboard24.png",
|
||||
@@ -100,7 +84,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsKeyboardExtension(
|
||||
"res/conditions/keyboard.png")
|
||||
.AddCodeOnlyParameter("currentScene", "");
|
||||
|
||||
extension
|
||||
extension
|
||||
.AddCondition("AnyKeyReleased",
|
||||
_("Any key released"),
|
||||
_("Check if any key is released"),
|
||||
|
@@ -16,11 +16,8 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsMouseExtension(
|
||||
.SetExtensionInformation(
|
||||
"BuiltinMouse",
|
||||
_("Mouse and touch"),
|
||||
"Conditions, actions and expressions to handle either the mouse or "
|
||||
"touches on a touchscreen. Notably: cursor position, mouse wheel, "
|
||||
"mouse buttons, touch positions, started/end touches, etc...\n"
|
||||
"\n"
|
||||
"By default, conditions related to the mouse will also "
|
||||
"Conditions and actions to handle either the mouse or touches on "
|
||||
"touchscreen. By default, conditions related to the mouse will also "
|
||||
"handle the touches - so that it's easier to handle both in your "
|
||||
"game. You can disable this behavior if you want to handle them "
|
||||
"separately in different events.",
|
||||
@@ -276,26 +273,28 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsMouseExtension(
|
||||
.SetHidden();
|
||||
|
||||
extension
|
||||
.AddCondition("MouseButtonFromTextPressed",
|
||||
_("Mouse button pressed or touch held"),
|
||||
_("Check if the specified mouse button is pressed or "
|
||||
"if a touch is in contact with the screen."),
|
||||
_("Touch or _PARAM1_ mouse button is down"),
|
||||
"",
|
||||
"res/conditions/mouse24.png",
|
||||
"res/conditions/mouse.png")
|
||||
.AddCondition(
|
||||
"MouseButtonFromTextPressed",
|
||||
_("Mouse button pressed or touch held"),
|
||||
_("Check if the specified mouse button is pressed or "
|
||||
"if a touch is in contact with the screen."),
|
||||
_("Touch or _PARAM1_ mouse button is down"),
|
||||
"",
|
||||
"res/conditions/mouse24.png",
|
||||
"res/conditions/mouse.png")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("mouseButton", _("Button to check"))
|
||||
.MarkAsSimple();
|
||||
|
||||
extension
|
||||
.AddCondition("MouseButtonFromTextReleased",
|
||||
_("Mouse button released"),
|
||||
_("Check if the specified mouse button was released."),
|
||||
_("Touch or _PARAM1_ mouse button is released"),
|
||||
"",
|
||||
"res/conditions/mouse24.png",
|
||||
"res/conditions/mouse.png")
|
||||
.AddCondition(
|
||||
"MouseButtonFromTextReleased",
|
||||
_("Mouse button released"),
|
||||
_("Check if the specified mouse button was released."),
|
||||
_("Touch or _PARAM1_ mouse button is released"),
|
||||
"",
|
||||
"res/conditions/mouse24.png",
|
||||
"res/conditions/mouse.png")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("mouseButton", _("Button to check"))
|
||||
.MarkAsSimple();
|
||||
|
@@ -15,9 +15,8 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsNetworkExtension(
|
||||
.SetExtensionInformation(
|
||||
"BuiltinNetwork",
|
||||
_("Network"),
|
||||
_("Actions to send web requests, communicate with external \"APIs\" "
|
||||
"and other network related tasks. Also contains an action to open "
|
||||
"a URL on the device browser."),
|
||||
_("Features to send web requests, communicate with external \"APIs\" "
|
||||
"and other network related tasks."),
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetExtensionHelpPath("/all-features/network")
|
||||
|
@@ -4,8 +4,8 @@
|
||||
* reserved. This project is released under the MIT License.
|
||||
*/
|
||||
#include "AllBuiltinExtensions.h"
|
||||
#include "GDCore/Extensions/Metadata/MultipleInstructionMetadata.h"
|
||||
#include "GDCore/Tools/Localization.h"
|
||||
#include "GDCore/Extensions/Metadata/MultipleInstructionMetadata.h"
|
||||
|
||||
using namespace std;
|
||||
namespace gd {
|
||||
@@ -16,11 +16,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsSceneExtension(
|
||||
.SetExtensionInformation(
|
||||
"BuiltinScene",
|
||||
_("Scene"),
|
||||
_("Actions/conditions to change the current scene (or pause it and "
|
||||
"launch another one, or go back to the previous one), check if a "
|
||||
"scene or the game has just started/resumed, preload assets of a "
|
||||
"scene, get the current scene name or loading progress, quit the "
|
||||
"game, set background color, or disable input when focus is lost."),
|
||||
_("Actions and conditions to manipulate the scenes during the game."),
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetExtensionHelpPath("" /*TODO: Add a documentation page for this */);
|
||||
@@ -170,28 +166,25 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsSceneExtension(
|
||||
.AddCodeOnlyParameter("currentScene", "");
|
||||
|
||||
extension
|
||||
.AddAction(
|
||||
"PrioritizeLoadingOfScene",
|
||||
_("Preload scene"),
|
||||
_("Preload a scene resources as soon as possible in background."),
|
||||
_("Preload scene _PARAM1_ in background"),
|
||||
"",
|
||||
"res/actions/hourglass_black.svg",
|
||||
"res/actions/hourglass_black.svg")
|
||||
.AddAction("PrioritizeLoadingOfScene",
|
||||
_("Preload scene"),
|
||||
_("Preload a scene resources as soon as possible in background."),
|
||||
_("Preload scene _PARAM1_ in background"),
|
||||
"",
|
||||
"res/actions/hourglass_black.svg",
|
||||
"res/actions/hourglass_black.svg")
|
||||
.SetHelpPath("/all-features/resources-loading")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("sceneName", _("Name of the new scene"))
|
||||
.MarkAsAdvanced();
|
||||
|
||||
extension
|
||||
.AddExpressionAndCondition("number",
|
||||
"SceneLoadingProgress",
|
||||
_("Scene loading progress"),
|
||||
_("The progress of resources loading in "
|
||||
"background for a scene (between 0 and 1)."),
|
||||
_("_PARAM1_ loading progress"),
|
||||
_(""),
|
||||
"res/actions/hourglass_black.svg")
|
||||
extension.AddExpressionAndCondition("number",
|
||||
"SceneLoadingProgress",
|
||||
_("Scene loading progress"),
|
||||
_("The progress of resources loading in background for a scene (between 0 and 1)."),
|
||||
_("_PARAM1_ loading progress"),
|
||||
_(""),
|
||||
"res/actions/hourglass_black.svg")
|
||||
.SetHelpPath("/all-features/resources-loading")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("sceneName", _("Scene name"))
|
||||
@@ -199,14 +192,13 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsSceneExtension(
|
||||
.MarkAsAdvanced();
|
||||
|
||||
extension
|
||||
.AddCondition(
|
||||
"AreSceneAssetsLoaded",
|
||||
_("Scene preloaded"),
|
||||
_("Check if scene resources have finished to load in background."),
|
||||
_("Scene _PARAM1_ was preloaded in background"),
|
||||
"",
|
||||
"res/actions/hourglass_black.svg",
|
||||
"res/actions/hourglass_black.svg")
|
||||
.AddCondition("AreSceneAssetsLoaded",
|
||||
_("Scene preloaded"),
|
||||
_("Check if scene resources have finished to load in background."),
|
||||
_("Scene _PARAM1_ was preloaded in background"),
|
||||
"",
|
||||
"res/actions/hourglass_black.svg",
|
||||
"res/actions/hourglass_black.svg")
|
||||
.SetHelpPath("/all-features/resources-loading")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("sceneName", _("Scene name"))
|
||||
|
@@ -15,13 +15,12 @@ namespace gd {
|
||||
void GD_CORE_API BuiltinExtensionsImplementer::ImplementsSpriteExtension(
|
||||
gd::PlatformExtension& extension) {
|
||||
extension
|
||||
.SetExtensionInformation(
|
||||
"Sprite",
|
||||
_("Sprite"),
|
||||
_("Sprite are animated objects which can be used "
|
||||
"for most elements of a 2D game."),
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetExtensionInformation("Sprite",
|
||||
_("Sprite"),
|
||||
_("Sprite are animated object which can be used "
|
||||
"for most elements of a game."),
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetExtensionHelpPath("/objects/sprite");
|
||||
extension.AddInstructionOrExpressionGroupMetadata(_("Sprite"))
|
||||
.SetIcon("CppPlatform/Extensions/spriteicon.png");
|
||||
@@ -31,7 +30,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsSpriteExtension(
|
||||
.AddObject<SpriteObject>("Sprite",
|
||||
_("Sprite"),
|
||||
_("Animated object which can be used for "
|
||||
"most elements of a 2D game."),
|
||||
"most elements of a game."),
|
||||
"CppPlatform/Extensions/spriteicon.png")
|
||||
.SetCategoryFullName(_("General"))
|
||||
.SetOpenFullEditorLabel(_("Edit animations"))
|
||||
@@ -646,12 +645,11 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsSpriteExtension(
|
||||
"res/actions/sprite.png")
|
||||
.AddParameter("object", _("Object"), "Sprite");
|
||||
|
||||
obj.AddExpression(
|
||||
"AnimationFrameCount",
|
||||
_("Number of frames"),
|
||||
_("Number of frames in the current animation of the object"),
|
||||
_("Animations and images"),
|
||||
"res/actions/sprite.png")
|
||||
obj.AddExpression("AnimationFrameCount",
|
||||
_("Number of frames"),
|
||||
_("Number of frames in the current animation of the object"),
|
||||
_("Animations and images"),
|
||||
"res/actions/sprite.png")
|
||||
.AddParameter("object", _("Object"), "Sprite");
|
||||
|
||||
// Deprecated
|
||||
|
@@ -16,8 +16,7 @@ BuiltinExtensionsImplementer::ImplementsStringInstructionsExtension(
|
||||
.SetExtensionInformation(
|
||||
"BuiltinStringInstructions",
|
||||
_("Text manipulation"),
|
||||
"Provides expressions to manipulate strings (also called texts): new "
|
||||
"line, upper/lowercase, substring, find, replace, etc...",
|
||||
"Provides expressions to manipulate strings (also called texts).",
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetExtensionHelpPath("" /*TODO: Add a documentation page for this */);
|
||||
@@ -192,8 +191,7 @@ BuiltinExtensionsImplementer::ImplementsStringInstructionsExtension(
|
||||
"res/conditions/toujours24_black.png")
|
||||
.AddParameter("string", _("Text in which the replacement must be done"))
|
||||
.AddParameter("string", _("Text to find inside the first text"))
|
||||
.AddParameter("string",
|
||||
_("Replacement to put instead of the text to find"));
|
||||
.AddParameter("string", _("Replacement to put instead of the text to find"));
|
||||
|
||||
extension
|
||||
.AddStrExpression("StrReplaceAll",
|
||||
@@ -201,11 +199,10 @@ BuiltinExtensionsImplementer::ImplementsStringInstructionsExtension(
|
||||
_("Replace all occurrences of a text by another."),
|
||||
"",
|
||||
"res/conditions/toujours24_black.png")
|
||||
.AddParameter("string",
|
||||
_("Text in which the replacement(s) must be done"))
|
||||
.AddParameter("string", _("Text in which the replacement(s) must be done"))
|
||||
.AddParameter("string", _("Text to find inside the first text"))
|
||||
.AddParameter("string",
|
||||
_("Replacement to put instead of the text to find"));
|
||||
.AddParameter("string", _("Replacement to put instead of the text to find"));
|
||||
|
||||
}
|
||||
|
||||
} // namespace gd
|
||||
|
@@ -15,12 +15,9 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsTimeExtension(
|
||||
.SetExtensionInformation(
|
||||
"BuiltinTime",
|
||||
_("Timers and time"),
|
||||
"Actions and conditions to start, pause or reset scene timers, "
|
||||
"modify the time scale (speed at which the game "
|
||||
"is running - useful for slow motion effects). Also contains an "
|
||||
"action that wait for a delay before running the next actions and "
|
||||
"sub-events and expressions to read the time scale, time delta of "
|
||||
"the last frame or timer elapsed time.",
|
||||
"Actions and conditions to run timers, get the current time or "
|
||||
"modify the time scale (speed at which the game is running - useful "
|
||||
"for slow motion effects).",
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetExtensionHelpPath("/all-features/timers-and-time");
|
||||
@@ -195,28 +192,26 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsTimeExtension(
|
||||
extension
|
||||
.AddExpression("TimerElapsedTime",
|
||||
_("Scene timer value"),
|
||||
_("Value of a scene timer (in seconds)"),
|
||||
_("Value of a scene timer"),
|
||||
"",
|
||||
"res/actions/time.png")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("identifier", _("Timer's name"), "sceneTimer");
|
||||
|
||||
extension
|
||||
.AddExpression(
|
||||
"TimeFromStart",
|
||||
_("Time elapsed since the beginning of the scene (in seconds)."),
|
||||
_("Time elapsed since the beginning of the scene (in seconds)."),
|
||||
"",
|
||||
"res/actions/time.png")
|
||||
.AddExpression("TimeFromStart",
|
||||
_("Time elapsed since the beginning of the scene"),
|
||||
_("Time elapsed since the beginning of the scene"),
|
||||
"",
|
||||
"res/actions/time.png")
|
||||
.AddCodeOnlyParameter("currentScene", "");
|
||||
|
||||
extension
|
||||
.AddExpression(
|
||||
"TempsDebut",
|
||||
_("Time elapsed since the beginning of the scene (in seconds)."),
|
||||
_("Time elapsed since the beginning of the scene (in seconds)."),
|
||||
"",
|
||||
"res/actions/time.png")
|
||||
.AddExpression("TempsDebut",
|
||||
_("Time elapsed since the beginning of the scene"),
|
||||
_("Time elapsed since the beginning of the scene"),
|
||||
"",
|
||||
"res/actions/time.png")
|
||||
.SetHidden()
|
||||
.AddCodeOnlyParameter("currentScene", "");
|
||||
|
||||
@@ -231,21 +226,16 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsTimeExtension(
|
||||
extension
|
||||
.AddExpression("Time",
|
||||
_("Current time"),
|
||||
_("Gives the current time"),
|
||||
_("Current time"),
|
||||
"",
|
||||
"res/actions/time.png")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter(
|
||||
"stringWithSelector",
|
||||
_("- Hour of the day: \"hour\"\n"
|
||||
"- Minutes: \"min\"\n"
|
||||
"- Seconds: \"sec\"\n"
|
||||
"- Day of month: \"mday\"\n"
|
||||
"- Months since January: \"mon\"\n"
|
||||
"- Year since 1900: \"year\"\n"
|
||||
"- Days since Sunday: \"wday\"\n"
|
||||
"- Days since Jan 1st: \"yday\"\n"
|
||||
"- Timestamp (ms): \"timestamp\""),
|
||||
_("Hour: hour - Minutes: min - Seconds: sec - Day of month: "
|
||||
"mday - Months since January: mon - Year since 1900: year - Days "
|
||||
"since Sunday: wday - Days since Jan 1st: yday - Timestamp (ms): "
|
||||
"timestamp\""),
|
||||
"[\"hour\", \"min\", \"sec\", \"mon\", \"year\", \"wday\", \"mday\", "
|
||||
"\"yday\", \"timestamp\"]");
|
||||
}
|
||||
|
@@ -15,17 +15,16 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsWindowExtension(
|
||||
.SetExtensionInformation(
|
||||
"BuiltinWindow",
|
||||
_("Game window and resolution"),
|
||||
"Actions and conditions to manipulate the game window or change how "
|
||||
"the game is resized according to the screen size. "
|
||||
"Provides actions and conditions to manipulate the game window. "
|
||||
"Depending on the platform on which the game is running, not all of "
|
||||
"these features can be applied.\n"
|
||||
"Also contains expressions to read the screen size.",
|
||||
"these features can be applied.",
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetCategory("User interface")
|
||||
.SetExtensionHelpPath("/all-features/window");
|
||||
extension
|
||||
.AddInstructionOrExpressionGroupMetadata(_("Game window and resolution"))
|
||||
.AddInstructionOrExpressionGroupMetadata(
|
||||
_("Game window and resolution"))
|
||||
.SetIcon("res/actions/window24.png");
|
||||
|
||||
extension
|
||||
|
@@ -298,19 +298,6 @@ class GD_CORE_API BehaviorMetadata : public InstructionOrExpressionContainerMeta
|
||||
return *this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the behavior can be used on objects from event-based objects.
|
||||
*/
|
||||
bool IsRelevantForChildObjects() const { return isRelevantForChildObjects; }
|
||||
|
||||
/**
|
||||
* Set that behavior can't be used on objects from event-based objects.
|
||||
*/
|
||||
BehaviorMetadata &MarkAsIrrelevantForChildObjects() {
|
||||
isRelevantForChildObjects = false;
|
||||
return *this;
|
||||
}
|
||||
|
||||
QuickCustomization::Visibility GetQuickCustomizationVisibility() const {
|
||||
return quickCustomizationVisibility;
|
||||
}
|
||||
@@ -406,7 +393,6 @@ class GD_CORE_API BehaviorMetadata : public InstructionOrExpressionContainerMeta
|
||||
mutable std::vector<gd::String> requiredBehaviors;
|
||||
bool isPrivate = false;
|
||||
bool isHidden = false;
|
||||
bool isRelevantForChildObjects = true;
|
||||
gd::String openFullEditorLabel;
|
||||
QuickCustomization::Visibility quickCustomizationVisibility = QuickCustomization::Visibility::Default;
|
||||
|
||||
|
@@ -277,10 +277,6 @@ class GD_CORE_API MetadataProvider {
|
||||
return &metadata == &badObjectInfo;
|
||||
}
|
||||
|
||||
static bool IsBadEffectMetadata(const gd::EffectMetadata& metadata) {
|
||||
return &metadata == &badEffectMetadata;
|
||||
}
|
||||
|
||||
virtual ~MetadataProvider();
|
||||
|
||||
private:
|
||||
|
@@ -194,8 +194,7 @@ void ParameterMetadataTools::IterateOverParameters(
|
||||
[&fn](const gd::ParameterMetadata& parameterMetadata,
|
||||
const gd::Expression& parameterValue,
|
||||
size_t parameterIndex,
|
||||
const gd::String& lastObjectName,
|
||||
size_t lastObjectIndex) {
|
||||
const gd::String& lastObjectName) {
|
||||
fn(parameterMetadata, parameterValue, lastObjectName);
|
||||
});
|
||||
}
|
||||
@@ -206,10 +205,8 @@ void ParameterMetadataTools::IterateOverParametersWithIndex(
|
||||
std::function<void(const gd::ParameterMetadata& parameterMetadata,
|
||||
const gd::Expression& parameterValue,
|
||||
size_t parameterIndex,
|
||||
const gd::String& lastObjectName,
|
||||
size_t lastObjectIndex)> fn) {
|
||||
const gd::String& lastObjectName)> fn) {
|
||||
gd::String lastObjectName = "";
|
||||
size_t lastObjectIndex = 0;
|
||||
for (std::size_t pNb = 0; pNb < parametersMetadata.GetParametersCount();
|
||||
++pNb) {
|
||||
const gd::ParameterMetadata ¶meterMetadata =
|
||||
@@ -221,17 +218,15 @@ void ParameterMetadataTools::IterateOverParametersWithIndex(
|
||||
? Expression(parameterMetadata.GetDefaultValue())
|
||||
: parameterValue;
|
||||
|
||||
fn(parameterMetadata, parameterValueOrDefault, pNb, lastObjectName, lastObjectIndex);
|
||||
fn(parameterMetadata, parameterValueOrDefault, pNb, lastObjectName);
|
||||
|
||||
// Memorize the last object name. By convention, parameters that require
|
||||
// an object (mainly, "objectvar" and "behavior") should be placed after
|
||||
// the object in the list of parameters (if possible, just after).
|
||||
// Search "lastObjectName" in the codebase for other place where this
|
||||
// convention is enforced.
|
||||
if (gd::ParameterMetadata::IsObject(parameterMetadata.GetType())) {
|
||||
if (gd::ParameterMetadata::IsObject(parameterMetadata.GetType()))
|
||||
lastObjectName = parameterValueOrDefault.GetPlainString();
|
||||
lastObjectIndex = pNb;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -64,8 +64,7 @@ class GD_CORE_API ParameterMetadataTools {
|
||||
std::function<void(const gd::ParameterMetadata& parameterMetadata,
|
||||
const gd::Expression& parameterValue,
|
||||
size_t parameterIndex,
|
||||
const gd::String& lastObjectName,
|
||||
size_t lastObjectIndex)> fn);
|
||||
const gd::String& lastObjectName)> fn);
|
||||
|
||||
/**
|
||||
* Iterate over the parameters of a FunctionCallNode.
|
||||
|
@@ -29,7 +29,7 @@ bool BehaviorParametersFiller::DoVisitInstruction(gd::Instruction &instruction,
|
||||
instruction.GetParameters(), metadata.GetParameters(),
|
||||
[&](const gd::ParameterMetadata ¶meterMetadata,
|
||||
const gd::Expression ¶meterValue, size_t parameterIndex,
|
||||
const gd::String &lastObjectName, size_t lastObjectIndex) {
|
||||
const gd::String &lastObjectName) {
|
||||
if (parameterMetadata.GetValueTypeMetadata().IsBehavior() &&
|
||||
parameterValue.GetPlainString().length() == 0) {
|
||||
|
||||
|
@@ -108,10 +108,12 @@ bool EventsBehaviorRenamer::DoVisitInstruction(gd::Instruction& instruction,
|
||||
platform, instruction.GetType());
|
||||
|
||||
gd::ParameterMetadataTools::IterateOverParametersWithIndex(
|
||||
instruction.GetParameters(), metadata.GetParameters(),
|
||||
[&](const gd::ParameterMetadata ¶meterMetadata,
|
||||
const gd::Expression ¶meterValue, size_t parameterIndex,
|
||||
const gd::String &lastObjectName, size_t lastObjectIndex) {
|
||||
instruction.GetParameters(),
|
||||
metadata.GetParameters(),
|
||||
[&](const gd::ParameterMetadata& parameterMetadata,
|
||||
const gd::Expression& parameterValue,
|
||||
size_t parameterIndex,
|
||||
const gd::String& lastObjectName) {
|
||||
const gd::String& type = parameterMetadata.GetType();
|
||||
|
||||
if (gd::ParameterMetadata::IsBehavior(type)) {
|
||||
|
@@ -183,10 +183,12 @@ bool EventsParameterReplacer::DoVisitInstruction(gd::Instruction& instruction,
|
||||
platform, instruction.GetType());
|
||||
|
||||
gd::ParameterMetadataTools::IterateOverParametersWithIndex(
|
||||
instruction.GetParameters(), metadata.GetParameters(),
|
||||
[&](const gd::ParameterMetadata ¶meterMetadata,
|
||||
const gd::Expression ¶meterValue, size_t parameterIndex,
|
||||
const gd::String &lastObjectName, size_t lastObjectIndex) {
|
||||
instruction.GetParameters(),
|
||||
metadata.GetParameters(),
|
||||
[&](const gd::ParameterMetadata& parameterMetadata,
|
||||
const gd::Expression& parameterValue,
|
||||
size_t parameterIndex,
|
||||
const gd::String& lastObjectName) {
|
||||
if (!gd::EventsParameterReplacer::CanContainParameter(
|
||||
parameterMetadata.GetValueTypeMetadata())) {
|
||||
return;
|
||||
|
@@ -217,10 +217,12 @@ bool EventsPropertyReplacer::DoVisitInstruction(gd::Instruction& instruction,
|
||||
bool shouldDeleteInstruction = false;
|
||||
|
||||
gd::ParameterMetadataTools::IterateOverParametersWithIndex(
|
||||
instruction.GetParameters(), metadata.GetParameters(),
|
||||
[&](const gd::ParameterMetadata ¶meterMetadata,
|
||||
const gd::Expression ¶meterValue, size_t parameterIndex,
|
||||
const gd::String &lastObjectName, size_t lastObjectIndex) {
|
||||
instruction.GetParameters(),
|
||||
metadata.GetParameters(),
|
||||
[&](const gd::ParameterMetadata& parameterMetadata,
|
||||
const gd::Expression& parameterValue,
|
||||
size_t parameterIndex,
|
||||
const gd::String& lastObjectName) {
|
||||
if (!gd::EventsPropertyReplacer::CanContainProperty(
|
||||
parameterMetadata.GetValueTypeMetadata())) {
|
||||
return;
|
||||
|
@@ -334,7 +334,7 @@ private:
|
||||
instruction.GetParameters(), metadata.GetParameters(),
|
||||
[&](const gd::ParameterMetadata ¶meterMetadata,
|
||||
const gd::Expression ¶meterValue, size_t parameterIndex,
|
||||
const gd::String &lastObjectName, size_t lastObjectIndex) {
|
||||
const gd::String &lastObjectName) {
|
||||
if (!gd::EventsObjectReplacer::CanContainObject(
|
||||
parameterMetadata.GetValueTypeMetadata())) {
|
||||
return;
|
||||
|
@@ -42,16 +42,18 @@ bool EventsVariableInstructionTypeSwitcher::DoVisitInstruction(gd::Instruction&
|
||||
platform, instruction.GetType());
|
||||
|
||||
gd::ParameterMetadataTools::IterateOverParametersWithIndex(
|
||||
instruction.GetParameters(), metadata.GetParameters(),
|
||||
[&](const gd::ParameterMetadata ¶meterMetadata,
|
||||
const gd::Expression ¶meterValue, size_t parameterIndex,
|
||||
const gd::String &lastObjectName, size_t lastObjectIndex) {
|
||||
instruction.GetParameters(),
|
||||
metadata.GetParameters(),
|
||||
[&](const gd::ParameterMetadata& parameterMetadata,
|
||||
const gd::Expression& parameterValue,
|
||||
size_t parameterIndex,
|
||||
const gd::String& lastObjectName) {
|
||||
const gd::String& type = parameterMetadata.GetType();
|
||||
|
||||
if (!gd::ParameterMetadata::IsExpression("variable", type) ||
|
||||
!gd::VariableInstructionSwitcher::IsSwitchableVariableInstruction(
|
||||
instruction.GetType())) {
|
||||
return;
|
||||
return;
|
||||
}
|
||||
const auto variableName =
|
||||
gd::ExpressionVariableNameFinder::GetVariableName(
|
||||
@@ -70,11 +72,10 @@ bool EventsVariableInstructionTypeSwitcher::DoVisitInstruction(gd::Instruction&
|
||||
.GetObjectOrGroupVariablesContainer(lastObjectName);
|
||||
}
|
||||
} else if (type == "variableOrProperty") {
|
||||
variablesContainer =
|
||||
&GetProjectScopedContainers()
|
||||
.GetVariablesContainersList()
|
||||
.GetVariablesContainerFromVariableOrPropertyName(
|
||||
variableName);
|
||||
variablesContainer =
|
||||
&GetProjectScopedContainers()
|
||||
.GetVariablesContainersList()
|
||||
.GetVariablesContainerFromVariableOrPropertyName(variableName);
|
||||
} else {
|
||||
if (GetProjectScopedContainers().GetVariablesContainersList().Has(
|
||||
variableName)) {
|
||||
|
@@ -448,10 +448,12 @@ bool EventsVariableReplacer::DoVisitInstruction(gd::Instruction& instruction,
|
||||
bool shouldDeleteInstruction = false;
|
||||
|
||||
gd::ParameterMetadataTools::IterateOverParametersWithIndex(
|
||||
instruction.GetParameters(), metadata.GetParameters(),
|
||||
[&](const gd::ParameterMetadata ¶meterMetadata,
|
||||
const gd::Expression ¶meterValue, size_t parameterIndex,
|
||||
const gd::String &lastObjectName, size_t lastObjectIndex) {
|
||||
instruction.GetParameters(),
|
||||
metadata.GetParameters(),
|
||||
[&](const gd::ParameterMetadata& parameterMetadata,
|
||||
const gd::Expression& parameterValue,
|
||||
size_t parameterIndex,
|
||||
const gd::String& lastObjectName) {
|
||||
const gd::String& type = parameterMetadata.GetType();
|
||||
|
||||
if (!gd::ParameterMetadata::IsExpression("variable", type) &&
|
||||
|
@@ -150,7 +150,7 @@ bool ProjectElementRenamer::DoVisitInstruction(gd::Instruction &instruction,
|
||||
instruction.GetParameters(), metadata.GetParameters(),
|
||||
[&](const gd::ParameterMetadata ¶meterMetadata,
|
||||
const gd::Expression ¶meterValue, size_t parameterIndex,
|
||||
const gd::String &lastObjectName, size_t lastObjectIndex) {
|
||||
const gd::String &lastObjectName) {
|
||||
if (parameterMetadata.GetType() == "layer") {
|
||||
if (parameterValue.GetPlainString().length() < 2) {
|
||||
// This is either the base layer or an invalid layer name.
|
||||
|
@@ -76,7 +76,6 @@ void ObjectAssetSerializer::SerializeTo(
|
||||
|
||||
double width = 0;
|
||||
double height = 0;
|
||||
std::unordered_set<gd::String> alreadyUsedVariantIdentifiers;
|
||||
if (project.HasEventsBasedObject(object.GetType())) {
|
||||
SerializerElement &variantsElement =
|
||||
objectAssetElement.AddChild("variants");
|
||||
@@ -88,6 +87,7 @@ void ObjectAssetSerializer::SerializeTo(
|
||||
height = variant->GetAreaMaxY() - variant->GetAreaMinY();
|
||||
}
|
||||
|
||||
std::unordered_set<gd::String> alreadyUsedVariantIdentifiers;
|
||||
gd::ObjectAssetSerializer::SerializeUsedVariantsTo(
|
||||
project, object, variantsElement, alreadyUsedVariantIdentifiers);
|
||||
}
|
||||
@@ -114,24 +114,14 @@ void ObjectAssetSerializer::SerializeTo(
|
||||
resourceElement.SetAttribute("name", resource.GetName());
|
||||
}
|
||||
|
||||
std::unordered_set<gd::String> usedExtensionNames;
|
||||
usedExtensionNames.insert(extensionName);
|
||||
for (auto &usedVariantIdentifier : alreadyUsedVariantIdentifiers) {
|
||||
usedExtensionNames.insert(PlatformExtension::GetExtensionFromFullObjectType(
|
||||
usedVariantIdentifier));
|
||||
}
|
||||
SerializerElement &requiredExtensionsElement =
|
||||
objectAssetElement.AddChild("requiredExtensions");
|
||||
requiredExtensionsElement.ConsiderAsArrayOf("requiredExtension");
|
||||
for (auto &usedExtensionName : usedExtensionNames) {
|
||||
if (project.HasEventsFunctionsExtensionNamed(usedExtensionName)) {
|
||||
auto &extension = project.GetEventsFunctionsExtension(usedExtensionName);
|
||||
SerializerElement &requiredExtensionElement =
|
||||
requiredExtensionsElement.AddChild("requiredExtension");
|
||||
requiredExtensionElement.SetAttribute("extensionName", usedExtensionName);
|
||||
requiredExtensionElement.SetAttribute("extensionVersion",
|
||||
extension.GetVersion());
|
||||
}
|
||||
if (project.HasEventsFunctionsExtensionNamed(extensionName)) {
|
||||
SerializerElement &requiredExtensionElement =
|
||||
requiredExtensionsElement.AddChild("requiredExtension");
|
||||
requiredExtensionElement.SetAttribute("extensionName", extensionName);
|
||||
requiredExtensionElement.SetAttribute("extensionVersion", "1.0.0");
|
||||
}
|
||||
|
||||
// TODO This can be removed when the asset script no longer require it.
|
||||
|
@@ -227,11 +227,12 @@ bool ResourceWorkerInEventsWorker::DoVisitInstruction(gd::Instruction& instructi
|
||||
platform, instruction.GetType());
|
||||
|
||||
gd::ParameterMetadataTools::IterateOverParametersWithIndex(
|
||||
instruction.GetParameters(), metadata.GetParameters(),
|
||||
[this, &instruction](
|
||||
const gd::ParameterMetadata ¶meterMetadata,
|
||||
const gd::Expression ¶meterExpression, size_t parameterIndex,
|
||||
const gd::String &lastObjectName, size_t lastObjectIndex) {
|
||||
instruction.GetParameters(),
|
||||
metadata.GetParameters(),
|
||||
[this, &instruction](const gd::ParameterMetadata& parameterMetadata,
|
||||
const gd::Expression& parameterExpression,
|
||||
size_t parameterIndex,
|
||||
const gd::String& lastObjectName) {
|
||||
const String& parameterValue = parameterExpression.GetPlainString();
|
||||
if (parameterMetadata.GetType() == "fontResource") {
|
||||
gd::String updatedParameterValue = parameterValue;
|
||||
|
@@ -248,13 +248,12 @@ gd::String PropertyFunctionGenerator::GetStringifiedExtraInfo(
|
||||
gd::String arrayString;
|
||||
arrayString += "[";
|
||||
bool isFirst = true;
|
||||
for (const auto &choice : property.GetChoices()) {
|
||||
for (const gd::String &choice : property.GetExtraInfo()) {
|
||||
if (!isFirst) {
|
||||
arrayString += ",";
|
||||
}
|
||||
isFirst = false;
|
||||
// TODO Handle labels (and search "choice label")
|
||||
arrayString += "\"" + choice.GetValue() + "\"";
|
||||
arrayString += "\"" + choice + "\"";
|
||||
}
|
||||
arrayString += "]";
|
||||
return arrayString;
|
||||
|
@@ -75,17 +75,6 @@ void ResourceExposer::ExposeProjectResources(
|
||||
// Expose global objects configuration resources
|
||||
auto objectWorker = gd::GetResourceWorkerOnObjects(project, worker);
|
||||
objectWorker.Launch(project.GetObjects());
|
||||
|
||||
// Exposed extension event resources
|
||||
// Note that using resources in extensions is very unlikely and probably not
|
||||
// worth the effort of something smart.
|
||||
auto eventWorker = gd::GetResourceWorkerOnEvents(project, worker);
|
||||
for (std::size_t e = 0; e < project.GetEventsFunctionsExtensionsCount();
|
||||
e++) {
|
||||
auto &eventsFunctionsExtension = project.GetEventsFunctionsExtension(e);
|
||||
gd::ProjectBrowserHelper::ExposeEventsFunctionsExtensionEvents(
|
||||
project, eventsFunctionsExtension, eventWorker);
|
||||
}
|
||||
}
|
||||
|
||||
void ResourceExposer::ExposeLayoutResources(
|
||||
@@ -114,6 +103,16 @@ void ResourceExposer::ExposeLayoutResources(
|
||||
auto eventWorker = gd::GetResourceWorkerOnEvents(project, worker);
|
||||
gd::ProjectBrowserHelper::ExposeLayoutEventsAndDependencies(
|
||||
project, layout, eventWorker);
|
||||
|
||||
// Exposed extension event resources
|
||||
// Note that using resources in extensions is very unlikely and probably not
|
||||
// worth the effort of something smart.
|
||||
for (std::size_t e = 0; e < project.GetEventsFunctionsExtensionsCount();
|
||||
e++) {
|
||||
auto &eventsFunctionsExtension = project.GetEventsFunctionsExtension(e);
|
||||
gd::ProjectBrowserHelper::ExposeEventsFunctionsExtensionEvents(
|
||||
project, eventsFunctionsExtension, eventWorker);
|
||||
}
|
||||
}
|
||||
|
||||
void ResourceExposer::ExposeEffectResources(
|
||||
|
@@ -37,7 +37,6 @@ void EventsBasedObjectVariant::SerializeTo(SerializerElement &element) const {
|
||||
|
||||
layers.SerializeLayersTo(element.AddChild("layers"));
|
||||
initialInstances.SerializeTo(element.AddChild("instances"));
|
||||
editorSettings.SerializeTo(element.AddChild("editionSettings"));
|
||||
}
|
||||
|
||||
void EventsBasedObjectVariant::UnserializeFrom(
|
||||
@@ -67,7 +66,6 @@ void EventsBasedObjectVariant::UnserializeFrom(
|
||||
layers.Reset();
|
||||
}
|
||||
initialInstances.UnserializeFrom(element.GetChild("instances"));
|
||||
editorSettings.UnserializeFrom(element.GetChild("editionSettings"));
|
||||
}
|
||||
|
||||
} // namespace gd
|
||||
|
@@ -5,7 +5,6 @@
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "GDCore/IDE/Dialogs/LayoutEditorCanvas/EditorSettings.h"
|
||||
#include "GDCore/Project/InitialInstancesContainer.h"
|
||||
#include "GDCore/Project/LayersContainer.h"
|
||||
#include "GDCore/Project/ObjectsContainer.h"
|
||||
@@ -200,19 +199,6 @@ 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;
|
||||
|
||||
@@ -238,7 +224,6 @@ private:
|
||||
* store.
|
||||
*/
|
||||
gd::String assetStoreOriginalName;
|
||||
gd::EditorSettings editorSettings;
|
||||
};
|
||||
|
||||
} // namespace gd
|
||||
|
@@ -34,20 +34,6 @@ void PropertyDescriptor::SerializeTo(SerializerElement& element) const {
|
||||
}
|
||||
}
|
||||
|
||||
if (!choices.empty()
|
||||
// Compatibility with GD <= 5.5.239
|
||||
|| !extraInformation.empty()
|
||||
// end of compatibility code
|
||||
) {
|
||||
SerializerElement &choicesElement = element.AddChild("choices");
|
||||
choicesElement.ConsiderAsArrayOf("choice");
|
||||
for (const auto &choice : choices) {
|
||||
auto &choiceElement = choicesElement.AddChild("Choice");
|
||||
choiceElement.SetStringAttribute("value", choice.GetValue());
|
||||
choiceElement.SetStringAttribute("label", choice.GetLabel());
|
||||
}
|
||||
}
|
||||
|
||||
if (hidden) {
|
||||
element.AddChild("hidden").SetBoolValue(hidden);
|
||||
}
|
||||
@@ -94,26 +80,6 @@ void PropertyDescriptor::UnserializeFrom(const SerializerElement& element) {
|
||||
extraInformationElement.GetChild(i).GetStringValue());
|
||||
}
|
||||
|
||||
if (element.HasChild("choices")) {
|
||||
choices.clear();
|
||||
const SerializerElement &choicesElement = element.GetChild("choices");
|
||||
choicesElement.ConsiderAsArrayOf("choice");
|
||||
for (std::size_t i = 0; i < choicesElement.GetChildrenCount(); ++i) {
|
||||
auto &choiceElement = choicesElement.GetChild(i);
|
||||
AddChoice(choiceElement.GetStringAttribute("value"),
|
||||
choiceElement.GetStringAttribute("label"));
|
||||
}
|
||||
}
|
||||
// Compatibility with GD <= 5.5.239
|
||||
else if (type == "Choice") {
|
||||
choices.clear();
|
||||
for (auto &choiceValue : extraInformation) {
|
||||
AddChoice(choiceValue, choiceValue);
|
||||
}
|
||||
extraInformation.clear();
|
||||
}
|
||||
// end of compatibility code
|
||||
|
||||
hidden = element.HasChild("hidden")
|
||||
? element.GetChild("hidden").GetBoolValue()
|
||||
: false;
|
||||
|
@@ -116,11 +116,6 @@ class GD_CORE_API PropertyDescriptor {
|
||||
return *this;
|
||||
}
|
||||
|
||||
PropertyDescriptor& ClearChoices() {
|
||||
choices.clear();
|
||||
return *this;
|
||||
}
|
||||
|
||||
PropertyDescriptor& AddChoice(const gd::String& value,
|
||||
const gd::String& label) {
|
||||
choices.push_back(PropertyDescriptorChoice(value, label));
|
||||
|
@@ -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
|
||||
|
@@ -764,6 +764,129 @@ TEST_CASE("ArbitraryResourceWorker", "[common][resources]") {
|
||||
REQUIRE(worker.audios[0] == "res4");
|
||||
}
|
||||
|
||||
SECTION("Can find resource usages in event-based functions") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
SetupProjectWithDummyPlatform(project, platform);
|
||||
|
||||
project.GetResourcesManager().AddResource(
|
||||
"res1", "path/to/file1.png", "image");
|
||||
project.GetResourcesManager().AddResource(
|
||||
"res2", "path/to/file2.png", "image");
|
||||
project.GetResourcesManager().AddResource(
|
||||
"res3", "path/to/file3.png", "image");
|
||||
ArbitraryResourceWorkerTest worker(project.GetResourcesManager());
|
||||
|
||||
auto& extension = project.InsertNewEventsFunctionsExtension("MyEventExtension", 0);
|
||||
auto &function = extension.GetEventsFunctions().InsertNewEventsFunction(
|
||||
"MyFreeFunction", 0);
|
||||
|
||||
gd::StandardEvent standardEvent;
|
||||
gd::Instruction instruction;
|
||||
instruction.SetType("MyExtension::DoSomethingWithResources");
|
||||
instruction.SetParametersCount(3);
|
||||
instruction.SetParameter(0, "res3");
|
||||
instruction.SetParameter(1, "res1");
|
||||
instruction.SetParameter(2, "res4");
|
||||
standardEvent.GetActions().Insert(instruction);
|
||||
function.GetEvents().InsertEvent(standardEvent);
|
||||
|
||||
auto& layout = project.InsertNewLayout("MyScene", 0);
|
||||
|
||||
// MyEventExtension::MyFreeFunction doesn't need to be actually used in
|
||||
// events because the implementation is naive.
|
||||
|
||||
gd::ResourceExposer::ExposeLayoutResources(project, layout, worker);
|
||||
REQUIRE(worker.bitmapFonts.size() == 1);
|
||||
REQUIRE(worker.bitmapFonts[0] == "res3");
|
||||
REQUIRE(worker.images.size() == 1);
|
||||
REQUIRE(worker.images[0] == "res1");
|
||||
REQUIRE(worker.audios.size() == 1);
|
||||
REQUIRE(worker.audios[0] == "res4");
|
||||
}
|
||||
|
||||
SECTION("Can find resource usages in event-based behavior functions") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
SetupProjectWithDummyPlatform(project, platform);
|
||||
|
||||
project.GetResourcesManager().AddResource(
|
||||
"res1", "path/to/file1.png", "image");
|
||||
project.GetResourcesManager().AddResource(
|
||||
"res2", "path/to/file2.png", "image");
|
||||
project.GetResourcesManager().AddResource(
|
||||
"res3", "path/to/file3.png", "image");
|
||||
ArbitraryResourceWorkerTest worker(project.GetResourcesManager());
|
||||
|
||||
auto& extension = project.InsertNewEventsFunctionsExtension("MyEventExtension", 0);
|
||||
auto& behavior = extension.GetEventsBasedBehaviors().InsertNew("MyBehavior", 0);
|
||||
auto& function = behavior.GetEventsFunctions().InsertNewEventsFunction("MyFunction", 0);
|
||||
|
||||
gd::StandardEvent standardEvent;
|
||||
gd::Instruction instruction;
|
||||
instruction.SetType("MyExtension::DoSomethingWithResources");
|
||||
instruction.SetParametersCount(3);
|
||||
instruction.SetParameter(0, "res3");
|
||||
instruction.SetParameter(1, "res1");
|
||||
instruction.SetParameter(2, "res4");
|
||||
standardEvent.GetActions().Insert(instruction);
|
||||
function.GetEvents().InsertEvent(standardEvent);
|
||||
|
||||
auto& layout = project.InsertNewLayout("MyScene", 0);
|
||||
|
||||
// MyEventExtension::MyBehavior::MyFunction doesn't need to be actually used in
|
||||
// events because the implementation is naive.
|
||||
|
||||
gd::ResourceExposer::ExposeLayoutResources(project, layout, worker);
|
||||
REQUIRE(worker.bitmapFonts.size() == 1);
|
||||
REQUIRE(worker.bitmapFonts[0] == "res3");
|
||||
REQUIRE(worker.images.size() == 1);
|
||||
REQUIRE(worker.images[0] == "res1");
|
||||
REQUIRE(worker.audios.size() == 1);
|
||||
REQUIRE(worker.audios[0] == "res4");
|
||||
}
|
||||
|
||||
SECTION("Can find resource usages in event-based object functions") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
SetupProjectWithDummyPlatform(project, platform);
|
||||
|
||||
project.GetResourcesManager().AddResource(
|
||||
"res1", "path/to/file1.png", "image");
|
||||
project.GetResourcesManager().AddResource(
|
||||
"res2", "path/to/file2.png", "image");
|
||||
project.GetResourcesManager().AddResource(
|
||||
"res3", "path/to/file3.png", "image");
|
||||
ArbitraryResourceWorkerTest worker(project.GetResourcesManager());
|
||||
|
||||
auto& extension = project.InsertNewEventsFunctionsExtension("MyEventExtension", 0);
|
||||
auto& object = extension.GetEventsBasedObjects().InsertNew("MyObject", 0);
|
||||
auto& function = object.GetEventsFunctions().InsertNewEventsFunction("MyFunction", 0);
|
||||
|
||||
gd::StandardEvent standardEvent;
|
||||
gd::Instruction instruction;
|
||||
instruction.SetType("MyExtension::DoSomethingWithResources");
|
||||
instruction.SetParametersCount(3);
|
||||
instruction.SetParameter(0, "res3");
|
||||
instruction.SetParameter(1, "res1");
|
||||
instruction.SetParameter(2, "res4");
|
||||
standardEvent.GetActions().Insert(instruction);
|
||||
function.GetEvents().InsertEvent(standardEvent);
|
||||
|
||||
auto& layout = project.InsertNewLayout("MyScene", 0);
|
||||
|
||||
// MyEventExtension::MyObject::MyFunction doesn't need to be actually used in
|
||||
// events because the implementation is naive.
|
||||
|
||||
gd::ResourceExposer::ExposeLayoutResources(project, layout, worker);
|
||||
REQUIRE(worker.bitmapFonts.size() == 1);
|
||||
REQUIRE(worker.bitmapFonts[0] == "res3");
|
||||
REQUIRE(worker.images.size() == 1);
|
||||
REQUIRE(worker.images[0] == "res1");
|
||||
REQUIRE(worker.audios.size() == 1);
|
||||
REQUIRE(worker.audios[0] == "res4");
|
||||
}
|
||||
|
||||
SECTION("Can find resource usages in layer effects") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
|
@@ -139,8 +139,8 @@ TEST_CASE("PropertyFunctionGenerator", "[common]") {
|
||||
.SetLabel("Dot shape")
|
||||
.SetDescription("The shape is used for collision.")
|
||||
.SetGroup("Movement");
|
||||
property.AddChoice("DotShape", "Dot shape");
|
||||
property.AddChoice("BoundingDisk", "Bounding disk");
|
||||
property.GetExtraInfo().push_back("Dot shape");
|
||||
property.GetExtraInfo().push_back("Bounding disk");
|
||||
|
||||
gd::PropertyFunctionGenerator::GenerateBehaviorGetterAndSetter(
|
||||
project, extension, behavior, property, false);
|
||||
@@ -157,7 +157,7 @@ TEST_CASE("PropertyFunctionGenerator", "[common]") {
|
||||
gd::EventsFunction::ExpressionAndCondition);
|
||||
REQUIRE(getter.GetExpressionType().GetName() == "stringWithSelector");
|
||||
REQUIRE(getter.GetExpressionType().GetExtraInfo() ==
|
||||
"[\"DotShape\",\"BoundingDisk\"]");
|
||||
"[\"Dot shape\",\"Bounding disk\"]");
|
||||
}
|
||||
|
||||
SECTION("Can generate functions for a boolean property in a behavior") {
|
||||
@@ -386,8 +386,8 @@ TEST_CASE("PropertyFunctionGenerator", "[common]") {
|
||||
.SetLabel("Dot shape")
|
||||
.SetDescription("The shape is used for collision.")
|
||||
.SetGroup("Movement");
|
||||
property.AddChoice("DotShape", "Dot shape");
|
||||
property.AddChoice("BoundingDisk", "Bounding disk");
|
||||
property.GetExtraInfo().push_back("Dot shape");
|
||||
property.GetExtraInfo().push_back("Bounding disk");
|
||||
|
||||
gd::PropertyFunctionGenerator::GenerateObjectGetterAndSetter(
|
||||
project, extension, object, property);
|
||||
@@ -404,7 +404,7 @@ TEST_CASE("PropertyFunctionGenerator", "[common]") {
|
||||
gd::EventsFunction::ExpressionAndCondition);
|
||||
REQUIRE(getter.GetExpressionType().GetName() == "stringWithSelector");
|
||||
REQUIRE(getter.GetExpressionType().GetExtraInfo() ==
|
||||
"[\"DotShape\",\"BoundingDisk\"]");
|
||||
"[\"Dot shape\",\"Bounding disk\"]");
|
||||
}
|
||||
|
||||
SECTION("Can generate functions for a boolean property in an object") {
|
||||
|
@@ -97,14 +97,6 @@ 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)
|
||||
@@ -115,13 +107,12 @@ namespace gdjs {
|
||||
this._setOriginalDepth(
|
||||
getValidDimensionValue(newObjectData.content.depth)
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): Object3DNetworkSyncData {
|
||||
getNetworkSyncData(): Object3DNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
...super.getNetworkSyncData(),
|
||||
z: this.getZ(),
|
||||
d: this.getDepth(),
|
||||
rx: this.getRotationX(),
|
||||
@@ -132,11 +123,8 @@ namespace gdjs {
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: Object3DNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
) {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
updateFromNetworkSyncData(networkSyncData: Object3DNetworkSyncData) {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
if (networkSyncData.z !== undefined) this.setZ(networkSyncData.z);
|
||||
if (networkSyncData.d !== undefined) this.setDepth(networkSyncData.d);
|
||||
if (networkSyncData.rx !== undefined)
|
||||
|
@@ -452,11 +452,9 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): Cube3DObjectNetworkSyncData {
|
||||
getNetworkSyncData(): Cube3DObjectNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
...super.getNetworkSyncData(),
|
||||
mt: this._materialType,
|
||||
fo: this._facesOrientation,
|
||||
bfu: this._backFaceUpThroughWhichAxisRotation,
|
||||
@@ -468,10 +466,9 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: Cube3DObjectNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
networkSyncData: Cube3DObjectNetworkSyncData
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
|
||||
if (networkSyncData.mt !== undefined) {
|
||||
this._materialType = networkSyncData.mt;
|
||||
|
@@ -1,16 +1,12 @@
|
||||
namespace gdjs {
|
||||
type CustomObject3DNetworkSyncDataType = {
|
||||
type CustomObject3DNetworkSyncDataType = CustomObjectNetworkSyncDataType & {
|
||||
z: float;
|
||||
d: float;
|
||||
rx: float;
|
||||
ry: float;
|
||||
ifz: boolean;
|
||||
ccz: float;
|
||||
};
|
||||
|
||||
type CustomObject3DNetworkSyncData = CustomObjectNetworkSyncData &
|
||||
CustomObject3DNetworkSyncDataType;
|
||||
|
||||
/**
|
||||
* Base class for 3D custom objects.
|
||||
*/
|
||||
@@ -89,25 +85,21 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): CustomObject3DNetworkSyncData {
|
||||
getNetworkSyncData(): CustomObject3DNetworkSyncDataType {
|
||||
return {
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
...super.getNetworkSyncData(),
|
||||
z: this.getZ(),
|
||||
d: this.getDepth(),
|
||||
rx: this.getRotationX(),
|
||||
ry: this.getRotationY(),
|
||||
ifz: this.isFlippedZ(),
|
||||
ccz: this._customCenterZ,
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: CustomObject3DNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
networkSyncData: CustomObject3DNetworkSyncDataType
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
if (networkSyncData.z !== undefined) this.setZ(networkSyncData.z);
|
||||
if (networkSyncData.d !== undefined) this.setDepth(networkSyncData.d);
|
||||
if (networkSyncData.rx !== undefined)
|
||||
@@ -115,8 +107,6 @@ 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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@@ -162,12 +162,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('3D object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'Base3DBehavior')
|
||||
.useStandardParameters(
|
||||
'number',
|
||||
gd.ParameterOptions.makeNewOptions().setDescription(
|
||||
_('Angle (in degrees)')
|
||||
)
|
||||
)
|
||||
.useStandardParameters('number', gd.ParameterOptions.makeNewOptions())
|
||||
.setFunctionName('setRotationX')
|
||||
.setGetter('getRotationX');
|
||||
|
||||
@@ -183,12 +178,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('3D object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'Base3DBehavior')
|
||||
.useStandardParameters(
|
||||
'number',
|
||||
gd.ParameterOptions.makeNewOptions().setDescription(
|
||||
_('Angle (in degrees)')
|
||||
)
|
||||
)
|
||||
.useStandardParameters('number', gd.ParameterOptions.makeNewOptions())
|
||||
.setFunctionName('setRotationY')
|
||||
.setGetter('getRotationY');
|
||||
|
||||
@@ -206,7 +196,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('3D object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'Base3DBehavior')
|
||||
.addParameter('number', _('Angle to add (in degrees)'), '', false)
|
||||
.addParameter('number', _('Rotation angle'), '', false)
|
||||
.markAsAdvanced()
|
||||
.setFunctionName('turnAroundX');
|
||||
|
||||
@@ -224,7 +214,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('3D object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'Base3DBehavior')
|
||||
.addParameter('number', _('Angle to add (in degrees)'), '', false)
|
||||
.addParameter('number', _('Rotation angle'), '', false)
|
||||
.markAsAdvanced()
|
||||
.setFunctionName('turnAroundY');
|
||||
|
||||
@@ -242,7 +232,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('3D object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'Base3DBehavior')
|
||||
.addParameter('number', _('Angle to add (in degrees)'), '', false)
|
||||
.addParameter('number', _('Rotation angle'), '', false)
|
||||
.markAsAdvanced()
|
||||
.setFunctionName('turnAroundZ');
|
||||
}
|
||||
@@ -252,7 +242,7 @@ module.exports = {
|
||||
.addObject(
|
||||
'Model3DObject',
|
||||
_('3D Model'),
|
||||
_('An animated 3D model, useful for most elements of a 3D game.'),
|
||||
_('An animated 3D model.'),
|
||||
'JsPlatform/Extensions/3d_model.svg',
|
||||
new gd.Model3DObjectConfiguration()
|
||||
)
|
||||
@@ -604,12 +594,7 @@ module.exports = {
|
||||
'res/conditions/3d_box.svg'
|
||||
)
|
||||
.addParameter('object', _('3D model'), 'Model3DObject', false)
|
||||
.useStandardParameters(
|
||||
'number',
|
||||
gd.ParameterOptions.makeNewOptions().setDescription(
|
||||
_('Angle (in degrees)')
|
||||
)
|
||||
)
|
||||
.useStandardParameters('number', gd.ParameterOptions.makeNewOptions())
|
||||
.setHidden()
|
||||
.setFunctionName('setRotationX')
|
||||
.setGetter('getRotationX');
|
||||
@@ -626,12 +611,7 @@ module.exports = {
|
||||
'res/conditions/3d_box.svg'
|
||||
)
|
||||
.addParameter('object', _('3D model'), 'Model3DObject', false)
|
||||
.useStandardParameters(
|
||||
'number',
|
||||
gd.ParameterOptions.makeNewOptions().setDescription(
|
||||
_('Angle (in degrees)')
|
||||
)
|
||||
)
|
||||
.useStandardParameters('number', gd.ParameterOptions.makeNewOptions())
|
||||
.setHidden()
|
||||
.setFunctionName('setRotationY')
|
||||
.setGetter('getRotationY');
|
||||
@@ -650,7 +630,7 @@ module.exports = {
|
||||
'res/conditions/3d_box.svg'
|
||||
)
|
||||
.addParameter('object', _('3D model'), 'Model3DObject', false)
|
||||
.addParameter('number', _('Angle to add (in degrees)'), '', false)
|
||||
.addParameter('number', _('Rotation angle'), '', false)
|
||||
.markAsAdvanced()
|
||||
.setHidden()
|
||||
.setFunctionName('turnAroundX');
|
||||
@@ -669,7 +649,7 @@ module.exports = {
|
||||
'res/conditions/3d_box.svg'
|
||||
)
|
||||
.addParameter('object', _('3D model'), 'Model3DObject', false)
|
||||
.addParameter('number', _('Angle to add (in degrees)'), '', false)
|
||||
.addParameter('number', _('Rotation angle'), '', false)
|
||||
.markAsAdvanced()
|
||||
.setHidden()
|
||||
.setFunctionName('turnAroundY');
|
||||
@@ -688,7 +668,7 @@ module.exports = {
|
||||
'res/conditions/3d_box.svg'
|
||||
)
|
||||
.addParameter('object', _('3D model'), 'Model3DObject', false)
|
||||
.addParameter('number', _('Angle to add (in degrees)'), '', false)
|
||||
.addParameter('number', _('Rotation angle'), '', false)
|
||||
.markAsAdvanced()
|
||||
.setHidden()
|
||||
.setFunctionName('turnAroundZ');
|
||||
@@ -1513,12 +1493,7 @@ module.exports = {
|
||||
'res/conditions/3d_box.svg'
|
||||
)
|
||||
.addParameter('object', _('3D cube'), 'Cube3DObject', false)
|
||||
.useStandardParameters(
|
||||
'number',
|
||||
gd.ParameterOptions.makeNewOptions().setDescription(
|
||||
_('Angle (in degrees)')
|
||||
)
|
||||
)
|
||||
.useStandardParameters('number', gd.ParameterOptions.makeNewOptions())
|
||||
.setFunctionName('setRotationX')
|
||||
.setHidden()
|
||||
.setGetter('getRotationX');
|
||||
@@ -1535,12 +1510,7 @@ module.exports = {
|
||||
'res/conditions/3d_box.svg'
|
||||
)
|
||||
.addParameter('object', _('3D cube'), 'Cube3DObject', false)
|
||||
.useStandardParameters(
|
||||
'number',
|
||||
gd.ParameterOptions.makeNewOptions().setDescription(
|
||||
_('Angle (in degrees)')
|
||||
)
|
||||
)
|
||||
.useStandardParameters('number', gd.ParameterOptions.makeNewOptions())
|
||||
.setFunctionName('setRotationY')
|
||||
.setHidden()
|
||||
.setGetter('getRotationY');
|
||||
@@ -1901,11 +1871,6 @@ 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');
|
||||
}
|
||||
{
|
||||
@@ -1913,9 +1878,7 @@ module.exports = {
|
||||
.addEffect('AmbientLight')
|
||||
.setFullName(_('Ambient light'))
|
||||
.setDescription(
|
||||
_(
|
||||
'A light that illuminates all objects from every direction. Often used along with a Directional light (though a Hemisphere light can be used instead of an Ambient light).'
|
||||
)
|
||||
_('A light that illuminates all objects from every direction.')
|
||||
)
|
||||
.markAsNotWorkingForObjects()
|
||||
.markAsOnlyWorkingFor3D()
|
||||
@@ -1936,11 +1899,7 @@ module.exports = {
|
||||
const effect = extension
|
||||
.addEffect('DirectionalLight')
|
||||
.setFullName(_('Directional light'))
|
||||
.setDescription(
|
||||
_(
|
||||
"A very far light source like the sun. This is the light to use for casting shadows for 3D objects (other lights won't emit shadows). Often used along with a Hemisphere light."
|
||||
)
|
||||
)
|
||||
.setDescription(_('A very far light source like the sun.'))
|
||||
.markAsNotWorkingForObjects()
|
||||
.markAsOnlyWorkingFor3D()
|
||||
.addIncludeFile('Extensions/3D/DirectionalLight.js');
|
||||
@@ -2024,7 +1983,7 @@ module.exports = {
|
||||
.setFullName(_('Hemisphere light'))
|
||||
.setDescription(
|
||||
_(
|
||||
'A light that illuminates objects from every direction with a gradient. Often used along with a Directional light.'
|
||||
'A light that illuminates objects from every direction with a gradient.'
|
||||
)
|
||||
)
|
||||
.markAsNotWorkingForObjects()
|
||||
@@ -2068,48 +2027,6 @@ module.exports = {
|
||||
.setType('number')
|
||||
.setGroup(_('Orientation'));
|
||||
}
|
||||
{
|
||||
const effect = extension
|
||||
.addEffect('Skybox')
|
||||
.setFullName(_('Skybox'))
|
||||
.setDescription(
|
||||
_('Display a background on a cube surrounding the scene.')
|
||||
)
|
||||
.markAsNotWorkingForObjects()
|
||||
.markAsOnlyWorkingFor3D()
|
||||
.addIncludeFile('Extensions/3D/Skybox.js');
|
||||
const properties = effect.getProperties();
|
||||
properties
|
||||
.getOrCreate('rightFaceResourceName')
|
||||
.setType('resource')
|
||||
.addExtraInfo('image')
|
||||
.setLabel(_('Right face (X+)'));
|
||||
properties
|
||||
.getOrCreate('leftFaceResourceName')
|
||||
.setType('resource')
|
||||
.addExtraInfo('image')
|
||||
.setLabel(_('Left face (X-)'));
|
||||
properties
|
||||
.getOrCreate('bottomFaceResourceName')
|
||||
.setType('resource')
|
||||
.addExtraInfo('image')
|
||||
.setLabel(_('Bottom face (Y+)'));
|
||||
properties
|
||||
.getOrCreate('topFaceResourceName')
|
||||
.setType('resource')
|
||||
.addExtraInfo('image')
|
||||
.setLabel(_('Top face (Y-)'));
|
||||
properties
|
||||
.getOrCreate('frontFaceResourceName')
|
||||
.setType('resource')
|
||||
.addExtraInfo('image')
|
||||
.setLabel(_('Front face (Z+)'));
|
||||
properties
|
||||
.getOrCreate('backFaceResourceName')
|
||||
.setType('resource')
|
||||
.addExtraInfo('image')
|
||||
.setLabel(_('Back face (Z-)'));
|
||||
}
|
||||
{
|
||||
const effect = extension
|
||||
.addEffect('HueAndSaturation')
|
||||
|
@@ -8,7 +8,6 @@ namespace gdjs {
|
||||
anis: Model3DAnimation[];
|
||||
ai: integer;
|
||||
ass: float;
|
||||
aet: float;
|
||||
ap: boolean;
|
||||
cfd: float;
|
||||
};
|
||||
@@ -153,14 +152,6 @@ 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
|
||||
@@ -190,14 +181,8 @@ namespace gdjs {
|
||||
oldObjectData.content.keepAspectRatio !==
|
||||
newObjectData.content.keepAspectRatio ||
|
||||
oldObjectData.content.materialType !==
|
||||
newObjectData.content.materialType ||
|
||||
oldObjectData.content.centerLocation !==
|
||||
newObjectData.content.centerLocation
|
||||
newObjectData.content.materialType
|
||||
) {
|
||||
// The center is applied to the model by `_updateModel`.
|
||||
this._centerPoint = getPointForLocation(
|
||||
newObjectData.content.centerLocation
|
||||
);
|
||||
this._updateModel(newObjectData);
|
||||
}
|
||||
if (
|
||||
@@ -207,7 +192,14 @@ namespace gdjs {
|
||||
this._originPoint = getPointForLocation(
|
||||
newObjectData.content.originLocation
|
||||
);
|
||||
this._renderer.updatePosition();
|
||||
}
|
||||
if (
|
||||
oldObjectData.content.centerLocation !==
|
||||
newObjectData.content.centerLocation
|
||||
) {
|
||||
this._centerPoint = getPointForLocation(
|
||||
newObjectData.content.centerLocation
|
||||
);
|
||||
}
|
||||
if (
|
||||
oldObjectData.content.isCastingShadow !==
|
||||
@@ -224,28 +216,24 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): Model3DObjectNetworkSyncData {
|
||||
getNetworkSyncData(): Model3DObjectNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
...super.getNetworkSyncData(),
|
||||
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,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
networkSyncData: Model3DObjectNetworkSyncData
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
|
||||
if (networkSyncData.mt !== undefined) {
|
||||
this._materialType = networkSyncData.mt;
|
||||
@@ -259,14 +247,11 @@ 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.aet !== undefined) {
|
||||
this.setAnimationElapsedTime(networkSyncData.aet);
|
||||
if (networkSyncData.ass !== undefined) {
|
||||
this.setAnimationSpeedScale(networkSyncData.ass);
|
||||
}
|
||||
if (networkSyncData.ap !== undefined) {
|
||||
if (networkSyncData.ap !== this.isAnimationPaused()) {
|
||||
@@ -288,17 +273,14 @@ 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,
|
||||
width,
|
||||
height,
|
||||
depth,
|
||||
this._getOriginalWidth(),
|
||||
this._getOriginalHeight(),
|
||||
this._getOriginalDepth(),
|
||||
keepAspectRatio
|
||||
);
|
||||
}
|
||||
|
@@ -233,10 +233,6 @@ 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,7 +286,6 @@ 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.
|
||||
|
@@ -1,102 +0,0 @@
|
||||
namespace gdjs {
|
||||
interface SkyboxFilterNetworkSyncData {}
|
||||
gdjs.PixiFiltersTools.registerFilterCreator(
|
||||
'Scene3D::Skybox',
|
||||
new (class implements gdjs.PixiFiltersTools.FilterCreator {
|
||||
makeFilter(
|
||||
target: EffectsTarget,
|
||||
effectData: EffectData
|
||||
): gdjs.PixiFiltersTools.Filter {
|
||||
if (typeof THREE === 'undefined') {
|
||||
return new gdjs.PixiFiltersTools.EmptyFilter();
|
||||
}
|
||||
return new (class implements gdjs.PixiFiltersTools.Filter {
|
||||
_cubeTexture: THREE.CubeTexture;
|
||||
_oldBackground:
|
||||
| THREE.CubeTexture
|
||||
| THREE.Texture
|
||||
| THREE.Color
|
||||
| null = null;
|
||||
_isEnabled: boolean = false;
|
||||
|
||||
constructor() {
|
||||
this._cubeTexture = target
|
||||
.getRuntimeScene()
|
||||
.getGame()
|
||||
.getImageManager()
|
||||
.getThreeCubeTexture(
|
||||
effectData.stringParameters.rightFaceResourceName,
|
||||
effectData.stringParameters.leftFaceResourceName,
|
||||
effectData.stringParameters.topFaceResourceName,
|
||||
effectData.stringParameters.bottomFaceResourceName,
|
||||
effectData.stringParameters.frontFaceResourceName,
|
||||
effectData.stringParameters.backFaceResourceName
|
||||
);
|
||||
}
|
||||
|
||||
isEnabled(target: EffectsTarget): boolean {
|
||||
return this._isEnabled;
|
||||
}
|
||||
setEnabled(target: EffectsTarget, enabled: boolean): boolean {
|
||||
if (this._isEnabled === enabled) {
|
||||
return true;
|
||||
}
|
||||
if (enabled) {
|
||||
return this.applyEffect(target);
|
||||
} else {
|
||||
return this.removeEffect(target);
|
||||
}
|
||||
}
|
||||
applyEffect(target: EffectsTarget): boolean {
|
||||
const scene = target.get3DRendererObject() as
|
||||
| THREE.Scene
|
||||
| null
|
||||
| undefined;
|
||||
if (!scene) {
|
||||
return false;
|
||||
}
|
||||
// TODO Add a background stack in LayerPixiRenderer to allow
|
||||
// filters to stack them.
|
||||
this._oldBackground = scene.background;
|
||||
scene.background = this._cubeTexture;
|
||||
if (!scene.environment) {
|
||||
scene.environment = this._cubeTexture;
|
||||
}
|
||||
this._isEnabled = true;
|
||||
return true;
|
||||
}
|
||||
removeEffect(target: EffectsTarget): boolean {
|
||||
const scene = target.get3DRendererObject() as
|
||||
| THREE.Scene
|
||||
| null
|
||||
| undefined;
|
||||
if (!scene) {
|
||||
return false;
|
||||
}
|
||||
scene.background = this._oldBackground;
|
||||
scene.environment = null;
|
||||
this._isEnabled = false;
|
||||
return true;
|
||||
}
|
||||
updatePreRender(target: gdjs.EffectsTarget): any {}
|
||||
updateDoubleParameter(parameterName: string, value: number): void {}
|
||||
getDoubleParameter(parameterName: string): number {
|
||||
return 0;
|
||||
}
|
||||
updateStringParameter(parameterName: string, value: string): void {}
|
||||
updateColorParameter(parameterName: string, value: number): void {}
|
||||
getColorParameter(parameterName: string): number {
|
||||
return 0;
|
||||
}
|
||||
updateBooleanParameter(parameterName: string, value: boolean): void {}
|
||||
getNetworkSyncData(): SkyboxFilterNetworkSyncData {
|
||||
return {};
|
||||
}
|
||||
updateFromNetworkSyncData(
|
||||
syncData: SkyboxFilterNetworkSyncData
|
||||
): void {}
|
||||
})();
|
||||
}
|
||||
})()
|
||||
);
|
||||
}
|
@@ -473,14 +473,7 @@ namespace gdjs {
|
||||
this._parentOldMaxY = instanceContainer.getUnrotatedViewportMaxY();
|
||||
}
|
||||
|
||||
doStepPostEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
// Custom objects can be resized during the events step.
|
||||
// The anchor constraints must be applied on child-objects after the parent events.
|
||||
const isChildObject = instanceContainer !== instanceContainer.getScene();
|
||||
if (isChildObject) {
|
||||
this.doStepPreEvents(instanceContainer);
|
||||
}
|
||||
}
|
||||
doStepPostEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {}
|
||||
|
||||
private _convertCoords(
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
|
@@ -145,11 +145,9 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
override getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): BBTextObjectNetworkSyncData {
|
||||
override getNetworkSyncData(): BBTextObjectNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
...super.getNetworkSyncData(),
|
||||
text: this._text,
|
||||
o: this._opacity,
|
||||
c: this._color,
|
||||
@@ -164,10 +162,9 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
override updateFromNetworkSyncData(
|
||||
networkSyncData: BBTextObjectNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
networkSyncData: BBTextObjectNetworkSyncData
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
if (this._text !== undefined) {
|
||||
this.setBBText(networkSyncData.text);
|
||||
}
|
||||
@@ -386,10 +383,6 @@ namespace gdjs {
|
||||
return this._renderer.getHeight();
|
||||
}
|
||||
|
||||
override setWidth(width: float): void {
|
||||
this.setWrappingWidth(width);
|
||||
}
|
||||
|
||||
override getDrawableY(): float {
|
||||
return (
|
||||
this.getY() -
|
||||
|
@@ -155,11 +155,9 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
override getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): BitmapTextObjectNetworkSyncData {
|
||||
override getNetworkSyncData(): BitmapTextObjectNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
...super.getNetworkSyncData(),
|
||||
text: this._text,
|
||||
opa: this._opacity,
|
||||
tint: this._tint,
|
||||
@@ -174,10 +172,9 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
override updateFromNetworkSyncData(
|
||||
networkSyncData: BitmapTextObjectNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
networkSyncData: BitmapTextObjectNetworkSyncData
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
if (this._text !== undefined) {
|
||||
this.setText(networkSyncData.text);
|
||||
}
|
||||
@@ -429,10 +426,6 @@ namespace gdjs {
|
||||
return this._renderer.getHeight();
|
||||
}
|
||||
|
||||
override setWidth(width: float): void {
|
||||
this.setWrappingWidth(width);
|
||||
}
|
||||
|
||||
override getDrawableY(): float {
|
||||
return (
|
||||
this.getY() -
|
||||
|
@@ -21,9 +21,7 @@ module.exports = {
|
||||
.setExtensionInformation(
|
||||
'DebuggerTools',
|
||||
_('Debugger Tools'),
|
||||
_(
|
||||
'Allow to interact with the editor debugger from the game (notably: enable 2D debug draw, log a message in the debugger console).'
|
||||
),
|
||||
_('Allow to interact with the editor debugger from the game.'),
|
||||
'Arthur Pacaud (arthuro555), Aurélien Vivet (Bouh)',
|
||||
'MIT'
|
||||
)
|
||||
|
@@ -12,8 +12,7 @@ This project is released under the MIT License.
|
||||
#include "GDCore/Tools/Localization.h"
|
||||
|
||||
void DestroyOutsideBehavior::InitializeContent(gd::SerializerElement& content) {
|
||||
content.SetAttribute("extraBorder", 200);
|
||||
content.SetAttribute("unseenGraceDistance", 10000);
|
||||
content.SetAttribute("extraBorder", 300);
|
||||
}
|
||||
|
||||
#if defined(GD_IDE_ONLY)
|
||||
@@ -28,15 +27,7 @@ DestroyOutsideBehavior::GetProperties(
|
||||
.SetType("Number")
|
||||
.SetMeasurementUnit(gd::MeasurementUnit::GetPixel())
|
||||
.SetLabel(_("Deletion margin"))
|
||||
.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."));
|
||||
.SetDescription(_("Margin before deleting the object, in pixels"));
|
||||
|
||||
return properties;
|
||||
}
|
||||
@@ -47,8 +38,6 @@ 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,7 +6,6 @@ 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"
|
||||
@@ -20,10 +19,11 @@ 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). If the object appears outside of the screen, it's not "
|
||||
"removed unless it goes beyond the unseen object grace distance."),
|
||||
"(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."),
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetCategory("Game mechanic")
|
||||
@@ -44,39 +44,34 @@ void DeclareDestroyOutsideBehaviorExtension(gd::PlatformExtension& extension) {
|
||||
std::shared_ptr<gd::BehaviorsSharedData>())
|
||||
.SetQuickCustomizationVisibility(gd::QuickCustomization::Hidden);
|
||||
|
||||
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")
|
||||
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")
|
||||
.AddParameter("object", _("Object"))
|
||||
.AddParameter("behavior", _("Behavior"), "DestroyOutside")
|
||||
.UseStandardParameters("number", gd::ParameterOptions::MakeNewOptions())
|
||||
.MarkAsAdvanced();
|
||||
.UseStandardRelationalOperatorParameters(
|
||||
"number", gd::ParameterOptions::MakeNewOptions())
|
||||
.MarkAsAdvanced()
|
||||
.SetFunctionName("GetExtraBorder");
|
||||
|
||||
// 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")
|
||||
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")
|
||||
.AddParameter("object", _("Object"))
|
||||
.AddParameter("behavior", _("Behavior"), "DestroyOutside")
|
||||
.UseStandardParameters("number", gd::ParameterOptions::MakeNewOptions())
|
||||
.MarkAsAdvanced();
|
||||
.UseStandardOperatorParameters("number",
|
||||
gd::ParameterOptions::MakeNewOptions())
|
||||
.MarkAsAdvanced()
|
||||
.SetFunctionName("SetExtraBorder")
|
||||
.SetGetter("GetExtraBorder");
|
||||
}
|
||||
|
@@ -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,36 +29,19 @@ 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");
|
||||
.SetFunctionName("getExtraBorder")
|
||||
.SetIncludeFile(
|
||||
"Extensions/DestroyOutsideBehavior/"
|
||||
"destroyoutsideruntimebehavior.js");
|
||||
GetAllActionsForBehavior("DestroyOutsideBehavior::DestroyOutside")
|
||||
["DestroyOutsideBehavior::ExtraBorder"]
|
||||
.SetFunctionName("setExtraBorder")
|
||||
.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");
|
||||
.SetGetter("getExtraBorder")
|
||||
.SetIncludeFile(
|
||||
"Extensions/DestroyOutsideBehavior/"
|
||||
"destroyoutsideruntimebehavior.js");
|
||||
|
||||
GD_COMPLETE_EXTENSION_COMPILATION_INFORMATION();
|
||||
};
|
||||
|
@@ -8,9 +8,7 @@ namespace gdjs {
|
||||
* The DestroyOutsideRuntimeBehavior represents a behavior that destroys the object when it leaves the screen.
|
||||
*/
|
||||
export class DestroyOutsideRuntimeBehavior extends gdjs.RuntimeBehavior {
|
||||
_extraBorder: float;
|
||||
_unseenGraceDistance: float;
|
||||
_hasBeenOnScreen: boolean;
|
||||
_extraBorder: any;
|
||||
|
||||
constructor(
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
@@ -19,20 +17,12 @@ 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;
|
||||
}
|
||||
|
||||
@@ -45,47 +35,23 @@ 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 < cameraLeft ||
|
||||
ocx - boundingCircleRadius - this._extraBorder > cameraRight ||
|
||||
ocy + boundingCircleRadius + this._extraBorder < cameraTop ||
|
||||
ocy - boundingCircleRadius - this._extraBorder > cameraBottom
|
||||
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
|
||||
) {
|
||||
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;
|
||||
//We are outside the camera area.
|
||||
this.owner.deleteFromScene();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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).
|
||||
* Set an additional border to the camera viewport as a buffer before the object gets destroyed.
|
||||
* @param val Border in pixels.
|
||||
*/
|
||||
setExtraBorder(val: number): void {
|
||||
@@ -93,36 +59,12 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the additional border outside the camera area.
|
||||
* Get the additional border of the camera viewport buffer which triggers the destruction of an object.
|
||||
* @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',
|
||||
|
@@ -21,9 +21,7 @@ module.exports = {
|
||||
.setExtensionInformation(
|
||||
'FileSystem',
|
||||
_('File system'),
|
||||
_(
|
||||
'Access the filesystem of the operating system - only works on native, desktop games exported to Windows, Linux or macOS.'
|
||||
),
|
||||
_('Access the filesystem of the operating system.'),
|
||||
'Matthias Meike',
|
||||
'Open source (MIT License)'
|
||||
)
|
||||
|
@@ -5,25 +5,23 @@ Copyright (c) 2008-2016 Florian Rival (Florian.Rival@gmail.com)
|
||||
This project is released under the MIT License.
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include "GDCore/Extensions/PlatformExtension.h"
|
||||
#include "GDCore/Tools/Localization.h"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
void DeclareInventoryExtension(gd::PlatformExtension& extension) {
|
||||
extension
|
||||
.SetExtensionInformation(
|
||||
"Inventory",
|
||||
_("Inventories"),
|
||||
_("Actions and conditions to store named inventories in memory, "
|
||||
"with items (indexed by their name), a count for each of them, "
|
||||
"a maximum count and an equipped state. Can be loaded/saved "
|
||||
"from/to a GDevelop variable."),
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
extension.SetExtensionInformation(
|
||||
"Inventory",
|
||||
_("Inventories"),
|
||||
_("Provides actions and conditions to add an inventory to your game, "
|
||||
"with items in memory."),
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetExtensionHelpPath("/all-features/inventory")
|
||||
.SetCategory("Game mechanic");
|
||||
extension.AddInstructionOrExpressionGroupMetadata(_("Inventories"))
|
||||
extension
|
||||
.AddInstructionOrExpressionGroupMetadata(_("Inventories"))
|
||||
.SetIcon("CppPlatform/Extensions/Inventoryicon.png");
|
||||
|
||||
extension
|
||||
@@ -166,15 +164,14 @@ void DeclareInventoryExtension(gd::PlatformExtension& extension) {
|
||||
.SetFunctionName("InventoryTools::IsEquipped");
|
||||
|
||||
extension
|
||||
.AddAction(
|
||||
"SerializeToVariable",
|
||||
_("Save an inventory in a scene variable"),
|
||||
_("Save all the items of the inventory in a scene variable, so that "
|
||||
"it can be restored later."),
|
||||
_("Save inventory _PARAM1_ in variable _PARAM2_"),
|
||||
_("Variables"),
|
||||
"CppPlatform/Extensions/Inventoryicon.png",
|
||||
"CppPlatform/Extensions/Inventoryicon.png")
|
||||
.AddAction("SerializeToVariable",
|
||||
_("Save an inventory in a scene variable"),
|
||||
_("Save all the items of the inventory in a scene variable, so that "
|
||||
"it can be restored later."),
|
||||
_("Save inventory _PARAM1_ in variable _PARAM2_"),
|
||||
_("Variables"),
|
||||
"CppPlatform/Extensions/Inventoryicon.png",
|
||||
"CppPlatform/Extensions/Inventoryicon.png")
|
||||
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("string", _("Inventory name"))
|
||||
@@ -207,14 +204,13 @@ void DeclareInventoryExtension(gd::PlatformExtension& extension) {
|
||||
.SetFunctionName("InventoryTools::Count");
|
||||
|
||||
extension
|
||||
.AddExpression("Maximum",
|
||||
_("Item maximum"),
|
||||
_("Get the maximum of an item in the inventory, or 0 if "
|
||||
"it is unlimited"),
|
||||
"",
|
||||
"CppPlatform/Extensions/Inventoryicon.png")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("string", _("Inventory name"))
|
||||
.AddParameter("string", _("Item name"))
|
||||
.SetFunctionName("InventoryTools::Maximum");
|
||||
.AddExpression("Maximum",
|
||||
_("Item maximum"),
|
||||
_("Get the maximum of an item in the inventory, or 0 if it is unlimited"),
|
||||
"",
|
||||
"CppPlatform/Extensions/Inventoryicon.png")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("string", _("Inventory name"))
|
||||
.AddParameter("string", _("Item name"))
|
||||
.SetFunctionName("InventoryTools::Maximum");
|
||||
}
|
||||
|
@@ -21,9 +21,7 @@ module.exports = {
|
||||
.setExtensionInformation(
|
||||
'Leaderboards',
|
||||
_('Leaderboards'),
|
||||
_(
|
||||
'Allow your game to send scores to your leaderboards (anonymously or from the logged-in player) or display existing leaderboards to the player.'
|
||||
),
|
||||
_('Allow your game to send scores to your leaderboards.'),
|
||||
'Florian Rival',
|
||||
'Open source (MIT License)'
|
||||
)
|
||||
|
@@ -33,49 +33,6 @@ namespace gdjs {
|
||||
claimSecret?: string;
|
||||
};
|
||||
|
||||
// Rolling window rate limiting
|
||||
// Implements rate limiting to prevent abuse:
|
||||
// - Maximum 12 successful successful entries per minute across all leaderboards
|
||||
// - Maximum 6 successful successful entries per minute per individual leaderboard
|
||||
// - Works in addition to existing 500ms cooldown between entry tentatives
|
||||
let _successfulEntriesGlobal: number[] = []; // Timestamps of successful entries across all leaderboards
|
||||
|
||||
const GLOBAL_RATE_LIMIT_COUNT = 12;
|
||||
const PER_LEADERBOARD_RATE_LIMIT_COUNT = 6;
|
||||
const RATE_LIMIT_WINDOW_MS = 60 * 1000; // 1 minute in milliseconds
|
||||
|
||||
/**
|
||||
* Clean old entries from the rolling window (older than 1 minute)
|
||||
*/
|
||||
const cleanOldEntries = (
|
||||
entries: number[],
|
||||
currentTime: number
|
||||
): number[] => {
|
||||
return entries.filter(
|
||||
(timestamp) => currentTime - timestamp < RATE_LIMIT_WINDOW_MS
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if adding a new entry would exceed global rate limits.
|
||||
*/
|
||||
const wouldExceedGlobalSuccessRateLimit = (): boolean => {
|
||||
const currentTime = Date.now();
|
||||
_successfulEntriesGlobal = cleanOldEntries(
|
||||
_successfulEntriesGlobal,
|
||||
currentTime
|
||||
);
|
||||
return _successfulEntriesGlobal.length >= GLOBAL_RATE_LIMIT_COUNT;
|
||||
};
|
||||
|
||||
/**
|
||||
* Record a successful entry for global rate limiting tracking.
|
||||
*/
|
||||
const recordGlobalSuccessfulEntry = (): void => {
|
||||
const currentTime = Date.now();
|
||||
_successfulEntriesGlobal.push(currentTime);
|
||||
};
|
||||
|
||||
/**
|
||||
* Hold the state of the save of a score for a leaderboard.
|
||||
*/
|
||||
@@ -86,9 +43,6 @@ namespace gdjs {
|
||||
/** The promise that will be resolved when the score saving is done (successfully or not). */
|
||||
lastSavingPromise: Promise<void> | null = null;
|
||||
|
||||
/** Timestamps of successful entries for this leaderboard (for rate limiting) */
|
||||
private _successfulEntries: number[] = [];
|
||||
|
||||
// Score that is being saved:
|
||||
private _currentlySavingScore: number | null = null;
|
||||
private _currentlySavingPlayerName: string | null = null;
|
||||
@@ -153,36 +107,13 @@ namespace gdjs {
|
||||
);
|
||||
}
|
||||
|
||||
private _wouldExceedPerLeaderboardTentativeRateLimit(): boolean {
|
||||
// Prevent entries within 500ms of each other (per leaderboard)
|
||||
// as this would indicate surely a score saved every frame.
|
||||
//
|
||||
// Note that is on lastScoreSavingStartedAt, not lastScoreSavingSucceededAt,
|
||||
// which means we limit tentatives here (and not successes).
|
||||
private _isTooSoonToSaveAnotherScore(): boolean {
|
||||
return (
|
||||
!!this.lastScoreSavingStartedAt &&
|
||||
Date.now() - this.lastScoreSavingStartedAt < 500
|
||||
);
|
||||
}
|
||||
|
||||
private _wouldExceedPerLeaderboardSuccessRateLimit(): boolean {
|
||||
const currentTime = Date.now();
|
||||
this._successfulEntries = cleanOldEntries(
|
||||
this._successfulEntries,
|
||||
currentTime
|
||||
);
|
||||
return (
|
||||
this._successfulEntries.length >= PER_LEADERBOARD_RATE_LIMIT_COUNT
|
||||
);
|
||||
}
|
||||
|
||||
private _recordPerLeaderboardAndGlobalSuccessfulEntry(): void {
|
||||
const currentTime = Date.now();
|
||||
this._successfulEntries.push(currentTime);
|
||||
|
||||
recordGlobalSuccessfulEntry();
|
||||
}
|
||||
|
||||
startSaving({
|
||||
playerName,
|
||||
playerId,
|
||||
@@ -210,7 +141,7 @@ namespace gdjs {
|
||||
throw new Error('Ignoring this saving request.');
|
||||
}
|
||||
|
||||
if (this._wouldExceedPerLeaderboardTentativeRateLimit()) {
|
||||
if (this._isTooSoonToSaveAnotherScore()) {
|
||||
logger.warn(
|
||||
'Last entry was sent too little time ago. Ignoring this one.'
|
||||
);
|
||||
@@ -223,24 +154,6 @@ namespace gdjs {
|
||||
throw new Error('Ignoring this saving request.');
|
||||
}
|
||||
|
||||
// Rolling window rate limiting check for successful entries.
|
||||
if (wouldExceedGlobalSuccessRateLimit()) {
|
||||
logger.warn(
|
||||
'Rate limit exceeded. Too many entries have been successfully sent recently across all leaderboards. Ignoring this one.'
|
||||
);
|
||||
this._setError('GLOBAL_RATE_LIMIT_EXCEEDED');
|
||||
|
||||
throw new Error('Ignoring this saving request.');
|
||||
}
|
||||
if (this._wouldExceedPerLeaderboardSuccessRateLimit()) {
|
||||
logger.warn(
|
||||
'Rate limit exceeded. Too many entries have been successfully sent recently for this leaderboard. Ignoring this one.'
|
||||
);
|
||||
this._setError('LEADERBOARD_RATE_LIMIT_EXCEEDED');
|
||||
|
||||
throw new Error('Ignoring this saving request.');
|
||||
}
|
||||
|
||||
let resolveSavingPromise: () => void;
|
||||
const savingPromise = new Promise<void>((resolve) => {
|
||||
resolveSavingPromise = resolve;
|
||||
@@ -256,9 +169,6 @@ namespace gdjs {
|
||||
|
||||
return {
|
||||
closeSaving: (leaderboardEntry) => {
|
||||
// Record successful entry for rolling window rate limiting.
|
||||
this._recordPerLeaderboardAndGlobalSuccessfulEntry();
|
||||
|
||||
if (savingPromise !== this.lastSavingPromise) {
|
||||
logger.info(
|
||||
'Score saving result received, but another save was launched in the meantime - ignoring the result of this one.'
|
||||
@@ -486,10 +396,7 @@ namespace gdjs {
|
||||
|
||||
try {
|
||||
const { closeSaving, closeSavingWithError } =
|
||||
scoreSavingState.startSaving({
|
||||
playerName,
|
||||
score,
|
||||
});
|
||||
scoreSavingState.startSaving({ playerName, score });
|
||||
|
||||
try {
|
||||
const leaderboardEntry = await saveScore({
|
||||
@@ -533,10 +440,7 @@ namespace gdjs {
|
||||
|
||||
try {
|
||||
const { closeSaving, closeSavingWithError } =
|
||||
scoreSavingState.startSaving({
|
||||
playerId,
|
||||
score,
|
||||
});
|
||||
scoreSavingState.startSaving({ playerId, score });
|
||||
|
||||
try {
|
||||
const leaderboardEntryId = await saveScore({
|
||||
|
@@ -22,7 +22,7 @@ module.exports = {
|
||||
'Lighting',
|
||||
_('Lights'),
|
||||
|
||||
'This provides a 2D light object, and a behavior to mark other 2D objects as being obstacles for the lights. This is a great way to create a special atmosphere to your game, along with effects, make it more realistic or to create gameplays based on lights.',
|
||||
'This provides a light object, and a behavior to mark other objects as being obstacles for the lights. This is a great way to create a special atmosphere to your game, along with effects, make it more realistic or to create gameplays based on lights.',
|
||||
'Harsimran Virk',
|
||||
'MIT'
|
||||
)
|
||||
@@ -51,7 +51,7 @@ module.exports = {
|
||||
_('Light Obstacle Behavior'),
|
||||
'LightObstacleBehavior',
|
||||
_(
|
||||
'Flag objects as being obstacles to 2D lights. The light emitted by light objects will be stopped by the object. This does not work on 3D objects and 3D games.'
|
||||
'Flag objects as being obstacles to light. The light emitted by light objects will be stopped by the object.'
|
||||
),
|
||||
'',
|
||||
'CppPlatform/Extensions/lightObstacleIcon32.png',
|
||||
@@ -164,7 +164,7 @@ module.exports = {
|
||||
'LightObject',
|
||||
_('Light'),
|
||||
_(
|
||||
'Displays a 2D light on the scene, with a customizable radius and color. Add then the Light Obstacle behavior to the objects that must act as obstacle to the lights.'
|
||||
'Displays a light on the scene, with a customizable radius and color. Add then the Light Obstacle behavior to the objects that must act as obstacle to the lights.'
|
||||
),
|
||||
'CppPlatform/Extensions/lightIcon32.png',
|
||||
lightObject
|
||||
|
@@ -87,21 +87,16 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): LightNetworkSyncData {
|
||||
getNetworkSyncData(): LightNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
...super.getNetworkSyncData(),
|
||||
rad: this.getRadius(),
|
||||
col: this.getColor(),
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: LightNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
updateFromNetworkSyncData(networkSyncData: LightNetworkSyncData): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
|
||||
if (networkSyncData.rad !== undefined) {
|
||||
this.setRadius(networkSyncData.rad);
|
||||
|
@@ -239,7 +239,7 @@ namespace gdjs {
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
objectsLists: Hashtable<gdjs.RuntimeObject[]>,
|
||||
obj: gdjs.RuntimeObject | null,
|
||||
eventsFunctionContext: EventsFunctionContext | null | undefined
|
||||
eventsFunctionContext: EventsFunctionContext | undefined
|
||||
) {
|
||||
if (obj === null) {
|
||||
return false;
|
||||
|
@@ -21,9 +21,7 @@ module.exports = {
|
||||
.setExtensionInformation(
|
||||
'Multiplayer',
|
||||
_('Multiplayer'),
|
||||
_(
|
||||
'This allows players to join online lobbies and synchronize gameplay across devices without needing to manage servers or networking.\n\nUse the "Open game lobbies" action to let players join a game, and use conditions like "Lobby game has just started" to begin gameplay. Add the "Multiplayer object" behavior to game objects that should be synchronized, and assign or change their ownership using player numbers. Variables and game state (like scenes, scores, or timers) are automatically synced by the host, with options to change ownership or disable sync when needed. Common multiplayer logic —like handling joins/leaves, collisions, and host migration— is supported out-of-the-box for up to 8 players per game.'
|
||||
),
|
||||
_('Allow players to connect to lobbies and play together.'),
|
||||
'Florian Rival',
|
||||
'Open source (MIT License)'
|
||||
)
|
||||
|
@@ -729,9 +729,7 @@ namespace gdjs {
|
||||
behavior.playerNumber = ownerPlayerNumber;
|
||||
}
|
||||
|
||||
instance.updateFromNetworkSyncData(messageData, {
|
||||
clearInputs: false,
|
||||
});
|
||||
instance.updateFromNetworkSyncData(messageData);
|
||||
|
||||
setLastClockReceivedForInstanceOnScene({
|
||||
sceneNetworkId,
|
||||
@@ -1739,7 +1737,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.
|
||||
@@ -1892,7 +1890,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.
|
||||
@@ -1920,7 +1918,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();
|
||||
@@ -1939,7 +1937,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,
|
||||
|
@@ -389,15 +389,26 @@ namespace gdjs {
|
||||
this.updatePosition();
|
||||
}
|
||||
|
||||
setColor(rgbOrHexColor: string): void {
|
||||
const tint = gdjs.rgbOrHexStringToNumber(rgbOrHexColor);
|
||||
this._centerSprite.tint = tint;
|
||||
setColor(rgbColor): void {
|
||||
const colors = rgbColor.split(';');
|
||||
if (colors.length < 3) {
|
||||
return;
|
||||
}
|
||||
this._centerSprite.tint = gdjs.rgbToHexNumber(
|
||||
parseInt(colors[0], 10),
|
||||
parseInt(colors[1], 10),
|
||||
parseInt(colors[2], 10)
|
||||
);
|
||||
for (
|
||||
let borderCounter = 0;
|
||||
borderCounter < this._borderSprites.length;
|
||||
borderCounter++
|
||||
) {
|
||||
this._borderSprites[borderCounter].tint = tint;
|
||||
this._borderSprites[borderCounter].tint = gdjs.rgbToHexNumber(
|
||||
parseInt(colors[0], 10),
|
||||
parseInt(colors[1], 10),
|
||||
parseInt(colors[2], 10)
|
||||
);
|
||||
}
|
||||
this._spritesContainer.cacheAsBitmap = false;
|
||||
}
|
||||
@@ -405,11 +416,11 @@ namespace gdjs {
|
||||
getColor() {
|
||||
const rgb = new PIXI.Color(this._centerSprite.tint).toRgbArray();
|
||||
return (
|
||||
Math.round(rgb[0] * 255) +
|
||||
Math.floor(rgb[0] * 255) +
|
||||
';' +
|
||||
Math.round(rgb[1] * 255) +
|
||||
Math.floor(rgb[1] * 255) +
|
||||
';' +
|
||||
Math.round(rgb[2] * 255)
|
||||
Math.floor(rgb[2] * 255)
|
||||
);
|
||||
}
|
||||
|
||||
|
@@ -119,21 +119,18 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): PanelSpriteNetworkSyncData {
|
||||
getNetworkSyncData(): PanelSpriteNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
...super.getNetworkSyncData(),
|
||||
op: this.getOpacity(),
|
||||
color: this.getColor(),
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: PanelSpriteNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
networkSyncData: PanelSpriteNetworkSyncData
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
|
||||
// Texture is not synchronized, see if this is asked or not.
|
||||
|
||||
|
@@ -370,11 +370,9 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): ParticleEmitterObjectNetworkSyncData {
|
||||
getNetworkSyncData(): ParticleEmitterObjectNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
...super.getNetworkSyncData(),
|
||||
prms: this.particleRotationMinSpeed,
|
||||
prmx: this.particleRotationMaxSpeed,
|
||||
mpc: this.maxParticlesCount,
|
||||
@@ -401,10 +399,9 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
syncData: ParticleEmitterObjectNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
syncData: ParticleEmitterObjectNetworkSyncData
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(syncData, options);
|
||||
super.updateFromNetworkSyncData(syncData);
|
||||
if (syncData.x !== undefined) {
|
||||
this.setX(syncData.x);
|
||||
}
|
||||
|
@@ -6,7 +6,7 @@ namespace gdjs {
|
||||
const logger = new gdjs.Logger('Pathfinding behavior');
|
||||
|
||||
interface PathfindingNetworkSyncDataType {
|
||||
// Syncing the path and its position on it should be enough to have a good prediction.
|
||||
// Syncing the path should be enough to have a good prediction.
|
||||
path: FloatPoint[];
|
||||
pf: boolean;
|
||||
sp: number;
|
||||
@@ -15,7 +15,6 @@ namespace gdjs {
|
||||
tss: number;
|
||||
re: boolean;
|
||||
ma: number;
|
||||
dos: number;
|
||||
}
|
||||
|
||||
export interface PathfindingNetworkSyncData extends BehaviorNetworkSyncData {
|
||||
@@ -134,11 +133,9 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(
|
||||
options: GetNetworkSyncDataOptions
|
||||
): PathfindingNetworkSyncData {
|
||||
getNetworkSyncData(): PathfindingNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(options),
|
||||
...super.getNetworkSyncData(),
|
||||
props: {
|
||||
path: this._path,
|
||||
pf: this._pathFound,
|
||||
@@ -148,16 +145,14 @@ namespace gdjs {
|
||||
tss: this._totalSegmentDistance,
|
||||
re: this._reachedEnd,
|
||||
ma: this._movementAngle,
|
||||
dos: this._distanceOnSegment,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: PathfindingNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
networkSyncData: PathfindingNetworkSyncData
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
const behaviorSpecificProps = networkSyncData.props;
|
||||
if (behaviorSpecificProps.path !== undefined) {
|
||||
this._path = behaviorSpecificProps.path;
|
||||
@@ -186,9 +181,6 @@ namespace gdjs {
|
||||
if (behaviorSpecificProps.ma !== undefined) {
|
||||
this._movementAngle = behaviorSpecificProps.ma;
|
||||
}
|
||||
if (behaviorSpecificProps.dos !== undefined) {
|
||||
this._distanceOnSegment = behaviorSpecificProps.dos;
|
||||
}
|
||||
}
|
||||
|
||||
setCellWidth(width: float): void {
|
||||
|
@@ -21,11 +21,7 @@ module.exports = {
|
||||
.setExtensionInformation(
|
||||
'Physics2',
|
||||
_('2D Physics Engine'),
|
||||
"The 2D physics engine simulates realistic object physics, with gravity, forces, collisions, joints, etc. It's perfect for 2D games that need to have realistic behaving objects and a gameplay centered around it.\n" +
|
||||
'\n' +
|
||||
'Objects like floors or wall objects should usually be set to "Static" as type. Objects that should be moveable are usually "Dynamic" (default). "Kinematic" objects (typically, players or controlled characters) are only moved by their "linear velocity" and "angular velocity" - they can interact with other objects but only these other objects will move.\n' +
|
||||
'\n' +
|
||||
'Forces (and impulses) are expressed in all conditions/expressions/actions of the 2D physics engine in Newtons (N). Typical values for a force are 10-200 N. One meter is 100 pixels by default in the game (check the world scale). Mass is expressed in kilograms (kg).',
|
||||
"The 2D physics engine simulates realistic object physics, with gravity, forces, collisions, joints, etc. It's perfect for 2D games that need to have realistic behaving objects and a gameplay centered around it.",
|
||||
'Florian Rival, Franco Maciel',
|
||||
'MIT'
|
||||
)
|
||||
@@ -531,7 +527,6 @@ module.exports = {
|
||||
physics2Behavior,
|
||||
sharedData
|
||||
)
|
||||
.markAsIrrelevantForChildObjects()
|
||||
.setIncludeFile('Extensions/Physics2Behavior/physics2runtimebehavior.js')
|
||||
.addIncludeFile('Extensions/Physics2Behavior/Box2D_v2.3.1_min.wasm.js')
|
||||
.addRequiredFile('Extensions/Physics2Behavior/Box2D_v2.3.1_min.wasm.wasm')
|
||||
|
@@ -499,9 +499,7 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(
|
||||
options: GetNetworkSyncDataOptions
|
||||
): Physics2NetworkSyncData {
|
||||
getNetworkSyncData(): Physics2NetworkSyncData {
|
||||
const bodyProps = this._body
|
||||
? {
|
||||
tpx: this._body.GetTransform().get_p().get_x(),
|
||||
@@ -522,7 +520,7 @@ namespace gdjs {
|
||||
aw: undefined,
|
||||
};
|
||||
return {
|
||||
...super.getNetworkSyncData(options),
|
||||
...super.getNetworkSyncData(),
|
||||
props: {
|
||||
...bodyProps,
|
||||
layers: this.layers,
|
||||
@@ -531,13 +529,45 @@ namespace gdjs {
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: Physics2NetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
) {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
updateFromNetworkSyncData(networkSyncData: Physics2NetworkSyncData) {
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
|
||||
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;
|
||||
@@ -546,38 +576,6 @@ 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() {
|
||||
|
@@ -21,11 +21,7 @@ module.exports = {
|
||||
.setExtensionInformation(
|
||||
'Physics3D',
|
||||
_('3D physics engine'),
|
||||
"The 3D physics engine simulates realistic object physics, with gravity, forces, collisions, joints, etc. It's perfect for almost all 3D games.\n" +
|
||||
'\n' +
|
||||
'Objects like floors or wall objects should usually be set to "Static" as type. Objects that should be moveable are usually "Dynamic" (default). "Kinematic" objects (typically, players or controlled characters) are only moved by their "linear velocity" and "angular velocity" - they can interact with other objects but only these other objects will move.\n' +
|
||||
'\n' +
|
||||
'Forces (and impulses) are expressed in all conditions/expressions/actions of the 3D physics engine in Newtons (N). Typical values for a force are 10-200 N. One meter is 100 pixels by default in the game (check the world scale). Mass is expressed in kilograms (kg).',
|
||||
"The 3D physics engine simulates realistic object physics, with gravity, forces, collisions, joints, etc. It's perfect for almost all 3D games.",
|
||||
'Florian Rival',
|
||||
'MIT'
|
||||
)
|
||||
@@ -679,7 +675,6 @@ module.exports = {
|
||||
behavior,
|
||||
sharedData
|
||||
)
|
||||
.markAsIrrelevantForChildObjects()
|
||||
.addIncludeFile(
|
||||
'Extensions/Physics3DBehavior/Physics3DRuntimeBehavior.js'
|
||||
)
|
||||
@@ -2048,12 +2043,7 @@ module.exports = {
|
||||
'PhysicsCharacter3D',
|
||||
_('3D physics character'),
|
||||
'PhysicsCharacter3D',
|
||||
_(
|
||||
'Allow an object to jump and run on platforms that have the 3D physics behavior' +
|
||||
'(and which are generally set to "Static" as type, unless the platform is animated/moved in events).\n' +
|
||||
'\n' +
|
||||
'This behavior is usually used with one or more "mapper" behavior to let the player move it.'
|
||||
),
|
||||
_('Jump and run on platforms.'),
|
||||
'',
|
||||
'JsPlatform/Extensions/physics_character3d.svg',
|
||||
'PhysicsCharacter3D',
|
||||
@@ -2622,7 +2612,7 @@ module.exports = {
|
||||
'JumpSustainTime',
|
||||
_('Jump sustain time'),
|
||||
_(
|
||||
'the jump sustain time of an object. This is the time during which keeping the jump button held allow the initial jump speed to be maintained'
|
||||
'the jump sustain time of an object. This is the time during which keeping the jump button held allow the initial jump speed to be maintained.'
|
||||
),
|
||||
_('the jump sustain time'),
|
||||
_('Character configuration'),
|
||||
@@ -3310,11 +3300,7 @@ module.exports = {
|
||||
'PhysicsCar3D',
|
||||
_('3D physics car'),
|
||||
'PhysicsCar3D',
|
||||
_(
|
||||
"Simulate a realistic car using the 3D physics engine. This is mostly useful for the car controlled by the player (it's usually too complex for other cars in a game).\n" +
|
||||
'\n' +
|
||||
'This behavior is usually used with one or more "mapper" behavior to let the player move it.'
|
||||
),
|
||||
_('Simulate a realistic car using the 3D physics engine.'),
|
||||
'',
|
||||
'JsPlatform/Extensions/physics_car3d.svg',
|
||||
'PhysicsCar3D',
|
||||
|
@@ -495,9 +495,7 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
override getNetworkSyncData(
|
||||
options: GetNetworkSyncDataOptions
|
||||
): Physics3DNetworkSyncData {
|
||||
override getNetworkSyncData(): Physics3DNetworkSyncData {
|
||||
let bodyProps;
|
||||
if (this._body) {
|
||||
const position = this._body.GetPosition();
|
||||
@@ -539,7 +537,7 @@ namespace gdjs {
|
||||
};
|
||||
}
|
||||
return {
|
||||
...super.getNetworkSyncData(options),
|
||||
...super.getNetworkSyncData(),
|
||||
props: {
|
||||
...bodyProps,
|
||||
layers: this.layers,
|
||||
@@ -549,40 +547,27 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
override updateFromNetworkSyncData(
|
||||
networkSyncData: Physics3DNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
networkSyncData: Physics3DNetworkSyncData
|
||||
) {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
|
||||
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
|
||||
) {
|
||||
this._sharedData.bodyInterface.SetPosition(
|
||||
this._body.GetID(),
|
||||
this.getRVec3(
|
||||
behaviorSpecificProps.px,
|
||||
behaviorSpecificProps.py,
|
||||
behaviorSpecificProps.pz
|
||||
),
|
||||
Jolt.EActivation_DontActivate
|
||||
);
|
||||
if (this._body) {
|
||||
this._sharedData.bodyInterface.SetPosition(
|
||||
this._body.GetID(),
|
||||
this.getRVec3(
|
||||
behaviorSpecificProps.px,
|
||||
behaviorSpecificProps.py,
|
||||
behaviorSpecificProps.pz
|
||||
),
|
||||
Jolt.EActivation_DontActivate
|
||||
);
|
||||
}
|
||||
}
|
||||
if (
|
||||
behaviorSpecificProps.rx !== undefined &&
|
||||
@@ -590,44 +575,56 @@ namespace gdjs {
|
||||
behaviorSpecificProps.rz !== undefined &&
|
||||
behaviorSpecificProps.rw !== undefined
|
||||
) {
|
||||
this._sharedData.bodyInterface.SetRotation(
|
||||
this._body.GetID(),
|
||||
this.getQuat(
|
||||
behaviorSpecificProps.rx,
|
||||
behaviorSpecificProps.ry,
|
||||
behaviorSpecificProps.rz,
|
||||
behaviorSpecificProps.rw
|
||||
),
|
||||
Jolt.EActivation_DontActivate
|
||||
);
|
||||
if (this._body) {
|
||||
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
|
||||
) {
|
||||
this._sharedData.bodyInterface.SetLinearVelocity(
|
||||
this._body.GetID(),
|
||||
this.getVec3(
|
||||
behaviorSpecificProps.lvx,
|
||||
behaviorSpecificProps.lvy,
|
||||
behaviorSpecificProps.lvz
|
||||
)
|
||||
);
|
||||
if (this._body) {
|
||||
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
|
||||
) {
|
||||
this._sharedData.bodyInterface.SetAngularVelocity(
|
||||
this._body.GetID(),
|
||||
this.getVec3(
|
||||
behaviorSpecificProps.avx,
|
||||
behaviorSpecificProps.avy,
|
||||
behaviorSpecificProps.avz
|
||||
)
|
||||
);
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -924,58 +921,31 @@ namespace gdjs {
|
||||
this.updateBodyFromObject();
|
||||
}
|
||||
|
||||
recreateBody(previousBodyData?: {
|
||||
linearVelocityX: float;
|
||||
linearVelocityY: float;
|
||||
linearVelocityZ: float;
|
||||
angularVelocityX: float;
|
||||
angularVelocityY: float;
|
||||
angularVelocityZ: float;
|
||||
}) {
|
||||
const bodyInterface = this._sharedData.bodyInterface;
|
||||
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;
|
||||
|
||||
if (this._body) {
|
||||
this.bodyUpdater.destroyBody();
|
||||
this._contactsEndedThisFrame.length = 0;
|
||||
this._contactsStartedThisFrame.length = 0;
|
||||
this._currentContacts.length = 0;
|
||||
recreateBody() {
|
||||
if (!this._body) {
|
||||
this._createBody();
|
||||
return;
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
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,7 +12,6 @@ namespace gdjs {
|
||||
etm: float;
|
||||
esm: float;
|
||||
ei: float;
|
||||
es: float;
|
||||
}
|
||||
|
||||
export interface PhysicsCar3DNetworkSyncData extends BehaviorNetworkSyncData {
|
||||
@@ -97,7 +96,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 _clearInputsBetweenFrames: boolean = true;
|
||||
private _dontClearInputsBetweenFrames: boolean = false;
|
||||
|
||||
constructor(
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
@@ -169,37 +168,12 @@ 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(previousBodyData);
|
||||
behavior.recreateBody();
|
||||
|
||||
return this._physics3D;
|
||||
}
|
||||
@@ -299,15 +273,13 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
override getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): PhysicsCar3DNetworkSyncData {
|
||||
override getNetworkSyncData(): PhysicsCar3DNetworkSyncData {
|
||||
// This method is called, so we are synchronizing this object.
|
||||
// Let's clear the inputs between frames as we control it.
|
||||
this._clearInputsBetweenFrames = true;
|
||||
this._dontClearInputsBetweenFrames = false;
|
||||
|
||||
return {
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
...super.getNetworkSyncData(),
|
||||
props: {
|
||||
lek: this._wasLeftKeyPressed,
|
||||
rik: this._wasRightKeyPressed,
|
||||
@@ -319,16 +291,14 @@ namespace gdjs {
|
||||
etm: this._engineTorqueMax,
|
||||
esm: this._engineSpeedMax,
|
||||
ei: this._engineInertia,
|
||||
es: this.getEngineSpeed(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
override updateFromNetworkSyncData(
|
||||
networkSyncData: PhysicsCar3DNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
networkSyncData: PhysicsCar3DNetworkSyncData
|
||||
) {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
|
||||
const behaviorSpecificProps = networkSyncData.props;
|
||||
this._hasPressedForwardKey = behaviorSpecificProps.upk;
|
||||
@@ -341,15 +311,9 @@ 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,
|
||||
// except if asked specifically.
|
||||
this._clearInputsBetweenFrames = !!options.clearInputs;
|
||||
// When the object is synchronized from the network, the inputs must not be cleared.
|
||||
this._dontClearInputsBetweenFrames = true;
|
||||
}
|
||||
|
||||
_getPhysicsPosition(result: Jolt.RVec3): Jolt.RVec3 {
|
||||
@@ -526,7 +490,7 @@ namespace gdjs {
|
||||
this._previousAcceleratorStickForce = this._acceleratorStickForce;
|
||||
this._previousSteeringStickForce = this._steeringStickForce;
|
||||
|
||||
if (this._clearInputsBetweenFrames) {
|
||||
if (!this._dontClearInputsBetweenFrames) {
|
||||
this._hasPressedForwardKey = false;
|
||||
this._hasPressedBackwardKey = false;
|
||||
this._hasPressedRightKey = false;
|
||||
|
@@ -2,24 +2,11 @@
|
||||
|
||||
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;
|
||||
cfs: float;
|
||||
cjs: float;
|
||||
fs: float;
|
||||
js: float;
|
||||
cj: boolean;
|
||||
lek: boolean;
|
||||
rik: boolean;
|
||||
@@ -115,7 +102,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 _clearInputsBetweenFrames: boolean = true;
|
||||
private _dontClearInputsBetweenFrames: boolean = false;
|
||||
|
||||
/**
|
||||
* A very small value compare to 1 pixel, yet very huge compare to rounding errors.
|
||||
@@ -220,35 +207,10 @@ 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(previousBodyData);
|
||||
behavior.recreateBody();
|
||||
|
||||
// Always begin in the direction of the object.
|
||||
this._forwardAngle = this.owner.getAngle();
|
||||
@@ -315,34 +277,19 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
override getNetworkSyncData(
|
||||
options: GetNetworkSyncDataOptions
|
||||
): PhysicsCharacter3DNetworkSyncData {
|
||||
override getNetworkSyncData(): PhysicsCharacter3DNetworkSyncData {
|
||||
// This method is called, so we are synchronizing this object.
|
||||
// Let's clear the inputs between frames as we control it.
|
||||
this._clearInputsBetweenFrames = true;
|
||||
this._dontClearInputsBetweenFrames = false;
|
||||
|
||||
return {
|
||||
...super.getNetworkSyncData(options),
|
||||
...super.getNetworkSyncData(),
|
||||
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,
|
||||
cfs: this._currentFallSpeed,
|
||||
cjs: this._currentJumpSpeed,
|
||||
fs: this._currentFallSpeed,
|
||||
js: this._currentJumpSpeed,
|
||||
cj: this._canJump,
|
||||
lek: this._wasLeftKeyPressed,
|
||||
rik: this._wasRightKeyPressed,
|
||||
@@ -359,30 +306,16 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
override updateFromNetworkSyncData(
|
||||
networkSyncData: PhysicsCharacter3DNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
networkSyncData: PhysicsCharacter3DNetworkSyncData
|
||||
) {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
|
||||
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.cfs;
|
||||
this._currentJumpSpeed = behaviorSpecificProps.cjs;
|
||||
this._currentFallSpeed = behaviorSpecificProps.fs;
|
||||
this._currentJumpSpeed = behaviorSpecificProps.js;
|
||||
this._canJump = behaviorSpecificProps.cj;
|
||||
this._hasPressedForwardKey = behaviorSpecificProps.upk;
|
||||
this._hasPressedBackwardKey = behaviorSpecificProps.dok;
|
||||
@@ -395,8 +328,8 @@ namespace gdjs {
|
||||
this._timeSinceCurrentJumpStart = behaviorSpecificProps.tscjs;
|
||||
this._jumpKeyHeldSinceJumpStart = behaviorSpecificProps.jkhsjs;
|
||||
|
||||
// Clear user inputs between frames only if requested.
|
||||
this._clearInputsBetweenFrames = !!options.clearInputs;
|
||||
// When the object is synchronized from the network, the inputs must not be cleared.
|
||||
this._dontClearInputsBetweenFrames = true;
|
||||
}
|
||||
|
||||
_getPhysicsPosition(result: Jolt.RVec3): Jolt.RVec3 {
|
||||
@@ -717,7 +650,7 @@ namespace gdjs {
|
||||
this._wasJumpKeyPressed = this._hasPressedJumpKey;
|
||||
this._wasStickUsed = this._hasUsedStick;
|
||||
|
||||
if (this._clearInputsBetweenFrames) {
|
||||
if (!this._dontClearInputsBetweenFrames) {
|
||||
this._hasPressedForwardKey = false;
|
||||
this._hasPressedBackwardKey = false;
|
||||
this._hasPressedRightKey = false;
|
||||
|
@@ -37,8 +37,7 @@ void DeclarePhysicsBehaviorExtension(gd::PlatformExtension& extension) {
|
||||
"res/physics-deprecated32.png",
|
||||
"PhysicsBehavior",
|
||||
std::make_shared<PhysicsBehavior>(),
|
||||
std::make_shared<ScenePhysicsDatas>())
|
||||
.MarkAsIrrelevantForChildObjects();
|
||||
std::make_shared<ScenePhysicsDatas>());
|
||||
|
||||
aut.AddAction("SetStatic",
|
||||
("Make the object static"),
|
||||
|
@@ -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.
|
||||
private _clearInputsBetweenFrames: boolean = true;
|
||||
_dontClearInputsBetweenFrames: boolean = false;
|
||||
// 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,16 +227,14 @@ namespace gdjs {
|
||||
this._state = this._falling;
|
||||
}
|
||||
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): PlatformerObjectNetworkSyncData {
|
||||
getNetworkSyncData(): PlatformerObjectNetworkSyncData {
|
||||
// This method is called, so we are synchronizing this object.
|
||||
// Let's clear the inputs between frames as we control it.
|
||||
this._clearInputsBetweenFrames = true;
|
||||
this._dontClearInputsBetweenFrames = false;
|
||||
this._ignoreDefaultControlsAsSyncedByNetwork = false;
|
||||
|
||||
return {
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
...super.getNetworkSyncData(),
|
||||
props: {
|
||||
cs: this._currentSpeed,
|
||||
|
||||
@@ -265,52 +263,11 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: PlatformerObjectNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
networkSyncData: PlatformerObjectNetworkSyncData
|
||||
) {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -360,10 +317,39 @@ namespace gdjs {
|
||||
this._jumpKeyHeldSinceJumpStart = behaviorSpecificProps.jkhsjs;
|
||||
}
|
||||
|
||||
// Clear user inputs between frames only if requested.
|
||||
this._clearInputsBetweenFrames = !!options.clearInputs;
|
||||
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;
|
||||
// And we are not using the default controls.
|
||||
this._ignoreDefaultControlsAsSyncedByNetwork = !options.keepControl;
|
||||
this._ignoreDefaultControlsAsSyncedByNetwork = true;
|
||||
}
|
||||
|
||||
updateFromBehaviorData(oldBehaviorData, newBehaviorData): boolean {
|
||||
@@ -559,9 +545,8 @@ namespace gdjs {
|
||||
this._wasJumpKeyPressed = this._jumpKey;
|
||||
this._wasReleasePlatformKeyPressed = this._releasePlatformKey;
|
||||
this._wasReleaseLadderKeyPressed = this._releaseLadderKey;
|
||||
|
||||
//4) Do not forget to reset pressed keys
|
||||
if (this._clearInputsBetweenFrames) {
|
||||
if (!this._dontClearInputsBetweenFrames) {
|
||||
// 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,57 +157,6 @@ 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);
|
||||
@@ -226,7 +175,34 @@ namespace gdjs {
|
||||
}*/
|
||||
|
||||
//Make sure the platform is or is not in the platforms manager.
|
||||
this.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;
|
||||
}
|
||||
}
|
||||
|
||||
//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();
|
||||
}
|
||||
}
|
||||
|
||||
doStepPostEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {}
|
||||
|
@@ -15,7 +15,7 @@ void DeclarePrimitiveDrawingExtension(gd::PlatformExtension& extension) {
|
||||
.SetExtensionInformation(
|
||||
"PrimitiveDrawing",
|
||||
_("Shape painter"),
|
||||
_("An object that can be used to draw arbitrary 2D shapes "
|
||||
_("This provides an object that can be used to draw arbitrary shapes "
|
||||
"on the screen using events."),
|
||||
"Florian Rival and Aurélien Vivet",
|
||||
"Open source (MIT License)")
|
||||
@@ -28,7 +28,7 @@ void DeclarePrimitiveDrawingExtension(gd::PlatformExtension& extension) {
|
||||
.AddObject<ShapePainterObject>(
|
||||
"Drawer", //"Drawer" is kept for compatibility with GD<=3.6.76
|
||||
_("Shape painter"),
|
||||
_("Allows to draw simple 2D shapes on the screen using the "
|
||||
_("Allows you to draw simple shapes on the screen using the "
|
||||
"events."),
|
||||
"CppPlatform/Extensions/primitivedrawingicon.png")
|
||||
.SetCategoryFullName(_("Advanced"))
|
||||
@@ -125,11 +125,11 @@ void DeclarePrimitiveDrawingExtension(gd::PlatformExtension& extension) {
|
||||
.SetFunctionName("DrawEllipse");
|
||||
|
||||
obj.AddAction("FilletRectangle",
|
||||
_("Fillet Rectangle"),
|
||||
_("Draw a fillet rectangle on screen"),
|
||||
_("Draw from _PARAM1_;_PARAM2_ to _PARAM3_;_PARAM4_ a fillet "
|
||||
"rectangle (fillet: _PARAM5_)"
|
||||
"with _PARAM0_"),
|
||||
_("Fillet Rectangle"),
|
||||
_("Draw a fillet rectangle on screen"),
|
||||
_("Draw from _PARAM1_;_PARAM2_ to _PARAM3_;_PARAM4_ a fillet "
|
||||
"rectangle (fillet: _PARAM5_)"
|
||||
"with _PARAM0_"),
|
||||
_("Drawing"),
|
||||
"res/actions/filletRectangle24.png",
|
||||
"res/actions/filletRectangle.png")
|
||||
@@ -142,6 +142,7 @@ void DeclarePrimitiveDrawingExtension(gd::PlatformExtension& extension) {
|
||||
.AddParameter("expression", _("Fillet (in pixels)"))
|
||||
.SetFunctionName("DrawFilletRectangle");
|
||||
|
||||
|
||||
obj.AddAction("RoundedRectangle",
|
||||
_("Rounded rectangle"),
|
||||
_("Draw a rounded rectangle on screen"),
|
||||
@@ -169,53 +170,54 @@ void DeclarePrimitiveDrawingExtension(gd::PlatformExtension& extension) {
|
||||
_("Drawing"),
|
||||
"res/actions/chamferRectangle24.png",
|
||||
"res/actions/chamferRectangle.png")
|
||||
.AddParameter("object", _("Shape Painter object"), "Drawer")
|
||||
.AddParameter("expression", _("Left X position"))
|
||||
.AddParameter("expression", _("Top Y position"))
|
||||
.AddParameter("expression", _("Right X position"))
|
||||
.AddParameter("expression", _("Bottom Y position"))
|
||||
.AddParameter("expression", _("Chamfer (in pixels)"))
|
||||
.SetFunctionName("DrawChamferRectangle");
|
||||
.AddParameter("object", _("Shape Painter object"), "Drawer")
|
||||
.AddParameter("expression", _("Left X position"))
|
||||
.AddParameter("expression", _("Top Y position"))
|
||||
.AddParameter("expression", _("Right X position"))
|
||||
.AddParameter("expression", _("Bottom Y position"))
|
||||
.AddParameter("expression", _("Chamfer (in pixels)"))
|
||||
.SetFunctionName("DrawChamferRectangle");
|
||||
|
||||
|
||||
obj.AddAction("Torus",
|
||||
_("Torus"),
|
||||
_("Draw a torus on screen"),
|
||||
_("Draw at _PARAM1_;_PARAM2_ a torus with "
|
||||
"inner radius: _PARAM3_, outer radius: _PARAM4_ and "
|
||||
"with start arc angle: _PARAM5_°, end angle: _PARAM6_° "
|
||||
"with _PARAM0_"),
|
||||
_("Drawing"),
|
||||
"res/actions/torus24.png",
|
||||
"res/actions/torus.png")
|
||||
|
||||
.AddParameter("object", _("Shape Painter object"), "Drawer")
|
||||
.AddParameter("expression", _("X position of center"))
|
||||
.AddParameter("expression", _("Y position of center"))
|
||||
.AddParameter("expression", _("Inner Radius (in pixels)"))
|
||||
.AddParameter("expression", _("Outer Radius (in pixels)"))
|
||||
.AddParameter("expression", _("Start Arc (in degrees)"))
|
||||
.AddParameter("expression", _("End Arc (in degrees)"))
|
||||
.SetFunctionName("DrawTorus");
|
||||
|
||||
_("Torus"),
|
||||
_("Draw a torus on screen"),
|
||||
_("Draw at _PARAM1_;_PARAM2_ a torus with "
|
||||
"inner radius: _PARAM3_, outer radius: _PARAM4_ and "
|
||||
"with start arc angle: _PARAM5_°, end angle: _PARAM6_° "
|
||||
"with _PARAM0_"),
|
||||
_("Drawing"),
|
||||
"res/actions/torus24.png",
|
||||
"res/actions/torus.png")
|
||||
|
||||
.AddParameter("object", _("Shape Painter object"), "Drawer")
|
||||
.AddParameter("expression", _("X position of center"))
|
||||
.AddParameter("expression", _("Y position of center"))
|
||||
.AddParameter("expression", _("Inner Radius (in pixels)"))
|
||||
.AddParameter("expression", _("Outer Radius (in pixels)"))
|
||||
.AddParameter("expression", _("Start Arc (in degrees)"))
|
||||
.AddParameter("expression", _("End Arc (in degrees)"))
|
||||
.SetFunctionName("DrawTorus");
|
||||
|
||||
|
||||
obj.AddAction("RegularPolygon",
|
||||
_("Regular Polygon"),
|
||||
_("Draw a regular polygon on screen"),
|
||||
_("Draw at _PARAM1_;_PARAM2_ a regular polygon with _PARAM3_ "
|
||||
"sides and radius: "
|
||||
_("Draw at _PARAM1_;_PARAM2_ a regular polygon with _PARAM3_ sides and radius: "
|
||||
"_PARAM4_ (rotation: _PARAM5_) "
|
||||
"with _PARAM0_"),
|
||||
_("Drawing"),
|
||||
"res/actions/regularPolygon24.png",
|
||||
"res/actions/regularPolygon.png")
|
||||
_("Drawing"),
|
||||
"res/actions/regularPolygon24.png",
|
||||
"res/actions/regularPolygon.png")
|
||||
|
||||
.AddParameter("object", _("Shape Painter object"), "Drawer")
|
||||
.AddParameter("expression", _("X position of center"))
|
||||
.AddParameter("expression", _("Y position of center"))
|
||||
.AddParameter("expression",
|
||||
_("Number of sides of the polygon (minimum: 3)"))
|
||||
.AddParameter("expression", _("Radius (in pixels)"))
|
||||
.AddParameter("expression", _("Rotation (in degrees)"))
|
||||
.SetFunctionName("DrawRegularPolygon");
|
||||
.AddParameter("object", _("Shape Painter object"), "Drawer")
|
||||
.AddParameter("expression", _("X position of center"))
|
||||
.AddParameter("expression", _("Y position of center"))
|
||||
.AddParameter("expression",
|
||||
_("Number of sides of the polygon (minimum: 3)"))
|
||||
.AddParameter("expression", _("Radius (in pixels)"))
|
||||
.AddParameter("expression", _("Rotation (in degrees)"))
|
||||
.SetFunctionName("DrawRegularPolygon");
|
||||
|
||||
obj.AddAction(
|
||||
"Star",
|
||||
|
@@ -37,24 +37,6 @@ 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.
|
||||
*/
|
||||
@@ -209,70 +191,6 @@ 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
|
||||
|
@@ -1,488 +0,0 @@
|
||||
//@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 [];
|
||||
},
|
||||
};
|
@@ -1,32 +0,0 @@
|
||||
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
|
||||
);
|
||||
}
|
@@ -1,696 +0,0 @@
|
||||
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;
|
||||
};
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@@ -202,18 +202,28 @@ namespace gdjs {
|
||||
this._loadingSpineAtlases.clear();
|
||||
}
|
||||
|
||||
unloadResource(resourceData: ResourceData): void {
|
||||
const loadedSpineAtlas = this._loadedSpineAtlases.get(resourceData);
|
||||
if (loadedSpineAtlas) {
|
||||
loadedSpineAtlas.dispose();
|
||||
this._loadedSpineAtlases.delete(resourceData);
|
||||
}
|
||||
/**
|
||||
* Unload the specified list of resources:
|
||||
* this clears the Spine atlases loaded in this manager.
|
||||
*
|
||||
* Usually called when scene resoures are unloaded.
|
||||
*
|
||||
* @param resourcesList The list of specific resources
|
||||
*/
|
||||
unloadResourcesList(resourcesList: ResourceData[]): void {
|
||||
resourcesList.forEach((resourceData) => {
|
||||
const loadedSpineAtlas = this._loadedSpineAtlases.get(resourceData);
|
||||
if (loadedSpineAtlas) {
|
||||
loadedSpineAtlas.dispose();
|
||||
this._loadedSpineAtlases.delete(resourceData);
|
||||
}
|
||||
|
||||
const loadingSpineAtlas = this._loadingSpineAtlases.get(resourceData);
|
||||
if (loadingSpineAtlas) {
|
||||
loadingSpineAtlas.then((atl) => atl.dispose());
|
||||
this._loadingSpineAtlases.delete(resourceData);
|
||||
}
|
||||
const loadingSpineAtlas = this._loadingSpineAtlases.get(resourceData);
|
||||
if (loadingSpineAtlas) {
|
||||
loadingSpineAtlas.then((atl) => atl.dispose());
|
||||
this._loadingSpineAtlases.delete(resourceData);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -127,11 +127,21 @@ namespace gdjs {
|
||||
this._loadedSpines.clear();
|
||||
}
|
||||
|
||||
unloadResource(resourceData: ResourceData): void {
|
||||
const loadedSpine = this._loadedSpines.get(resourceData);
|
||||
if (loadedSpine) {
|
||||
this._loadedSpines.delete(resourceData);
|
||||
}
|
||||
/**
|
||||
* Unload the specified list of resources:
|
||||
* this clears the Spine skeleton data loaded in this manager.
|
||||
*
|
||||
* Usually called when scene resoures are unloaded.
|
||||
*
|
||||
* @param resourcesList The list of specific resources
|
||||
*/
|
||||
unloadResourcesList(resourcesList: ResourceData[]): void {
|
||||
resourcesList.forEach((resourceData) => {
|
||||
const loadedSpine = this._loadedSpines.get(resourceData);
|
||||
if (loadedSpine) {
|
||||
this._loadedSpines.delete(resourceData);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -53,8 +53,6 @@ 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
|
||||
@@ -76,10 +74,6 @@ 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();
|
||||
}
|
||||
@@ -117,11 +111,9 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): SpineNetworkSyncData {
|
||||
getNetworkSyncData(): SpineNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
...super.getNetworkSyncData(),
|
||||
opa: this._opacity,
|
||||
scaX: this.getScaleX(),
|
||||
scaY: this.getScaleY(),
|
||||
@@ -135,11 +127,8 @@ namespace gdjs {
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
syncData: SpineNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(syncData, options);
|
||||
updateFromNetworkSyncData(syncData: SpineNetworkSyncData): void {
|
||||
super.updateFromNetworkSyncData(syncData);
|
||||
|
||||
if (syncData.opa !== undefined && syncData.opa !== this._opacity) {
|
||||
this.setOpacity(syncData.opa);
|
||||
@@ -194,14 +183,6 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
updateHitBoxes(): void {
|
||||
if (SpineRuntimeObject.isHitBoxesUpdateDisabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
super.updateHitBoxes();
|
||||
}
|
||||
|
||||
extraInitializationFromInitialInstance(
|
||||
initialInstanceData: InstanceData
|
||||
): void {
|
||||
|
@@ -13,8 +13,7 @@ void DeclareSystemInfoExtension(gd::PlatformExtension& extension) {
|
||||
.SetExtensionInformation(
|
||||
"SystemInfo",
|
||||
_("System information"),
|
||||
_("Conditions to check if the device has a touchscreen, is a mobile, "
|
||||
"or if the game runs as a preview."),
|
||||
_("Get information about the system and device running the game."),
|
||||
"Florian Rival",
|
||||
"Open source (MIT License)")
|
||||
.SetCategory("Advanced");
|
||||
|
@@ -267,11 +267,9 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): TextInputNetworkSyncData {
|
||||
getNetworkSyncData(): TextInputNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
...super.getNetworkSyncData(),
|
||||
opa: this.getOpacity(),
|
||||
txt: this.getText(),
|
||||
frn: this.getFontResourceName(),
|
||||
@@ -290,11 +288,8 @@ namespace gdjs {
|
||||
};
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
syncData: TextInputNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(syncData, options);
|
||||
updateFromNetworkSyncData(syncData: TextInputNetworkSyncData): void {
|
||||
super.updateFromNetworkSyncData(syncData);
|
||||
|
||||
if (syncData.opa !== undefined) this.setOpacity(syncData.opa);
|
||||
if (syncData.txt !== undefined) this.setText(syncData.txt);
|
||||
|
@@ -449,16 +449,6 @@ void DeclareTextObjectExtension(gd::PlatformExtension& extension) {
|
||||
.AddParameter("object", _("Object"), "Text")
|
||||
.UseStandardParameters("number", gd::ParameterOptions::MakeNewOptions());
|
||||
|
||||
obj.AddExpressionAndConditionAndAction("number",
|
||||
"LineHeight",
|
||||
_("Line height"),
|
||||
_("the line height of a text object"),
|
||||
_("the line height"),
|
||||
"",
|
||||
"res/actions/font24.png")
|
||||
.AddParameter("object", _("Object"), "Text")
|
||||
.UseStandardParameters("number", gd::ParameterOptions::MakeNewOptions());
|
||||
|
||||
// Support for deprecated "Size" actions/conditions:
|
||||
obj.AddDuplicatedAction("Size", "Text::SetFontSize").SetHidden();
|
||||
obj.AddDuplicatedCondition("Size", "Text::FontSize").SetHidden();
|
||||
|
@@ -96,14 +96,6 @@ class TextObjectJsExtension : public gd::PlatformExtension {
|
||||
.SetFunctionName("setOutlineThickness")
|
||||
.SetGetter("getOutlineThickness");
|
||||
|
||||
GetAllExpressionsForObject("TextObject::Text")["LineHeight"]
|
||||
.SetFunctionName("getLineHeight");
|
||||
GetAllConditionsForObject("TextObject::Text")["TextObject::Text::LineHeight"]
|
||||
.SetFunctionName("getLineHeight");
|
||||
GetAllActionsForObject("TextObject::Text")["TextObject::Text::SetLineHeight"]
|
||||
.SetFunctionName("setLineHeight")
|
||||
.SetGetter("getLineHeight");
|
||||
|
||||
GetAllActionsForObject("TextObject::Text")["TextObject::ShowShadow"]
|
||||
.SetFunctionName("showShadow");
|
||||
GetAllConditionsForObject("TextObject::Text")["TextObject::Text::IsShadowEnabled"]
|
||||
|
@@ -20,7 +20,6 @@ using namespace std;
|
||||
TextObject::TextObject()
|
||||
: text("Text"),
|
||||
characterSize(20),
|
||||
lineHeight(0),
|
||||
fontName(""),
|
||||
smoothed(true),
|
||||
bold(false),
|
||||
@@ -51,10 +50,6 @@ bool TextObject::UpdateProperty(const gd::String& propertyName,
|
||||
characterSize = newValue.To<double>();
|
||||
return true;
|
||||
}
|
||||
if (propertyName == "lineHeight") {
|
||||
lineHeight = newValue.To<double>();
|
||||
return true;
|
||||
}
|
||||
if (propertyName == "font") {
|
||||
fontName = newValue;
|
||||
return true;
|
||||
@@ -134,13 +129,6 @@ std::map<gd::String, gd::PropertyDescriptor> TextObject::GetProperties() const {
|
||||
.SetMeasurementUnit(gd::MeasurementUnit::GetPixel())
|
||||
.SetGroup(_("Font"));
|
||||
|
||||
objectProperties["lineHeight"]
|
||||
.SetValue(gd::String::From(lineHeight))
|
||||
.SetType("number")
|
||||
.SetLabel(_("Line height"))
|
||||
.SetMeasurementUnit(gd::MeasurementUnit::GetPixel())
|
||||
.SetGroup(_("Font"));
|
||||
|
||||
objectProperties["font"]
|
||||
.SetValue(fontName)
|
||||
.SetType("resource")
|
||||
@@ -283,7 +271,6 @@ void TextObject::DoUnserializeFrom(gd::Project& project,
|
||||
SetCharacterSize(content.GetChild("characterSize", 0, "CharacterSize")
|
||||
.GetValue()
|
||||
.GetInt());
|
||||
SetLineHeight(content.GetDoubleAttribute("lineHeight", 0));
|
||||
smoothed = content.GetBoolAttribute("smoothed");
|
||||
bold = content.GetBoolAttribute("bold");
|
||||
italic = content.GetBoolAttribute("italic");
|
||||
@@ -352,7 +339,6 @@ void TextObject::DoSerializeTo(gd::SerializerElement& element) const {
|
||||
content.AddChild("textAlignment").SetValue(GetTextAlignment());
|
||||
content.AddChild("verticalTextAlignment").SetValue(GetVerticalTextAlignment());
|
||||
content.AddChild("characterSize").SetValue(GetCharacterSize());
|
||||
content.AddChild("lineHeight").SetValue(GetLineHeight());
|
||||
content.AddChild("color").SetValue(GetColor());
|
||||
|
||||
content.SetAttribute("smoothed", smoothed);
|
||||
|
@@ -49,12 +49,6 @@ class GD_EXTENSION_API TextObject : public gd::ObjectConfiguration {
|
||||
*/
|
||||
inline double GetCharacterSize() const { return characterSize; };
|
||||
|
||||
/** \brief Change the line height. */
|
||||
inline void SetLineHeight(double value) { lineHeight = value; };
|
||||
|
||||
/** \brief Get the line height. */
|
||||
inline double GetLineHeight() const { return lineHeight; };
|
||||
|
||||
/** \brief Return the name of the font resource used for the text.
|
||||
*/
|
||||
inline const gd::String& GetFontName() const { return fontName; };
|
||||
@@ -126,7 +120,6 @@ class GD_EXTENSION_API TextObject : public gd::ObjectConfiguration {
|
||||
|
||||
gd::String text;
|
||||
double characterSize;
|
||||
double lineHeight;
|
||||
gd::String fontName;
|
||||
bool smoothed;
|
||||
bool bold, italic, underlined;
|
||||
|
@@ -86,7 +86,6 @@ namespace gdjs {
|
||||
? style.dropShadowDistance + style.dropShadowBlur
|
||||
: 0;
|
||||
style.padding = Math.ceil(this._object._padding + extraPaddingForShadow);
|
||||
style.lineHeight = this._object._lineHeight;
|
||||
|
||||
// Prevent spikey outlines by adding a miter limit
|
||||
style.miterLimit = 3;
|
||||
|
@@ -22,8 +22,6 @@ namespace gdjs {
|
||||
text: string;
|
||||
textAlignment: string;
|
||||
verticalTextAlignment: string;
|
||||
/** The line height */
|
||||
lineHeight: float;
|
||||
|
||||
isOutlineEnabled: boolean;
|
||||
outlineThickness: float;
|
||||
@@ -52,7 +50,6 @@ namespace gdjs {
|
||||
c: number[];
|
||||
scale: number;
|
||||
ta: string;
|
||||
vta: string;
|
||||
wrap: boolean;
|
||||
wrapw: float;
|
||||
oena: boolean;
|
||||
@@ -65,7 +62,6 @@ namespace gdjs {
|
||||
sha: float;
|
||||
shb: float;
|
||||
pad: integer;
|
||||
lh: float;
|
||||
};
|
||||
|
||||
export type TextObjectNetworkSyncData = ObjectNetworkSyncData &
|
||||
@@ -105,8 +101,6 @@ namespace gdjs {
|
||||
_shadowAngle: float;
|
||||
_shadowBlur: float;
|
||||
|
||||
_lineHeight: float;
|
||||
|
||||
_padding: integer = 5;
|
||||
_str: string;
|
||||
_renderer: gdjs.TextRuntimeObjectRenderer;
|
||||
@@ -145,7 +139,6 @@ namespace gdjs {
|
||||
this._shadowDistance = content.shadowDistance;
|
||||
this._shadowBlur = content.shadowBlurRadius;
|
||||
this._shadowAngle = content.shadowAngle;
|
||||
this._lineHeight = content.lineHeight || 0;
|
||||
|
||||
this._renderer = new gdjs.TextRuntimeObjectRenderer(
|
||||
this,
|
||||
@@ -156,7 +149,7 @@ namespace gdjs {
|
||||
this.onCreated();
|
||||
}
|
||||
|
||||
override updateFromObjectData(
|
||||
updateFromObjectData(
|
||||
oldObjectData: TextObjectData,
|
||||
newObjectData: TextObjectData
|
||||
): boolean {
|
||||
@@ -180,6 +173,9 @@ 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);
|
||||
}
|
||||
@@ -215,21 +211,12 @@ namespace gdjs {
|
||||
if (oldContent.shadowBlurRadius !== newContent.shadowBlurRadius) {
|
||||
this.setShadowBlurRadius(newContent.shadowBlurRadius);
|
||||
}
|
||||
if ((oldContent.lineHeight || 0) !== (newContent.lineHeight || 0)) {
|
||||
this.setLineHeight(newContent.lineHeight || 0);
|
||||
}
|
||||
if (oldContent.underlined !== newContent.underlined) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
override getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): TextObjectNetworkSyncData {
|
||||
getNetworkSyncData(): TextObjectNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
...super.getNetworkSyncData(),
|
||||
str: this._str,
|
||||
o: this.opacity,
|
||||
cs: this._characterSize,
|
||||
@@ -240,7 +227,6 @@ namespace gdjs {
|
||||
c: this._color,
|
||||
scale: this.getScale(),
|
||||
ta: this._textAlign,
|
||||
vta: this._verticalTextAlignment,
|
||||
wrap: this._wrapping,
|
||||
wrapw: this._wrappingWidth,
|
||||
oena: this._isOutlineEnabled,
|
||||
@@ -252,16 +238,14 @@ namespace gdjs {
|
||||
shd: this._shadowDistance,
|
||||
sha: this._shadowAngle,
|
||||
shb: this._shadowBlur,
|
||||
lh: this._lineHeight,
|
||||
pad: this._padding,
|
||||
};
|
||||
}
|
||||
|
||||
override updateFromNetworkSyncData(
|
||||
networkSyncData: TextObjectNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: TextObjectNetworkSyncData
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
if (networkSyncData.str !== undefined) {
|
||||
this.setText(networkSyncData.str);
|
||||
}
|
||||
@@ -292,8 +276,8 @@ namespace gdjs {
|
||||
if (networkSyncData.ta !== undefined) {
|
||||
this.setTextAlignment(networkSyncData.ta);
|
||||
}
|
||||
if (networkSyncData.vta !== undefined) {
|
||||
this.setVerticalTextAlignment(networkSyncData.vta);
|
||||
if (networkSyncData.ta !== undefined) {
|
||||
this.setVerticalTextAlignment(networkSyncData.ta);
|
||||
}
|
||||
if (networkSyncData.wrap !== undefined) {
|
||||
this.setWrapping(networkSyncData.wrap);
|
||||
@@ -328,30 +312,28 @@ namespace gdjs {
|
||||
if (networkSyncData.shb !== undefined) {
|
||||
this.setShadowBlurRadius(networkSyncData.shb);
|
||||
}
|
||||
if (networkSyncData.lh !== undefined) {
|
||||
this.setLineHeight(networkSyncData.lh);
|
||||
}
|
||||
if (networkSyncData.pad !== undefined) {
|
||||
this.setPadding(networkSyncData.pad);
|
||||
}
|
||||
}
|
||||
|
||||
override getRendererObject() {
|
||||
getRendererObject() {
|
||||
return this._renderer.getRendererObject();
|
||||
}
|
||||
|
||||
override update(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
update(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
this._renderer.ensureUpToDate();
|
||||
}
|
||||
|
||||
override onDestroyed(): void {
|
||||
onDestroyed(): void {
|
||||
super.onDestroyed();
|
||||
this._renderer.destroy();
|
||||
}
|
||||
|
||||
override extraInitializationFromInitialInstance(
|
||||
initialInstanceData: InstanceData
|
||||
) {
|
||||
/**
|
||||
* Initialize the extra parameters that could be set for an instance.
|
||||
*/
|
||||
extraInitializationFromInitialInstance(initialInstanceData: InstanceData) {
|
||||
if (initialInstanceData.customSize) {
|
||||
this.setWrappingWidth(initialInstanceData.width);
|
||||
this.setWrapping(true);
|
||||
@@ -371,17 +353,27 @@ namespace gdjs {
|
||||
this._renderer.updatePosition();
|
||||
}
|
||||
|
||||
override setX(x: float): void {
|
||||
/**
|
||||
* Set object position on X axis.
|
||||
*/
|
||||
setX(x: float): void {
|
||||
super.setX(x);
|
||||
this._updateTextPosition();
|
||||
}
|
||||
|
||||
override setY(y: float): void {
|
||||
/**
|
||||
* Set object position on Y axis.
|
||||
*/
|
||||
setY(y: float): void {
|
||||
super.setY(y);
|
||||
this._updateTextPosition();
|
||||
}
|
||||
|
||||
override setAngle(angle: float): void {
|
||||
/**
|
||||
* Set the angle of the object.
|
||||
* @param angle The new angle of the object
|
||||
*/
|
||||
setAngle(angle: float): void {
|
||||
super.setAngle(angle);
|
||||
this._renderer.updateAngle();
|
||||
}
|
||||
@@ -463,22 +455,6 @@ namespace gdjs {
|
||||
this._renderer.updateStyle();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the line height of the text.
|
||||
*/
|
||||
getLineHeight(): float {
|
||||
return this._lineHeight;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the line height of the text.
|
||||
* @param value The new line height for the text.
|
||||
*/
|
||||
setLineHeight(value: float): void {
|
||||
this._lineHeight = value;
|
||||
this._renderer.updateStyle();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the name of the resource to use for the font.
|
||||
* @param fontResourceName The name of the font resource.
|
||||
@@ -523,14 +499,14 @@ namespace gdjs {
|
||||
/**
|
||||
* Get width of the text.
|
||||
*/
|
||||
override getWidth(): float {
|
||||
getWidth(): float {
|
||||
return this._wrapping ? this._wrappingWidth : this._renderer.getWidth();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get height of the text.
|
||||
*/
|
||||
override getHeight(): float {
|
||||
getHeight(): float {
|
||||
return this._renderer.getHeight();
|
||||
}
|
||||
|
||||
@@ -608,10 +584,16 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* Change the text color.
|
||||
* @param rgbOrHexColor color as a "R;G;B" string, for example: "255;0;0"
|
||||
* @param colorString color as a "R;G;B" string, for example: "255;0;0"
|
||||
*/
|
||||
setColor(rgbOrHexColor: string): void {
|
||||
this._color = gdjs.rgbOrHexToRGBColor(rgbOrHexColor);
|
||||
setColor(colorString: string): void {
|
||||
const color = colorString.split(';');
|
||||
if (color.length < 3) {
|
||||
return;
|
||||
}
|
||||
this._color[0] = parseInt(color[0], 10);
|
||||
this._color[1] = parseInt(color[1], 10);
|
||||
this._color[2] = parseInt(color[2], 10);
|
||||
this._useGradient = false;
|
||||
this._renderer.updateStyle();
|
||||
}
|
||||
@@ -703,11 +685,11 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
override setWidth(width: float): void {
|
||||
setWidth(width: float): void {
|
||||
this.setWrappingWidth(width);
|
||||
}
|
||||
|
||||
override getDrawableY(): float {
|
||||
getDrawableY(): float {
|
||||
return (
|
||||
this.getY() -
|
||||
(this._verticalTextAlignment === 'center'
|
||||
@@ -720,12 +702,18 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* Set the outline for the text object.
|
||||
* @param rgbOrHexColor color as a "R;G;B" string, for example: "255;0;0"
|
||||
* @param str color as a "R;G;B" string, for example: "255;0;0"
|
||||
* @param thickness thickness of the outline (0 = disabled)
|
||||
* @deprecated Prefer independent setters.
|
||||
*/
|
||||
setOutline(rgbOrHexColor: string, thickness: number): void {
|
||||
this._outlineColor = gdjs.rgbOrHexToRGBColor(rgbOrHexColor);
|
||||
setOutline(str: string, thickness: number): void {
|
||||
const color = str.split(';');
|
||||
if (color.length < 3) {
|
||||
return;
|
||||
}
|
||||
this._outlineColor[0] = parseInt(color[0], 10);
|
||||
this._outlineColor[1] = parseInt(color[1], 10);
|
||||
this._outlineColor[2] = parseInt(color[2], 10);
|
||||
this._outlineThickness = thickness;
|
||||
this._renderer.updateStyle();
|
||||
}
|
||||
@@ -767,19 +755,25 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* Set the shadow for the text object.
|
||||
* @param rgbOrHexColor color as a "R;G;B" string, for example: "255;0;0"
|
||||
* @param str color as a "R;G;B" string, for example: "255;0;0"
|
||||
* @param distance distance between the shadow and the text, in pixels.
|
||||
* @param blur amount of shadow blur, in pixels.
|
||||
* @param angle shadow offset direction, in degrees.
|
||||
* @deprecated Prefer independent setters.
|
||||
*/
|
||||
setShadow(
|
||||
rgbOrHexColor: string,
|
||||
str: string,
|
||||
distance: number,
|
||||
blur: integer,
|
||||
angle: float
|
||||
): void {
|
||||
this._shadowColor = gdjs.rgbOrHexToRGBColor(rgbOrHexColor);
|
||||
const color = str.split(';');
|
||||
if (color.length < 3) {
|
||||
return;
|
||||
}
|
||||
this._shadowColor[0] = parseInt(color[0], 10);
|
||||
this._shadowColor[1] = parseInt(color[1], 10);
|
||||
this._shadowColor[2] = parseInt(color[2], 10);
|
||||
this._shadowDistance = distance;
|
||||
this._shadowBlur = blur;
|
||||
this._shadowAngle = angle;
|
||||
@@ -892,18 +886,38 @@ namespace gdjs {
|
||||
strThirdColor: string,
|
||||
strFourthColor: string
|
||||
): void {
|
||||
const colorFirst = strFirstColor.split(';');
|
||||
const colorSecond = strSecondColor.split(';');
|
||||
const colorThird = strThirdColor.split(';');
|
||||
const colorFourth = strFourthColor.split(';');
|
||||
this._gradient = [];
|
||||
if (strFirstColor) {
|
||||
this._gradient.push(gdjs.rgbOrHexToRGBColor(strFirstColor));
|
||||
if (colorFirst.length == 3) {
|
||||
this._gradient.push([
|
||||
parseInt(colorFirst[0], 10),
|
||||
parseInt(colorFirst[1], 10),
|
||||
parseInt(colorFirst[2], 10),
|
||||
]);
|
||||
}
|
||||
if (strSecondColor) {
|
||||
this._gradient.push(gdjs.rgbOrHexToRGBColor(strSecondColor));
|
||||
if (colorSecond.length == 3) {
|
||||
this._gradient.push([
|
||||
parseInt(colorSecond[0], 10),
|
||||
parseInt(colorSecond[1], 10),
|
||||
parseInt(colorSecond[2], 10),
|
||||
]);
|
||||
}
|
||||
if (strThirdColor) {
|
||||
this._gradient.push(gdjs.rgbOrHexToRGBColor(strThirdColor));
|
||||
if (colorThird.length == 3) {
|
||||
this._gradient.push([
|
||||
parseInt(colorThird[0], 10),
|
||||
parseInt(colorThird[1], 10),
|
||||
parseInt(colorThird[2], 10),
|
||||
]);
|
||||
}
|
||||
if (strFourthColor) {
|
||||
this._gradient.push(gdjs.rgbOrHexToRGBColor(strFourthColor));
|
||||
if (colorFourth.length == 3) {
|
||||
this._gradient.push([
|
||||
parseInt(colorFourth[0], 10),
|
||||
parseInt(colorFourth[1], 10),
|
||||
parseInt(colorFourth[2], 10),
|
||||
]);
|
||||
}
|
||||
this._gradientType = strGradientType;
|
||||
this._useGradient = this._gradient.length > 1 ? true : false;
|
||||
|
@@ -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 rendering ({@link TileMapRuntimeObjectPixiRenderer})
|
||||
* This model is used for rending ({@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(): EditableTileMapAsJsObject;
|
||||
toJSObject(): Object;
|
||||
/**
|
||||
* @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(): EditableTileMapLayerAsJsObject;
|
||||
toJSObject(): Object;
|
||||
/**
|
||||
* @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(): EditableTileMapLayerAsJsObject;
|
||||
toJSObject(): Object;
|
||||
/**
|
||||
* The opacity (between 0-1) of the layer
|
||||
*/
|
||||
|
@@ -2,6 +2,7 @@
|
||||
namespace gdjs {
|
||||
export type SimpleTileMapObjectDataType = {
|
||||
content: {
|
||||
opacity: number;
|
||||
atlasImage: string;
|
||||
rowCount: number;
|
||||
columnCount: number;
|
||||
@@ -15,7 +16,8 @@ namespace gdjs {
|
||||
|
||||
export type SimpleTileMapNetworkSyncDataType = {
|
||||
op: number;
|
||||
tm?: TileMapHelper.EditableTileMapAsJsObject;
|
||||
ai: string;
|
||||
// TODO: Support tilemap synchronization. Find an efficient way to send tiles changes.
|
||||
};
|
||||
|
||||
export type SimpleTileMapNetworkSyncData = ObjectNetworkSyncData &
|
||||
@@ -36,7 +38,6 @@ 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;
|
||||
@@ -61,6 +62,7 @@ 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;
|
||||
@@ -85,19 +87,16 @@ namespace gdjs {
|
||||
instanceContainer
|
||||
);
|
||||
|
||||
this._loadTileMap(
|
||||
this._initialTileMapAsJsObject,
|
||||
(tileMap: TileMapHelper.EditableTileMap) => {
|
||||
this._renderer.updatePosition();
|
||||
this._loadInitialTileMap((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();
|
||||
@@ -140,8 +139,8 @@ namespace gdjs {
|
||||
);
|
||||
if (!shouldContinue) return;
|
||||
if (this._collisionTileMap) {
|
||||
if (this._tileMap)
|
||||
this._collisionTileMap.updateFromTileMap(this._tileMap);
|
||||
const tileMap = this._renderer.getTileMap();
|
||||
if (tileMap) this._collisionTileMap.updateFromTileMap(tileMap);
|
||||
}
|
||||
this._isTileMapDirty = false;
|
||||
}
|
||||
@@ -151,6 +150,9 @@ 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
|
||||
) {
|
||||
@@ -161,58 +163,27 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNetworkSyncData(
|
||||
syncOptions: GetNetworkSyncDataOptions
|
||||
): SimpleTileMapNetworkSyncData {
|
||||
const syncData: SimpleTileMapNetworkSyncData = {
|
||||
...super.getNetworkSyncData(syncOptions),
|
||||
getNetworkSyncData(): SimpleTileMapNetworkSyncData {
|
||||
return {
|
||||
...super.getNetworkSyncData(),
|
||||
op: this._opacity,
|
||||
ai: this._atlasImage,
|
||||
};
|
||||
if (this._tileMap && syncOptions.syncFullTileMaps) {
|
||||
const currentTileMapAsJsObject = this._tileMap.toJSObject();
|
||||
syncData.tm = currentTileMapAsJsObject;
|
||||
}
|
||||
|
||||
return syncData;
|
||||
}
|
||||
|
||||
updateFromNetworkSyncData(
|
||||
networkSyncData: SimpleTileMapNetworkSyncData,
|
||||
options: UpdateFromNetworkSyncDataOptions
|
||||
networkSyncData: SimpleTileMapNetworkSyncData
|
||||
): void {
|
||||
super.updateFromNetworkSyncData(networkSyncData, options);
|
||||
super.updateFromNetworkSyncData(networkSyncData);
|
||||
|
||||
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();
|
||||
}
|
||||
);
|
||||
if (
|
||||
networkSyncData.op !== undefined &&
|
||||
networkSyncData.op !== this._opacity
|
||||
) {
|
||||
this.setOpacity(networkSyncData.op);
|
||||
}
|
||||
if (networkSyncData.ai !== undefined) {
|
||||
// TODO: support changing the atlas texture
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,43 +199,39 @@ namespace gdjs {
|
||||
|
||||
// 2. Update the renderer so that it updates the tilemap object
|
||||
// (used for width and position calculations).
|
||||
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);
|
||||
}
|
||||
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.updateTransformation();
|
||||
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.updateTransformation();
|
||||
});
|
||||
}
|
||||
|
||||
private _loadTileMap(
|
||||
tileMapAsJsObject: TileMapHelper.EditableTileMapAsJsObject,
|
||||
private _loadInitialTileMap(
|
||||
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.`
|
||||
@@ -273,7 +240,7 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
this._tileMapManager.getOrLoadSimpleTileMap(
|
||||
tileMapAsJsObject,
|
||||
this._initialTileMapAsJsObject,
|
||||
this.name,
|
||||
this._tileSize,
|
||||
this._columnCount,
|
||||
@@ -317,8 +284,7 @@ namespace gdjs {
|
||||
// getOrLoadTextureCache already log warns and errors.
|
||||
return;
|
||||
}
|
||||
this._tileMap = tileMap;
|
||||
this._renderer.refreshPixiTileMap(textureCache);
|
||||
this._renderer.updatePixiTileMap(tileMap, textureCache);
|
||||
tileMapLoadingCallback(tileMap);
|
||||
},
|
||||
(error) => {
|
||||
@@ -674,7 +640,7 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
getTileAtGridCoordinates(columnIndex: integer, rowIndex: integer): integer {
|
||||
return this.getTileId(columnIndex, rowIndex, 0);
|
||||
return this._renderer.getTileId(columnIndex, rowIndex, 0);
|
||||
}
|
||||
|
||||
setTileAtPosition(tileId: number, x: float, y: float) {
|
||||
@@ -688,10 +654,11 @@ namespace gdjs {
|
||||
columnIndex: integer,
|
||||
rowIndex: integer
|
||||
) {
|
||||
if (!this._tileMap) {
|
||||
const tileMap = this._renderer._tileMap;
|
||||
if (!tileMap) {
|
||||
return;
|
||||
}
|
||||
const layer = this._tileMap.getTileLayer(this._layerIndex);
|
||||
const layer = tileMap.getTileLayer(this._layerIndex);
|
||||
if (!layer) {
|
||||
return;
|
||||
}
|
||||
@@ -703,8 +670,8 @@ namespace gdjs {
|
||||
|
||||
if (this._collisionTileMap) {
|
||||
const oldTileDefinition =
|
||||
oldTileId !== undefined && this._tileMap.getTileDefinition(oldTileId);
|
||||
const newTileDefinition = this._tileMap.getTileDefinition(tileId);
|
||||
oldTileId !== undefined && tileMap.getTileDefinition(oldTileId);
|
||||
const newTileDefinition = tileMap.getTileDefinition(tileId);
|
||||
const hadFullHitBox =
|
||||
!!oldTileDefinition &&
|
||||
oldTileDefinition.hasFullHitBox(this._hitBoxTag);
|
||||
@@ -740,7 +707,7 @@ namespace gdjs {
|
||||
rowIndex: integer,
|
||||
flip: boolean
|
||||
) {
|
||||
this.flipTileOnY(columnIndex, rowIndex, 0, flip);
|
||||
this._renderer.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.
|
||||
@@ -751,7 +718,7 @@ namespace gdjs {
|
||||
rowIndex: integer,
|
||||
flip: boolean
|
||||
) {
|
||||
this.flipTileOnX(columnIndex, rowIndex, 0, flip);
|
||||
this._renderer.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.
|
||||
@@ -761,22 +728,22 @@ namespace gdjs {
|
||||
const [columnIndex, rowIndex] =
|
||||
this.getGridCoordinatesFromSceneCoordinates(x, y);
|
||||
|
||||
return this.isTileFlippedOnX(columnIndex, rowIndex, 0);
|
||||
return this._renderer.isTileFlippedOnX(columnIndex, rowIndex, 0);
|
||||
}
|
||||
|
||||
isTileFlippedOnXAtGridCoordinates(columnIndex: integer, rowIndex: integer) {
|
||||
return this.isTileFlippedOnX(columnIndex, rowIndex, 0);
|
||||
return this._renderer.isTileFlippedOnX(columnIndex, rowIndex, 0);
|
||||
}
|
||||
|
||||
isTileFlippedOnYAtPosition(x: float, y: float) {
|
||||
const [columnIndex, rowIndex] =
|
||||
this.getGridCoordinatesFromSceneCoordinates(x, y);
|
||||
|
||||
return this.isTileFlippedOnY(columnIndex, rowIndex, 0);
|
||||
return this._renderer.isTileFlippedOnY(columnIndex, rowIndex, 0);
|
||||
}
|
||||
|
||||
isTileFlippedOnYAtGridCoordinates(columnIndex: integer, rowIndex: integer) {
|
||||
return this.isTileFlippedOnY(columnIndex, rowIndex, 0);
|
||||
return this._renderer.isTileFlippedOnY(columnIndex, rowIndex, 0);
|
||||
}
|
||||
|
||||
removeTileAtPosition(x: float, y: float) {
|
||||
@@ -786,10 +753,11 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
removeTileAtGridCoordinates(columnIndex: integer, rowIndex: integer) {
|
||||
if (!this._tileMap) {
|
||||
const tileMap = this._renderer._tileMap;
|
||||
if (!tileMap) {
|
||||
return;
|
||||
}
|
||||
const layer = this._tileMap.getTileLayer(this._layerIndex);
|
||||
const layer = tileMap.getTileLayer(this._layerIndex);
|
||||
if (!layer) {
|
||||
return;
|
||||
}
|
||||
@@ -811,28 +779,24 @@ namespace gdjs {
|
||||
|
||||
setGridRowCount(targetRowCount: integer) {
|
||||
if (targetRowCount <= 0) return;
|
||||
if (!this._tileMap) return;
|
||||
this._tileMap.setDimensionY(targetRowCount);
|
||||
this._renderer.setGridRowCount(targetRowCount);
|
||||
this._isTileMapDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
setGridColumnCount(targetColumnCount: integer) {
|
||||
if (targetColumnCount <= 0) return;
|
||||
if (!this._tileMap) return;
|
||||
this._tileMap.setDimensionX(targetColumnCount);
|
||||
this._renderer.setGridColumnCount(targetColumnCount);
|
||||
this._isTileMapDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
getGridRowCount(): integer {
|
||||
if (!this._tileMap) return 0;
|
||||
return this._tileMap.getDimensionY();
|
||||
return this._renderer.getGridRowCount();
|
||||
}
|
||||
|
||||
getGridColumnCount(): integer {
|
||||
if (!this._tileMap) return 0;
|
||||
return this._tileMap.getDimensionX();
|
||||
return this._renderer.getGridColumnCount();
|
||||
}
|
||||
|
||||
getTilesetColumnCount(): integer {
|
||||
@@ -842,73 +806,6 @@ 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',
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user