Compare commits

..

4 Commits

Author SHA1 Message Date
Florian Rival
825aaebe22 Fix flow 2025-06-23 18:49:51 +02:00
Florian Rival
f63a823fd0 Improve angle related descriptions and wiki links 2025-06-23 18:43:40 +02:00
Florian Rival
f7f63847c5 Add hint to scrap old instances descriptions for AI agent 2025-06-23 00:55:50 +02:00
Florian Rival
deaa49d2bf [WIP] Improve AI instances painting 2025-06-23 00:19:01 +02:00
300 changed files with 3032 additions and 21953 deletions

View File

@@ -18,13 +18,13 @@ jobs:
# Build the **entire** app for macOS (including the GDevelop.js library).
build-macos:
macos:
xcode: 16.4.0
resource_class: m4pro.medium
xcode: 14.2.0
resource_class: macos.m1.large.gen1
steps:
- checkout
# Install Rosetta for AWS CLI and disable TSO to speed up S3 uploads (https://support.circleci.com/hc/en-us/articles/19334402064027-Troubleshooting-slow-uploads-to-S3-for-jobs-using-an-m1-macOS-resource-class)
- macos/install-rosetta
# - run: sudo sysctl net.inet.tcp.tso=0
- run: sudo sysctl net.inet.tcp.tso=0
# Install a recent version of npm to workaround a notarization issue because of a symlink made by npm: https://github.com/electron-userland/electron-builder/issues/7755
# Node.js v20.14.0 comes with npm v10.7.0.
@@ -94,29 +94,25 @@ jobs:
name: Deploy to S3 (specific commit)
command: |
export PATH=~/.local/bin:$PATH
for i in 1 2 3 4 5 6 7; do
for i in 1 2 3; do
aws s3 sync newIDE/electron-app/dist s3://gdevelop-releases/$(git rev-parse --abbrev-ref HEAD)/commit/$(git rev-parse HEAD)/ && break
echo "Retry $i failed... retrying in 10 seconds"
sleep 10
done
if [ $i -eq 7 ]; then
echo "All retries for deployment failed!" >&2
exit 1
fi
echo "All retries for deployment failed!" >&2
exit 1
- run:
name: Deploy to S3 (latest)
command: |
export PATH=~/.local/bin:$PATH
for i in 1 2 3 4 5 6 7; do
for i in 1 2 3; do
aws s3 sync newIDE/electron-app/dist s3://gdevelop-releases/$(git rev-parse --abbrev-ref HEAD)/latest/ && break
echo "Retry $i failed... retrying in 10 seconds"
sleep 10
done
if [ $i -eq 7 ]; then
echo "All retries for deployment failed!" >&2
exit 1
fi
echo "All retries for deployment failed!" >&2
exit 1
# Build the app for Linux (using a pre-built GDevelop.js library).
build-linux:

View File

@@ -37,8 +37,8 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
.SetIcon("res/actions/position24_black.png");
extension.AddInstructionOrExpressionGroupMetadata(_("Angle"))
.SetIcon("res/actions/direction24_black.png");
extension.AddInstructionOrExpressionGroupMetadata(_("Size")).SetIcon(
"res/actions/scale24_black.png");
extension.AddInstructionOrExpressionGroupMetadata(_("Size"))
.SetIcon("res/actions/scale24_black.png");
gd::ObjectMetadata& obj = extension.AddObject<gd::ObjectConfiguration>(
"", _("Base object"), _("Base object"), "res/objeticon24.png");
@@ -838,13 +838,14 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
.MarkAsAdvanced()
.SetRelevantForLayoutEventsOnly();
obj.AddAction("PushBooleanToObjectVariable",
_("Add value to object array variable"),
_("Adds a boolean to the end of an object array variable."),
_("Add value _PARAM2_ to array variable _PARAM1_ of _PARAM0_"),
_("Variables Arrays and structures"),
"res/actions/var24.png",
"res/actions/var.png")
obj.AddAction(
"PushBooleanToObjectVariable",
_("Add value to object array variable"),
_("Adds a boolean to the end of an object array variable."),
_("Add value _PARAM2_ to array variable _PARAM1_ of _PARAM0_"),
_("Variables Arrays and structures"),
"res/actions/var24.png",
"res/actions/var.png")
.AddParameter("object", _("Object"))
.AddParameter("objectvar", _("Array variable"))
.AddParameter("trueorfalse", _("Boolean to add"))
@@ -1574,9 +1575,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
extension
.AddAction("Create",
_("Create an object"),
_("Create an instance of the object at the specified position."
"The created object instance will be available for the next "
"actions and sub-events."),
_("Create an object at specified position"),
_("Create object _PARAM1_ at position _PARAM2_;_PARAM3_ "
"(layer: _PARAM4_)"),
"",

View File

@@ -72,8 +72,7 @@ BuiltinExtensionsImplementer::ImplementsMathematicalToolsExtension(
extension
.AddExpression("normalize",
_("Normalize a value between `min` and `max` to a value "
"between 0 and 1."),
_("Normalize a value between `min` and `max` to a value between 0 and 1."),
_("Remap a value between 0 and 1."),
"",
"res/mathfunction.png")
@@ -125,8 +124,7 @@ BuiltinExtensionsImplementer::ImplementsMathematicalToolsExtension(
extension
.AddExpression("mod",
_("Modulo"),
_("Compute \"x mod y\". GDevelop does NOT support the \% "
"operator. Use this mod(x, y) function instead."),
_("x mod y"),
"",
"res/mathfunction.png")
.AddParameter("expression", _("x (as in x mod y)"))
@@ -186,8 +184,11 @@ BuiltinExtensionsImplementer::ImplementsMathematicalToolsExtension(
.AddParameter("expression", _("Expression"));
extension
.AddExpression(
"asinh", _("Arcsine"), _("Arcsine"), "", "res/mathfunction.png")
.AddExpression("asinh",
_("Arcsine"),
_("Arcsine"),
"",
"res/mathfunction.png")
.AddParameter("expression", _("Expression"));
extension
@@ -217,8 +218,11 @@ BuiltinExtensionsImplementer::ImplementsMathematicalToolsExtension(
.AddParameter("expression", _("Expression"));
extension
.AddExpression(
"cbrt", _("Cube root"), _("Cube root"), "", "res/mathfunction.png")
.AddExpression("cbrt",
_("Cube root"),
_("Cube root"),
"",
"res/mathfunction.png")
.AddParameter("expression", _("Expression"));
extension
@@ -256,13 +260,12 @@ BuiltinExtensionsImplementer::ImplementsMathematicalToolsExtension(
.AddParameter("expression", _("Expression"), "", true);
extension
.AddExpression(
"cos",
_("Cosine"),
_("Cosine of an angle (in radian). "
"If you want to use degrees, use`ToRad`: `sin(ToRad(45))`."),
"",
"res/mathfunction.png")
.AddExpression("cos",
_("Cosine"),
_("Cosine of an angle (in radian). "
"If you want to use degrees, use`ToRad`: `sin(ToRad(45))`."),
"",
"res/mathfunction.png")
.AddParameter("expression", _("Expression"));
extension
@@ -290,20 +293,29 @@ BuiltinExtensionsImplementer::ImplementsMathematicalToolsExtension(
.AddParameter("expression", _("Expression"));
extension
.AddExpression(
"int", _("Round"), _("Round a number"), "", "res/mathfunction.png")
.AddExpression("int",
_("Round"),
_("Round a number"),
"",
"res/mathfunction.png")
.SetHidden()
.AddParameter("expression", _("Expression"));
extension
.AddExpression(
"rint", _("Round"), _("Round a number"), "", "res/mathfunction.png")
.AddExpression("rint",
_("Round"),
_("Round a number"),
"",
"res/mathfunction.png")
.SetHidden()
.AddParameter("expression", _("Expression"));
extension
.AddExpression(
"round", _("Round"), _("Round a number"), "", "res/mathfunction.png")
.AddExpression("round",
_("Round"),
_("Round a number"),
"",
"res/mathfunction.png")
.AddParameter("expression", _("Expression"));
extension
@@ -312,8 +324,8 @@ BuiltinExtensionsImplementer::ImplementsMathematicalToolsExtension(
_("Round a number to the Nth decimal place"),
"",
"res/mathfunction.png")
.AddParameter("expression", _("Number to Round"))
.AddParameter("expression", _("Decimal Places"), "", true);
.AddParameter("expression", _("Expression"))
.AddParameter("expression", _("Expression"), "", true);
extension
.AddExpression("exp",
@@ -324,13 +336,19 @@ BuiltinExtensionsImplementer::ImplementsMathematicalToolsExtension(
.AddParameter("expression", _("Expression"));
extension
.AddExpression(
"log", _("Logarithm"), _("Logarithm"), "", "res/mathfunction.png")
.AddExpression("log",
_("Logarithm"),
_("Logarithm"),
"",
"res/mathfunction.png")
.AddParameter("expression", _("Expression"));
extension
.AddExpression(
"ln", _("Logarithm"), _("Logarithm"), "", "res/mathfunction.png")
.AddExpression("ln",
_("Logarithm"),
_("Logarithm"),
"",
"res/mathfunction.png")
.SetHidden()
.AddParameter("expression", _("Expression"));
@@ -369,8 +387,11 @@ BuiltinExtensionsImplementer::ImplementsMathematicalToolsExtension(
.AddParameter("expression", _("The exponent (n in x^n)"));
extension
.AddExpression(
"sec", _("Secant"), _("Secant"), "", "res/mathfunction.png")
.AddExpression("sec",
_("Secant"),
_("Secant"),
"",
"res/mathfunction.png")
.AddParameter("expression", _("Expression"));
extension
@@ -382,13 +403,12 @@ BuiltinExtensionsImplementer::ImplementsMathematicalToolsExtension(
.AddParameter("expression", _("Expression"));
extension
.AddExpression(
"sin",
_("Sine"),
_("Sine of an angle (in radian). "
"If you want to use degrees, use`ToRad`: `sin(ToRad(45))`."),
"",
"res/mathfunction.png")
.AddExpression("sin",
_("Sine"),
_("Sine of an angle (in radian). "
"If you want to use degrees, use`ToRad`: `sin(ToRad(45))`."),
"",
"res/mathfunction.png")
.AddParameter("expression", _("Expression"));
extension
@@ -408,13 +428,12 @@ BuiltinExtensionsImplementer::ImplementsMathematicalToolsExtension(
.AddParameter("expression", _("Expression"));
extension
.AddExpression(
"tan",
_("Tangent"),
_("Tangent of an angle (in radian). "
"If you want to use degrees, use`ToRad`: `tan(ToRad(45))`."),
"",
"res/mathfunction.png")
.AddExpression("tan",
_("Tangent"),
_("Tangent of an angle (in radian). "
"If you want to use degrees, use`ToRad`: `tan(ToRad(45))`."),
"",
"res/mathfunction.png")
.AddParameter("expression", _("Expression"));
extension
@@ -444,28 +463,26 @@ BuiltinExtensionsImplementer::ImplementsMathematicalToolsExtension(
.AddParameter("expression", _("x (in a+(b-a)*x)"));
extension
.AddExpression(
"XFromAngleAndDistance",
_("X position from angle and distance"),
_("Compute the X position when given an angle and distance "
"relative to the origin (0;0). This is also known as "
"getting the cartesian coordinates of a 2D vector, using "
"its polar coordinates."),
"",
"res/mathfunction.png")
.AddExpression("XFromAngleAndDistance",
_("X position from angle and distance"),
_("Compute the X position when given an angle and distance "
"relative to the origin (0;0). This is also known as "
"getting the cartesian coordinates of a 2D vector, using "
"its polar coordinates."),
"",
"res/mathfunction.png")
.AddParameter("expression", _("Angle, in degrees"))
.AddParameter("expression", _("Distance"));
extension
.AddExpression(
"YFromAngleAndDistance",
_("Y position from angle and distance"),
_("Compute the Y position when given an angle and distance "
"relative to the origin (0;0). This is also known as "
"getting the cartesian coordinates of a 2D vector, using "
"its polar coordinates."),
"",
"res/mathfunction.png")
.AddExpression("YFromAngleAndDistance",
_("Y position from angle and distance"),
_("Compute the Y position when given an angle and distance "
"relative to the origin (0;0). This is also known as "
"getting the cartesian coordinates of a 2D vector, using "
"its polar coordinates."),
"",
"res/mathfunction.png")
.AddParameter("expression", _("Angle, in degrees"))
.AddParameter("expression", _("Distance"));
@@ -480,8 +497,7 @@ BuiltinExtensionsImplementer::ImplementsMathematicalToolsExtension(
extension
.AddExpression("lerpAngle",
_("Lerp (Linear interpolation) between two angles"),
_("Linearly interpolates between two angles (in degrees) "
"by taking the shortest direction around the circle."),
_("Linearly interpolates between two angles (in degrees) by taking the shortest direction around the circle."),
"",
"res/mathfunction.png")
.AddParameter("expression", _("Starting angle, in degrees"))

View File

@@ -250,28 +250,25 @@ void CustomObjectConfiguration::ExposeResources(gd::ArbitraryResourceWorker& wor
}
const auto &eventsBasedObject = project->GetEventsBasedObject(GetType());
if (IsForcedToOverrideEventsBasedObjectChildrenConfiguration()) {
for (auto &childObject : eventsBasedObject.GetObjects().GetObjects()) {
auto &configuration = GetChildObjectConfiguration(childObject->GetName());
configuration.ExposeResources(worker);
}
}
else if (eventsBasedObject.GetVariants().HasVariantNamed(variantName)) {
for (auto &childObject : eventsBasedObject.GetVariants()
.GetVariant(variantName)
.GetObjects()
.GetObjects()) {
childObject->GetConfiguration().ExposeResources(worker);
}
} else if (isMarkedAsOverridingEventsBasedObjectChildrenConfiguration) {
if (isMarkedAsOverridingEventsBasedObjectChildrenConfiguration) {
for (auto &childObject : eventsBasedObject.GetObjects().GetObjects()) {
auto &configuration = GetChildObjectConfiguration(childObject->GetName());
configuration.ExposeResources(worker);
}
} else {
for (auto &childObject :
eventsBasedObject.GetDefaultVariant().GetObjects().GetObjects()) {
childObject->GetConfiguration().ExposeResources(worker);
if (variantName.empty() ||
!eventsBasedObject.GetVariants().HasVariantNamed(variantName)) {
for (auto &childObject :
eventsBasedObject.GetDefaultVariant().GetObjects().GetObjects()) {
childObject->GetConfiguration().ExposeResources(worker);
}
} else {
for (auto &childObject : eventsBasedObject.GetVariants()
.GetVariant(variantName)
.GetObjects()
.GetObjects()) {
childObject->GetConfiguration().ExposeResources(worker);
}
}
}
}

View File

@@ -78,15 +78,6 @@ public:
variantName = variantName_;
}
/**
* Legacy events-based objects don't have any instance in their default
* variant since there wasn't a graphical editor at the time. In this case,
* the editor doesn't allow to choose a variant, but a variant may have stayed
* after a user rolled back the extension. This variant must be ignored.
*
* @return true when its events-based object doesn't have any initial
* instance.
*/
bool IsForcedToOverrideEventsBasedObjectChildrenConfiguration() const;
bool IsMarkedAsOverridingEventsBasedObjectChildrenConfiguration() const {

View File

@@ -3,7 +3,8 @@
* Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights
* reserved. This project is released under the MIT License.
*/
#pragma once
#ifndef GDCORE_EFFECT_H
#define GDCORE_EFFECT_H
#include <map>
namespace gd {
class SerializerElement;
@@ -42,10 +43,6 @@ class GD_CORE_API Effect {
return doubleParameters[name];
}
bool HasDoubleParameter(const gd::String& name) {
return doubleParameters.find(name) != doubleParameters.end();
}
void SetStringParameter(const gd::String& name, const gd::String& value) {
stringParameters[name] = value;
}
@@ -54,10 +51,6 @@ class GD_CORE_API Effect {
return stringParameters[name];
}
bool HasStringParameter(const gd::String& name) {
return stringParameters.find(name) != stringParameters.end();
}
void SetBooleanParameter(const gd::String& name, bool value) {
booleanParameters[name] = value;
}
@@ -66,10 +59,6 @@ class GD_CORE_API Effect {
return booleanParameters[name];
}
bool HasBooleanParameter(const gd::String& name) {
return booleanParameters.find(name) != booleanParameters.end();
}
const std::map<gd::String, double>& GetAllDoubleParameters() const {
return doubleParameters;
}
@@ -108,3 +97,4 @@ class GD_CORE_API Effect {
};
} // namespace gd
#endif

View File

@@ -36,7 +36,7 @@ namespace gd {
gd::BehaviorsSharedData Layout::badBehaviorSharedData("", "");
Layout::Layout(const Layout& other)
Layout::Layout(const Layout &other)
: objectsContainer(gd::ObjectsContainer::SourceType::Scene) {
Init(other);
}
@@ -54,8 +54,6 @@ Layout::Layout()
backgroundColorG(209),
backgroundColorB(209),
stopSoundsOnStartup(true),
resourcesPreloading("inherit"),
resourcesUnloading("inherit"),
standardSortMethod(true),
disableInputWhenNotFocused(true),
variables(gd::VariablesContainer::SourceType::Scene),
@@ -246,10 +244,6 @@ void Layout::SerializeTo(SerializerElement& element) const {
element.SetAttribute("title", GetWindowDefaultTitle());
element.SetAttribute("standardSortMethod", standardSortMethod);
element.SetAttribute("stopSoundsOnStartup", stopSoundsOnStartup);
if (resourcesPreloading != "inherit")
element.SetAttribute("resourcesPreloading", resourcesPreloading);
if (resourcesUnloading != "inherit")
element.SetAttribute("resourcesUnloading", resourcesUnloading);
element.SetAttribute("disableInputWhenNotFocused",
disableInputWhenNotFocused);
@@ -310,10 +304,6 @@ void Layout::UnserializeFrom(gd::Project& project,
element.GetStringAttribute("title", "(No title)", "titre"));
standardSortMethod = element.GetBoolAttribute("standardSortMethod");
stopSoundsOnStartup = element.GetBoolAttribute("stopSoundsOnStartup");
resourcesPreloading =
element.GetStringAttribute("resourcesPreloading", "inherit");
resourcesUnloading =
element.GetStringAttribute("resourcesUnloading", "inherit");
disableInputWhenNotFocused =
element.GetBoolAttribute("disableInputWhenNotFocused");
@@ -401,8 +391,6 @@ void Layout::Init(const Layout& other) {
standardSortMethod = other.standardSortMethod;
title = other.title;
stopSoundsOnStartup = other.stopSoundsOnStartup;
resourcesPreloading = other.resourcesPreloading;
resourcesUnloading = other.resourcesUnloading;
disableInputWhenNotFocused = other.disableInputWhenNotFocused;
initialInstances = other.initialInstances;
layers = other.layers;

View File

@@ -349,36 +349,6 @@ class GD_CORE_API Layout {
* launched
*/
bool StopSoundsOnStartup() const { return stopSoundsOnStartup; }
/**
* Set when the scene must preload its resources: `at-startup`, `never` or
* `inherit` (default).
*/
void SetResourcesPreloading(gd::String resourcesPreloading_) {
resourcesPreloading = resourcesPreloading_;
}
/**
* Get when the scene must preload its resources: `at-startup`, `never` or
* `inherit` (default).
*/
const gd::String& GetResourcesPreloading() const {
return resourcesPreloading;
}
/**
* Set when the scene must unload its resources: `at-scene-exit`, `never` or
* `inherit` (default).
*/
void SetResourcesUnloading(gd::String resourcesUnloading_) {
resourcesUnloading = resourcesUnloading_;
}
/**
* Get when the scene must unload its resources: `at-scene-exit`, `never` or
* `inherit` (default).
*/
const gd::String& GetResourcesUnloading() const { return resourcesUnloading; }
///@}
/** \name Saving and loading
@@ -411,10 +381,6 @@ class GD_CORE_API Layout {
behaviorsSharedData; ///< Initial shared datas of behaviors
bool stopSoundsOnStartup = true; ///< True to make the scene stop all sounds at
///< startup.
gd::String
resourcesPreloading; ///< `at-startup`, `never` or `inherit` (default).
gd::String
resourcesUnloading; ///< `at-scene-exit`, `never` or `inherit` (default).
bool standardSortMethod = true; ///< True to sort objects using standard sort.
bool disableInputWhenNotFocused = true; /// If set to true, the input must be
/// disabled when the window do not have the

View File

@@ -74,9 +74,7 @@ Project::Project()
gdMinorVersion(gd::VersionWrapper::Minor()),
gdBuildVersion(gd::VersionWrapper::Build()),
variables(gd::VariablesContainer::SourceType::Global),
objectsContainer(gd::ObjectsContainer::SourceType::Global),
sceneResourcesPreloading("at-startup"),
sceneResourcesUnloading("never") {}
objectsContainer(gd::ObjectsContainer::SourceType::Global) {}
Project::~Project() {}
@@ -1168,13 +1166,6 @@ void Project::SerializeTo(SerializerElement& element) const {
else
std::cout << "ERROR: The project current platform is NULL.";
if (sceneResourcesPreloading != "at-startup") {
propElement.SetAttribute("sceneResourcesPreloading", sceneResourcesPreloading);
}
if (sceneResourcesUnloading != "never") {
propElement.SetAttribute("sceneResourcesUnloading", sceneResourcesUnloading);
}
resourcesManager.SerializeTo(element.AddChild("resources"));
objectsContainer.SerializeObjectsTo(element.AddChild("objects"));
objectsContainer.SerializeFoldersTo(element.AddChild("objectsFolderStructure"));
@@ -1316,9 +1307,6 @@ void Project::Init(const gd::Project& game) {
variables = game.GetVariables();
projectFile = game.GetProjectFile();
sceneResourcesPreloading = game.sceneResourcesPreloading;
sceneResourcesUnloading = game.sceneResourcesUnloading;
}
} // namespace gd

View File

@@ -964,37 +964,6 @@ class GD_CORE_API Project {
*/
ResourcesManager& GetResourcesManager() { return resourcesManager; }
/**
* Set when the scenes must preload their resources: `at-startup`, `never`
* (default).
*/
void SetSceneResourcesPreloading(gd::String sceneResourcesPreloading_) {
sceneResourcesPreloading = sceneResourcesPreloading_;
}
/**
* Get when the scenes must preload their resources: `at-startup`, `never`
* (default).
*/
const gd::String& GetSceneResourcesPreloading() const {
return sceneResourcesPreloading;
}
/**
* Set when the scenes must unload their resources: `at-scene-exit`, `never`
* (default).
*/
void SetSceneResourcesUnloading(gd::String sceneResourcesUnloading_) {
sceneResourcesUnloading = sceneResourcesUnloading_;
}
/**
* Get when the scenes must unload their resources: `at-scene-exit`, `never`
* (default).
*/
const gd::String& GetSceneResourcesUnloading() const {
return sceneResourcesUnloading;
}
///@}
/** \name Variable management
@@ -1152,10 +1121,6 @@ class GD_CORE_API Project {
ExtensionProperties
extensionProperties; ///< The properties of the extensions.
gd::WholeProjectDiagnosticReport wholeProjectDiagnosticReport;
gd::String sceneResourcesPreloading; ///< `at-startup` or `never`
///< (default: `at-startup`).
gd::String sceneResourcesUnloading; ///< `at-scene-exit` or `never`
///< (default: `never`).
mutable unsigned int gdMajorVersion =
0; ///< The GD major version used the last
///< time the project was saved.

View File

@@ -7,9 +7,9 @@
#define GDCORE_PROPERTYDESCRIPTOR
#include <vector>
#include "GDCore/String.h"
#include "GDCore/Project/MeasurementUnit.h"
#include "GDCore/Project/QuickCustomization.h"
#include "GDCore/String.h"
namespace gd {
class SerializerElement;
@@ -17,19 +17,6 @@ class SerializerElement;
namespace gd {
class GD_CORE_API PropertyDescriptorChoice {
public:
PropertyDescriptorChoice(const gd::String& value, const gd::String& label)
: value(value), label(label) {}
const gd::String& GetValue() const { return value; }
const gd::String& GetLabel() const { return label; }
private:
gd::String value;
gd::String label;
};
/**
* \brief Used to describe a property shown in a property grid.
* \see gd::Object
@@ -44,12 +31,8 @@ class GD_CORE_API PropertyDescriptor {
* \param propertyValue The value of the property.
*/
PropertyDescriptor(gd::String propertyValue)
: currentValue(propertyValue),
type("string"),
label(""),
hidden(false),
deprecated(false),
advanced(false),
: currentValue(propertyValue), type("string"), label(""), hidden(false),
deprecated(false), advanced(false),
hasImpactOnOtherProperties(false),
measurementUnit(gd::MeasurementUnit::GetUndefined()),
quickCustomizationVisibility(QuickCustomization::Visibility::Default) {}
@@ -58,13 +41,10 @@ class GD_CORE_API PropertyDescriptor {
* \brief Empty constructor creating an empty property to be displayed.
*/
PropertyDescriptor()
: hidden(false),
deprecated(false),
advanced(false),
: hidden(false), deprecated(false), advanced(false),
hasImpactOnOtherProperties(false),
measurementUnit(gd::MeasurementUnit::GetUndefined()),
quickCustomizationVisibility(QuickCustomization::Visibility::Default) {
};
quickCustomizationVisibility(QuickCustomization::Visibility::Default){};
/**
* \brief Destructor
@@ -108,20 +88,13 @@ class GD_CORE_API PropertyDescriptor {
}
/**
* \brief Change the group where this property is displayed to the user, if
* any.
* \brief Change the group where this property is displayed to the user, if any.
*/
PropertyDescriptor& SetGroup(gd::String group_) {
group = group_;
return *this;
}
PropertyDescriptor& AddChoice(const gd::String& value,
const gd::String& label) {
choices.push_back(PropertyDescriptorChoice(value, label));
return *this;
}
/**
* \brief Set and replace the additional information for the property.
*/
@@ -145,8 +118,7 @@ class GD_CORE_API PropertyDescriptor {
/**
* \brief Change the unit of measurement of the property value.
*/
PropertyDescriptor& SetMeasurementUnit(
const gd::MeasurementUnit& measurementUnit_) {
PropertyDescriptor& SetMeasurementUnit(const gd::MeasurementUnit &measurementUnit_) {
measurementUnit = measurementUnit_;
return *this;
}
@@ -156,18 +128,14 @@ class GD_CORE_API PropertyDescriptor {
const gd::String& GetLabel() const { return label; }
const gd::String& GetDescription() const { return description; }
const gd::String& GetGroup() const { return group; }
const gd::MeasurementUnit& GetMeasurementUnit() const {
return measurementUnit;
}
const gd::MeasurementUnit& GetMeasurementUnit() const { return measurementUnit; }
const std::vector<gd::String>& GetExtraInfo() const {
return extraInformation;
}
std::vector<gd::String>& GetExtraInfo() { return extraInformation; }
const std::vector<PropertyDescriptorChoice>& GetChoices() const {
return choices;
std::vector<gd::String>& GetExtraInfo() {
return extraInformation;
}
/**
@@ -210,26 +178,23 @@ class GD_CORE_API PropertyDescriptor {
bool IsAdvanced() const { return advanced; }
/**
* \brief Check if the property has impact on other properties - which means a
* change must re-render other properties.
* \brief Check if the property has impact on other properties - which means a change
* must re-render other properties.
*/
bool HasImpactOnOtherProperties() const { return hasImpactOnOtherProperties; }
/**
* \brief Set if the property has impact on other properties - which means a
* change must re-render other properties.
* \brief Set if the property has impact on other properties - which means a change
* must re-render other properties.
*/
PropertyDescriptor& SetHasImpactOnOtherProperties(bool enable) {
hasImpactOnOtherProperties = enable;
return *this;
}
QuickCustomization::Visibility GetQuickCustomizationVisibility() const {
return quickCustomizationVisibility;
}
QuickCustomization::Visibility GetQuickCustomizationVisibility() const { return quickCustomizationVisibility; }
PropertyDescriptor& SetQuickCustomizationVisibility(
QuickCustomization::Visibility visibility) {
PropertyDescriptor& SetQuickCustomizationVisibility(QuickCustomization::Visibility visibility) {
quickCustomizationVisibility = visibility;
return *this;
}
@@ -266,17 +231,15 @@ class GD_CORE_API PropertyDescriptor {
gd::String label; //< The user-friendly property name
gd::String description; //< The user-friendly property description
gd::String group; //< The user-friendly property group
std::vector<PropertyDescriptorChoice>
choices; //< The optional choices for the property.
std::vector<gd::String>
extraInformation; ///< Can be used to store an additional information
///< like an object type.
extraInformation; ///< Can be used to store for example the available
///< choices, if a property is a displayed as a combo
///< box.
bool hidden;
bool deprecated;
bool advanced;
bool hasImpactOnOtherProperties;
gd::MeasurementUnit
measurementUnit; //< The unit of measurement of the property vale.
gd::MeasurementUnit measurementUnit; //< The unit of measurement of the property vale.
QuickCustomization::Visibility quickCustomizationVisibility;
};

View File

@@ -25,8 +25,6 @@ namespace gdjs {
topFaceVisible: boolean;
bottomFaceVisible: boolean;
tint: string | undefined;
isCastingShadow: boolean;
isReceivingShadow: boolean;
materialType: 'Basic' | 'StandardWithoutMetalness';
};
}
@@ -73,10 +71,8 @@ namespace gdjs {
string,
];
_materialType: gdjs.Cube3DRuntimeObject.MaterialType =
gdjs.Cube3DRuntimeObject.MaterialType.StandardWithoutMetalness;
gdjs.Cube3DRuntimeObject.MaterialType.Basic;
_tint: string;
_isCastingShadow: boolean = true;
_isReceivingShadow: boolean = true;
constructor(
instanceContainer: gdjs.RuntimeInstanceContainer,
@@ -125,8 +121,6 @@ namespace gdjs {
];
this._tint = objectData.content.tint || '255;255;255';
this._isCastingShadow = objectData.content.isCastingShadow || false;
this._isReceivingShadow = objectData.content.isReceivingShadow || false;
this._materialType = this._convertMaterialType(
objectData.content.materialType
@@ -436,18 +430,6 @@ namespace gdjs {
) {
this.setMaterialType(newObjectData.content.materialType);
}
if (
oldObjectData.content.isCastingShadow !==
newObjectData.content.isCastingShadow
) {
this.updateShadowCasting(newObjectData.content.isCastingShadow);
}
if (
oldObjectData.content.isReceivingShadow !==
newObjectData.content.isReceivingShadow
) {
this.updateShadowReceiving(newObjectData.content.isReceivingShadow);
}
return true;
}
@@ -549,14 +531,6 @@ namespace gdjs {
this._materialType = newMaterialType;
this._renderer._updateMaterials();
}
updateShadowCasting(value: boolean) {
this._isCastingShadow = value;
this._renderer.updateShadowCasting();
}
updateShadowReceiving(value: boolean) {
this._isReceivingShadow = value;
this._renderer.updateShadowReceiving();
}
}
export namespace Cube3DRuntimeObject {

View File

@@ -81,14 +81,13 @@ namespace gdjs {
.map((_, index) =>
getFaceMaterial(runtimeObject, materialIndexToFaceIndex[index])
);
const boxMesh = new THREE.Mesh(geometry, materials);
super(runtimeObject, instanceContainer, boxMesh);
this._boxMesh = boxMesh;
this._cube3DRuntimeObject = runtimeObject;
boxMesh.receiveShadow = this._cube3DRuntimeObject._isReceivingShadow;
boxMesh.castShadow = this._cube3DRuntimeObject._isCastingShadow;
this.updateSize();
this.updatePosition();
this.updateRotation();
@@ -115,13 +114,6 @@ namespace gdjs {
new THREE.BufferAttribute(new Float32Array(tints), 3)
);
}
updateShadowCasting() {
this._boxMesh.castShadow = this._cube3DRuntimeObject._isCastingShadow;
}
updateShadowReceiving() {
this._boxMesh.receiveShadow =
this._cube3DRuntimeObject._isReceivingShadow;
}
updateFace(faceIndex: integer) {
const materialIndex = faceIndexToMaterialIndex[faceIndex];

View File

@@ -34,6 +34,7 @@ namespace gdjs {
objectData: gdjs.Object3DData & gdjs.CustomObjectConfiguration
) {
super(parent, objectData);
this._renderer.reinitialize(this, parent);
}
protected override _createRender() {

View File

@@ -44,7 +44,10 @@ namespace gdjs {
) {
this._object = object;
this._isContainerDirty = true;
this._threeGroup.clear();
const layer = parent.getLayer('');
if (layer) {
layer.getRenderer().add3DRendererObject(this._threeGroup);
}
}
_updateThreeGroup() {

View File

@@ -6,7 +6,6 @@ namespace gdjs {
r: number;
t: string;
}
const shadowHelper = false;
gdjs.PixiFiltersTools.registerFilterCreator(
'Scene3D::DirectionalLight',
new (class implements gdjs.PixiFiltersTools.FilterCreator {
@@ -18,63 +17,19 @@ namespace gdjs {
return new gdjs.PixiFiltersTools.EmptyFilter();
}
return new (class implements gdjs.PixiFiltersTools.Filter {
private _top: string = 'Z+';
private _elevation: float = 45;
private _rotation: float = 0;
private _shadowMapSize: float = 1024;
private _minimumShadowBias: float = 0;
private _distanceFromCamera: float = 1500;
private _frustumSize: float = 4000;
private _isEnabled: boolean = false;
private _light: THREE.DirectionalLight;
private _shadowMapDirty = true;
private _shadowCameraDirty = true;
private _shadowCameraHelper: THREE.CameraHelper | null;
light: THREE.DirectionalLight;
rotationObject: THREE.Group;
_isEnabled: boolean = false;
top: string = 'Y-';
elevation: float = 45;
rotation: float = 0;
constructor() {
this._light = new THREE.DirectionalLight();
if (shadowHelper) {
this._shadowCameraHelper = new THREE.CameraHelper(
this._light.shadow.camera
);
} else {
this._shadowCameraHelper = null;
}
this._light.shadow.camera.updateProjectionMatrix();
}
private _updateShadowCamera(): void {
if (!this._shadowCameraDirty) {
return;
}
this._shadowCameraDirty = false;
this._light.shadow.camera.near = 1;
this._light.shadow.camera.far = this._distanceFromCamera + 10000;
this._light.shadow.camera.right = this._frustumSize / 2;
this._light.shadow.camera.left = -this._frustumSize / 2;
this._light.shadow.camera.top = this._frustumSize / 2;
this._light.shadow.camera.bottom = -this._frustumSize / 2;
}
private _updateShadowMapSize(): void {
if (!this._shadowMapDirty) {
return;
}
this._shadowMapDirty = false;
this._light.shadow.mapSize.set(
this._shadowMapSize,
this._shadowMapSize
);
// Force the recreation of the shadow map texture:
this._light.shadow.map?.dispose();
this._light.shadow.map = null;
this._light.shadow.needsUpdate = true;
this.light = new THREE.DirectionalLight();
this.light.position.set(1, 0, 0);
this.rotationObject = new THREE.Group();
this.rotationObject.add(this.light);
this.updateRotation();
}
isEnabled(target: EffectsTarget): boolean {
@@ -98,12 +53,7 @@ namespace gdjs {
if (!scene) {
return false;
}
scene.add(this._light);
scene.add(this._light.target);
if (this._shadowCameraHelper) {
scene.add(this._shadowCameraHelper);
}
scene.add(this.rotationObject);
this._isEnabled = true;
return true;
}
@@ -115,164 +65,82 @@ namespace gdjs {
if (!scene) {
return false;
}
scene.remove(this._light);
scene.remove(this._light.target);
if (this._shadowCameraHelper) {
scene.remove(this._shadowCameraHelper);
}
scene.remove(this.rotationObject);
this._isEnabled = false;
return true;
}
updatePreRender(target: gdjs.EffectsTarget): any {
// Apply any update to the camera or shadow map size.
this._updateShadowCamera();
this._updateShadowMapSize();
// Avoid shadow acne due to depth buffer precision.
const biasMultiplier =
this._shadowMapSize < 1024
? 2
: this._shadowMapSize < 2048
? 1.25
: 1;
this._light.shadow.bias = -this._minimumShadowBias * biasMultiplier;
// Apply update to the light position and its target.
// By doing this, the shadows are "following" the GDevelop camera.
if (!target.getRuntimeLayer) {
return;
}
const layer = target.getRuntimeLayer();
const x = layer.getCameraX();
const y = layer.getCameraY();
const z = layer.getCameraZ(layer.getInitialCamera3DFieldOfView());
const roundedX = Math.floor(x / 100) * 100;
const roundedY = Math.floor(y / 100) * 100;
const roundedZ = Math.floor(z / 100) * 100;
if (this._top === 'Y-') {
const posLightX =
roundedX +
this._distanceFromCamera *
Math.cos(gdjs.toRad(-this._rotation + 90)) *
Math.cos(gdjs.toRad(this._elevation));
const posLightY =
roundedY -
this._distanceFromCamera *
Math.sin(gdjs.toRad(this._elevation));
const posLightZ =
roundedZ +
this._distanceFromCamera *
Math.sin(gdjs.toRad(-this._rotation + 90)) *
Math.cos(gdjs.toRad(this._elevation));
this._light.position.set(posLightX, posLightY, posLightZ);
this._light.target.position.set(roundedX, roundedY, roundedZ);
} else {
const posLightX =
roundedX +
this._distanceFromCamera *
Math.cos(gdjs.toRad(this._rotation)) *
Math.cos(gdjs.toRad(this._elevation));
const posLightY =
roundedY +
this._distanceFromCamera *
Math.sin(gdjs.toRad(this._rotation)) *
Math.cos(gdjs.toRad(this._elevation));
const posLightZ =
roundedZ +
this._distanceFromCamera *
Math.sin(gdjs.toRad(this._elevation));
this._light.position.set(posLightX, posLightY, posLightZ);
this._light.target.position.set(roundedX, roundedY, roundedZ);
}
}
updatePreRender(target: gdjs.EffectsTarget): any {}
updateDoubleParameter(parameterName: string, value: number): void {
if (parameterName === 'intensity') {
this._light.intensity = value;
this.light.intensity = value;
} else if (parameterName === 'elevation') {
this._elevation = value;
this.elevation = value;
this.updateRotation();
} else if (parameterName === 'rotation') {
this._rotation = value;
} else if (parameterName === 'distanceFromCamera') {
this._distanceFromCamera = value;
} else if (parameterName === 'frustumSize') {
this._frustumSize = value;
} else if (parameterName === 'minimumShadowBias') {
this._minimumShadowBias = value;
this.rotation = value;
this.updateRotation();
}
}
getDoubleParameter(parameterName: string): number {
if (parameterName === 'intensity') {
return this._light.intensity;
return this.light.intensity;
} else if (parameterName === 'elevation') {
return this._elevation;
return this.elevation;
} else if (parameterName === 'rotation') {
return this._rotation;
} else if (parameterName === 'distanceFromCamera') {
return this._distanceFromCamera;
} else if (parameterName === 'frustumSize') {
return this._frustumSize;
} else if (parameterName === 'minimumShadowBias') {
return this._minimumShadowBias;
return this.rotation;
}
return 0;
}
updateStringParameter(parameterName: string, value: string): void {
if (parameterName === 'color') {
this._light.color = new THREE.Color(
this.light.color = new THREE.Color(
gdjs.rgbOrHexStringToNumber(value)
);
}
if (parameterName === 'top') {
this._top = value;
}
if (parameterName === 'shadowQuality') {
if (value === 'low' && this._shadowMapSize !== 512) {
this._shadowMapSize = 512;
this._shadowMapDirty = true;
}
if (value === 'medium' && this._shadowMapSize !== 1024) {
this._shadowMapSize = 1024;
this._shadowMapDirty = true;
}
if (value === 'high' && this._shadowMapSize !== 2048) {
this._shadowMapSize = 2048;
this._shadowMapDirty = true;
}
this.top = value;
this.updateRotation();
}
}
updateColorParameter(parameterName: string, value: number): void {
if (parameterName === 'color') {
this._light.color.setHex(value);
this.light.color.setHex(value);
}
}
getColorParameter(parameterName: string): number {
if (parameterName === 'color') {
return this._light.color.getHex();
return this.light.color.getHex();
}
return 0;
}
updateBooleanParameter(parameterName: string, value: boolean): void {
if (parameterName === 'isCastingShadow') {
this._light.castShadow = value;
updateBooleanParameter(parameterName: string, value: boolean): void {}
updateRotation() {
if (this.top === 'Z+') {
// 0° is a light from the right of the screen.
this.rotationObject.rotation.z = gdjs.toRad(this.rotation);
this.rotationObject.rotation.y = -gdjs.toRad(this.elevation);
} else {
// 0° becomes a light from Z+.
this.rotationObject.rotation.y = gdjs.toRad(this.rotation - 90);
this.rotationObject.rotation.z = -gdjs.toRad(this.elevation);
}
}
getNetworkSyncData(): DirectionalLightFilterNetworkSyncData {
return {
i: this._light.intensity,
c: this._light.color.getHex(),
e: this._elevation,
r: this._rotation,
t: this._top,
i: this.light.intensity,
c: this.light.color.getHex(),
e: this.elevation,
r: this.rotation,
t: this.top,
};
}
updateFromNetworkSyncData(syncData: any): void {
this._light.intensity = syncData.i;
this._light.color.setHex(syncData.c);
this._elevation = syncData.e;
this._rotation = syncData.r;
this._top = syncData.t;
this.light.intensity = syncData.i;
this.light.color.setHex(syncData.c);
this.elevation = syncData.e;
this.rotation = syncData.r;
this.top = syncData.t;
this.updateRotation();
}
})();
}

View File

@@ -18,15 +18,18 @@ namespace gdjs {
return new gdjs.PixiFiltersTools.EmptyFilter();
}
return new (class implements gdjs.PixiFiltersTools.Filter {
_top: string = 'Z+';
_elevation: float = 90;
_rotation: float = 0;
light: THREE.HemisphereLight;
rotationObject: THREE.Group;
_isEnabled: boolean = false;
_light: THREE.HemisphereLight;
top: string = 'Y-';
elevation: float = 45;
rotation: float = 0;
constructor() {
this._light = new THREE.HemisphereLight();
this.light = new THREE.HemisphereLight();
this.light.position.set(1, 0, 0);
this.rotationObject = new THREE.Group();
this.rotationObject.add(this.light);
this.updateRotation();
}
@@ -51,7 +54,7 @@ namespace gdjs {
if (!scene) {
return false;
}
scene.add(this._light);
scene.add(this.rotationObject);
this._isEnabled = true;
return true;
}
@@ -63,106 +66,96 @@ namespace gdjs {
if (!scene) {
return false;
}
scene.remove(this._light);
scene.remove(this.rotationObject);
this._isEnabled = false;
return true;
}
updatePreRender(target: gdjs.EffectsTarget): any {}
updateDoubleParameter(parameterName: string, value: number): void {
if (parameterName === 'intensity') {
this._light.intensity = value;
this.light.intensity = value;
} else if (parameterName === 'elevation') {
this._elevation = value;
this.elevation = value;
this.updateRotation();
} else if (parameterName === 'rotation') {
this._rotation = value;
this.rotation = value;
this.updateRotation();
}
}
getDoubleParameter(parameterName: string): number {
if (parameterName === 'intensity') {
return this._light.intensity;
return this.light.intensity;
} else if (parameterName === 'elevation') {
return this._elevation;
return this.elevation;
} else if (parameterName === 'rotation') {
return this._rotation;
return this.rotation;
}
return 0;
}
updateStringParameter(parameterName: string, value: string): void {
if (parameterName === 'skyColor') {
this._light.color = new THREE.Color(
this.light.color = new THREE.Color(
gdjs.rgbOrHexStringToNumber(value)
);
}
if (parameterName === 'groundColor') {
this._light.groundColor = new THREE.Color(
this.light.groundColor = new THREE.Color(
gdjs.rgbOrHexStringToNumber(value)
);
}
if (parameterName === 'top') {
this._top = value;
this.top = value;
this.updateRotation();
}
}
updateColorParameter(parameterName: string, value: number): void {
if (parameterName === 'skyColor') {
this._light.color.setHex(value);
this.light.color.setHex(value);
}
if (parameterName === 'groundColor') {
this._light.groundColor.setHex(value);
this.light.groundColor.setHex(value);
}
}
getColorParameter(parameterName: string): number {
if (parameterName === 'skyColor') {
return this._light.color.getHex();
return this.light.color.getHex();
}
if (parameterName === 'groundColor') {
return this._light.groundColor.getHex();
return this.light.groundColor.getHex();
}
return 0;
}
updateBooleanParameter(parameterName: string, value: boolean): void {}
updateRotation() {
if (this._top === 'Y-') {
// `rotation` at 0° becomes a light from Z+.
this._light.position.set(
Math.cos(gdjs.toRad(-this._rotation + 90)) *
Math.cos(gdjs.toRad(this._elevation)),
-Math.sin(gdjs.toRad(this._elevation)),
Math.sin(gdjs.toRad(-this._rotation + 90)) *
Math.cos(gdjs.toRad(this._elevation))
);
if (this.top === 'Z+') {
// 0° is a light from the right of the screen.
this.rotationObject.rotation.z = gdjs.toRad(this.rotation);
this.rotationObject.rotation.y = -gdjs.toRad(this.elevation);
} else {
// `rotation` at 0° is a light from the right of the screen.
this._light.position.set(
Math.cos(gdjs.toRad(this._rotation)) *
Math.cos(gdjs.toRad(this._elevation)),
Math.sin(gdjs.toRad(this._rotation)) *
Math.cos(gdjs.toRad(this._elevation)),
Math.sin(gdjs.toRad(this._elevation))
);
// 0° becomes a light from Z+.
this.rotationObject.rotation.y = gdjs.toRad(this.rotation - 90);
this.rotationObject.rotation.z = -gdjs.toRad(this.elevation);
}
}
getNetworkSyncData(): HemisphereLightFilterNetworkSyncData {
return {
i: this._light.intensity,
sc: this._light.color.getHex(),
gc: this._light.groundColor.getHex(),
e: this._elevation,
r: this._rotation,
t: this._top,
i: this.light.intensity,
sc: this.light.color.getHex(),
gc: this.light.groundColor.getHex(),
e: this.elevation,
r: this.rotation,
t: this.top,
};
}
updateFromNetworkSyncData(
syncData: HemisphereLightFilterNetworkSyncData
): void {
this._light.intensity = syncData.i;
this._light.color.setHex(syncData.sc);
this._light.groundColor.setHex(syncData.gc);
this._elevation = syncData.e;
this._rotation = syncData.r;
this._top = syncData.t;
this.light.intensity = syncData.i;
this.light.color.setHex(syncData.sc);
this.light.groundColor.setHex(syncData.gc);
this.elevation = syncData.e;
this.rotation = syncData.r;
this.top = syncData.t;
this.updateRotation();
}
})();

View File

@@ -859,9 +859,7 @@ module.exports = {
propertyName === 'rightFaceResourceRepeat' ||
propertyName === 'topFaceResourceRepeat' ||
propertyName === 'bottomFaceResourceRepeat' ||
propertyName === 'enableTextureTransparency' ||
propertyName === 'isCastingShadow' ||
propertyName === 'isReceivingShadow'
propertyName === 'enableTextureTransparency'
) {
objectContent[propertyName] = newValue === '1';
return true;
@@ -889,8 +887,8 @@ module.exports = {
.getOrCreate('facesOrientation')
.setValue(objectContent.facesOrientation || 'Y')
.setType('choice')
.addChoice('Y', 'Y')
.addChoice('Z', 'Z')
.addExtraInfo('Y')
.addExtraInfo('Z')
.setLabel(_('Faces orientation'))
.setDescription(
_(
@@ -950,8 +948,8 @@ module.exports = {
.getOrCreate('backFaceUpThroughWhichAxisRotation')
.setValue(objectContent.backFaceUpThroughWhichAxisRotation || 'X')
.setType('choice')
.addChoice('X', 'X')
.addChoice('Y', 'Y')
.addExtraInfo('X')
.addExtraInfo('Y')
.setLabel(_('Back face orientation'))
.setDescription(
_(
@@ -1085,29 +1083,11 @@ module.exports = {
objectProperties
.getOrCreate('materialType')
.setValue(objectContent.materialType || 'StandardWithoutMetalness')
.setValue(objectContent.materialType || 'Basic')
.setType('choice')
.addChoice('Basic', _('Basic (no lighting, no shadows)'))
.addChoice(
'StandardWithoutMetalness',
_('Standard (without metalness)')
)
.setLabel(_('Material type'))
.setGroup(_('Lighting'));
objectProperties
.getOrCreate('isCastingShadow')
.setValue(objectContent.isCastingShadow ? 'true' : 'false')
.setType('boolean')
.setLabel(_('Shadow casting'))
.setGroup(_('Lighting'));
objectProperties
.getOrCreate('isReceivingShadow')
.setValue(objectContent.isReceivingShadow ? 'true' : 'false')
.setType('boolean')
.setLabel(_('Shadow receiving'))
.setGroup(_('Lighting'));
.addExtraInfo('Basic')
.addExtraInfo('StandardWithoutMetalness')
.setLabel(_('Material type'));
return objectProperties;
};
@@ -1136,10 +1116,8 @@ module.exports = {
rightFaceResourceRepeat: false,
topFaceResourceRepeat: false,
bottomFaceResourceRepeat: false,
materialType: 'StandardWithoutMetalness',
materialType: 'Basic',
tint: '255;255;255',
isCastingShadow: true,
isReceivingShadow: true,
};
Cube3DObject.updateInitialInstanceProperty = function (
@@ -1916,11 +1894,11 @@ module.exports = {
.setType('number');
properties
.getOrCreate('top')
.setValue('Z+')
.setValue('Y-')
.setLabel(_('3D world top'))
.setType('choice')
.addExtraInfo('Z+')
.addExtraInfo('Y-')
.addExtraInfo('Z+')
.setGroup(_('Orientation'));
properties
.getOrCreate('elevation')
@@ -1935,47 +1913,6 @@ module.exports = {
.setLabel(_('Rotation (in degrees)'))
.setType('number')
.setGroup(_('Orientation'));
properties
.getOrCreate('isCastingShadow')
.setValue('false')
.setLabel(_('Shadow casting'))
.setType('boolean')
.setGroup(_('Shadows'));
properties
.getOrCreate('shadowQuality')
.setValue('medium')
.addChoice('low', _('Low quality'))
.addChoice('medium', _('Medium quality'))
.addChoice('high', _('High quality'))
.setLabel(_('Shadow quality'))
.setType('choice')
.setGroup(_('Shadows'));
properties
.getOrCreate('minimumShadowBias')
.setValue('0')
.setLabel(_('Shadow bias'))
.setDescription(
_(
'Use this to avoid "shadow acne" due to depth buffer precision. Choose a value small enough like 0.001 to avoid creating distance between shadows and objects but not too small to avoid shadow glitches on low/medium quality. This value is used for high quality, and multiplied by 1.25 for medium quality and 2 for low quality.'
)
)
.setType('number')
.setGroup(_('Shadows'))
.setAdvanced(true);
properties
.getOrCreate('frustumSize')
.setValue('4000')
.setLabel(_('Shadow frustum size'))
.setType('number')
.setGroup(_('Shadows'))
.setAdvanced(true);
properties
.getOrCreate('distanceFromCamera')
.setValue('1500')
.setLabel(_("Distance from layer's camera"))
.setType('number')
.setGroup(_('Shadows'))
.setAdvanced(true);
}
{
const effect = extension
@@ -2007,11 +1944,11 @@ module.exports = {
.setType('number');
properties
.getOrCreate('top')
.setValue('Z+')
.setValue('Y-')
.setLabel(_('3D world top'))
.setType('choice')
.addExtraInfo('Z+')
.addExtraInfo('Y-')
.addExtraInfo('Z+')
.setGroup(_('Orientation'));
properties
.getOrCreate('elevation')
@@ -3273,8 +3210,6 @@ module.exports = {
this._threeObject = new THREE.Group();
this._threeObject.rotation.order = 'ZYX';
this._threeObject.castShadow = true;
this._threeObject.receiveShadow = true;
this._threeGroup.add(this._threeObject);
}

View File

@@ -23,7 +23,7 @@ Model3DObjectConfiguration::Model3DObjectConfiguration()
: width(100), height(100), depth(100), rotationX(0), rotationY(0),
rotationZ(0), modelResourceName(""), materialType("StandardWithoutMetalness"),
originLocation("ModelOrigin"), centerLocation("ModelOrigin"),
keepAspectRatio(true), crossfadeDuration(0.1f), isCastingShadow(true), isReceivingShadow(true) {}
keepAspectRatio(true), crossfadeDuration(0.1f) {}
bool Model3DObjectConfiguration::UpdateProperty(const gd::String &propertyName,
const gd::String &newValue) {
@@ -75,16 +75,6 @@ bool Model3DObjectConfiguration::UpdateProperty(const gd::String &propertyName,
crossfadeDuration = newValue.To<double>();
return true;
}
if(propertyName == "isCastingShadow")
{
isCastingShadow = newValue == "1";
return true;
}
if(propertyName == "isReceivingShadow")
{
isReceivingShadow = newValue == "1";
return true;
}
return false;
}
@@ -153,20 +143,19 @@ Model3DObjectConfiguration::GetProperties() const {
objectProperties["materialType"]
.SetValue(materialType.empty() ? "Basic" : materialType)
.SetType("choice")
.AddChoice("Basic", _("Basic (no lighting, no shadows)"))
.AddChoice("StandardWithoutMetalness", _("Standard (without metalness)"))
.AddChoice("KeepOriginal", _("Keep original"))
.SetLabel(_("Material"))
.SetGroup(_("Lighting"));
.AddExtraInfo("Basic")
.AddExtraInfo("StandardWithoutMetalness")
.AddExtraInfo("KeepOriginal")
.SetLabel(_("Material"));
objectProperties["originLocation"]
.SetValue(originLocation.empty() ? "TopLeft" : originLocation)
.SetType("choice")
.AddChoice("ModelOrigin", _("Model origin"))
.AddChoice("TopLeft", _("Top left"))
.AddChoice("ObjectCenter", _("Object center"))
.AddChoice("BottomCenterZ", _("Bottom center (Z)"))
.AddChoice("BottomCenterY", _("Bottom center (Y)"))
.AddExtraInfo("ModelOrigin")
.AddExtraInfo("TopLeft")
.AddExtraInfo("ObjectCenter")
.AddExtraInfo("BottomCenterZ")
.AddExtraInfo("BottomCenterY")
.SetLabel(_("Origin point"))
.SetGroup(_("Points"))
.SetAdvanced(true);
@@ -174,10 +163,10 @@ Model3DObjectConfiguration::GetProperties() const {
objectProperties["centerLocation"]
.SetValue(centerLocation.empty() ? "ObjectCenter" : centerLocation)
.SetType("choice")
.AddChoice("ModelOrigin", _("Model origin"))
.AddChoice("ObjectCenter", _("Object center"))
.AddChoice("BottomCenterZ", _("Bottom center (Z)"))
.AddChoice("BottomCenterY", _("Bottom center (Y)"))
.AddExtraInfo("ModelOrigin")
.AddExtraInfo("ObjectCenter")
.AddExtraInfo("BottomCenterZ")
.AddExtraInfo("BottomCenterY")
.SetLabel(_("Center point"))
.SetGroup(_("Points"))
.SetAdvanced(true);
@@ -189,20 +178,6 @@ Model3DObjectConfiguration::GetProperties() const {
.SetGroup(_("Animations"))
.SetMeasurementUnit(gd::MeasurementUnit::GetSecond());
objectProperties["isCastingShadow"]
.SetValue(isCastingShadow ? "true" : "false")
.SetType("boolean")
.SetLabel(_("Shadow casting"))
.SetGroup(_("Lighting"));
objectProperties["isReceivingShadow"]
.SetValue(isReceivingShadow ? "true" : "false")
.SetType("boolean")
.SetLabel(_("Shadow receiving"))
.SetGroup(_("Lighting"));
return objectProperties;
}
@@ -235,8 +210,6 @@ void Model3DObjectConfiguration::DoUnserializeFrom(
centerLocation = content.GetStringAttribute("centerLocation");
keepAspectRatio = content.GetBoolAttribute("keepAspectRatio");
crossfadeDuration = content.GetDoubleAttribute("crossfadeDuration");
isCastingShadow = content.GetBoolAttribute("isCastingShadow");
isReceivingShadow = content.GetBoolAttribute("isReceivingShadow");
RemoveAllAnimations();
auto &animationsElement = content.GetChild("animations");
@@ -266,8 +239,6 @@ void Model3DObjectConfiguration::DoSerializeTo(
content.SetAttribute("centerLocation", centerLocation);
content.SetAttribute("keepAspectRatio", keepAspectRatio);
content.SetAttribute("crossfadeDuration", crossfadeDuration);
content.SetAttribute("isCastingShadow", isCastingShadow);
content.SetAttribute("isReceivingShadow", isReceivingShadow);
auto &animationsElement = content.AddChild("animations");
animationsElement.ConsiderAsArrayOf("animation");

View File

@@ -160,8 +160,6 @@ public:
const gd::String& GetCenterLocation() const { return centerLocation; };
bool shouldKeepAspectRatio() const { return keepAspectRatio; };
bool shouldCastShadow() const { return isCastingShadow; };
bool shouldReceiveShadow() const { return isReceivingShadow; };
///@}
protected:
@@ -184,8 +182,6 @@ private:
gd::String centerLocation;
bool keepAspectRatio;
bool isCastingShadow;
bool isReceivingShadow;
std::vector<Model3DAnimation> animations;
static Model3DAnimation badAnimation; //< Bad animation when an out of bound

View File

@@ -38,8 +38,6 @@ namespace gdjs {
| 'BottomCenterY';
animations: Model3DAnimation[];
crossfadeDuration: float;
isCastingShadow: boolean;
isReceivingShadow: boolean;
};
}
@@ -103,8 +101,6 @@ namespace gdjs {
_animationSpeedScale: float = 1;
_animationPaused: boolean = false;
_crossfadeDuration: float = 0;
_isCastingShadow: boolean = true;
_isReceivingShadow: boolean = true;
constructor(
instanceContainer: gdjs.RuntimeInstanceContainer,
@@ -127,8 +123,6 @@ namespace gdjs {
objectData.content.materialType
);
this.setIsCastingShadow(objectData.content.isCastingShadow);
this.setIsReceivingShadow(objectData.content.isReceivingShadow);
this.onModelChanged(objectData);
this._crossfadeDuration = objectData.content.crossfadeDuration || 0;
@@ -201,18 +195,6 @@ namespace gdjs {
newObjectData.content.centerLocation
);
}
if (
oldObjectData.content.isCastingShadow !==
newObjectData.content.isCastingShadow
) {
this.setIsCastingShadow(newObjectData.content.isCastingShadow);
}
if (
oldObjectData.content.isReceivingShadow !==
newObjectData.content.isReceivingShadow
) {
this.setIsReceivingShadow(newObjectData.content.isReceivingShadow);
}
return true;
}
@@ -376,16 +358,6 @@ namespace gdjs {
return this._renderer.hasAnimationEnded();
}
setIsCastingShadow(value: boolean): void {
this._isCastingShadow = value;
this._renderer._updateShadow();
}
setIsReceivingShadow(value: boolean): void {
this._isReceivingShadow = value;
this._renderer._updateShadow();
}
setCrossfadeDuration(duration: number): void {
if (this._crossfadeDuration === duration) return;
this._crossfadeDuration = duration;

View File

@@ -286,7 +286,6 @@ namespace gdjs {
this.get3DRendererObject().remove(this._threeObject);
this.get3DRendererObject().add(threeObject);
this._threeObject = threeObject;
this._updateShadow();
// Start the current animation on the new 3D object.
this._animationMixer = new THREE.AnimationMixer(root);
@@ -324,13 +323,6 @@ namespace gdjs {
return this._originalModel.animations[animationIndex].name;
}
_updateShadow() {
this._threeObject.traverse((child) => {
child.castShadow = this._model3DRuntimeObject._isCastingShadow;
child.receiveShadow = this._model3DRuntimeObject._isReceivingShadow;
});
}
/**
* Return true if animation has ended.
* The animation had ended if:

View File

@@ -14,7 +14,6 @@ describe('gdjs.AnchorRuntimeBehavior', () => {
effects: [],
content: {},
childrenContent: {},
isInnerAreaFollowingParentSize: false,
});
runtimeScene.addObject(customObject);
customObject.setPosition(500, 250);

View File

@@ -75,9 +75,9 @@ module.exports = {
.getOrCreate('align')
.setValue(objectContent.align)
.setType('choice')
.addChoice('left', _('Left'))
.addChoice('center', _('Center'))
.addChoice('right', _('Right'))
.addExtraInfo('left')
.addExtraInfo('center')
.addExtraInfo('right')
.setLabel(_('Base alignment'))
.setGroup(_('Appearance'));
@@ -88,9 +88,9 @@ module.exports = {
.getOrCreate('verticalTextAlignment')
.setValue(objectContent.verticalTextAlignment)
.setType('choice')
.addChoice('top', _('Top'))
.addChoice('center', _('Center'))
.addChoice('bottom', _('Bottom'))
.addExtraInfo('top')
.addExtraInfo('center')
.addExtraInfo('bottom')
.setLabel(_('Vertical alignment'))
.setGroup(_('Appearance'));

View File

@@ -61,9 +61,9 @@ module.exports = {
.getOrCreate('align')
.setValue(objectContent.align)
.setType('choice')
.addChoice('left', _('Left'))
.addChoice('center', _('Center'))
.addChoice('right', _('Right'))
.addExtraInfo('left')
.addExtraInfo('center')
.addExtraInfo('right')
.setLabel(_('Alignment'))
.setGroup(_('Appearance'));
@@ -74,9 +74,9 @@ module.exports = {
.getOrCreate('verticalTextAlignment')
.setValue(objectContent.verticalTextAlignment)
.setType('choice')
.addChoice('top', _('Top'))
.addChoice('center', _('Center'))
.addChoice('bottom', _('Bottom'))
.addExtraInfo('top')
.addExtraInfo('center')
.addExtraInfo('bottom')
.setLabel(_('Vertical alignment'))
.setGroup(_('Appearance'));

View File

@@ -194,9 +194,9 @@ ParticleEmitterObject::GetProperties() const {
: GetRendererType() == Line ? "Line"
: "Image")
.SetType("choice")
.AddChoice("Circle", _("Circle"))
.AddChoice("Line", _("Line"))
.AddChoice("Image", _("Image"))
.AddExtraInfo("Circle")
.AddExtraInfo("Line")
.AddExtraInfo("Image")
.SetLabel(_("Particle type"))
.SetHasImpactOnOtherProperties(true);

View File

@@ -818,7 +818,7 @@ module.exports = {
)
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics2Behavior')
.addParameter('yesorno', _('Treat as bullet'), '', false)
.addParameter('yesorno', _('Treat as bullet?'), '', false)
.setDefaultValue('false')
.getCodeExtraInformation()
.setFunctionName('setBullet');
@@ -852,7 +852,7 @@ module.exports = {
)
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics2Behavior')
.addParameter('yesorno', _('Fixed rotation'), '', false)
.addParameter('yesorno', _('Fixed rotation?'), '', false)
.setDefaultValue('false')
.getCodeExtraInformation()
.setFunctionName('setFixedRotation');
@@ -886,7 +886,7 @@ module.exports = {
)
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics2Behavior')
.addParameter('yesorno', _('Can sleep'), '', false)
.addParameter('yesorno', _('Can sleep?'), '', false)
.setDefaultValue('true')
.getCodeExtraInformation()
.setFunctionName('setSleepingAllowed');
@@ -1296,7 +1296,7 @@ module.exports = {
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics2Behavior')
.addParameter('expression', _('Layer (1 - 16)'))
.addParameter('yesorno', _('Enable'), '', false)
.addParameter('yesorno', _('Enable?'), '', false)
.setDefaultValue('true')
.getCodeExtraInformation()
.setFunctionName('enableLayer');
@@ -1332,7 +1332,7 @@ module.exports = {
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics2Behavior')
.addParameter('expression', _('Mask (1 - 16)'))
.addParameter('yesorno', _('Enable'), '', false)
.addParameter('yesorno', _('Enable?'), '', false)
.setDefaultValue('true')
.getCodeExtraInformation()
.setFunctionName('enableMask');
@@ -2409,7 +2409,7 @@ module.exports = {
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics2Behavior')
.addParameter('expression', _('Joint ID'))
.addParameter('yesorno', _('Enable'))
.addParameter('yesorno', _('Enable?'))
.getCodeExtraInformation()
.setFunctionName('enableRevoluteJointLimits');
@@ -2488,7 +2488,7 @@ module.exports = {
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics2Behavior')
.addParameter('expression', _('Joint ID'))
.addParameter('yesorno', _('Enable'))
.addParameter('yesorno', _('Enable?'))
.getCodeExtraInformation()
.setFunctionName('enableRevoluteJointMotor');
@@ -2727,7 +2727,7 @@ module.exports = {
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics2Behavior')
.addParameter('expression', _('Joint ID'))
.addParameter('yesorno', _('Enable'))
.addParameter('yesorno', _('Enable?'))
.getCodeExtraInformation()
.setFunctionName('enablePrismaticJointLimits');
@@ -2806,7 +2806,7 @@ module.exports = {
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics2Behavior')
.addParameter('expression', _('Joint ID'))
.addParameter('yesorno', _('Enable'))
.addParameter('yesorno', _('Enable?'))
.getCodeExtraInformation()
.setFunctionName('enablePrismaticJointMotor');
@@ -3486,7 +3486,7 @@ module.exports = {
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics2Behavior')
.addParameter('expression', _('Joint ID'))
.addParameter('yesorno', _('Enable'))
.addParameter('yesorno', _('Enable?'))
.getCodeExtraInformation()
.setFunctionName('enableWheelJointMotor');

View File

@@ -274,7 +274,7 @@ module.exports = {
.setLabel('Fixed Rotation')
.setDescription(
_(
"If enabled, the object won't rotate and will stay at the same angle."
"If enabled, the object won't rotate and will stay at the same angle. Useful for characters for example."
)
)
.setGroup(_('Movement'));
@@ -845,7 +845,7 @@ module.exports = {
)
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics3DBehavior')
.addParameter('yesorno', _('Treat as bullet'), '', false)
.addParameter('yesorno', _('Treat as bullet?'), '', false)
.setDefaultValue('false')
.getCodeExtraInformation()
.setFunctionName('setBullet');
@@ -870,7 +870,7 @@ module.exports = {
'SetFixedRotation',
_('Fixed rotation'),
_(
"Enable or disable an object fixed rotation. If enabled the object won't be able to rotate. This action has no effect on characters."
"Enable or disable an object fixed rotation. If enabled the object won't be able to rotate."
),
_('Set _PARAM0_ fixed rotation: _PARAM2_'),
_('Dynamics'),
@@ -879,7 +879,7 @@ module.exports = {
)
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics3DBehavior')
.addParameter('yesorno', _('Fixed rotation'), '', false)
.addParameter('yesorno', _('Fixed rotation?'), '', false)
.setDefaultValue('false')
.getCodeExtraInformation()
.setFunctionName('setFixedRotation');
@@ -1054,7 +1054,7 @@ module.exports = {
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics3DBehavior')
.addParameter('expression', _('Layer (1 - 8)'))
.addParameter('yesorno', _('Enable'), '', false)
.addParameter('yesorno', _('Enable?'), '', false)
.setDefaultValue('true')
.getCodeExtraInformation()
.setFunctionName('enableLayer');
@@ -1090,7 +1090,7 @@ module.exports = {
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics3DBehavior')
.addParameter('expression', _('Mask (1 - 8)'))
.addParameter('yesorno', _('Enable'), '', false)
.addParameter('yesorno', _('Enable?'), '', false)
.setDefaultValue('true')
.getCodeExtraInformation()
.setFunctionName('enableMask');
@@ -1270,7 +1270,7 @@ module.exports = {
.addParameter('expression', _('Application point on Z axis'))
.setParameterLongDescription(
_(
'Use `MassCenterX`, `MassCenterY` and `MassCenterZ` expressions to avoid any rotation.'
'Use `MassCenterX` and `MassCenterY` expressions to avoid any rotation.'
)
)
.getCodeExtraInformation()
@@ -1544,19 +1544,6 @@ module.exports = {
.addParameter('behavior', _('Behavior'), 'Physics3DBehavior')
.getCodeExtraInformation()
.setFunctionName('getMassCenterY');
aut
.addExpression(
'MassCenterZ',
_('Mass center Z'),
_('Mass center Z'),
'',
'JsPlatform/Extensions/physics3d.svg'
)
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics3DBehavior')
.getCodeExtraInformation()
.setFunctionName('getMassCenterZ');
}
// Collision
extension

View File

@@ -927,7 +927,9 @@ namespace gdjs {
const angularVelocityY = angularVelocity.GetY();
const angularVelocityZ = angularVelocity.GetZ();
this.bodyUpdater.destroyBody();
let bodyID = this._body.GetID();
bodyInterface.RemoveBody(bodyID);
bodyInterface.DestroyBody(bodyID);
this._contactsEndedThisFrame.length = 0;
this._contactsStartedThisFrame.length = 0;
this._currentContacts.length = 0;
@@ -936,7 +938,7 @@ namespace gdjs {
if (!this._body) {
return;
}
const bodyID = this._body.GetID();
bodyID = this._body.GetID();
bodyInterface.SetLinearVelocity(
bodyID,
this.getVec3(linearVelocityX, linearVelocityY, linearVelocityZ)

View File

@@ -733,7 +733,7 @@ namespace gdjs {
}
setWheelOffsetZ(wheelOffsetZ: float): void {
this._wheelOffsetZ = wheelOffsetZ;
this._wheelOffsetY = wheelOffsetZ;
this._updateWheels();
}
@@ -783,11 +783,11 @@ namespace gdjs {
}
hasFrontWheelDrive(): boolean {
return this._hasFrontWheelDrive;
return this._hasBackWheelDrive;
}
setFrontWheelDrive(hasFrontWheelDrive: boolean): void {
this._hasFrontWheelDrive = hasFrontWheelDrive;
this._hasBackWheelDrive = hasFrontWheelDrive;
this.invalidateShape();
}

View File

@@ -486,16 +486,7 @@ namespace gdjs {
this._state.beforeMovingX();
//Ensure the object is not stuck
const hasPopOutOfPlatform = this._separateFromPlatforms(
this._potentialCollidingObjects,
true
);
if (hasPopOutOfPlatform && !this._jumpKey) {
// TODO This is probably unnecessary because `_canJump` is already set
// to true when entering the `OnFloor` state.
// This is wrongly allowing double jumps when characters are flipped
// with an offset center.
if (this._separateFromPlatforms(this._potentialCollidingObjects, true)) {
//After being unstuck, the object must be able to jump again.
this._canJump = true;
}

View File

@@ -246,10 +246,10 @@ std::map<gd::String, gd::PropertyDescriptor> ShapePainterObject::GetProperties()
objectProperties["antialiasing"]
.SetValue(GetAntialiasing())
.SetType("choice")
.AddChoice("none", _("None"))
.AddChoice("low", _("Low quality"))
.AddChoice("medium", _("Medium quality"))
.AddChoice("high", _("High quality"))
.AddExtraInfo("none")
.AddExtraInfo("low")
.AddExtraInfo("medium")
.AddExtraInfo("high")
.SetGroup(_("Drawing"))
.SetLabel(_("Antialiasing"))
.SetDescription(_("Antialiasing mode"));

View File

@@ -195,35 +195,11 @@ namespace gdjs {
}
/**
* To be called when the game is disposed.
* Clear the Spine atlases loaded in this manager.
* Clear the Spine Atlases loaded in this manager.
*/
dispose(): void {
this._loadedSpineAtlases.clear();
this._loadingSpineAtlases.clear();
}
/**
* 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);
}
});
}
}
}

View File

@@ -126,22 +126,5 @@ namespace gdjs {
dispose(): void {
this._loadedSpines.clear();
}
/**
* 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);
}
});
}
}
}

View File

@@ -131,14 +131,14 @@ module.exports = {
.getOrCreate('inputType')
.setValue(objectContent.inputType || '')
.setType('choice')
.addChoice('text', _('Text'))
.addChoice('text area', _('Text area'))
.addChoice('email', _('Email'))
.addChoice('password', _('Password'))
.addChoice('number', _('Number'))
.addChoice('telephone number', _('Telephone number'))
.addChoice('url', _('URL'))
.addChoice('search', _('Search'))
.addExtraInfo('text')
.addExtraInfo('text area')
.addExtraInfo('email')
.addExtraInfo('password')
.addExtraInfo('number')
.addExtraInfo('telephone number')
.addExtraInfo('url')
.addExtraInfo('search')
.setLabel(_('Input type'))
.setDescription(
_(
@@ -250,9 +250,9 @@ module.exports = {
.getOrCreate('textAlign')
.setValue(objectContent.textAlign || 'left')
.setType('choice')
.addChoice('left', _('Left'))
.addChoice('center', _('Center'))
.addChoice('right', _('Right'))
.addExtraInfo('left')
.addExtraInfo('center')
.addExtraInfo('right')
.setLabel(_('Text alignment'))
.setGroup(_('Field appearance'));

View File

@@ -160,9 +160,9 @@ std::map<gd::String, gd::PropertyDescriptor> TextObject::GetProperties() const {
objectProperties["textAlignment"]
.SetValue(textAlignment)
.SetType("choice")
.AddChoice("left", _("Left"))
.AddChoice("center", _("Center"))
.AddChoice("right", _("Right"))
.AddExtraInfo("left")
.AddExtraInfo("center")
.AddExtraInfo("right")
.SetLabel(_("Alignment"))
.SetDescription(_("Alignment of the text when multiple lines are displayed"))
.SetGroup(_("Font"))
@@ -171,9 +171,9 @@ std::map<gd::String, gd::PropertyDescriptor> TextObject::GetProperties() const {
objectProperties["verticalTextAlignment"]
.SetValue(verticalTextAlignment)
.SetType("choice")
.AddChoice("top", _("Top"))
.AddChoice("center", _("Center"))
.AddChoice("bottom", _("Bottom"))
.AddExtraInfo("top")
.AddExtraInfo("center")
.AddExtraInfo("bottom")
.SetLabel(_("Vertical alignment"))
.SetGroup(_("Font"))
.SetQuickCustomizationVisibility(gd::QuickCustomization::Hidden);

View File

@@ -102,9 +102,9 @@ const defineTileMap = function (extension, _, gd) {
'displayMode',
new gd.PropertyDescriptor(objectContent.displayMode)
.setType('choice')
.addChoice('visible', _('Visible layers'))
.addChoice('all', _('All layers'))
.addChoice('index', _('Only the layer with the specified index'))
.addExtraInfo('visible')
.addExtraInfo('all')
.addExtraInfo('index')
.setLabel(_('Display mode'))
.setGroup(_('Appearance'))
);

View File

@@ -14,7 +14,6 @@ namespace gdjs {
animatable?: SpriteAnimationData[];
variant: string;
childrenContent: { [objectName: string]: ObjectConfiguration & any };
isInnerAreaFollowingParentSize: boolean;
};
/**
@@ -112,19 +111,9 @@ namespace gdjs {
name: '',
};
}
// Legacy events-based objects don't have any instance in their default
// variant since there wasn't a graphical editor at the time.
// In this case, the editor doesn't allow to choose a variant, but a
// variant may have stayed after a user rolled back the extension.
// This variant must be ignored to match what the editor shows.
const isForcedToOverrideEventsBasedObjectChildrenConfiguration =
eventsBasedObjectData.defaultVariant.instances.length == 0;
let usedVariantData: EventsBasedObjectVariantData =
eventsBasedObjectData.defaultVariant;
if (
customObjectData.variant &&
!isForcedToOverrideEventsBasedObjectChildrenConfiguration
) {
if (customObjectData.variant) {
for (
let variantIndex = 0;
variantIndex < eventsBasedObjectData.variants.length;
@@ -165,12 +154,10 @@ namespace gdjs {
override reinitialize(objectData: ObjectData & CustomObjectConfiguration) {
super.reinitialize(objectData);
this._reinitializeRenderer();
this._initializeFromObjectData(objectData);
this._reinitializeRenderer();
// When changing the variant, the instance is like a new instance.
// We call again `onCreated` at the end, like done by the constructor
// the first time it's created.
// The generated code calls the onCreated super implementation at the end.
this.onCreated();
}
@@ -185,34 +172,6 @@ namespace gdjs {
newObjectData.animatable || []
);
}
if (oldObjectData.variant !== newObjectData.variant) {
const width = this.getWidth();
const height = this.getHeight();
const hasInnerAreaChanged =
oldObjectData.isInnerAreaFollowingParentSize &&
this._instanceContainer._initialInnerArea &&
this._innerArea &&
(this._instanceContainer._initialInnerArea.min[0] !==
this._innerArea.min[0] ||
this._instanceContainer._initialInnerArea.min[1] !==
this._innerArea.min[1] ||
this._instanceContainer._initialInnerArea.max[0] !==
this._innerArea.max[0] ||
this._instanceContainer._initialInnerArea.max[1] !==
this._innerArea.max[1]);
this._reinitializeRenderer();
this._initializeFromObjectData(newObjectData);
// The generated code calls the onCreated super implementation at the end.
this.onCreated();
// Keep the custom size
if (hasInnerAreaChanged) {
this.setWidth(width);
this.setHeight(height);
}
}
return true;
}
@@ -253,12 +212,7 @@ namespace gdjs {
// Let behaviors do something before the object is destroyed.
super.onDeletedFromScene();
// Destroy the children.
this._instanceContainer.onDeletedFromScene(this._runtimeScene);
}
override onDestroyed(): void {
this._instanceContainer._destroy();
super.onDestroyed();
this._instanceContainer.onDestroyFromScene(this._runtimeScene);
}
override update(parent: gdjs.RuntimeInstanceContainer): void {
@@ -281,8 +235,6 @@ namespace gdjs {
/**
* This method is called when the preview is being hot-reloaded.
*
* Custom objects implement this method with code generated from events.
*/
onHotReloading(parent: gdjs.RuntimeInstanceContainer) {}
@@ -291,8 +243,6 @@ namespace gdjs {
/**
* This method is called each tick after events are done.
*
* Custom objects implement this method with code generated from events.
* @param parent The instanceContainer owning the object
*/
doStepPostEvents(parent: gdjs.RuntimeInstanceContainer) {}
@@ -300,8 +250,6 @@ namespace gdjs {
/**
* This method is called when the object is being removed from its parent
* container and is about to be destroyed/reused later.
*
* Custom objects implement this method with code generated from events.
*/
onDestroy(parent: gdjs.RuntimeInstanceContainer) {}

View File

@@ -8,6 +8,7 @@ namespace gdjs {
objectData: ObjectData & CustomObjectConfiguration
) {
super(parent, objectData);
this.getRenderer().reinitialize(this, parent);
}
protected override _createRender(): gdjs.CustomRuntimeObject2DRenderer {

View File

@@ -24,7 +24,7 @@ namespace gdjs {
*
* @see gdjs.CustomRuntimeObject._innerArea
**/
_initialInnerArea: {
private _initialInnerArea: {
min: [float, float, float];
max: [float, float, float];
} | null = null;
@@ -47,9 +47,6 @@ namespace gdjs {
}
addLayer(layerData: LayerData) {
if (this._layers.containsKey(layerData.name)) {
return;
}
const layer = new gdjs.RuntimeCustomObjectLayer(layerData, this);
this._layers.put(layerData.name, layer);
this._orderedLayers.push(layer);
@@ -71,13 +68,9 @@ namespace gdjs {
eventsBasedObjectVariantData: EventsBasedObjectVariantData
) {
if (this._isLoaded) {
this.onDeletedFromScene(this._parent);
this.onDestroyFromScene(this._parent);
}
const isForcedToOverrideEventsBasedObjectChildrenConfiguration =
!eventsBasedObjectVariantData.name &&
eventsBasedObjectVariantData.instances.length == 0;
this._setOriginalInnerArea(eventsBasedObjectVariantData);
// Registering objects
@@ -90,8 +83,7 @@ namespace gdjs {
// The children configuration override only applies to the default variant.
if (
customObjectData.childrenContent &&
(!eventsBasedObjectVariantData.name ||
isForcedToOverrideEventsBasedObjectChildrenConfiguration)
!eventsBasedObjectVariantData.name
) {
this.registerObject({
...childObjectData,
@@ -186,25 +178,26 @@ namespace gdjs {
*
* @param instanceContainer The container owning the object.
*/
onDeletedFromScene(instanceContainer: gdjs.RuntimeInstanceContainer): void {
onDestroyFromScene(instanceContainer: gdjs.RuntimeInstanceContainer): void {
if (!this._isLoaded) {
return;
}
// Notify the objects they are being destroyed
const allInstancesList = this.getAdhocListOfAllInstances();
for (let i = 0, len = allInstancesList.length; i < len; ++i) {
const object = allInstancesList[i];
object.onDeletedFromScene();
// The object can free all its resource directly...
object.onDestroyed();
}
// ...as its container cache `_instancesRemoved` is also destroy.
this._destroy();
this._isLoaded = false;
}
override _destroy() {
const allInstancesList = this.getAdhocListOfAllInstances();
for (let i = 0, len = allInstancesList.length; i < len; ++i) {
const object = allInstancesList[i];
object.onDestroyed();
}
_destroy() {
// It should not be necessary to reset these variables, but this help
// ensuring that all memory related to the container is released immediately.
super._destroy();

View File

@@ -162,29 +162,5 @@ namespace gdjs {
this._invalidModel.scene.clear();
}
}
/**
* Unload the specified list of resources:
* this clears the models, resources loaded and destroy 3D models loaders 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 loadedThreeModel = this._loadedThreeModels.get(resourceData);
if (loadedThreeModel) {
loadedThreeModel.scene.clear();
this._loadedThreeModels.delete(resourceData);
}
const downloadedArrayBuffer =
this._downloadedArrayBuffers.get(resourceData);
if (downloadedArrayBuffer) {
this._downloadedArrayBuffers.delete(resourceData);
}
});
}
}
}

View File

@@ -5,7 +5,6 @@
*/
namespace gdjs {
const logger = new gdjs.Logger('ResourceLoader');
const debugLogger = new gdjs.Logger('ResourceLoader - debug').enable(false);
const addSearchParameterToUrl = (
url: string,
@@ -97,15 +96,17 @@ namespace gdjs {
*/
private _globalResources: Array<string>;
/**
* Resources and the loading state of each scene, indexed by scene name.
* Resources by scene names.
*/
private _sceneLoadingStates: Map<
string,
{
resourceNames: Array<string>;
status: 'not-loaded' | 'loaded' | 'ready';
}
> = new Map();
private _sceneResources: Map<string, Array<string>>;
/**
* Keep track of which scene whose resources has already be pre-loaded.
*/
private _sceneNamesToLoad: Set<string>;
/**
* Keep track of which scene whose resources has already be loaded.
*/
private _sceneNamesToMakeReady: Set<string>;
/**
* A queue of scenes whose resources are still to be pre-loaded.
*/
@@ -126,12 +127,11 @@ namespace gdjs {
private _spineManager: SpineManager | null = null;
/**
* The name of the scene for which resources are currently being loaded.
* Only used by events.
*/
private currentLoadingSceneName: string = '';
/**
* The progress, between 0 and 1, of the loading of the resource, for the
* scene that is being loaded (see `currentLoadingSceneName`).
* Only used by events.
*/
private currentSceneLoadingProgress: float = 0;
/**
@@ -144,8 +144,8 @@ namespace gdjs {
/**
* @param runtimeGame The game.
* @param resourceDataArray The resources data of the game.
* @param globalResources The resources needed for any scene.
* @param layoutDataArray The resources used by each scene.
* @param globalResources The resources needed for any layer.
* @param layoutDataArray The resources used by each layer.
*/
constructor(
runtimeGame: RuntimeGame,
@@ -158,6 +158,9 @@ namespace gdjs {
this._globalResources = globalResources;
// These 3 attributes are filled by `setResources`.
this._sceneResources = new Map<string, Array<string>>();
this._sceneNamesToLoad = new Set<string>();
this._sceneNamesToMakeReady = new Set<string>();
this.setResources(resourceDataArray, globalResources, layoutDataArray);
this._imageManager = new gdjs.ImageManager(this);
@@ -221,31 +224,23 @@ namespace gdjs {
): void {
this._globalResources = globalResources;
this._sceneLoadingStates.clear();
this._sceneResources.clear();
this._sceneNamesToLoad.clear();
this._sceneNamesToMakeReady.clear();
for (const layoutData of layoutDataArray) {
this._sceneLoadingStates.set(layoutData.name, {
resourceNames: layoutData.usedResources.map(
(resource) => resource.name
),
status: 'not-loaded',
});
this._sceneResources.set(
layoutData.name,
layoutData.usedResources.map((resource) => resource.name)
);
this._sceneNamesToLoad.add(layoutData.name);
this._sceneNamesToMakeReady.add(layoutData.name);
}
// TODO Clearing the queue doesn't abort the running task, but it should
// not matter as resource loading is really fast in preview mode.
this._sceneToLoadQueue.length = 0;
for (let index = layoutDataArray.length - 1; index >= 0; index--) {
const layoutData = layoutDataArray[index];
const resourcesPreloading = layoutData.resourcesPreloading || 'inherit';
const resolvedResourcesPreloading =
resourcesPreloading === 'inherit'
? this._runtimeGame.getSceneResourcesPreloading()
: resourcesPreloading;
if (resolvedResourcesPreloading === 'at-startup') {
this._sceneToLoadQueue.push(new SceneLoadingTask(layoutData.name));
}
this._sceneToLoadQueue.push(new SceneLoadingTask(layoutData.name));
}
this._resources.clear();
@@ -276,10 +271,8 @@ namespace gdjs {
onProgress(loadedCount, this._resources.size);
}
);
for (const sceneLoadingState of this._sceneLoadingStates.values()) {
sceneLoadingState.status = 'ready';
}
this._sceneNamesToLoad.clear();
this._sceneNamesToMakeReady.clear();
}
/**
@@ -289,21 +282,17 @@ namespace gdjs {
firstSceneName: string,
onProgress: (count: number, total: number) => void
): Promise<void> {
const firstSceneState = this._sceneLoadingStates.get(firstSceneName);
if (!firstSceneState) {
const sceneResources = this._sceneResources.get(firstSceneName);
if (!sceneResources) {
logger.warn(
'Can\'t load resource for unknown scene: "' + firstSceneName + '".'
);
return;
}
let loadedCount = 0;
const resourceNames = [
...this._globalResources,
...firstSceneState.resourceNames,
];
const resources = [...this._globalResources, ...sceneResources.values()];
await processAndRetryIfNeededWithPromisePool(
resourceNames,
resources,
maxForegroundConcurrency,
maxAttempt,
async (resourceName) => {
@@ -315,11 +304,11 @@ namespace gdjs {
await this._loadResource(resource);
await this._processResource(resource);
loadedCount++;
onProgress(loadedCount, resourceNames.length);
onProgress(loadedCount, resources.length);
}
);
firstSceneState.status = 'ready';
this._setSceneAssetsLoaded(firstSceneName);
this._setSceneAssetsReady(firstSceneName);
}
/**
@@ -329,32 +318,17 @@ namespace gdjs {
* scenes.
*/
async loadAllSceneInBackground(): Promise<void> {
if (this.currentLoadingSceneName) {
return;
}
debugLogger.log('Loading all scene resources, in background.');
while (this._sceneToLoadQueue.length > 0) {
debugLogger.log(
`Still resources of ${this._sceneToLoadQueue.length} scene(s) to load: ${this._sceneToLoadQueue.map((task) => task.sceneName).join(', ')}`
);
const task = this._sceneToLoadQueue[this._sceneToLoadQueue.length - 1];
if (task === undefined) {
continue;
}
this.currentLoadingSceneName = task.sceneName;
if (!this.areSceneAssetsLoaded(task.sceneName)) {
debugLogger.log(
`Loading (but not processing) resources for scene ${task.sceneName}.`
);
await this._doLoadSceneResources(
task.sceneName,
async (count, total) => task.onProgress(count, total)
);
debugLogger.log(
`Done loading (but not processing) resources for scene ${task.sceneName}.`
);
// A scene may have been moved last while awaiting resources to be
// downloaded (see _prioritizeScene).
this._sceneToLoadQueue.splice(
@@ -366,7 +340,6 @@ namespace gdjs {
this._sceneToLoadQueue.pop();
}
}
debugLogger.log(`Scene resources loading finished.`);
this.currentLoadingSceneName = '';
}
@@ -374,17 +347,16 @@ namespace gdjs {
sceneName: string,
onProgress?: (count: number, total: number) => Promise<void>
): Promise<void> {
const sceneState = this._sceneLoadingStates.get(sceneName);
if (!sceneState) {
const sceneResources = this._sceneResources.get(sceneName);
if (!sceneResources) {
logger.warn(
'Can\'t load resource for unknown scene: "' + sceneName + '".'
);
return;
}
let loadedCount = 0;
await processAndRetryIfNeededWithPromisePool(
sceneState.resourceNames,
[...sceneResources.values()],
this._isLoadingInForeground
? maxForegroundConcurrency
: maxBackgroundConcurrency,
@@ -397,13 +369,11 @@ namespace gdjs {
}
await this._loadResource(resource);
loadedCount++;
this.currentSceneLoadingProgress =
loadedCount / sceneState.resourceNames.length;
onProgress &&
(await onProgress(loadedCount, sceneState.resourceNames.length));
this.currentSceneLoadingProgress = loadedCount / this._resources.size;
onProgress && (await onProgress(loadedCount, this._resources.size));
}
);
sceneState.status = 'loaded';
this._setSceneAssetsLoaded(sceneName);
}
private async _loadResource(resource: ResourceData): Promise<void> {
@@ -435,8 +405,8 @@ namespace gdjs {
}
await this.loadSceneResources(sceneName, onProgress);
const sceneState = this._sceneLoadingStates.get(sceneName);
if (!sceneState) {
const sceneResources = this._sceneResources.get(sceneName);
if (!sceneResources) {
logger.warn(
'Can\'t load resource for unknown scene: "' + sceneName + '".'
);
@@ -444,7 +414,7 @@ namespace gdjs {
}
let parsedCount = 0;
for (const resourceName of sceneState.resourceNames) {
for (const resourceName of sceneResources) {
const resource = this._resources.get(resourceName);
if (!resource) {
logger.warn('Unable to find resource "' + resourceName + '".');
@@ -452,10 +422,9 @@ namespace gdjs {
}
await this._processResource(resource);
parsedCount++;
onProgress &&
(await onProgress(parsedCount, sceneState.resourceNames.length));
onProgress && (await onProgress(parsedCount, sceneResources.length));
}
sceneState.status = 'ready';
this._setSceneAssetsReady(sceneName);
}
/**
@@ -469,25 +438,15 @@ namespace gdjs {
sceneName: string,
onProgress?: (count: number, total: number) => void
): Promise<void> {
debugLogger.log(
`Prioritization of loading of resources for scene ${sceneName} was requested.`
);
this._isLoadingInForeground = true;
const task = this._prioritizeScene(sceneName);
return new Promise<void>((resolve, reject) => {
if (!task) {
this._isLoadingInForeground = false;
debugLogger.log(
`Loading of resources for scene ${sceneName} was immediately resolved.`
);
resolve();
return;
}
task.registerCallback(() => {
debugLogger.log(
`Loading of resources for scene ${sceneName} just finished.`
);
this._isLoadingInForeground = false;
resolve();
}, onProgress);
@@ -504,51 +463,6 @@ namespace gdjs {
}
}
/**
* To be called when a scene is unloaded.
*/
unloadSceneResources({
unloadedSceneName,
newSceneName,
}: {
unloadedSceneName: string;
newSceneName: string | null;
}): void {
if (!unloadedSceneName) return;
debugLogger.log(
`Unloading of resources for scene ${unloadedSceneName} was requested.`
);
const sceneUniqueResourcesByKindMap =
this._getResourcesByKindOnlyUsedInUnloadedScene({
unloadedSceneName,
newSceneName,
});
for (const [kindResourceManager, resourceManager] of this
._resourceManagersMap) {
const resources =
sceneUniqueResourcesByKindMap.get(kindResourceManager);
if (resources) {
debugLogger.log(
`Unloading of resources of kind ${kindResourceManager} for scene ${unloadedSceneName}: `,
resources.map((resource) => resource.name).join(', ')
);
resourceManager.unloadResourcesList(resources);
}
}
debugLogger.log(
`Unloading of resources for scene ${unloadedSceneName} finished.`
);
const sceneState = this._sceneLoadingStates.get(unloadedSceneName);
if (sceneState) {
sceneState.status = 'not-loaded';
}
// TODO: mark the scene as unloaded so it's not automatically loaded again eagerly.
}
/**
* Put a given scene at the end of the queue.
*
@@ -556,41 +470,16 @@ namespace gdjs {
* this scene will be the next to be loaded.
*/
private _prioritizeScene(sceneName: string): SceneLoadingTask | null {
const sceneState = this._sceneLoadingStates.get(sceneName);
if (!sceneState) return null;
if (sceneState.status === 'loaded' || sceneState.status === 'ready') {
debugLogger.log(
`Scene ${sceneName} is already loaded. Skipping prioritization.`
);
// The scene is already loaded, nothing to do.
return null;
}
// The scene is not loaded: either prioritize it or add it to the loading queue.
const taskIndex = this._sceneToLoadQueue.findIndex(
(task) => task.sceneName === sceneName
);
let task: SceneLoadingTask;
if (taskIndex !== -1) {
// There is already a task for this scene in the queue.
// Move it so that it's loaded first.
task = this._sceneToLoadQueue[taskIndex];
this._sceneToLoadQueue.splice(taskIndex, 1);
this._sceneToLoadQueue.push(task);
} else {
// There is no task for this scene in the queue.
// It might be because the scene was unloaded or never loaded.
// In this case, we need to add a new task to the queue.
task = new SceneLoadingTask(sceneName);
this._sceneToLoadQueue.push(task);
if (taskIndex < 0) {
// The scene is already loaded.
return null;
}
// Re-start the loading process in the background. While at the beginning of the game
// it's not needed because already launched, a scene might be unloaded. This means
// that we then need to relaunch the loading process.
this.loadAllSceneInBackground();
const task = this._sceneToLoadQueue[taskIndex];
this._sceneToLoadQueue.splice(taskIndex, 1);
this._sceneToLoadQueue.push(task);
return task;
}
@@ -622,10 +511,7 @@ namespace gdjs {
* (but maybe not parsed).
*/
areSceneAssetsLoaded(sceneName: string): boolean {
const sceneState = this._sceneLoadingStates.get(sceneName);
if (!sceneState) return false;
return sceneState.status === 'loaded' || sceneState.status === 'ready';
return !this._sceneNamesToLoad.has(sceneName);
}
/**
@@ -633,10 +519,15 @@ namespace gdjs {
* parsed.
*/
areSceneAssetsReady(sceneName: string): boolean {
const sceneState = this._sceneLoadingStates.get(sceneName);
if (!sceneState) return false;
return !this._sceneNamesToMakeReady.has(sceneName);
}
return sceneState.status === 'ready';
private _setSceneAssetsLoaded(sceneName: string): void {
this._sceneNamesToLoad.delete(sceneName);
}
private _setSceneAssetsReady(sceneName: string): void {
this._sceneNamesToMakeReady.delete(sceneName);
}
getResource(resourceName: string): ResourceData | null {
@@ -745,70 +636,6 @@ namespace gdjs {
getSpineAtlasManager(): gdjs.SpineAtlasManager | null {
return this._spineAtlasManager;
}
injectMockResourceManagerForTesting(
resourceKind: ResourceKind,
resourceManager: ResourceManager
) {
this._resourceManagersMap.set(resourceKind, resourceManager);
}
/**
* Get the map of resources that are only used in the scene that is being unloaded,
* and that are not used in any other loaded scene (or the scene that is coming next).
*/
private _getResourcesByKindOnlyUsedInUnloadedScene({
unloadedSceneName,
newSceneName,
}: {
unloadedSceneName: string;
newSceneName: string | null;
}): Map<ResourceKind, ResourceData[]> {
const unloadedSceneState =
this._sceneLoadingStates.get(unloadedSceneName);
if (!unloadedSceneState) {
return new Map<ResourceKind, ResourceData[]>();
}
// Construct the set of all resources to unload. These are the resources
// used in the scene that is being unloaded minus all the resources used
// by the other scenes that are loaded (and the possible scene that is coming next).
const resourceNamesToUnload = new Set<string>(
unloadedSceneState.resourceNames
);
for (const [
sceneName,
sceneState,
] of this._sceneLoadingStates.entries()) {
if (sceneName === unloadedSceneName) continue;
if (
sceneName === newSceneName ||
sceneState.status === 'loaded' ||
sceneState.status === 'ready'
) {
sceneState.resourceNames.forEach((resourceName) => {
resourceNamesToUnload.delete(resourceName);
});
}
}
const result = new Map<ResourceKind, ResourceData[]>();
resourceNamesToUnload.forEach((resourceName) => {
const resourceData = this._resources.get(resourceName);
if (!resourceData) return;
const kind = resourceData.kind;
const resources = result.get(kind);
if (resources) {
resources.push(resourceData);
} else {
result.set(kind, [resourceData]);
}
});
return result;
}
}
type PromiseError<T> = { item: T; error: Error };

View File

@@ -35,15 +35,5 @@ namespace gdjs {
* Using the manager after calling this method is undefined behavior.
*/
dispose(): void;
/**
* Should clear all specified resources data and anything stored by this manager
* for these resources.
*
* Usually called when scene resoures are unloaded.
*
* @param resourcesList The list of specific resources that need to be clear
*/
unloadResourcesList(resourcesList: ResourceData[]): void;
}
}

View File

@@ -811,8 +811,6 @@ namespace gdjs {
this._objectsCtor = new Hashtable();
this._allInstancesList = [];
this._instancesRemoved = [];
this._layersCameraCoordinates = {};
this._initialBehaviorSharedData = new Hashtable();
}
}
}

View File

@@ -116,9 +116,6 @@ namespace gdjs {
}
}
getRuntimeLayer(): gdjs.RuntimeLayer {
return this;
}
getRenderer(): gdjs.LayerRenderer {
return this._renderer;
}

View File

@@ -222,9 +222,7 @@ namespace gdjs {
kind: 'fatal',
message:
'Unexpected error happened while hot-reloading: ' +
error.message +
'\n' +
error.stack,
error.message,
});
}
})
@@ -474,24 +472,13 @@ namespace gdjs {
newExternalLayoutData.associatedLayout
);
const oldObjectDataList =
HotReloader.resolveCustomObjectConfigurations(
oldProjectData,
oldLayoutData ? oldLayoutData.objects : []
);
const newObjectDataList =
HotReloader.resolveCustomObjectConfigurations(
newProjectData,
newLayoutData ? newLayoutData.objects : []
);
sceneStack._stack.forEach((runtimeScene) => {
this._hotReloadRuntimeSceneInstances(
oldProjectData,
newProjectData,
changedRuntimeBehaviors,
oldObjectDataList,
newObjectDataList,
oldLayoutData ? oldLayoutData.objects : [],
newLayoutData ? newLayoutData.objects : [],
oldExternalLayoutData.instances,
newExternalLayoutData.instances,
runtimeScene
@@ -738,6 +725,7 @@ namespace gdjs {
// scene (see `_hotReloadRuntimeInstanceContainer` call from
// `_hotReloadRuntimeSceneInstances`).
objects: mergedChildObjectDataList,
childrenContent: mergedChildObjectDataList,
};
return mergedObjectConfiguration;
});

View File

@@ -362,7 +362,8 @@ namespace gdjs {
if (objectsLists.items.hasOwnProperty(name)) {
const allObjects = objectsContext.getObjects(name);
const objectsList = objectsLists.items[name];
gdjs.copyArray(allObjects, objectsList);
objectsList.length = 0;
objectsList.push.apply(objectsList, allObjects);
}
}
return true;

View File

@@ -205,28 +205,6 @@ namespace gdjs {
this._loadedFontFamily.clear();
this._loadedFontFamilySet.clear();
}
/**
* Unload the specified list of resources:
* this clears the caches of loaded font families.
*
* Usually called when scene resoures are unloaded.
*
* @param resourcesList The list of specific resources
*/
unloadResourcesList(resourcesList: ResourceData[]): void {
resourcesList.forEach((resourceData) => {
const resource = this._loadedFontFamily.get(resourceData);
if (resource) {
this._loadedFontFamily.delete(resourceData);
}
const fontName = this._getFontFamilyFromFilename(resourceData);
if (fontName) {
this._loadedFontFamilySet.delete(fontName);
}
});
}
}
//Register the class to let the engine use it.

View File

@@ -939,28 +939,6 @@ namespace gdjs {
dispose(): void {
this.unloadAll();
}
/**
* Unload the specified list of resources:
* this unloads all audio from the specified resources from memory.
*
* Usually called when scene resoures are unloaded.
*
* @param resourcesList The list of specific resources
*/
unloadResourcesList(resourcesList: ResourceData[]): void {
resourcesList.forEach((resourceData) => {
const musicRes = this._loadedMusics.get(resourceData);
if (musicRes) {
this.unloadAudio(resourceData.name, true);
}
const soundRes = this._loadedSounds.get(resourceData);
if (soundRes) {
this.unloadAudio(resourceData.name, false);
}
});
}
}
// Register the class to let the engine use it.

View File

@@ -208,26 +208,5 @@ namespace gdjs {
this._loadedJsons.clear();
this._callbacks.clear();
}
/**
* Unload the specified list of resources:
* this clears the JSONs 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 loadedJson = this._loadedJsons.get(resourceData);
if (loadedJson) {
this._loadedJsons.delete(resourceData);
}
const callback = this._callbacks.get(resourceData);
if (callback) {
this._callbacks.delete(resourceData);
}
});
}
}
}

View File

@@ -66,7 +66,6 @@ namespace gdjs {
*/
export class Logger {
private readonly group: string;
private enabled: boolean = true;
/**
* Create a new logger with the given group name.
@@ -77,30 +76,21 @@ namespace gdjs {
}
log(...messages: any[]): void {
if (!this.enabled) return;
loggerOutput.log(this.group, objectsToString(messages), 'info');
}
info(...messages: any[]): void {
if (!this.enabled) return;
loggerOutput.log(this.group, objectsToString(messages), 'info');
}
warn(...messages: any[]): void {
if (!this.enabled) return;
loggerOutput.log(this.group, objectsToString(messages), 'warning');
}
error(...messages: any[]): void {
if (!this.enabled) return;
loggerOutput.log(this.group, objectsToString(messages), 'error');
}
enable(enabled: boolean): gdjs.Logger {
this.enabled = enabled;
return this;
}
/**
* Give access to the console output used by default by the logger.
* This can be useful to restore the default log method if you overrode it

View File

@@ -50,7 +50,12 @@ namespace gdjs {
) {
this._object = object;
this._isContainerDirty = true;
this._pixiContainer.removeChildren();
const layer = parent.getLayer('');
if (layer) {
layer
.getRenderer()
.addRendererObject(this._pixiContainer, object.getZOrder());
}
}
getRendererObject() {

View File

@@ -307,34 +307,6 @@ namespace gdjs {
this._pixiBitmapFontsToUninstall.length = 0;
this._loadedFontsData.clear();
}
/**
* Unload the specified list of resources:
* this uninstalls fonts from memory and clear cache of loaded fonts.
*
* Usually called when scene resoures are unloaded.
*
* @param resourcesList The list of specific resources
*/
unloadResourcesList(resourcesList: ResourceData[]): void {
resourcesList.forEach((resourceData) => {
const loadedFont = this._loadedFontsData.get(resourceData);
if (loadedFont) {
this._loadedFontsData.delete(resourceData);
}
for (const bitmapFontInstallKey in this._pixiBitmapFontsInUse) {
if (bitmapFontInstallKey.endsWith(resourceData.file))
PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
}
for (const bitmapFontInstallKey of this._pixiBitmapFontsToUninstall) {
if (bitmapFontInstallKey.endsWith(resourceData.file))
PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
}
});
}
}
// Register the class to let the engine use it.

View File

@@ -17,7 +17,6 @@ namespace gdjs {
getName: () => string;
getRendererObject: () => RendererObjectInterface | null | undefined;
get3DRendererObject: () => THREE.Object3D | null | undefined;
getRuntimeLayer?: () => gdjs.RuntimeLayer;
}
/**

View File

@@ -519,37 +519,6 @@ namespace gdjs {
}
this._scaledTextures.clear();
}
/**
* Unload the specified list of resources:
* this clears the cache of loaded textures associated to these resources.
*
* Usually called when scene resoures are unloaded.
*
* @param resourcesList The list of specific resources
*/
unloadResourcesList(resourcesList: ResourceData[]): void {
resourcesList.forEach((resourceData) => {
const resourceName = resourceData.name;
const resource = this._loadedTextures.get(resourceData);
if (resource) {
resource.destroy(true);
this._loadedTextures.delete(resourceData);
}
const threeTexture = this._loadedThreeTextures.get(resourceName);
if (threeTexture) {
threeTexture.dispose();
this._loadedThreeTextures.remove(resourceName);
}
const threeMaterials = this._loadedThreeMaterials.get(resourceName);
if (threeMaterials) {
threeMaterials.dispose();
this._loadedThreeMaterials.remove(resourceName);
}
});
}
}
//Register the class to let the engine use it.

View File

@@ -97,8 +97,6 @@ namespace gdjs {
!gdjs.evtTools.common.isMobile()),
preserveDrawingBuffer: true, // Keep to true to allow screenshots.
});
this._threeRenderer.shadowMap.enabled = true;
this._threeRenderer.shadowMap.type = THREE.PCFSoftShadowMap;
this._threeRenderer.useLegacyLights = true;
this._threeRenderer.autoClear = false;
this._threeRenderer.setSize(

View File

@@ -184,9 +184,6 @@ namespace gdjs {
*/
_embeddedResourcesMappings: Map<string, Record<string, string>>;
_sceneResourcesPreloading: 'at-startup' | 'never';
_sceneResourcesUnloading: 'at-scene-exit' | 'never';
/**
* Optional client to connect to a debugger server.
*/
@@ -226,11 +223,6 @@ namespace gdjs {
this._data = data;
this._updateSceneAndExtensionsData();
this._sceneResourcesPreloading =
this._data.properties.sceneResourcesPreloading || 'at-startup';
this._sceneResourcesUnloading =
this._data.properties.sceneResourcesUnloading || 'never';
this._resourcesLoader = new gdjs.ResourceLoader(
this,
data.resources.resources,
@@ -253,7 +245,6 @@ namespace gdjs {
this._antialiasingMode = this._data.properties.antialiasingMode;
this._isAntialisingEnabledOnMobile =
this._data.properties.antialisingEnabledOnMobile;
this._renderer = new gdjs.RuntimeGameRenderer(
this,
this._options.forceFullscreen || false
@@ -372,14 +363,6 @@ namespace gdjs {
return this._variablesByExtensionName.get(extensionName) || null;
}
/**
* Get the gdjs.ResourceLoader of the RuntimeGame.
* @return The resource loader.
*/
getResourceLoader(): gdjs.ResourceLoader {
return this._resourcesLoader;
}
/**
* Get the gdjs.SoundManager of the RuntimeGame.
* @return The sound manager.
@@ -781,22 +764,6 @@ namespace gdjs {
return this._resourcesLoader.areSceneAssetsReady(sceneName);
}
/**
* Returns the scene resources preloading mode.
* It can be overriden by each scene.
*/
getSceneResourcesPreloading(): 'at-startup' | 'never' {
return this._sceneResourcesPreloading;
}
/**
* Returns the scene resources unloading mode.
* It can be overriden by each scene.
*/
getSceneResourcesUnloading(): 'at-scene-exit' | 'never' {
return this._sceneResourcesUnloading;
}
/**
* Load all assets needed to display the 1st scene, displaying progress in
* renderer.

View File

@@ -292,7 +292,7 @@ namespace gdjs {
/**
* Called to reset the object to its default state. This is used for objects that are
* "recycled": they are dismissed (at which point `onDeletedFromScene` is called) but still
* "recycled": they are dismissed (at which point `onDestroyFromScene` is called) but still
* stored in a cache to be reused next time an object must be created. At this point,
* `reinitialize` will be called. The object must then work as if it was a newly constructed
* object.
@@ -596,7 +596,7 @@ namespace gdjs {
/**
* Remove an object from a scene.
*
* Do not change/redefine this method. Instead, redefine the onDeletedFromScene method.
* Do not change/redefine this method. Instead, redefine the onDestroyFromScene method.
*/
deleteFromScene(): void {
if (this._livingOnScene) {
@@ -614,12 +614,9 @@ namespace gdjs {
}
/**
* Called when the object is deleted (because it is removed from a scene or
* the scene is being unloaded). The object is not actually destroyed and
* can still be used by events.
*
* If you redefine this function, **make sure to call the original method**
* (`super.onDeletedFromScene();`).
* Called when the object is destroyed (because it is removed from a scene or the scene
* is being unloaded). If you redefine this function, **make sure to call the original method**
* (`RuntimeObject.prototype.onDestroyFromScene.call(this, runtimeScene);`).
*/
onDeletedFromScene(): void {
const theLayer = this._runtimeScene.getLayer(this.layer);
@@ -638,10 +635,6 @@ namespace gdjs {
this.clearEffects();
}
/**
* Called on deleted objects after all events has been executed for the
* current frame and the object can be safely destroyed.
*/
onDestroyed(): void {}
/**

View File

@@ -23,7 +23,6 @@ namespace gdjs {
_timeManager: TimeManager;
_gameStopRequested: boolean = false;
_requestedScene: string = '';
_resourcesUnloading: 'at-scene-exit' | 'never' | 'inherit' = 'inherit';
private _asyncTasksManager = new gdjs.AsyncTasksManager();
/** True if loadFromScene was called and the scene is being played. */
@@ -142,7 +141,6 @@ namespace gdjs {
this._runtimeGame.getRenderer().setWindowTitle(sceneData.title);
}
this._name = sceneData.name;
this._resourcesUnloading = sceneData.resourcesUnloading || 'inherit';
this.setBackgroundColor(sceneData.r, sceneData.v, sceneData.b);
//Load layers
@@ -308,7 +306,7 @@ namespace gdjs {
this.onGameResolutionResized();
}
override _destroy() {
_destroy() {
// It should not be necessary to reset these variables, but this help
// ensuring that all memory related to the RuntimeScene is released immediately.
super._destroy();
@@ -580,13 +578,6 @@ namespace gdjs {
return this._name;
}
/**
* Get the strategy to unload resources of this scene.
*/
getResourcesUnloading(): 'at-scene-exit' | 'never' | 'inherit' {
return this._resourcesUnloading;
}
/**
* Create an identifier for a new object of the scene.
*/

View File

@@ -63,14 +63,10 @@ namespace gdjs {
this.pop();
} else if (request === gdjs.SceneChangeRequest.PUSH_SCENE) {
this.push(currentScene.getRequestedScene());
} else if (
request === gdjs.SceneChangeRequest.REPLACE_SCENE ||
request === gdjs.SceneChangeRequest.CLEAR_SCENES
) {
this.replace(
currentScene.getRequestedScene(),
request === gdjs.SceneChangeRequest.CLEAR_SCENES
);
} else if (request === gdjs.SceneChangeRequest.REPLACE_SCENE) {
this.replace(currentScene.getRequestedScene());
} else if (request === gdjs.SceneChangeRequest.CLEAR_SCENES) {
this.replace(currentScene.getRequestedScene(), true);
} else {
logger.error('Unrecognized change in scene stack: ' + request);
}
@@ -105,10 +101,7 @@ namespace gdjs {
if (!scene) {
return;
}
this._unloadSceneAndPossiblyResources({
scene,
newSceneName: null,
});
scene.unloadScene();
}
// Tell the new current scene it's being resumed
@@ -147,7 +140,6 @@ namespace gdjs {
this._loadNewScene(newSceneName);
this._isNextLayoutLoading = false;
});
return null;
}
@@ -194,7 +186,7 @@ namespace gdjs {
while (this._stack.length !== 0) {
let scene = this._stack.pop();
if (scene) {
this._unloadSceneAndPossiblyResources({ scene, newSceneName });
scene.unloadScene();
}
}
} else {
@@ -202,7 +194,7 @@ namespace gdjs {
if (this._stack.length !== 0) {
let scene = this._stack.pop();
if (scene) {
this._unloadSceneAndPossiblyResources({ scene, newSceneName });
scene.unloadScene();
}
}
}
@@ -380,52 +372,14 @@ namespace gdjs {
* Unload all the scenes and clear the stack.
*/
dispose(): void {
while (this._stack.length > 0) {
const scene = this._stack.pop();
if (scene) {
this._unloadSceneAndPossiblyResources({
scene,
newSceneName: null,
});
}
for (const item of this._stack) {
item.unloadScene();
}
this._stack.length = 0;
this._wasDisposed = true;
}
private _unloadSceneAndPossiblyResources({
scene,
newSceneName,
}: {
scene: gdjs.RuntimeScene;
newSceneName: string | null;
}): void {
const unloadedSceneName = scene.getName();
const resourcesUnloading = scene.getResourcesUnloading();
const resolvedResourcesUnloading =
resourcesUnloading === 'inherit'
? this._runtimeGame.getSceneResourcesUnloading()
: resourcesUnloading;
const shouldUnloadResources =
resolvedResourcesUnloading === 'at-scene-exit' &&
// Unload resources only if it's the last scene with this name in the stack.
newSceneName !== scene.getName() &&
this._stack.every((scene) => scene.getName() !== unloadedSceneName);
scene.unloadScene();
// After this point, `scene` is no longer valid and should not be used anymore.
// It was "disposed".
if (shouldUnloadResources) {
this._runtimeGame.getResourceLoader().unloadSceneResources({
unloadedSceneName,
newSceneName,
});
}
}
private _throwIfDisposed(): void {
if (this._wasDisposed) {
throw 'The scene stack has been disposed and should not be used anymore.';

View File

@@ -169,8 +169,6 @@ declare interface LayoutData extends InstanceContainerData {
title: string;
behaviorsSharedData: BehaviorSharedData[];
usedResources: ResourceReference[];
resourcesPreloading?: 'at-startup' | 'never' | 'inherit';
resourcesUnloading?: 'at-scene-exit' | 'never' | 'inherit';
}
declare interface LayoutNetworkSyncData {
@@ -231,7 +229,7 @@ declare interface EventsBasedObjectVariantData extends InstanceContainerData {
/**
* A value shared by every object instances.
*
* @see gdjs.CustomRuntimeObjectInstanceContainer._initialInnerArea
* @see gdjs.CustomRuntimeObjectInstanceContainer._originalInnerArea
**/
_initialInnerArea: {
min: [float, float, float];
@@ -372,8 +370,6 @@ declare interface ProjectPropertiesData {
extensionProperties: Array<ExtensionProperty>;
useDeprecatedZeroAsDefaultZOrder?: boolean;
projectUuid?: string;
sceneResourcesPreloading?: 'at-startup' | 'never';
sceneResourcesUnloading?: 'at-scene-exit' | 'never';
}
declare interface ExtensionProperty {
@@ -441,5 +437,4 @@ declare type ResourceKind =
| 'bitmapFont'
| 'model3D'
| 'atlas'
| 'spine'
| 'fake-resource-kind-for-testing-only';
| 'spine';

View File

@@ -225,7 +225,7 @@ const identifyClassNames = (code) => {
.replace(/( hide\w*\(.*\))(: any)? {/g, '$1: void {')
.replace(/( reset\w*\(.*\))(: any)? {/g, '$1: void {')
.replace(/( deleteFromScene\w*\(.*\))(: any)? {/g, '$1: void {')
.replace(/( onDeletedFromScene\w*\(.*\))(: any)? {/g, '$1: void {')
.replace(/( onDestroyFromScene\w*\(.*\))(: any)? {/g, '$1: void {')
.replace(/( enable\w*\(.*\))(: any)? {/g, '$1: void {')
// Members:
.replace(/(\w*): any = (\d)/g, '$1: number = $2')

Binary file not shown.

Before

Width:  |  Height:  |  Size: 277 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 202 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 654 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 926 B

View File

@@ -16,7 +16,6 @@ describe('gdjs.CustomRuntimeObject', function () {
name: 'MyCustomObject',
type: 'MyExtension::MyEventsBasedObject',
variant: '',
isInnerAreaFollowingParentSize: false,
variables: [],
behaviors: [],
effects: [],

View File

@@ -1,47 +1,24 @@
// @ts-check
/*
* GDevelop JS Platform
* Copyright 2013-2023 Florian Rival (Florian.Rival@gmail.com). All rights reserved.
* This project is released under the MIT License.
*/
/**
* @implements {gdjs.ResourceManager}
*/
// implements gdjs.ResourceManager
gdjs.MockedResourceManager = class MockedResourceManager {
loadResourcePromises = new Map();
loadResourceCallbacks = new Map();
disposedResources = new Set();
loadedResources = new Set();
waitingForProcessing = new Set();
readyResources = new Set();
loadResource(resourceName) {
if (
this.loadedResources.has(resourceName) ||
this.waitingForProcessing.has(resourceName)
) {
return Promise.resolve();
}
const existingPromise = this.loadResourcePromises.get(resourceName);
if (existingPromise) {
return existingPromise;
}
const promise = new Promise((resolve) => {
this.loadResourceCallbacks.set(resourceName, resolve);
const that = this;
return new Promise((resolve, reject) => {
that.loadResourceCallbacks.set(resourceName, resolve);
});
this.loadResourcePromises.set(resourceName, promise);
return promise;
}
async processResource(resourceName) {
// Mark resource as fully processed
this.readyResources.add(resourceName);
}
async processResource(resourceName) {}
/**
* @param {string} resourceName
* @param {string} resourceName
* @returns {boolean}
*/
isResourceDownloadPending(resourceName) {
@@ -49,64 +26,15 @@ gdjs.MockedResourceManager = class MockedResourceManager {
}
/**
* @param {string} resourceName
* @param {string} resourceName
*/
markPendingResourcesAsLoaded(resourceName) {
const loadResourceCallback = this.loadResourceCallbacks.get(resourceName);
if (loadResourceCallback) {
this.loadedResources.add(resourceName);
loadResourceCallback();
this.loadResourceCallbacks.delete(resourceName);
this.loadResourcePromises.delete(resourceName);
} else {
throw new Error(
`Resource ${resourceName} was not being loaded, so cannot be marked as loaded.`
);
}
loadResourceCallback();
this.loadResourceCallbacks.delete(resourceName);
}
/**
* Check if a resource is loaded (but maybe not yet processed)
*/
isResourceLoaded(resourceName) {
return this.loadedResources.has(resourceName);
}
/**
* Check if a resource has been disposed
*/
isResourceDisposed(resourceName) {
return this.disposedResources.has(resourceName);
}
/**
* Dispose all resources
*/
dispose() {
for (const resourceName of this.loadedResources) {
this.disposedResources.add(resourceName);
}
this.loadedResources.clear();
this.loadResourceCallbacks.clear();
this.loadResourcePromises.clear();
}
/**
* Dispose specific resources
*/
unloadResourcesList(resourcesList) {
for (const resource of resourcesList) {
this.disposedResources.add(resource.name);
this.loadedResources.delete(resource.name);
this.loadResourceCallbacks.delete(resource.name);
this.loadResourcePromises.delete(resource.name);
}
}
/**
* @returns {ResourceKind[]}
*/
getResourceKinds() {
return ['fake-resource-kind-for-testing-only'];
return ['fake-heavy-resource'];
}
}

View File

@@ -1,347 +0,0 @@
// @ts-check
/**
* Tests for gdjs.ResourceLoader.
*/
describe('gdjs.ResourceLoader', () => {
const delay = (ms) => new Promise((res) => setTimeout(res, ms));
/** @returns {LayoutData} */
const createSceneData = (name, usedResources) => {
return {
r: 0,
v: 0,
b: 0,
mangledName: name,
name,
objects: [],
layers: [],
instances: [],
behaviorsSharedData: [],
stopSoundsOnStartup: false,
title: '',
variables: [],
usedResources,
};
};
/** @type {{layouts?: LayoutData[], resources?: ResourcesData}} */
const gameSettingsWithThreeScenes = {
layouts: [
createSceneData('Scene1', [
{ name: 'scene1-resource1.png' },
{ name: 'scene1-resource2.png' },
]),
createSceneData('Scene2', [
{ name: 'scene2-resource1.png' },
{ name: 'shared-resource.png' },
]),
createSceneData('Scene3', [
{ name: 'scene3-resource1.png' },
{ name: 'shared-resource.png' },
]),
],
resources: {
resources: [
{
kind: 'fake-resource-kind-for-testing-only',
name: 'scene1-resource1.png',
metadata: '',
file: 'scene1-resource1.png',
userAdded: true,
},
{
kind: 'fake-resource-kind-for-testing-only',
name: 'scene1-resource2.png',
metadata: '',
file: 'scene1-resource2.png',
userAdded: true,
},
{
kind: 'fake-resource-kind-for-testing-only',
name: 'scene2-resource1.png',
metadata: '',
file: 'scene2-resource1.png',
userAdded: true,
},
{
kind: 'fake-resource-kind-for-testing-only',
name: 'scene3-resource1.png',
metadata: '',
file: 'scene3-resource1.png',
userAdded: true,
},
{
kind: 'fake-resource-kind-for-testing-only',
name: 'shared-resource.png',
metadata: '',
file: 'shared-resource.png',
userAdded: true,
},
],
},
};
it('should load first scene resources, then others in background', async () => {
const mockedResourceManager = new gdjs.MockedResourceManager();
const runtimeGame = gdjs.getPixiRuntimeGame(gameSettingsWithThreeScenes);
const resourceLoader = runtimeGame.getResourceLoader();
resourceLoader.injectMockResourceManagerForTesting(
'fake-resource-kind-for-testing-only',
mockedResourceManager
);
// Initially, no scene assets should be loaded
expect(resourceLoader.areSceneAssetsLoaded('Scene1')).to.be(false);
expect(resourceLoader.areSceneAssetsLoaded('Scene2')).to.be(false);
expect(resourceLoader.areSceneAssetsLoaded('Scene3')).to.be(false);
expect(resourceLoader.areSceneAssetsReady('Scene1')).to.be(false);
expect(resourceLoader.areSceneAssetsReady('Scene2')).to.be(false);
expect(resourceLoader.areSceneAssetsReady('Scene3')).to.be(false);
// Start loading first scene and background loading
runtimeGame.loadFirstAssetsAndStartBackgroundLoading('Scene1');
// Scene1 resources should be pending download
expect(
mockedResourceManager.isResourceDownloadPending('scene1-resource1.png')
).to.be(true);
expect(
mockedResourceManager.isResourceDownloadPending('scene1-resource2.png')
).to.be(true);
expect(resourceLoader.areSceneAssetsReady('Scene1')).to.be(false);
// Mark Scene1 resources as loaded
mockedResourceManager.markPendingResourcesAsLoaded('scene1-resource1.png');
mockedResourceManager.markPendingResourcesAsLoaded('scene1-resource2.png');
await delay(10);
// Scene1 should now be ready
expect(resourceLoader.areSceneAssetsLoaded('Scene1')).to.be(true);
expect(resourceLoader.areSceneAssetsReady('Scene1')).to.be(true);
// Background loading should have started for Scene2
await delay(20); // Wait for background loading to start
expect(
mockedResourceManager.isResourceDownloadPending('scene2-resource1.png')
).to.be(true);
expect(
mockedResourceManager.isResourceDownloadPending('shared-resource.png')
).to.be(true);
// Mark Scene2 resources as loaded
mockedResourceManager.markPendingResourcesAsLoaded('scene2-resource1.png');
mockedResourceManager.markPendingResourcesAsLoaded('shared-resource.png');
await delay(10);
// Scene2 should now be loaded
expect(resourceLoader.areSceneAssetsLoaded('Scene2')).to.be(true);
expect(resourceLoader.areSceneAssetsReady('Scene2')).to.be(false);
// Scene 2 resources can be processed so the scene is fully ready:
resourceLoader.loadAndProcessSceneResources('Scene2');
await delay(10);
expect(resourceLoader.areSceneAssetsLoaded('Scene2')).to.be(true);
expect(resourceLoader.areSceneAssetsReady('Scene2')).to.be(true);
// Scene 3 resources are not loaded nor processed yet:
expect(resourceLoader.areSceneAssetsLoaded('Scene3')).to.be(false);
expect(resourceLoader.areSceneAssetsReady('Scene3')).to.be(false);
// Background loading should have started for Scene3
await delay(20); // Wait for background loading to start
expect(
mockedResourceManager.isResourceDownloadPending('scene3-resource1.png')
).to.be(true);
expect(
mockedResourceManager.isResourceDownloadPending('shared-resource.png')
// shared-resource.png should already be loaded, so not pending:
).to.be(false);
// Mark Scene3 resources as loaded
mockedResourceManager.markPendingResourcesAsLoaded('scene3-resource1.png');
await delay(10);
// Scene3 should now be loaded
expect(resourceLoader.areSceneAssetsLoaded('Scene3')).to.be(true);
expect(resourceLoader.areSceneAssetsReady('Scene3')).to.be(false);
// Scene3 resources can be processed so the scene is fully ready:
resourceLoader.loadAndProcessSceneResources('Scene3');
await delay(10);
expect(resourceLoader.areSceneAssetsLoaded('Scene3')).to.be(true);
expect(resourceLoader.areSceneAssetsReady('Scene3')).to.be(true);
});
it('should unload only resources unique to the unloaded scene', async () => {
const mockedResourceManager = new gdjs.MockedResourceManager();
const runtimeGame = gdjs.getPixiRuntimeGame(gameSettingsWithThreeScenes);
const resourceLoader = runtimeGame.getResourceLoader();
resourceLoader.injectMockResourceManagerForTesting(
'fake-resource-kind-for-testing-only',
mockedResourceManager
);
// Load all resources for all scenes
resourceLoader.loadGlobalAndFirstSceneResources('Scene1', () => {});
mockedResourceManager.markPendingResourcesAsLoaded('scene1-resource1.png');
mockedResourceManager.markPendingResourcesAsLoaded('scene1-resource2.png');
resourceLoader.loadAndProcessSceneResources('Scene2');
mockedResourceManager.markPendingResourcesAsLoaded('scene2-resource1.png');
mockedResourceManager.markPendingResourcesAsLoaded('shared-resource.png');
await delay(10);
resourceLoader.loadAndProcessSceneResources('Scene3');
mockedResourceManager.markPendingResourcesAsLoaded('scene3-resource1.png');
await delay(10);
// Verify all resources are loaded
expect(resourceLoader.areSceneAssetsReady('Scene1')).to.be(true);
expect(resourceLoader.areSceneAssetsReady('Scene2')).to.be(true);
expect(resourceLoader.areSceneAssetsReady('Scene3')).to.be(true);
// Verify no resources are disposed initially
expect(
mockedResourceManager.isResourceDisposed('scene1-resource1.png')
).to.be(false);
expect(
mockedResourceManager.isResourceDisposed('scene1-resource2.png')
).to.be(false);
expect(
mockedResourceManager.isResourceDisposed('scene2-resource1.png')
).to.be(false);
expect(
mockedResourceManager.isResourceDisposed('scene3-resource1.png')
).to.be(false);
expect(
mockedResourceManager.isResourceDisposed('shared-resource.png')
).to.be(false);
// Simulate Scene2 and Scene3 being loaded/active by marking Scene1 as unloaded
// while Scene2 will be the new scene
resourceLoader.unloadSceneResources({
unloadedSceneName: 'Scene1',
newSceneName: 'Scene2',
});
// Only Scene1-specific resources should be disposed
// shared-resource.png should NOT be disposed because it's used in Scene2 and Scene3
expect(
mockedResourceManager.isResourceDisposed('scene1-resource1.png')
).to.be(true);
expect(
mockedResourceManager.isResourceDisposed('scene1-resource2.png')
).to.be(true);
expect(
mockedResourceManager.isResourceDisposed('scene2-resource1.png')
).to.be(false);
expect(
mockedResourceManager.isResourceDisposed('scene3-resource1.png')
).to.be(false);
expect(
mockedResourceManager.isResourceDisposed('shared-resource.png')
).to.be(false);
// Scene1 should be marked as not loaded
expect(resourceLoader.areSceneAssetsLoaded('Scene1')).to.be(false);
expect(resourceLoader.areSceneAssetsReady('Scene1')).to.be(false);
// Other scenes should still be loaded
expect(resourceLoader.areSceneAssetsLoaded('Scene2')).to.be(true);
expect(resourceLoader.areSceneAssetsReady('Scene2')).to.be(true);
expect(resourceLoader.areSceneAssetsLoaded('Scene3')).to.be(true);
expect(resourceLoader.areSceneAssetsReady('Scene3')).to.be(true);
});
it('should unload shared resources only when no other scene uses them', async () => {
const mockedResourceManager = new gdjs.MockedResourceManager();
const runtimeGame = gdjs.getPixiRuntimeGame(gameSettingsWithThreeScenes);
const resourceLoader = runtimeGame.getResourceLoader();
resourceLoader.injectMockResourceManagerForTesting(
'fake-resource-kind-for-testing-only',
mockedResourceManager
);
// Load all resources for all scenes
resourceLoader.loadAllResources(() => {});
await delay(10);
// First, unload Scene2 (which shares resources with Scene3)
resourceLoader.unloadSceneResources({
unloadedSceneName: 'Scene2',
newSceneName: 'Scene3',
});
// Only Scene2-specific resources should be disposed
// shared-resource.png should NOT be disposed because it's still used in Scene3
expect(
mockedResourceManager.isResourceDisposed('scene2-resource1.png')
).to.be(true);
expect(
mockedResourceManager.isResourceDisposed('shared-resource.png')
).to.be(false);
// Now unload Scene3 (which also uses shared-resource.png)
resourceLoader.unloadSceneResources({
unloadedSceneName: 'Scene3',
newSceneName: 'Scene1',
});
// Now shared-resource.png should be disposed because no loaded scene uses it
expect(
mockedResourceManager.isResourceDisposed('scene3-resource1.png')
).to.be(true);
expect(
mockedResourceManager.isResourceDisposed('shared-resource.png')
).to.be(true);
// Scene1 resources should still be loaded
expect(
mockedResourceManager.isResourceDisposed('scene1-resource1.png')
).to.be(false);
expect(
mockedResourceManager.isResourceDisposed('scene1-resource2.png')
).to.be(false);
});
it('should handle background scene loading progress correctly', async () => {
const mockedResourceManager = new gdjs.MockedResourceManager();
const runtimeGame = gdjs.getPixiRuntimeGame(gameSettingsWithThreeScenes);
const resourceLoader = runtimeGame.getResourceLoader();
resourceLoader.injectMockResourceManagerForTesting(
'fake-resource-kind-for-testing-only',
mockedResourceManager
);
// Initially progress should be 0
expect(resourceLoader.getSceneLoadingProgress('Scene1')).to.be(0);
expect(resourceLoader.getSceneLoadingProgress('Scene2')).to.be(0);
// Start loading first scene
runtimeGame.loadFirstAssetsAndStartBackgroundLoading('Scene1');
mockedResourceManager.markPendingResourcesAsLoaded('scene1-resource1.png');
mockedResourceManager.markPendingResourcesAsLoaded('scene1-resource2.png');
await delay(10);
// Progress should still be 0 until resources start loading
expect(resourceLoader.getSceneLoadingProgress('Scene2')).to.be(0);
// Mark first resource as loaded
mockedResourceManager.markPendingResourcesAsLoaded('scene2-resource1.png');
await delay(10);
// Progress should be partial (1 out of 2 resources)
console.log(resourceLoader.getSceneLoadingProgress('Scene2'));
expect(resourceLoader.getSceneLoadingProgress('Scene2')).to.be(0.5);
// Mark second resource as loaded
mockedResourceManager.markPendingResourcesAsLoaded('shared-resource.png');
await delay(10);
// Progress should be complete (1.0)
expect(resourceLoader.getSceneLoadingProgress('Scene2')).to.be(1);
});
});

View File

@@ -100,7 +100,6 @@ describe('gdjs.HotReloader._hotReloadRuntimeGame', () => {
effects: [],
content: {},
childrenContent: {},
isInnerAreaFollowingParentSize: false,
};
/** @type {LayerData} */

View File

@@ -6,7 +6,7 @@
describe('gdjs.SceneStack', () => {
const delay = (ms) => new Promise((res) => setTimeout(res, ms));
const createSceneData = (name, usedResources) => {
const createSene = (name, usedResources) => {
return {
r: 0,
v: 0,
@@ -24,13 +24,10 @@ describe('gdjs.SceneStack', () => {
};
};
/** @type {{layouts?: LayoutData[], resources?: ResourcesData}} */
const gameSettings = {
layouts: [
createSceneData('Scene 1', []),
createSceneData('Scene 2', [
{ name: 'base/tests-utils/assets/64x64.jpg' },
]),
createSene('Scene 1', []),
createSene('Scene 2', [{ name: 'base/tests-utils/assets/64x64.jpg' }]),
],
resources: {
resources: [
@@ -46,11 +43,11 @@ describe('gdjs.SceneStack', () => {
};
it('should support pushing, replacing and popping scenes', async () => {
//@ts-ignore
const runtimeGame = gdjs.getPixiRuntimeGame(gameSettings);
let sceneStack = runtimeGame._sceneStack;
// Async asset loading is not tested here.
const resourcesLoader = runtimeGame.getResourceLoader();
await resourcesLoader.loadAllResources(() => {});
await runtimeGame._resourcesLoader.loadAllResources(() => {});
// Set up some scene callbacks.
/** @type gdjs.RuntimeScene | null */
@@ -149,39 +146,38 @@ describe('gdjs.SceneStack', () => {
gdjs._unregisterCallback(onRuntimeSceneResumed);
});
/** @type {{layouts?: LayoutData[], resources?: ResourcesData}} */
const gameSettingsWithHeavyResource = {
layouts: [
createSceneData('Scene 1', [{ name: 'fake-heavy-resource1.png' }]),
createSceneData('Scene 2', [{ name: 'fake-heavy-resource2.png' }]),
createSceneData('Scene 3', [{ name: 'fake-heavy-resource3.png' }]),
createSceneData('Scene 4', [{ name: 'fake-heavy-resource4.png' }]),
createSene('Scene 1', [{ name: 'fake-heavy-resource1.png' }]),
createSene('Scene 2', [{ name: 'fake-heavy-resource2.png' }]),
createSene('Scene 3', [{ name: 'fake-heavy-resource3.png' }]),
createSene('Scene 4', [{ name: 'fake-heavy-resource4.png' }]),
],
resources: {
resources: [
{
kind: 'fake-resource-kind-for-testing-only',
kind: 'fake-heavy-resource',
name: 'fake-heavy-resource1.png',
metadata: '',
file: 'fake-heavy-resource1.png',
userAdded: true,
},
{
kind: 'fake-resource-kind-for-testing-only',
kind: 'fake-heavy-resource',
name: 'fake-heavy-resource2.png',
metadata: '',
file: 'fake-heavy-resource2.png',
userAdded: true,
},
{
kind: 'fake-resource-kind-for-testing-only',
kind: 'fake-heavy-resource',
name: 'fake-heavy-resource3.png',
metadata: '',
file: 'fake-heavy-resource3.png',
userAdded: true,
},
{
kind: 'fake-resource-kind-for-testing-only',
kind: 'fake-heavy-resource',
name: 'fake-heavy-resource4.png',
metadata: '',
file: 'fake-heavy-resource4.png',
@@ -193,11 +189,11 @@ describe('gdjs.SceneStack', () => {
it('can start a layout when all its assets are already downloaded', async () => {
const mockedResourceManager = new gdjs.MockedResourceManager();
//@ts-ignore
const runtimeGame = gdjs.getPixiRuntimeGame(gameSettingsWithHeavyResource);
const resourcesLoader = runtimeGame.getResourceLoader();
resourcesLoader.injectMockResourceManagerForTesting(
'fake-resource-kind-for-testing-only',
runtimeGame._resourcesLoader._resourceManagersMap.set(
//@ts-ignore
'fake-heavy-resource',
mockedResourceManager
);
let sceneStack = runtimeGame._sceneStack;
@@ -303,11 +299,11 @@ describe('gdjs.SceneStack', () => {
it('can start a layout while assets loading and wait them to finish', async () => {
const mockedResourceManager = new gdjs.MockedResourceManager();
//@ts-ignore
const runtimeGame = gdjs.getPixiRuntimeGame(gameSettingsWithHeavyResource);
const resourcesLoader = runtimeGame.getResourceLoader();
resourcesLoader.injectMockResourceManagerForTesting(
'fake-resource-kind-for-testing-only',
runtimeGame._resourcesLoader._resourceManagersMap.set(
//@ts-ignore
'fake-heavy-resource',
mockedResourceManager
);
let sceneStack = runtimeGame._sceneStack;
@@ -408,10 +404,11 @@ describe('gdjs.SceneStack', () => {
it("can start a layout which assets loading didn't stated yet and wait them to finish", async () => {
const mockedResourceManager = new gdjs.MockedResourceManager();
//@ts-ignore
const runtimeGame = gdjs.getPixiRuntimeGame(gameSettingsWithHeavyResource);
const resourcesLoader = runtimeGame.getResourceLoader();
resourcesLoader.injectMockResourceManagerForTesting(
'fake-resource-kind-for-testing-only',
runtimeGame._resourcesLoader._resourceManagersMap.set(
//@ts-ignore
'fake-heavy-resource',
mockedResourceManager
);
let sceneStack = runtimeGame._sceneStack;

View File

@@ -666,11 +666,6 @@ interface Project {
[Ref] ObjectsContainer GetObjects();
[Ref] ResourcesManager GetResourcesManager();
void SetSceneResourcesPreloading([Const] DOMString resourcesPreloading);
[Const, Ref] DOMString GetSceneResourcesPreloading();
void SetSceneResourcesUnloading([Const] DOMString resourcesUnloading);
[Const, Ref] DOMString GetSceneResourcesUnloading();
void SerializeTo([Ref] SerializerElement element);
void UnserializeFrom([Const, Ref] SerializerElement element);
@@ -1007,11 +1002,6 @@ interface Layout {
void SetStopSoundsOnStartup(boolean enable);
boolean StopSoundsOnStartup();
void SetResourcesPreloading([Const] DOMString resourcesPreloading);
[Const, Ref] DOMString GetResourcesPreloading();
void SetResourcesUnloading([Const] DOMString resourcesUnloading);
[Const, Ref] DOMString GetResourcesUnloading();
};
interface ExternalEvents {
@@ -1059,13 +1049,10 @@ interface Effect {
void SetDoubleParameter([Const] DOMString name, double value);
double GetDoubleParameter([Const] DOMString name);
boolean HasDoubleParameter([Const] DOMString name);
void SetStringParameter([Const] DOMString name, [Const] DOMString value);
[Const, Ref] DOMString GetStringParameter([Const] DOMString name);
boolean HasStringParameter([Const] DOMString name);
void SetBooleanParameter([Const] DOMString name, boolean value);
boolean GetBooleanParameter([Const] DOMString name);
boolean HasBooleanParameter([Const] DOMString name);
[Const, Ref] MapStringDouble GetAllDoubleParameters();
[Const, Ref] MapStringString GetAllStringParameters();
[Const, Ref] MapStringBoolean GetAllBooleanParameters();
@@ -1149,17 +1136,6 @@ interface LayersContainer {
void UnserializeLayersFrom([Const, Ref] SerializerElement element);
};
interface PropertyDescriptorChoice {
void PropertyDescriptorChoice([Const] DOMString value, [Const] DOMString label);
[Const, Ref] DOMString GetValue();
[Const, Ref] DOMString GetLabel();
};
interface VectorPropertyDescriptorChoice {
unsigned long size();
[Const, Ref] PropertyDescriptorChoice at(unsigned long index);
};
interface PropertyDescriptor {
void PropertyDescriptor([Const] DOMString propValue);
@@ -1173,8 +1149,6 @@ interface PropertyDescriptor {
[Const, Ref] DOMString GetDescription();
[Ref] PropertyDescriptor SetGroup([Const] DOMString label);
[Const, Ref] DOMString GetGroup();
[Ref] PropertyDescriptor AddChoice([Const] DOMString value, [Const] DOMString label);
[Const, Ref] VectorPropertyDescriptorChoice GetChoices();
[Ref] PropertyDescriptor AddExtraInfo([Const] DOMString type);
[Ref] PropertyDescriptor SetExtraInfo([Const, Ref] VectorString info);
[Ref] VectorString GetExtraInfo();

View File

@@ -481,7 +481,6 @@ typedef ExtensionAndMetadata<ExpressionMetadata> ExtensionAndExpressionMetadata;
typedef ExtensionAndMetadata<ExpressionMetadata> ExtensionAndExpressionMetadata;
typedef ExtensionAndMetadata<ExpressionMetadata> ExtensionAndExpressionMetadata;
typedef ExtensionAndMetadata<ExpressionMetadata> ExtensionAndExpressionMetadata;
typedef std::vector<gd::PropertyDescriptorChoice> VectorPropertyDescriptorChoice;
// Customize some functions implementation thanks to WRAPPED_* macros
// The original names will be reconstructed in the js file (see postjs.js)

View File

@@ -475,7 +475,7 @@ class RuntimeObject {
}
/** @param {RuntimeScene} runtimeScene */
onDeletedFromScene(runtimeScene) {
onDestroyFromScene(runtimeScene) {
// Note: these mocks don't support behaviors nor layers or effects.
this.destroyCallbacks.forEach((c) => c());
@@ -789,7 +789,7 @@ class RuntimeScene {
}
//Notify the object it was removed from the scene
obj.onDeletedFromScene(this);
obj.onDestroyFromScene(this);
}
getObjects(objectName) {

View File

@@ -619,10 +619,6 @@ export class Project extends EmscriptenObject {
getVariables(): VariablesContainer;
getObjects(): ObjectsContainer;
getResourcesManager(): ResourcesManager;
setSceneResourcesPreloading(resourcesPreloading: string): void;
getSceneResourcesPreloading(): string;
setSceneResourcesUnloading(resourcesUnloading: string): void;
getSceneResourcesUnloading(): string;
serializeTo(element: SerializerElement): void;
unserializeFrom(element: SerializerElement): void;
getWholeProjectDiagnosticReport(): WholeProjectDiagnosticReport;
@@ -827,10 +823,6 @@ export class Layout extends EmscriptenObject {
unserializeFrom(project: Project, element: SerializerElement): void;
setStopSoundsOnStartup(enable: boolean): void;
stopSoundsOnStartup(): boolean;
setResourcesPreloading(resourcesPreloading: string): void;
getResourcesPreloading(): string;
setResourcesUnloading(resourcesUnloading: string): void;
getResourcesUnloading(): string;
}
export class ExternalEvents extends EmscriptenObject {
@@ -866,13 +858,10 @@ export class Effect extends EmscriptenObject {
isFolded(): boolean;
setDoubleParameter(name: string, value: number): void;
getDoubleParameter(name: string): number;
hasDoubleParameter(name: string): boolean;
setStringParameter(name: string, value: string): void;
getStringParameter(name: string): string;
hasStringParameter(name: string): boolean;
setBooleanParameter(name: string, value: boolean): void;
getBooleanParameter(name: string): boolean;
hasBooleanParameter(name: string): boolean;
getAllDoubleParameters(): MapStringDouble;
getAllStringParameters(): MapStringString;
getAllBooleanParameters(): MapStringBoolean;
@@ -947,17 +936,6 @@ export class LayersContainer extends EmscriptenObject {
unserializeLayersFrom(element: SerializerElement): void;
}
export class PropertyDescriptorChoice extends EmscriptenObject {
constructor(value: string, label: string);
getValue(): string;
getLabel(): string;
}
export class VectorPropertyDescriptorChoice extends EmscriptenObject {
size(): number;
at(index: number): PropertyDescriptorChoice;
}
export class PropertyDescriptor extends EmscriptenObject {
constructor(propValue: string);
setValue(value: string): PropertyDescriptor;
@@ -970,8 +948,6 @@ export class PropertyDescriptor extends EmscriptenObject {
getDescription(): string;
setGroup(label: string): PropertyDescriptor;
getGroup(): string;
addChoice(value: string, label: string): PropertyDescriptor;
getChoices(): VectorPropertyDescriptorChoice;
addExtraInfo(type: string): PropertyDescriptor;
setExtraInfo(info: VectorString): PropertyDescriptor;
getExtraInfo(): VectorString;

View File

@@ -9,13 +9,10 @@ declare class gdEffect {
isFolded(): boolean;
setDoubleParameter(name: string, value: number): void;
getDoubleParameter(name: string): number;
hasDoubleParameter(name: string): boolean;
setStringParameter(name: string, value: string): void;
getStringParameter(name: string): string;
hasStringParameter(name: string): boolean;
setBooleanParameter(name: string, value: boolean): void;
getBooleanParameter(name: string): boolean;
hasBooleanParameter(name: string): boolean;
getAllDoubleParameters(): gdMapStringDouble;
getAllStringParameters(): gdMapStringString;
getAllBooleanParameters(): gdMapStringBoolean;

View File

@@ -32,10 +32,6 @@ declare class gdLayout {
unserializeFrom(project: gdProject, element: gdSerializerElement): void;
setStopSoundsOnStartup(enable: boolean): void;
stopSoundsOnStartup(): boolean;
setResourcesPreloading(resourcesPreloading: string): void;
getResourcesPreloading(): string;
setResourcesUnloading(resourcesUnloading: string): void;
getResourcesUnloading(): string;
delete(): void;
ptr: number;
};

View File

@@ -107,10 +107,6 @@ declare class gdProject {
getVariables(): gdVariablesContainer;
getObjects(): gdObjectsContainer;
getResourcesManager(): gdResourcesManager;
setSceneResourcesPreloading(resourcesPreloading: string): void;
getSceneResourcesPreloading(): string;
setSceneResourcesUnloading(resourcesUnloading: string): void;
getSceneResourcesUnloading(): string;
serializeTo(element: gdSerializerElement): void;
unserializeFrom(element: gdSerializerElement): void;
getWholeProjectDiagnosticReport(): gdWholeProjectDiagnosticReport;

View File

@@ -11,8 +11,6 @@ declare class gdPropertyDescriptor {
getDescription(): string;
setGroup(label: string): gdPropertyDescriptor;
getGroup(): string;
addChoice(value: string, label: string): gdPropertyDescriptor;
getChoices(): gdVectorPropertyDescriptorChoice;
addExtraInfo(type: string): gdPropertyDescriptor;
setExtraInfo(info: gdVectorString): gdPropertyDescriptor;
getExtraInfo(): gdVectorString;

View File

@@ -1,8 +0,0 @@
// Automatically generated by GDevelop.js/scripts/generate-types.js
declare class gdPropertyDescriptorChoice {
constructor(value: string, label: string): void;
getValue(): string;
getLabel(): string;
delete(): void;
ptr: number;
};

View File

@@ -1,7 +0,0 @@
// Automatically generated by GDevelop.js/scripts/generate-types.js
declare class gdVectorPropertyDescriptorChoice {
size(): number;
at(index: number): gdPropertyDescriptorChoice;
delete(): void;
ptr: number;
};

View File

@@ -105,8 +105,6 @@ declare class libGDevelop {
EffectsContainer: Class<gdEffectsContainer>;
Layer: Class<gdLayer>;
LayersContainer: Class<gdLayersContainer>;
PropertyDescriptorChoice: Class<gdPropertyDescriptorChoice>;
VectorPropertyDescriptorChoice: Class<gdVectorPropertyDescriptorChoice>;
PropertyDescriptor: Class<gdPropertyDescriptor>;
MeasurementUnit: Class<gdMeasurementUnit>;
MeasurementBaseUnit: Class<gdMeasurementBaseUnit>;

View File

@@ -1,3 +1,2 @@
# Prettier has troubles handling the generic typing with flow in this file.
src/Utils/UseOptimisticState.js
src/Utils/Sha256.js
src/Utils/UseOptimisticState.js

View File

@@ -441,17 +441,6 @@
}
},
"rst": {
"ai-generated-event-move-handle": {
"gradient-color-1": {
"value": "#9932cc"
},
"gradient-color-2": {
"value": "#fa7ff1"
},
"gradient-color-3": {
"value": "#9932cc"
}
},
"move-handle": {
"background-color": {
"value": "#494949"

View File

@@ -30,21 +30,6 @@
justify-content: center;
animation: new-chat-appear 0.5s;
margin-bottom: var(--safe-area-inset-bottom);
}
.aiRequestChatContainer {
display: flex;
margin-left: 8px;
margin-right: 8px;
flex-direction: column;
align-items: stretch;
justify-content: stretch;
flex: 1 1 0%;
min-height: 0px;
margin-bottom: var(--safe-area-inset-bottom);
}
.thinkingText {

View File

@@ -11,7 +11,7 @@ import { Tooltip } from '@material-ui/core';
import Text from '../../UI/Text';
import RaisedButton from '../../UI/RaisedButton';
import { Trans } from '@lingui/macro';
import FlatButtonWithSplitMenu from '../../UI/FlatButtonWithSplitMenu';
import RaisedButtonWithSplitMenu from '../../UI/RaisedButtonWithSplitMenu';
import Check from '../../UI/CustomSvgIcons/Check';
import Error from '../../UI/CustomSvgIcons/Error';
import GDevelopThemeContext from '../../UI/Theme/GDevelopThemeContext';
@@ -22,7 +22,7 @@ import {
type EditorCallbacks,
} from '../../EditorFunctions';
import Link from '../../UI/Link';
import { LineStackLayout, ResponsiveLineStackLayout } from '../../UI/Layout';
import { LineStackLayout } from '../../UI/Layout';
import ChevronArrowRight from '../../UI/CustomSvgIcons/ChevronArrowRight';
import ChevronArrowBottom from '../../UI/CustomSvgIcons/ChevronArrowBottom';
import Paper from '../../UI/Paper';
@@ -142,73 +142,60 @@ export const FunctionCallRow = React.memo<Props>(function FunctionCallRow({
)}
</div>
</Tooltip>
<ResponsiveLineStackLayout
justifyContent="space-between"
expand
noOverflowParent
>
<LineStackLayout noMargin alignItems="baseline">
<Text>{text || 'Working...'}</Text>
{hasDetailsToShow && (
<Text size="body-small" color="secondary">
<Link
color="inherit"
href={'#'}
onClick={() => setShowDetails(!showDetails)}
>
<Trans>Details</Trans>
{details ? (
<ChevronArrowBottom
fontSize="small"
style={{
verticalAlign: 'middle',
}}
/>
) : (
<ChevronArrowRight
fontSize="small"
style={{
verticalAlign: 'middle',
}}
/>
)}
</Link>
</Text>
)}
</LineStackLayout>
<LineStackLayout
noMargin
alignItems="baseline"
justifyContent="flex-end"
neverShrink
>
{!isFinished && !isWorking && (
<FlatButtonWithSplitMenu
primary
style={{ flexShrink: 0 }}
onClick={() => onProcessFunctionCalls([functionCall])}
label={<Trans>Execute this action</Trans>}
buildMenuTemplate={i18n => [
{
label: i18n._(t`Ignore this`),
click: () => {
onProcessFunctionCalls([functionCall], {
ignore: true,
});
},
},
]}
/>
)}
{functionCallResultIsErrored && (
<RaisedButton
color="primary"
onClick={() => onProcessFunctionCalls([functionCall])}
label={<Trans>Retry</Trans>}
/>
)}
</LineStackLayout>
</ResponsiveLineStackLayout>
<LineStackLayout noMargin alignItems="baseline">
<Text>{text || 'Working...'}</Text>
{hasDetailsToShow && (
<Text size="body-small" color="secondary">
<Link
color="inherit"
href={'#'}
onClick={() => setShowDetails(!showDetails)}
>
<Trans>Details</Trans>
{details ? (
<ChevronArrowBottom
fontSize="small"
style={{
verticalAlign: 'middle',
}}
/>
) : (
<ChevronArrowRight
fontSize="small"
style={{
verticalAlign: 'middle',
}}
/>
)}
</Link>
</Text>
)}
</LineStackLayout>
{!isFinished && (
<RaisedButtonWithSplitMenu
primary
disabled={isWorking}
onClick={() => onProcessFunctionCalls([functionCall])}
label={<Trans>Apply</Trans>}
buildMenuTemplate={i18n => [
{
label: i18n._(t`Ignore this`),
click: () => {
onProcessFunctionCalls([functionCall], {
ignore: true,
});
},
},
]}
/>
)}
{functionCallResultIsErrored && (
<RaisedButton
color="primary"
onClick={() => onProcessFunctionCalls([functionCall])}
label={<Trans>Retry</Trans>}
/>
)}
</LineStackLayout>
{details && (
<div className={classes.detailsPaperContainer}>

View File

@@ -37,7 +37,7 @@ import Hammer from '../../UI/CustomSvgIcons/Hammer';
import { ChatMessages } from './ChatMessages';
import Send from '../../UI/CustomSvgIcons/Send';
import { FeedbackBanner } from './FeedbackBanner';
import classNames from 'classnames';
import LeftLoader from '../../UI/LeftLoader';
const TOO_MANY_USER_MESSAGES_WARNING_COUNT = 5;
const TOO_MANY_USER_MESSAGES_ERROR_COUNT = 10;
@@ -136,26 +136,12 @@ const getQuotaOrCreditsText = ({
>
<div>
{isMobile ? (
increaseQuotaOffering === 'subscribe' ? (
<Trans>{quota.max - quota.current} trial requests left</Trans>
) : (
<Trans>{quota.max - quota.current} free requests left</Trans>
)
) : quota.period === '30days' ? (
increaseQuotaOffering === 'subscribe' ? (
<Trans>
{quota.max - quota.current} free trial requests left this month
</Trans>
) : (
<Trans>
{quota.max - quota.current} of {quota.max} free requests left this
month
</Trans>
)
) : quota.period === '1day' ? (
<Trans>{quota.max - quota.current} free requests left today</Trans>
) : (
<Trans>{quota.max - quota.current} free requests left</Trans>
) : (
<Trans>
{quota.max - quota.current} of {quota.max} free requests left this
month
</Trans>
)}
</div>
</Tooltip>
@@ -345,7 +331,6 @@ export const AiRequestChat = React.forwardRef<Props, AiRequestChatInterface>(
const subscriptionBanner =
quota && quota.limitReached && increaseQuotaOffering !== 'none' ? (
<GetSubscriptionCard
placementId="ai-requests"
subscriptionDialogOpeningReason={
increaseQuotaOffering === 'subscribe'
? 'AI requests (subscribe)'
@@ -402,13 +387,7 @@ export const AiRequestChat = React.forwardRef<Props, AiRequestChatInterface>(
if (!aiRequest) {
return (
<div
className={classNames({
[classes.newChatContainer]: true,
// Move the entire screen up when the soft keyboard is open:
'avoid-soft-keyboard': true,
})}
>
<div className={classes.newChatContainer}>
<ColumnStackLayout justifyContent="center" expand>
<Line noMargin justifyContent="center">
<RobotIcon rotating size={40} />
@@ -458,8 +437,6 @@ export const AiRequestChat = React.forwardRef<Props, AiRequestChatInterface>(
maxLength={6000}
value={userRequestTextPerAiRequestId[''] || ''}
disabled={isSending}
hasNeonCorner
hasAnimatedNeonCorner={isSending}
errored={!!lastSendError}
onChange={userRequestText =>
setUserRequestTextPerRequestId(
@@ -483,32 +460,35 @@ export const AiRequestChat = React.forwardRef<Props, AiRequestChatInterface>(
alignItems="center"
justifyContent="flex-end"
>
<RaisedButton
color="primary"
icon={<Send />}
label={
newAiRequestMode === 'agent' ? (
hasOpenedProject ? (
<Trans>Build this on my game</Trans>
<LeftLoader isLoading={isSending}>
<RaisedButton
color="primary"
icon={<Send />}
label={
newAiRequestMode === 'agent' ? (
hasOpenedProject ? (
<Trans>Build this on my game</Trans>
) : (
<Trans>Start building the game</Trans>
)
) : (
<Trans>Start building the game</Trans>
<Trans>Send question</Trans>
)
) : (
<Trans>Send question</Trans>
)
}
style={{ flexShrink: 0 }}
disabled={
isSending ||
!userRequestTextPerAiRequestId[aiRequestId]
}
onClick={() => {
onStartNewAiRequest({
mode: newAiRequestMode,
userRequest: userRequestTextPerAiRequestId[''],
});
}}
/>
}
style={{ flexShrink: 0 }}
disabled={
isSending ||
!userRequestTextPerAiRequestId[aiRequestId]
}
onClick={() => {
onStartNewAiRequest({
mode: newAiRequestMode,
userRequest:
userRequestTextPerAiRequestId[''],
});
}}
/>
</LeftLoader>
</LineStackLayout>
</Column>
}
@@ -595,14 +575,11 @@ export const AiRequestChat = React.forwardRef<Props, AiRequestChatInterface>(
aiRequest,
editorFunctionCallResults,
});
const isPausedAndHasFunctionCallsToProcess =
!isAutoProcessingFunctionCalls && allFunctionCallsToProcess.length > 0;
const lastMessageIndex = aiRequest.output.length - 1;
const lastMessage = aiRequest.output[lastMessageIndex];
const shouldDisplayFeedbackBanner =
!hasWorkingFunctionCalls &&
!isPausedAndHasFunctionCallsToProcess &&
!isSending &&
aiRequest.status === 'ready' &&
aiRequest.mode === 'agent' &&
@@ -642,10 +619,11 @@ export const AiRequestChat = React.forwardRef<Props, AiRequestChatInterface>(
) : null;
return (
<div
className={classNames({
[classes.aiRequestChatContainer]: true,
})}
<Column
expand
alignItems="stretch"
justifyContent="stretch"
useFullHeight
>
<ScrollView ref={scrollViewRef} style={styles.chatScrollView}>
<ChatMessages
@@ -684,10 +662,6 @@ export const AiRequestChat = React.forwardRef<Props, AiRequestChatInterface>(
userMessage: userRequestTextPerAiRequestId[aiRequestId] || '',
});
}}
className={classNames({
// Move the form up when the soft keyboard is open:
'avoid-soft-keyboard': true,
})}
>
<ColumnStackLayout
justifyContent="stretch"
@@ -699,14 +673,14 @@ export const AiRequestChat = React.forwardRef<Props, AiRequestChatInterface>(
(hasWorkingFunctionCalls ||
isSending ||
aiRequest.status === 'working') ? (
<Paper background="dark" variant="outlined">
<Paper background="dark" variant="outlined" square>
<Column>
<LineStackLayout
justifyContent="space-between"
alignItems="center"
>
<LineStackLayout alignItems="center" noMargin>
<CircularProgress variant="indeterminate" size={12} />
<CircularProgress variant="indeterminate" size={10} />
<Text size="body" color="secondary" noMargin>
<Trans>The AI is building your request.</Trans>
</Text>
@@ -726,8 +700,9 @@ export const AiRequestChat = React.forwardRef<Props, AiRequestChatInterface>(
</Column>
</Paper>
) : aiRequest.mode === 'agent' &&
isPausedAndHasFunctionCallsToProcess ? (
<Paper background="dark" variant="outlined">
!isAutoProcessingFunctionCalls &&
allFunctionCallsToProcess.length > 0 ? (
<Paper background="dark" variant="outlined" square>
<Column>
<LineStackLayout
justifyContent="space-between"
@@ -747,7 +722,9 @@ export const AiRequestChat = React.forwardRef<Props, AiRequestChatInterface>(
onProcessFunctionCalls(allFunctionCallsToProcess);
}}
>
<Trans>Resume all</Trans>
<Trans>
Apply everything and continue autonomously
</Trans>
</Link>
</Text>
</LineStackLayout>
@@ -759,8 +736,6 @@ export const AiRequestChat = React.forwardRef<Props, AiRequestChatInterface>(
value={userRequestTextPerAiRequestId[aiRequestId] || ''}
disabled={isSending || isForAnotherProject}
errored={!!lastSendError}
hasNeonCorner
hasAnimatedNeonCorner={isSending}
onChange={userRequestText =>
setUserRequestTextPerRequestId(
userRequestTextPerAiRequestId => ({
@@ -823,7 +798,7 @@ export const AiRequestChat = React.forwardRef<Props, AiRequestChatInterface>(
</Column>
</ColumnStackLayout>
</form>
</div>
</Column>
);
}
);

View File

@@ -2,10 +2,7 @@
import * as React from 'react';
import { type I18n as I18nType } from '@lingui/core';
import { I18n } from '@lingui/react';
import {
type RenderEditorContainerPropsWithRef,
type SceneEventsOutsideEditorChanges,
} from '../MainFrame/EditorContainers/BaseEditor';
import { type RenderEditorContainerPropsWithRef } from '../MainFrame/EditorContainers/BaseEditor';
import { type ObjectWithContext } from '../ObjectsList/EnumerateObjects';
import Paper from '../UI/Paper';
import { AiRequestChat, type AiRequestChatInterface } from './AiRequestChat';
@@ -51,7 +48,6 @@ import {
} from '../Utils/Analytics/EventSender';
import { useCreateAiProjectDialog } from './UseCreateAiProjectDialog';
import { type ExampleShortHeader } from '../Utils/GDevelopServices/Example';
import { prepareAiUserContent } from './PrepareAiUserContent';
const gd: libGDevelop = global.gd;
@@ -135,9 +131,7 @@ const useProcessFunctionCalls = ({
string,
Array<EditorFunctionCallResult>
) => void,
onSceneEventsModifiedOutsideEditor: (
changes: SceneEventsOutsideEditorChanges
) => void,
onSceneEventsModifiedOutsideEditor: (scene: gdLayout) => void,
onExtensionInstalled: (extensionNames: Array<string>) => void,
|}) => {
const { ensureExtensionInstalled } = useEnsureExtensionInstalled({
@@ -479,9 +473,7 @@ type Props = {|
| 'none',
|}
) => void,
onSceneEventsModifiedOutsideEditor: (
changes: SceneEventsOutsideEditorChanges
) => void,
onSceneEventsModifiedOutsideEditor: (scene: gdLayout) => void,
onExtensionInstalled: (extensionNames: Array<string>) => void,
|};
@@ -495,9 +487,7 @@ export type AskAiEditorInterface = {|
objectWithContext: ObjectWithContext
) => void,
onSceneObjectsDeleted: (scene: gdLayout) => void,
onSceneEventsModifiedOutsideEditor: (
changes: SceneEventsOutsideEditorChanges
) => void,
onSceneEventsModifiedOutsideEditor: (scene: gdLayout) => void,
startNewChat: () => void,
|};
@@ -724,17 +714,11 @@ export const AskAiEditor = React.memo<Props>(
setSendingAiRequest(null, true);
const preparedAiUserContent = await prepareAiUserContent({
getAuthorizationHeader,
userId: profile.id,
simplifiedProjectJson,
projectSpecificExtensionsSummaryJson,
});
const aiRequest = await createAiRequest(getAuthorizationHeader, {
userRequest: userRequest,
userId: profile.id,
...preparedAiUserContent,
gameProjectJson: simplifiedProjectJson,
projectSpecificExtensionsSummaryJson,
payWithCredits,
gameId: project ? project.getProjectUuid() : null,
fileMetadata,
@@ -805,19 +789,6 @@ export const AskAiEditor = React.memo<Props>(
]
);
const hasFunctionsCallsToProcess = React.useMemo(
() =>
selectedAiRequest
? getFunctionCallsToProcess({
aiRequest: selectedAiRequest,
editorFunctionCallResults: getEditorFunctionCallResults(
selectedAiRequest.id
),
}).length > 0
: false,
[selectedAiRequest, getEditorFunctionCallResults]
);
// Send the results of the function call outputs, if any, and the user message (if any).
const onSendMessage = React.useCallback(
async ({ userMessage }: {| userMessage: string |}) => {
@@ -840,7 +811,6 @@ export const AskAiEditor = React.memo<Props>(
// If anything is not finished yet, stop there (we only send all
// results at once, AI do not support partial results).
if (hasUnfinishedResult) return;
if (hasFunctionsCallsToProcess) return;
// If nothing to send, stop there.
if (functionCallOutputs.length === 0 && !userMessage) return;
@@ -879,19 +849,13 @@ export const AskAiEditor = React.memo<Props>(
)
: null;
const preparedAiUserContent = await prepareAiUserContent({
getAuthorizationHeader,
userId: profile.id,
simplifiedProjectJson,
projectSpecificExtensionsSummaryJson,
});
const aiRequest: AiRequest = await retryIfFailed({ times: 2 }, () =>
addMessageToAiRequest(getAuthorizationHeader, {
userId: profile.id,
aiRequestId: selectedAiRequestId,
functionCallOutputs,
...preparedAiUserContent,
gameProjectJson: simplifiedProjectJson,
projectSpecificExtensionsSummaryJson,
payWithCredits,
userMessage,
})
@@ -949,7 +913,6 @@ export const AskAiEditor = React.memo<Props>(
setLastSendError,
onRefreshLimits,
project,
hasFunctionsCallsToProcess,
]
);
const onSendEditorFunctionCallResults = React.useCallback(

View File

@@ -1,233 +0,0 @@
// @flow
import axios from 'axios';
import { retryIfFailed } from '../Utils/RetryIfFailed';
import {
createAiUserContentPresignedUrls,
type AiUserContentPresignedUrlsResult,
} from '../Utils/GDevelopServices/Generation';
import jsSHA from '../Utils/Sha256';
type UploadInfo = {
uploadedAt: number,
userRelativeKey: string | null,
};
const makeUploadCache = ({
minimalContentLength,
}: {|
minimalContentLength: number | null,
|}) => {
const uploadCacheByHash: {
[string]: UploadInfo,
} = {};
return {
getUserRelativeKey: (hash: string | null) => {
if (!hash) {
return null;
}
return (
(uploadCacheByHash[hash] && uploadCacheByHash[hash].userRelativeKey) ||
null
);
},
storeUpload: (hash: string | null, uploadInfo: UploadInfo) => {
if (!hash) return;
uploadCacheByHash[hash] = uploadInfo;
},
shouldUpload: ({
hash,
contentLength,
}: {|
hash: string | null,
contentLength: number,
|}) => {
if (!hash) {
// No hash, so no content to upload.
return false;
}
if (minimalContentLength && contentLength < minimalContentLength) {
// The content is too small to be uploaded.
return false;
}
if (
uploadCacheByHash[hash] &&
uploadCacheByHash[hash].uploadedAt > Date.now() - 1000 * 60 * 30
) {
// The content was already uploaded recently (and recently enough so that it has not expired in such a short time).
// We don't need to upload it again.
return false;
}
// The content was not uploaded, or not recently: we'll upload it now.
return true;
},
};
};
const projectSpecificExtensionsSummaryUploadCache = makeUploadCache({
minimalContentLength: null, // Always upload the project specific extensions summary.
});
const gameProjectJsonUploadCache = makeUploadCache({
minimalContentLength: 10 * 1000, // Roughly 10KB.
});
const computeSha256 = (payload: string): string => {
const shaObj = new jsSHA('SHA-256', 'TEXT', { encoding: 'UTF8' });
shaObj.update(payload);
return shaObj.getHash('HEX');
};
/**
* Prepare the user content to be used by the AI.
* It either uploads the content (and avoid uploading it again for a while)
* so that the request will just refer to the key where it's stored, or
* return the content so it's sent as part of the request itself (if it's small enough).
*/
export const prepareAiUserContent = async ({
getAuthorizationHeader,
userId,
simplifiedProjectJson,
projectSpecificExtensionsSummaryJson,
}: {|
getAuthorizationHeader: () => Promise<string>,
userId: string,
simplifiedProjectJson: string | null,
projectSpecificExtensionsSummaryJson: string | null,
|}) => {
// Hash the contents, if provided, to then upload it only once (as long as the hash stays
// the same, no need to re-upload it for a while).
// If the content is not provided, no hash is computed because there is no content to upload.
const startTime = Date.now();
const gameProjectJsonHash = simplifiedProjectJson
? computeSha256(simplifiedProjectJson)
: null;
const projectSpecificExtensionsSummaryJsonHash = projectSpecificExtensionsSummaryJson
? computeSha256(projectSpecificExtensionsSummaryJson)
: null;
const endTime = Date.now();
console.info(
`Hash of simplified project json and project specific extensions summary json took ${(
endTime - startTime
).toFixed(2)}ms`
);
const shouldUploadProjectSpecificExtensionsSummary = projectSpecificExtensionsSummaryUploadCache.shouldUpload(
{
hash: projectSpecificExtensionsSummaryJsonHash,
contentLength: projectSpecificExtensionsSummaryJson
? projectSpecificExtensionsSummaryJson.length
: 0,
}
);
const shouldUploadGameProjectJson = gameProjectJsonUploadCache.shouldUpload({
hash: gameProjectJsonHash,
contentLength: simplifiedProjectJson ? simplifiedProjectJson.length : 0,
});
if (
shouldUploadGameProjectJson ||
shouldUploadProjectSpecificExtensionsSummary
) {
const startTime = Date.now();
const {
gameProjectJsonSignedUrl,
gameProjectJsonUserRelativeKey,
projectSpecificExtensionsSummaryJsonSignedUrl,
projectSpecificExtensionsSummaryJsonUserRelativeKey,
}: AiUserContentPresignedUrlsResult = await retryIfFailed(
{ times: 3 },
() =>
createAiUserContentPresignedUrls(getAuthorizationHeader, {
userId,
gameProjectJsonHash: shouldUploadGameProjectJson
? gameProjectJsonHash
: null,
projectSpecificExtensionsSummaryJsonHash: shouldUploadProjectSpecificExtensionsSummary
? projectSpecificExtensionsSummaryJsonHash
: null,
})
);
const uploadedAt = Date.now();
await Promise.all([
gameProjectJsonSignedUrl
? retryIfFailed({ times: 3 }, () =>
axios.put(gameProjectJsonSignedUrl, simplifiedProjectJson, {
headers: {
'Content-Type': 'application/json',
},
// Allow any arbitrary large file to be sent
maxContentLength: Infinity,
})
).then(() => {
gameProjectJsonUploadCache.storeUpload(gameProjectJsonHash, {
uploadedAt,
userRelativeKey: gameProjectJsonUserRelativeKey || null,
});
})
: null,
projectSpecificExtensionsSummaryJsonSignedUrl
? retryIfFailed({ times: 3 }, () =>
axios.put(
projectSpecificExtensionsSummaryJsonSignedUrl,
projectSpecificExtensionsSummaryJson,
{
headers: {
'Content-Type': 'application/json',
},
// Allow any arbitrary large file to be sent
maxContentLength: Infinity,
}
)
).then(() => {
projectSpecificExtensionsSummaryUploadCache.storeUpload(
projectSpecificExtensionsSummaryJsonHash,
{
uploadedAt,
userRelativeKey:
projectSpecificExtensionsSummaryJsonUserRelativeKey || null,
}
);
})
: null,
]);
const endTime = Date.now();
console.info(
`Upload of ${[
shouldUploadGameProjectJson ? 'simplified project' : null,
shouldUploadProjectSpecificExtensionsSummary
? 'project specific extensions summary'
: null,
]
.filter(Boolean)
.join(' and ')} took ${(endTime - startTime).toFixed(2)}ms`
);
}
// Get the key at which the content was uploaded, if it was uploaded.
// If not, the content will be sent as part of the request instead of the upload key.
const gameProjectJsonUserRelativeKey = gameProjectJsonUploadCache.getUserRelativeKey(
gameProjectJsonHash
);
const projectSpecificExtensionsSummaryJsonUserRelativeKey = projectSpecificExtensionsSummaryUploadCache.getUserRelativeKey(
projectSpecificExtensionsSummaryJsonHash
);
return {
gameProjectJsonUserRelativeKey,
gameProjectJson: gameProjectJsonUserRelativeKey
? null
: simplifiedProjectJson,
projectSpecificExtensionsSummaryJsonUserRelativeKey,
projectSpecificExtensionsSummaryJson: projectSpecificExtensionsSummaryJsonUserRelativeKey
? null
: projectSpecificExtensionsSummaryJson,
};
};

View File

@@ -10,7 +10,6 @@ import {
import { type EventsGenerationResult } from '../EditorFunctions';
import { makeSimplifiedProjectBuilder } from '../EditorFunctions/SimplifiedProject/SimplifiedProject';
import { prepareAiUserContent } from './PrepareAiUserContent';
const gd: libGDevelop = global.gd;
@@ -41,24 +40,21 @@ export const useGenerateEvents = ({ project }: {| project: ?gdProject |}) => {
if (!profile) throw new Error('User should be authenticated.');
const simplifiedProjectBuilder = makeSimplifiedProjectBuilder(gd);
const simplifiedProjectJson = JSON.stringify(
simplifiedProjectBuilder.getSimplifiedProject(project, {})
);
const projectSpecificExtensionsSummaryJson = JSON.stringify(
simplifiedProjectBuilder.getProjectSpecificExtensionsSummary(project)
);
const preparedAiUserContent = await prepareAiUserContent({
getAuthorizationHeader,
userId: profile.id,
simplifiedProjectJson,
projectSpecificExtensionsSummaryJson,
});
const createResult = await retryIfFailed({ times: 2 }, () =>
createAiGeneratedEvent(getAuthorizationHeader, {
userId: profile.id,
...preparedAiUserContent,
partialGameProjectJson: JSON.stringify(
simplifiedProjectBuilder.getSimplifiedProject(project, {
scopeToScene: sceneName,
}),
null,
2
),
projectSpecificExtensionsSummaryJson,
sceneName,
eventsDescription,
extensionNamesList,

View File

@@ -27,20 +27,13 @@ import ThreeDotsMenu from '../../UI/CustomSvgIcons/ThreeDotsMenu';
import useAlertDialog from '../../UI/Alert/useAlertDialog';
import ExtensionInstallDialog from '../ExtensionStore/ExtensionInstallDialog';
import { getIDEVersion } from '../../Version';
import InAppTutorialContext from '../../InAppTutorial/InAppTutorialContext';
export const useExtensionUpdateAlertDialog = () => {
const { showConfirmation } = useAlertDialog();
const { currentlyRunningInAppTutorial } = React.useContext(
InAppTutorialContext
);
return async (
project: gdProject,
behaviorShortHeader: BehaviorShortHeader
): Promise<boolean> => {
if (currentlyRunningInAppTutorial) {
return false;
}
return await showConfirmation({
title: t`Extension update`,
message:

View File

@@ -49,15 +49,11 @@ import ErrorBoundary from '../UI/ErrorBoundary';
import type { ObjectFolderOrObjectWithContext } from '../ObjectsList/EnumerateObjectFolderOrObject';
import LoaderModal from '../UI/LoaderModal';
import { AssetStoreNavigatorContext } from './AssetStoreNavigator';
import InAppTutorialContext from '../InAppTutorial/InAppTutorialContext';
const isDev = Window.isDev();
export const useExtensionUpdateAlertDialog = () => {
const { showConfirmation, showDeleteConfirmation } = useAlertDialog();
const { currentlyRunningInAppTutorial } = React.useContext(
InAppTutorialContext
);
return async ({
project,
outOfDateExtensionShortHeaders,
@@ -65,9 +61,6 @@ export const useExtensionUpdateAlertDialog = () => {
project: gdProject,
outOfDateExtensionShortHeaders: Array<ExtensionShortHeader>,
|}): Promise<string> => {
if (currentlyRunningInAppTutorial) {
return 'skip';
}
const breakingChanges = new Map<
ExtensionShortHeader,
Array<ExtensionChange>

View File

@@ -656,7 +656,6 @@ const PrivateAssetPackInformationPage = ({
analyticsMetadata: {
reason: 'Claim asset pack',
recommendedPlanId: 'gdevelop_gold',
placementId: 'claim-asset-pack',
},
filter: 'individual',
})

Some files were not shown because too many files have changed in this diff Show More