Compare commits

...

35 Commits

Author SHA1 Message Date
Clément Pasteau
d7d17400dd Fix error accessing deleted objects after an object is deleted from a scene (#7612) 2025-05-15 18:18:09 +02:00
D8H
b219d50fd8 Fix a typo in the "hand brake" action (#7613)
- Don't show in changelog
2025-05-15 16:48:30 +02:00
Clément Pasteau
88f318e6df Bump to 5.5.231 (#7610)
Do not show in changelog
2025-05-15 11:03:54 +02:00
github-actions[bot]
d12ac44b7d Update translations [skip ci] (#7611)
Co-authored-by: ClementPasteau <4895034+ClementPasteau@users.noreply.github.com>
2025-05-15 11:03:32 +02:00
Clément Pasteau
7155eea716 Show gd.games homepage on play section by default on mobile (#7609) 2025-05-15 10:46:49 +02:00
github-actions[bot]
ca0796f131 Update translations [skip ci] (#7595)
Co-authored-by: ClementPasteau <4895034+ClementPasteau@users.noreply.github.com>
2025-05-15 10:35:56 +02:00
Clément Pasteau
c4b33e2481 Prevent continuing to use GDevelop if not all extensions have been loaded (#7608)
* GDevelop sometimes has faulty updates, for instance when the computer is shut down during an update. This was causing the app to be incomplete and projects to become corrupted after a save (ex: BBText objects being broken)
* This check shows an unskippable dialog suggesting a re-install of GDevelop
2025-05-15 10:15:42 +02:00
D8H
ff95564b6b Add new 3D physics-based vehicle behavior (#7479)
* You can now simulate realistic 3D cars using the new Vehicle behavior powered by the 3D physics engine.
* Advanced details can be customized: from wheel setup and gear ratios to engine torque, steering, brakes, anti-roll bars, and drivetrain (front/rear).
* The default setup offers a semi-realistic, arcade-style driving feel. For smoother gameplay, explore the example projects to see how fine-tuning makes a big difference.
* Jolt physics engine was upgraded to version 0.34.0.
2025-05-14 10:52:47 +02:00
Clément Pasteau
cecf1ab791 Fix crash when selecting a resource after switching tabs in the Resource selection dialog (#7607) 2025-05-14 10:28:12 +02:00
D8H
a571445e0e Allow custom objects to self-destruct (#7605) 2025-05-12 14:03:21 +02:00
D8H
89e418cd24 Fix grid snapping of pasted instances (#7602) 2025-05-12 11:41:42 +02:00
Florian Rival
896ccfcffa Add hint that mapper behaviors should be used for platformer (#7601)
Don't show in changelog
2025-05-12 10:51:09 +02:00
Clément Pasteau
d98d181755 Fix typo (#7604)
Do not show in changelog
2025-05-12 10:30:08 +02:00
Florian Rival
3c63f9b617 Update 3D extension internal descriptions
Only show in developer changelog
2025-05-08 12:26:54 +02:00
D8H
8312bbe4f8 Fix 3D Physics "apply force/impulse toward position" action (#7600) 2025-05-06 21:04:02 +02:00
Clément Pasteau
bb77a71f26 Bump to 5.5.230 (#7593)
Do not show in changelog
2025-05-06 10:10:48 +02:00
D8H
4353469554 Fix bitmap text alignment and rotation (#7597)
* Fix BBText rotation
2025-05-05 20:10:21 +02:00
Clément Pasteau
46ea431f62 Fix firebase tests (#7594)
Do not show in changelog
2025-05-05 15:16:39 +02:00
github-actions[bot]
2d29d43355 Update translations [skip ci] (#7577)
Co-authored-by: ClementPasteau <4895034+ClementPasteau@users.noreply.github.com>
2025-05-05 11:22:08 +02:00
Clément Pasteau
28a4e253a1 Update desktop & web icons with latest GDevelop branding (#7578) 2025-05-05 10:22:40 +02:00
D8H
f3dcb8eec8 Fix asset export for objects with unused children overriding (#7590) 2025-05-05 09:53:11 +02:00
Florian Rival
bf9e38ff31 Improve descriptions of boolean logic conditions
Only show in developer changelog
2025-05-04 16:08:36 +02:00
D8H
87649b9def Ensure variants downloaded from the store comply to their events-based object (#7587) 2025-05-02 12:51:58 +02:00
D8H
60d332e872 Fix rendered custom objects in the editor with an overriding of children configuration (#7585)
- Fix children overriding to only apply to the default variant at runtime
2025-05-02 12:51:14 +02:00
D8H
bdab12b1e6 Fix variant edition: forbid to edit variants from the store (they should be duplicated instead) (#7586) 2025-05-02 12:05:49 +02:00
Florian Rival
02f795f2c1 Update AI requests wording 2025-04-29 09:52:19 +02:00
AlexandreS
6e64d8521f Submit ai question with Ctrl+Enter or Go to button of mobile soft keyboard (#7579)
Don't show in changelog
2025-04-28 18:51:39 +02:00
Clément Pasteau
0e9aea1c9d Fix showing Checkered background on sprite project resources (#7580)
Do not show in changelog
2025-04-28 18:31:24 +02:00
Clément Pasteau
99901bf539 Bump newIDE version (#7576) 2025-04-28 12:07:23 +02:00
github-actions[bot]
53f1d745f5 Update translations [skip ci] (#7572)
Co-authored-by: ClementPasteau <4895034+ClementPasteau@users.noreply.github.com>
2025-04-28 10:28:31 +02:00
D8H
b72034a475 Fix the sentence parameter of "loading progress" condition (#7574) 2025-04-28 10:27:04 +02:00
AlexandreS
926f6a2c56 Remove useless param when changing user subscription (#7573)
Don't show in changelog
2025-04-25 17:20:23 +02:00
D8H
32cc6a3109 Fix an anchor behavior test (#7571)
- Don't show in changelogs
2025-04-25 11:04:48 +02:00
github-actions[bot]
f9ab65155d Update translations [skip ci] (#7561)
Co-authored-by: 4ian <1280130+4ian@users.noreply.github.com>
2025-04-25 10:57:40 +02:00
github-actions[bot]
d700a9d26d Update extension translations [skip ci] (#7565)
Co-authored-by: 4ian <1280130+4ian@users.noreply.github.com>
2025-04-25 10:57:08 +02:00
237 changed files with 6146 additions and 3539 deletions

View File

@@ -59,36 +59,44 @@ BuiltinExtensionsImplementer::ImplementsCommonInstructionsExtension(
// end of compatibility code
extension
.AddCondition("Or",
_("Or"),
_("Check if one of the sub conditions is true"),
_("If one of these conditions is true:"),
"",
"res/conditions/or24_black.png",
"res/conditions/or_black.png")
.SetCanHaveSubInstructions()
.MarkAsAdvanced();
extension
.AddCondition("And",
_("And"),
_("Check if all sub conditions are true"),
_("If all of these conditions are true:"),
"",
"res/conditions/and24_black.png",
"res/conditions/and_black.png")
.AddCondition(
"Or",
_("Or"),
_("Checks if at least one sub-condition is true. If no "
"sub-condition is specified, it will always be false. "
"This is rarely used — multiple events and sub-events are "
"usually a better approach."),
_("If one of these conditions is true:"),
"",
"res/conditions/or24_black.png",
"res/conditions/or_black.png")
.SetCanHaveSubInstructions()
.MarkAsAdvanced();
extension
.AddCondition(
"Not",
_("Not"),
_("Return the contrary of the result of the sub conditions"),
_("Invert the logical result of these conditions:"),
"And",
_("And"),
_("Checks if all sub-conditions are true. If no sub-condition is "
"specified, it will always be false. This is rarely needed, as "
"events already check all conditions before running actions."),
_("If all of these conditions are true:"),
"",
"res/conditions/not24_black.png",
"res/conditions/not_black.png")
"res/conditions/and24_black.png",
"res/conditions/and_black.png")
.SetCanHaveSubInstructions()
.MarkAsAdvanced();
extension
.AddCondition("Not",
_("Not"),
_("Returns the opposite of the sub-condition(s) result. "
"This is rarely needed, as most conditions can be "
"inverted or expressed more simply."),
_("Invert the logical result of these conditions:"),
"",
"res/conditions/not24_black.png",
"res/conditions/not_black.png")
.SetCanHaveSubInstructions()
.MarkAsAdvanced();

View File

@@ -182,7 +182,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsSceneExtension(
"SceneLoadingProgress",
_("Scene loading progress"),
_("The progress of resources loading in background for a scene (between 0 and 1)."),
_("_PARAM0_ loading progress"),
_("_PARAM1_ loading progress"),
_(""),
"res/actions/hourglass_black.svg")
.SetHelpPath("/all-features/resources-loading")

View File

@@ -128,24 +128,25 @@ void ObjectAssetSerializer::SerializeUsedVariantsTo(
if (!project.HasEventsBasedObject(object.GetType())) {
return;
}
const auto &eventsBasedObject =
project.GetEventsBasedObject(object.GetType());
const auto &variants = eventsBasedObject.GetVariants();
const auto *customObjectConfiguration =
dynamic_cast<const gd::CustomObjectConfiguration *>(
&object.GetConfiguration());
if (customObjectConfiguration
->IsMarkedAsOverridingEventsBasedObjectChildrenConfiguration() ||
customObjectConfiguration
->IsForcedToOverrideEventsBasedObjectChildrenConfiguration()) {
const auto &variantName = customObjectConfiguration->GetVariantName();
if (!variants.HasVariantNamed(variantName) &&
(customObjectConfiguration
->IsMarkedAsOverridingEventsBasedObjectChildrenConfiguration() ||
customObjectConfiguration
->IsForcedToOverrideEventsBasedObjectChildrenConfiguration())) {
return;
}
const auto &variantName = customObjectConfiguration->GetVariantName();
const auto &variantIdentifier =
object.GetType() + gd::PlatformExtension::GetNamespaceSeparator() +
variantName;
auto insertResult = alreadyUsedVariantIdentifiers.insert(variantIdentifier);
if (insertResult.second) {
const auto &eventsBasedObject =
project.GetEventsBasedObject(object.GetType());
const auto &variants = eventsBasedObject.GetVariants();
const auto &variant = variants.HasVariantNamed(variantName)
? variants.GetVariant(variantName)
: eventsBasedObject.GetDefaultVariant();
@@ -154,7 +155,7 @@ void ObjectAssetSerializer::SerializeUsedVariantsTo(
pairElement.SetAttribute("objectType", object.GetType());
SerializerElement &variantElement = pairElement.AddChild("variant");
variant.SerializeTo(variantElement);
// TODO Recursivity
for (auto &object : variant.GetObjects().GetObjects()) {
gd::ObjectAssetSerializer::SerializeUsedVariantsTo(
project, *object, variantsElement, alreadyUsedVariantIdentifiers);

View File

@@ -33,7 +33,132 @@ using namespace gd;
TEST_CASE("ObjectAssetSerializer", "[common]") {
SECTION("Can serialize custom objects as assets") {
SECTION("Can serialize custom objects as assets with variant") {
gd::Platform platform;
gd::Project project;
SetupProjectWithDummyPlatform(project, platform);
auto &eventsExtension =
project.InsertNewEventsFunctionsExtension("MyEventsExtension", 0);
auto &eventsBasedObject = eventsExtension.GetEventsBasedObjects().InsertNew(
"MyEventsBasedObject", 0);
eventsBasedObject.SetFullName("My events based object");
eventsBasedObject.SetDescription("An events based object for test");
auto &childObject = eventsBasedObject.GetObjects().InsertNewObject(
project, "MyExtension::Sprite", "MyChild", 0);
auto &childInstance =
eventsBasedObject.GetInitialInstances().InsertNewInitialInstance();
childInstance.SetObjectName("MyChild");
auto &resourceManager = project.GetResourcesManager();
gd::ImageResource imageResource;
imageResource.SetName("assets/Idle.png");
imageResource.SetFile("assets/Idle.png");
imageResource.SetSmooth(true);
resourceManager.AddResource(imageResource);
gd::Layout &layout = project.InsertNewLayout("Scene", 0);
gd::Object &object = layout.GetObjects().InsertNewObject(
project, "MyEventsExtension::MyEventsBasedObject", "MyObject", 0);
auto *spriteConfiguration =
dynamic_cast<gd::SpriteObject *>(&childObject.GetConfiguration());
REQUIRE(spriteConfiguration != nullptr);
{
gd::Animation animation;
animation.SetName("Idle");
animation.SetDirectionsCount(1);
auto &direction = animation.GetDirection(0);
gd::Sprite frame;
frame.SetImageName("assets/Idle.png");
direction.AddSprite(frame);
spriteConfiguration->GetAnimations().AddAnimation(animation);
}
SerializerElement assetElement;
std::vector<gd::String> usedResourceNames;
ObjectAssetSerializer::SerializeTo(project, object, "My Object",
assetElement, usedResourceNames);
// This list is used to copy resource files.
REQUIRE(usedResourceNames.size() == 1);
REQUIRE(usedResourceNames[0] == "assets/Idle.png");
// Check that the project is left untouched.
REQUIRE(resourceManager.HasResource("assets/Idle.png"));
REQUIRE(resourceManager.GetResource("assets/Idle.png").GetFile() ==
"assets/Idle.png");
REQUIRE(!resourceManager.HasResource("Idle.png"));
REQUIRE(assetElement.HasChild("objectAssets"));
auto &objectAssetsElement = assetElement.GetChild("objectAssets");
objectAssetsElement.ConsiderAsArrayOf("objectAsset");
REQUIRE(objectAssetsElement.GetChildrenCount() == 1);
auto &objectAssetElement = objectAssetsElement.GetChild(0);
REQUIRE(objectAssetElement.HasChild("variants"));
auto &variantsElement = objectAssetElement.GetChild("variants");
variantsElement.ConsiderAsArrayOf("variant");
REQUIRE(variantsElement.GetChildrenCount() == 1);
auto &variantPairElement = variantsElement.GetChild(0);
REQUIRE(variantPairElement.GetStringAttribute("objectType") ==
"MyEventsExtension::MyEventsBasedObject");
REQUIRE(variantPairElement.HasChild("variant"));
auto &variantElement = variantPairElement.GetChild("variant");
REQUIRE(variantElement.GetStringAttribute("name") == "");
REQUIRE(variantElement.HasChild("objects"));
auto &objectsElement = variantElement.GetChild("objects");
objectsElement.ConsiderAsArrayOf("object");
REQUIRE(objectsElement.GetChildrenCount() == 1);
auto &childElement = objectsElement.GetChild(0);
REQUIRE(childElement.HasChild("animations"));
auto &animationsElement = childElement.GetChild("animations");
animationsElement.ConsiderAsArrayOf("animation");
REQUIRE(animationsElement.GetChildrenCount() == 1);
auto &animationElement = animationsElement.GetChild(0);
REQUIRE(animationElement.GetStringAttribute("name") == "Idle");
auto &directionsElement = animationElement.GetChild("directions");
directionsElement.ConsiderAsArrayOf("direction");
REQUIRE(directionsElement.GetChildrenCount() == 1);
auto &directionElement = directionsElement.GetChild(0);
auto &spritesElement = directionElement.GetChild("sprites");
spritesElement.ConsiderAsArrayOf("sprite");
REQUIRE(spritesElement.GetChildrenCount() == 1);
auto &spriteElement = spritesElement.GetChild(0);
REQUIRE(spriteElement.GetStringAttribute("image") == "assets/Idle.png");
REQUIRE(objectAssetElement.HasChild("requiredExtensions"));
auto &requiredExtensionsElement =
objectAssetElement.GetChild("requiredExtensions");
requiredExtensionsElement.ConsiderAsArrayOf("requiredExtension");
REQUIRE(requiredExtensionsElement.GetChildrenCount() == 1);
auto &requiredExtensionElement = requiredExtensionsElement.GetChild(0);
REQUIRE(requiredExtensionElement.GetStringAttribute("extensionName") ==
"MyEventsExtension");
// Resources are renamed according to asset script naming conventions.
REQUIRE(objectAssetElement.HasChild("resources"));
auto &resourcesElement = objectAssetElement.GetChild("resources");
resourcesElement.ConsiderAsArrayOf("resource");
REQUIRE(resourcesElement.GetChildrenCount() == 1);
{
auto &resourceElement = resourcesElement.GetChild(0);
REQUIRE(resourceElement.GetStringAttribute("name") == "assets/Idle.png");
REQUIRE(resourceElement.GetStringAttribute("file") == "assets/Idle.png");
REQUIRE(resourceElement.GetStringAttribute("kind") == "image");
REQUIRE(resourceElement.GetBoolAttribute("smoothed") == true);
}
// Resources used in object configuration are updated.
REQUIRE(objectAssetElement.HasChild("object"));
auto &objectElement = objectAssetElement.GetChild("object");
REQUIRE(objectElement.GetStringAttribute("name") == "MyObject");
REQUIRE(objectElement.GetStringAttribute("type") ==
"MyEventsExtension::MyEventsBasedObject");
}
SECTION("Can serialize custom objects as assets with children overriding") {
gd::Platform platform;
gd::Project project;
SetupProjectWithDummyPlatform(project, platform);

View File

@@ -21,7 +21,9 @@ module.exports = {
.setExtensionInformation(
'Scene3D',
_('3D'),
_('Support for 3D in GDevelop.'),
_(
'Support for 3D in GDevelop: this provides 3D objects and the common features for all 3D objects.'
),
'Florian Rival',
'MIT'
)
@@ -36,7 +38,9 @@ module.exports = {
'Base3DBehavior',
_('3D capability'),
'Object3D',
_('Move the object in 3D space.'),
_(
'Common features for all 3D objects: position in 3D space (including the Z axis, in addition to X and Y), size (including depth, in addition to width and height), rotation (on X and Y axis, in addition to the Z axis), scale (including Z axis, in addition to X and Y), flipping (on Z axis, in addition to horizontal (Y)/vertical (X) flipping).'
),
'',
'res/conditions/3d_box.svg',
'Base3DBehavior',

View File

@@ -1,5 +1,5 @@
// @ts-check
describe.only('gdjs.AnchorRuntimeBehavior', () => {
describe('gdjs.AnchorRuntimeBehavior', () => {
it('can fill a custom object with an child', async () => {
const runtimeGame = await gdjs.getPixiRuntimeGameWithAssets();
const runtimeScene = new gdjs.TestRuntimeScene(runtimeGame);
@@ -8,6 +8,7 @@ describe.only('gdjs.AnchorRuntimeBehavior', () => {
const customObject = new gdjs.CustomRuntimeObject2D(runtimeScene, {
name: 'MyCustomObject',
type: 'MyExtension::MyLayoutedEventsBasedObject',
variant: '',
variables: [],
behaviors: [],
effects: [],

View File

@@ -618,7 +618,7 @@ module.exports = {
this._pixiObject.dirty = true;
}
if (this._instance.hasCustomSize()) {
if (this._instance.hasCustomSize() && this._pixiObject.width !== 0) {
const alignmentX =
object.content.align === 'right'
? 1

View File

@@ -103,7 +103,7 @@ namespace gdjs {
}
updatePosition(): void {
if (this._object.isWrapping()) {
if (this._object.isWrapping() && this._pixiObject.width !== 0) {
const alignmentX =
this._object._textAlign === 'right'
? 1

View File

@@ -376,7 +376,7 @@ namespace gdjs {
}
override getWidth(): float {
return this._renderer.getWidth();
return this._wrapping ? this._wrappingWidth : this._renderer.getWidth();
}
override getHeight(): float {

View File

@@ -721,7 +721,7 @@ module.exports = {
this._pixiObject.dirty = true;
}
if (this._instance.hasCustomSize()) {
if (this._instance.hasCustomSize() && this.getDefaultWidth() !== 0) {
const alignmentX =
object.content.align === 'right'
? 1
@@ -730,17 +730,16 @@ module.exports = {
: 0;
const width = this.getCustomWidth();
const renderedWidth = this.getDefaultWidth();
// A vector from the custom size center to the renderer center.
const centerToCenterX =
(width - this._pixiObject.width) * (alignmentX - 0.5);
const centerToCenterX = (width - renderedWidth) * (alignmentX - 0.5);
this._pixiObject.position.x = this._instance.getX() + width / 2;
this._pixiObject.anchor.x =
0.5 - centerToCenterX / this._pixiObject.width;
this._pixiObject.anchor.x = 0.5 - centerToCenterX / renderedWidth;
} else {
this._pixiObject.position.x =
this._instance.getX() + this._pixiObject.width / 2;
this._instance.getX() + this.getDefaultWidth() / 2;
this._pixiObject.anchor.x = 0.5;
}
const alignmentY =
@@ -750,7 +749,7 @@ module.exports = {
? 0.5
: 0;
this._pixiObject.position.y =
this._instance.getY() + this._pixiObject.height * (0.5 - alignmentY);
this._instance.getY() + this.getDefaultHeight() * (0.5 - alignmentY);
this._pixiObject.anchor.y = 0.5;
this._pixiObject.rotation = RenderedInstance.toRad(
@@ -774,11 +773,11 @@ module.exports = {
}
getDefaultWidth() {
return this._pixiObject.width;
return this._pixiObject.textWidth * this._pixiObject.scale.x;
}
getDefaultHeight() {
return this._pixiObject.height;
return this._pixiObject.textHeight * this._pixiObject.scale.y;
}
getOriginY() {

View File

@@ -146,7 +146,7 @@ namespace gdjs {
}
updatePosition(): void {
if (this._object.isWrapping()) {
if (this._object.isWrapping() && this.getWidth() !== 0) {
const alignmentX =
this._object._textAlign === 'right'
? 1
@@ -155,17 +155,15 @@ namespace gdjs {
: 0;
const width = this._object.getWrappingWidth();
const renderedWidth = this.getWidth();
// A vector from the custom size center to the renderer center.
const centerToCenterX =
(width - this._pixiObject.width) * (alignmentX - 0.5);
const centerToCenterX = (width - renderedWidth) * (alignmentX - 0.5);
this._pixiObject.position.x = this._object.x + width / 2;
this._pixiObject.anchor.x =
0.5 - centerToCenterX / this._pixiObject.width;
this._pixiObject.anchor.x = 0.5 - centerToCenterX / renderedWidth;
} else {
this._pixiObject.position.x =
this._object.x + this._pixiObject.width / 2;
this._pixiObject.position.x = this._object.x + this.getWidth() / 2;
this._pixiObject.anchor.x = 0.5;
}
@@ -176,7 +174,7 @@ namespace gdjs {
? 0.5
: 0;
this._pixiObject.position.y =
this._object.y + this._pixiObject.height * (0.5 - alignmentY);
this._object.y + this.getHeight() * (0.5 - alignmentY);
this._pixiObject.anchor.y = 0.5;
}

View File

@@ -419,7 +419,7 @@ namespace gdjs {
}
override getWidth(): float {
return this._renderer.getWidth();
return this._wrapping ? this._wrappingWidth : this._renderer.getWidth();
}
override getHeight(): float {

View File

@@ -46,7 +46,7 @@ namespace gdjs {
layer.getCameraY() + layer.getCameraHeight() / 2
) {
//We are outside the camera area.
this.owner.deleteFromScene(instanceContainer);
this.owner.deleteFromScene();
}
}

View File

@@ -50,6 +50,11 @@ describeIfOnline('Firebase extension end-to-end tests', function () {
.replace('.', '-')}-${Date.now()}`;
before(async function setupFirebase() {
// Delete any existing Firebase app before setup
if (firebase.apps.length !== 0) {
await firebase.app().delete();
}
await gdjs.evtTools.firebaseTools._setupFirebase({
getGame: () => ({
getExtensionProperty: () => JSON.stringify(firebaseConfig),

View File

@@ -1340,7 +1340,7 @@ namespace gdjs {
debugLogger.info(
`Destroying object ${objectName} with instance network ID ${instanceNetworkId}.`
);
instance.deleteFromScene(runtimeScene);
instance.deleteFromScene();
debugLogger.info(
`Sending acknowledgment of destruction of object ${objectName} with instance network ID ${instanceNetworkId} to ${messageSender}.`
@@ -2280,7 +2280,7 @@ namespace gdjs {
behavior.getActionOnPlayerDisconnect();
if (actionOnPlayerDisconnect === 'DestroyObject') {
// No need to remove the ownership, as the destroy message will be sent to all players.
instance.deleteFromScene(runtimeScene);
instance.deleteFromScene();
} else if (actionOnPlayerDisconnect === 'GiveOwnershipToHost') {
// Removing the ownership will send a message to all players.
behavior.removeObjectOwnership();

View File

@@ -99,7 +99,7 @@ namespace gdjs {
debugLogger.info(
`Lobby game is running on a synced scene and object ${owner.getName()} has not been assigned a networkId after a short delay, destroying it.`
);
owner.deleteFromScene(instanceContainer);
owner.deleteFromScene();
}
}, this._timeBeforeDestroyingObjectWithoutNetworkIdInMs);
}
@@ -262,7 +262,7 @@ namespace gdjs {
debugLogger.info(
`Player number ${this.playerNumber} does not exist in the lobby at the moment. Destroying the object.`
);
this.owner.deleteFromScene(this.owner.getInstanceContainer());
this.owner.deleteFromScene();
return;
}

View File

@@ -1130,7 +1130,7 @@ describe('Multiplayer', () => {
'MySpriteObject'
)[0];
p1SpriteObject1.deleteFromScene(p1RuntimeScene);
p1SpriteObject1.deleteFromScene();
p1RuntimeScene.renderAndStep(1000 / 60);
}
@@ -1297,7 +1297,7 @@ describe('Multiplayer', () => {
'MySpriteObject'
)[0];
p2SpriteObject1.deleteFromScene(p2RuntimeScene);
p2SpriteObject1.deleteFromScene();
p2RuntimeScene.renderAndStep(1000 / 60);
}

View File

@@ -560,7 +560,7 @@ namespace gdjs {
!this._isEmissionPaused &&
this._renderer._mayHaveEndedEmission()
) {
this.deleteFromScene(instanceContainer);
this.deleteFromScene();
}
if (
this.jumpForwardInTimeOnCreation > 0 &&

View File

@@ -24,7 +24,7 @@ describe('Physics2RuntimeBehavior', () => {
doStepPreEvents(runtimeScene) {
if (this.shouldDeleteInPreEvent) {
this.owner.deleteFromScene(runtimeScene);
this.owner.deleteFromScene();
}
}
}
@@ -159,7 +159,7 @@ describe('Physics2RuntimeBehavior', () => {
);
// Delete object from scene
object.deleteFromScene(runtimeScene);
object.deleteFromScene();
expect(behavior.destroyedDuringFrameLogic).to.be(true);
expect(behavior.getBody()).to.be(null);
expect(behavior._sharedData._registeredBehaviors.size).to.be(0);
@@ -194,7 +194,7 @@ describe('Physics2RuntimeBehavior', () => {
false
);
object.deleteFromScene(runtimeScene);
object.deleteFromScene();
expect(behavior.destroyedDuringFrameLogic).to.be(true);
expect(behavior.getBody()).to.be(null);
@@ -712,7 +712,7 @@ describe('Physics2RuntimeBehavior', () => {
// Destroy (handled by postEvent).
runtimeScene.renderAndStepWithEventsFunction(1000 / fps, () => {
movingObject.deleteFromScene(runtimeScene);
movingObject.deleteFromScene();
});
// Collision should be reset on destroyed object and

File diff suppressed because it is too large Load Diff

View File

@@ -305,7 +305,14 @@ namespace gdjs {
private shapeDimensionA: float;
private shapeDimensionB: float;
private shapeDimensionC: float;
private shapeOffsetX: float;
private shapeOffsetY: float;
shapeOffsetZ: float;
private massCenterOffsetX: float;
private massCenterOffsetY: float;
private massCenterOffsetZ: float;
private density: float;
massOverride: float;
friction: float;
restitution: float;
linearDamping: float;
@@ -313,7 +320,7 @@ namespace gdjs {
gravityScale: float;
private layers: integer;
private masks: integer;
private shapeScale: number = 1;
shapeScale: number = 1;
/**
* Array containing the beginning of contacts reported by onContactBegin. Each contact
@@ -348,7 +355,10 @@ namespace gdjs {
/**
* When set to `true` the shape will be recreated before the next physics step.
*/
private _needToRecreateShape: boolean = false;
_needToRecreateShape: boolean = false;
_shapeHalfWidth: float = 0;
_shapeHalfHeight: float = 0;
/**
* Used by {@link gdjs.PhysicsCharacter3DRuntimeBehavior} to convert coordinates.
*/
@@ -392,7 +402,14 @@ namespace gdjs {
this.shapeDimensionA = behaviorData.shapeDimensionA;
this.shapeDimensionB = behaviorData.shapeDimensionB;
this.shapeDimensionC = behaviorData.shapeDimensionC;
this.shapeOffsetX = behaviorData.shapeOffsetX || 0;
this.shapeOffsetY = behaviorData.shapeOffsetY || 0;
this.shapeOffsetZ = behaviorData.shapeOffsetZ || 0;
this.massCenterOffsetX = behaviorData.massCenterOffsetX || 0;
this.massCenterOffsetY = behaviorData.massCenterOffsetY || 0;
this.massCenterOffsetZ = behaviorData.massCenterOffsetZ || 0;
this.density = behaviorData.density;
this.massOverride = behaviorData.massOverride || 0;
this.friction = behaviorData.friction;
this.restitution = behaviorData.restitution;
this.linearDamping = Math.max(0, behaviorData.linearDamping);
@@ -634,6 +651,39 @@ namespace gdjs {
}
createShape(): Jolt.Shape {
if (
this.massCenterOffsetX === 0 &&
this.massCenterOffsetY === 0 &&
this.massCenterOffsetZ === 0
) {
return this.createShapeWithoutMassCenterOffset();
}
const rotatedShapeSettings =
this._createNewShapeSettingsWithoutMassCenterOffset();
const shapeScale = this.shapeScale * this._sharedData.worldInvScale;
const offsetCenterShapeSettings =
new Jolt.OffsetCenterOfMassShapeSettings(
this.getVec3(
this.massCenterOffsetX * shapeScale,
this.massCenterOffsetY * shapeScale,
this.massCenterOffsetZ * shapeScale
),
rotatedShapeSettings
);
const shape = offsetCenterShapeSettings.Create().Get();
Jolt.destroy(offsetCenterShapeSettings);
return shape;
}
createShapeWithoutMassCenterOffset(): Jolt.Shape {
const rotatedShapeSettings =
this._createNewShapeSettingsWithoutMassCenterOffset();
const shape = rotatedShapeSettings.Create().Get();
Jolt.destroy(rotatedShapeSettings);
return shape;
}
private _createNewShapeSettingsWithoutMassCenterOffset(): Jolt.RotatedTranslatedShapeSettings {
let width = this.owner3D.getWidth() * this._sharedData.worldInvScale;
let height = this.owner3D.getHeight() * this._sharedData.worldInvScale;
let depth = this.owner3D.getDepth() * this._sharedData.worldInvScale;
@@ -679,6 +729,8 @@ namespace gdjs {
convexRadius
);
quat = this.getQuat(0, 0, 0, 1);
this._shapeHalfWidth = boxWidth / 2;
this._shapeHalfHeight = boxHeight / 2;
this._shapeHalfDepth = boxDepth / 2;
} else if (this.shape === 'Capsule') {
const radius =
@@ -694,8 +746,12 @@ namespace gdjs {
radius
);
quat = this._getShapeOrientationQuat();
this._shapeHalfWidth =
this.shapeOrientation === 'X' ? capsuleDepth / 2 : radius;
this._shapeHalfHeight =
this.shapeOrientation === 'Y' ? capsuleDepth / 2 : radius;
this._shapeHalfDepth =
this.shapeOrientation !== 'Z' ? radius : capsuleDepth / 2;
this.shapeOrientation === 'Z' ? capsuleDepth / 2 : radius;
} else if (this.shape === 'Cylinder') {
const radius =
shapeDimensionA > 0
@@ -716,8 +772,12 @@ namespace gdjs {
convexRadius
);
quat = this._getShapeOrientationQuat();
this._shapeHalfWidth =
this.shapeOrientation === 'X' ? cylinderDepth / 2 : radius;
this._shapeHalfHeight =
this.shapeOrientation === 'Y' ? cylinderDepth / 2 : radius;
this._shapeHalfDepth =
this.shapeOrientation !== 'Z' ? radius : cylinderDepth / 2;
this.shapeOrientation === 'Z' ? cylinderDepth / 2 : radius;
} else {
// Create a 'Sphere' by default.
const radius =
@@ -728,17 +788,20 @@ namespace gdjs {
: onePixel;
shapeSettings = new Jolt.SphereShapeSettings(radius);
quat = this.getQuat(0, 0, 0, 1);
this._shapeHalfWidth = radius;
this._shapeHalfHeight = radius;
this._shapeHalfDepth = radius;
}
shapeSettings.mDensity = this.density;
const rotatedShapeSettings = new Jolt.RotatedTranslatedShapeSettings(
this.getVec3(0, 0, 0),
return new Jolt.RotatedTranslatedShapeSettings(
this.getVec3(
this.shapeOffsetX * shapeScale,
this.shapeOffsetY * shapeScale,
this.shapeOffsetZ * shapeScale
),
quat,
shapeSettings
);
const rotatedShape = rotatedShapeSettings.Create().Get();
Jolt.destroy(rotatedShapeSettings);
return rotatedShape;
}
private _getShapeOrientationQuat(): Jolt.Quat {
@@ -933,7 +996,7 @@ namespace gdjs {
);
}
getPhysicsPosition(result: Jolt.RVec3): Jolt.RVec3 {
_getPhysicsPosition(result: Jolt.RVec3): Jolt.RVec3 {
result.Set(
this.owner3D.getCenterXInScene() * this._sharedData.worldInvScale,
this.owner3D.getCenterYInScene() * this._sharedData.worldInvScale,
@@ -942,7 +1005,7 @@ namespace gdjs {
return result;
}
getPhysicsRotation(result: Jolt.Quat): Jolt.Quat {
_getPhysicsRotation(result: Jolt.Quat): Jolt.Quat {
const threeObject = this.owner3D.get3DRendererObject();
result.Set(
threeObject.quaternion.x,
@@ -953,7 +1016,7 @@ namespace gdjs {
return result;
}
moveObjectToPhysicsPosition(physicsPosition: Jolt.RVec3): void {
_moveObjectToPhysicsPosition(physicsPosition: Jolt.RVec3): void {
this.owner3D.setCenterXInScene(
physicsPosition.GetX() * this._sharedData.worldScale
);
@@ -965,7 +1028,7 @@ namespace gdjs {
);
}
moveObjectToPhysicsRotation(physicsRotation: Jolt.Quat): void {
_moveObjectToPhysicsRotation(physicsRotation: Jolt.Quat): void {
const threeObject = this.owner3D.get3DRendererObject();
threeObject.quaternion.x = physicsRotation.GetX();
threeObject.quaternion.y = physicsRotation.GetY();
@@ -1103,6 +1166,18 @@ namespace gdjs {
this._needToRecreateShape = true;
}
getMassOverride(): float {
return this.massOverride;
}
setMassOverride(mass: float): void {
if (this.massOverride === mass) {
return;
}
this.massOverride = mass;
this._needToRecreateBody = true;
}
getFriction(): float {
return this.friction;
}
@@ -1470,11 +1545,11 @@ namespace gdjs {
const deltaX = towardX - body.GetPosition().GetX();
const deltaY = towardY - body.GetPosition().GetY();
const deltaZ = towardZ - body.GetPosition().GetZ();
const distance = deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ;
if (distance === 0) {
const distanceSq = deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ;
if (distanceSq === 0) {
return;
}
const ratio = length / distance;
const ratio = length / Math.sqrt(distanceSq);
this._sharedData.bodyInterface.AddForce(
body.GetID(),
@@ -1540,11 +1615,11 @@ namespace gdjs {
const deltaX = towardX - originX;
const deltaY = towardY - originY;
const deltaZ = towardZ - originZ;
const distance = deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ;
if (distance === 0) {
const distanceSq = deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ;
if (distanceSq === 0) {
return;
}
const ratio = length / distance;
const ratio = length / Math.sqrt(distanceSq);
this._sharedData.bodyInterface.AddImpulse(
body.GetID(),
@@ -1784,8 +1859,8 @@ namespace gdjs {
const shape = behavior.createShape();
const bodyCreationSettings = new Jolt.BodyCreationSettings(
shape,
behavior.getPhysicsPosition(_sharedData.getRVec3(0, 0, 0)),
behavior.getPhysicsRotation(_sharedData.getQuat(0, 0, 0, 1)),
behavior._getPhysicsPosition(_sharedData.getRVec3(0, 0, 0)),
behavior._getPhysicsRotation(_sharedData.getQuat(0, 0, 0, 1)),
behavior.bodyType === 'Static'
? Jolt.EMotionType_Static
: behavior.bodyType === 'Kinematic'
@@ -1806,6 +1881,12 @@ namespace gdjs {
bodyCreationSettings.mLinearDamping = behavior.linearDamping;
bodyCreationSettings.mAngularDamping = behavior.angularDamping;
bodyCreationSettings.mGravityFactor = behavior.gravityScale;
if (behavior.massOverride > 0) {
bodyCreationSettings.mOverrideMassProperties =
Jolt.EOverrideMassProperties_CalculateInertia;
bodyCreationSettings.mMassPropertiesOverride.mMass =
behavior.massOverride;
}
const bodyInterface = _sharedData.bodyInterface;
const body = bodyInterface.CreateBody(bodyCreationSettings);
@@ -1824,8 +1905,8 @@ namespace gdjs {
// If the body is null, we just don't do anything
// (but still run the physics simulation - this is independent).
if (_body !== null && _body.IsActive()) {
behavior.moveObjectToPhysicsPosition(_body.GetPosition());
behavior.moveObjectToPhysicsRotation(_body.GetRotation());
behavior._moveObjectToPhysicsPosition(_body.GetPosition());
behavior._moveObjectToPhysicsRotation(_body.GetRotation());
}
}
@@ -1847,8 +1928,8 @@ namespace gdjs {
) {
_sharedData.bodyInterface.SetPositionAndRotationWhenChanged(
body.GetID(),
this.behavior.getPhysicsPosition(_sharedData.getRVec3(0, 0, 0)),
this.behavior.getPhysicsRotation(_sharedData.getQuat(0, 0, 0, 1)),
this.behavior._getPhysicsPosition(_sharedData.getRVec3(0, 0, 0)),
this.behavior._getPhysicsRotation(_sharedData.getQuat(0, 0, 0, 1)),
Jolt.EActivation_Activate
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -323,7 +323,7 @@ namespace gdjs {
this._dontClearInputsBetweenFrames = true;
}
getPhysicsPosition(result: Jolt.RVec3): Jolt.RVec3 {
_getPhysicsPosition(result: Jolt.RVec3): Jolt.RVec3 {
const physics3D = this.getPhysics3D();
if (!physics3D) {
result.Set(0, 0, 0);
@@ -343,7 +343,7 @@ namespace gdjs {
return result;
}
getPhysicsRotation(result: Jolt.Quat): Jolt.Quat {
_getPhysicsRotation(result: Jolt.Quat): Jolt.Quat {
// Characters body should not rotate around X and Y.
const rotation = result.sEulerAngles(
this.getVec3(0, 0, gdjs.toRad(this.owner3D.getAngle()))
@@ -358,7 +358,7 @@ namespace gdjs {
return result;
}
moveObjectToPhysicsPosition(physicsPosition: Jolt.RVec3): void {
_moveObjectToPhysicsPosition(physicsPosition: Jolt.RVec3): void {
const physics3D = this.getPhysics3D();
if (!physics3D) {
return;
@@ -376,7 +376,7 @@ namespace gdjs {
);
}
moveObjectToPhysicsRotation(physicsRotation: Jolt.Quat): void {
_moveObjectToPhysicsRotation(physicsRotation: Jolt.Quat): void {
const threeObject = this.owner3D.get3DRendererObject();
threeObject.quaternion.x = physicsRotation.GetX();
threeObject.quaternion.y = physicsRotation.GetY();
@@ -1503,7 +1503,8 @@ namespace gdjs {
const { behavior } = physics3D;
const { _slopeMaxAngle, owner3D, _sharedData } = this.characterBehavior;
const shape = behavior.createShape();
// Jolt doesn't support center of mass offset for characters.
const shape = behavior.createShapeWithoutMassCenterOffset();
const settings = new Jolt.CharacterVirtualSettings();
// Characters innerBody are Kinematic body, they don't allow other
@@ -1542,10 +1543,10 @@ namespace gdjs {
);
const character = new Jolt.CharacterVirtual(
settings,
this.characterBehavior.getPhysicsPosition(
this.characterBehavior._getPhysicsPosition(
_sharedData.getRVec3(0, 0, 0)
),
behavior.getPhysicsRotation(_sharedData.getQuat(0, 0, 0, 1)),
behavior._getPhysicsRotation(_sharedData.getQuat(0, 0, 0, 1)),
_sharedData.physicsSystem
);
Jolt.destroy(settings);
@@ -1622,6 +1623,19 @@ namespace gdjs {
contactNormal,
settings
) => {};
characterContactListener.OnContactPersisted = (
inCharacter,
inBodyID2,
inSubShapeID2,
inContactPosition,
inContactNormal,
ioSettings
) => {};
characterContactListener.OnContactRemoved = (
inCharacter,
inBodyID2,
inSubShapeID2
) => {};
characterContactListener.OnCharacterContactAdded = (
character,
otherCharacter,
@@ -1630,6 +1644,19 @@ namespace gdjs {
contactNormal,
settings
) => {};
characterContactListener.OnCharacterContactPersisted = (
inCharacter,
inOtherCharacter,
inSubShapeID2,
inContactPosition,
inContactNormal,
ioSettings
) => {};
characterContactListener.OnCharacterContactRemoved = (
inCharacter,
inOtherCharacter,
inSubShapeID2
) => {};
characterContactListener.OnContactSolve = (
character,
bodyID2,
@@ -1666,10 +1693,10 @@ namespace gdjs {
return;
}
// We can't rely on the body position because of mCharacterPadding.
this.characterBehavior.moveObjectToPhysicsPosition(
this.characterBehavior._moveObjectToPhysicsPosition(
character.GetPosition()
);
this.characterBehavior.moveObjectToPhysicsRotation(
this.characterBehavior._moveObjectToPhysicsRotation(
character.GetRotation()
);
}
@@ -1697,7 +1724,7 @@ namespace gdjs {
behavior._objectOldRotationZ !== owner3D.getAngle()
) {
character.SetRotation(
this.characterBehavior.getPhysicsRotation(
this.characterBehavior._getPhysicsRotation(
_sharedData.getQuat(0, 0, 0, 1)
)
);
@@ -1710,7 +1737,7 @@ namespace gdjs {
return;
}
character.SetPosition(
this.characterBehavior.getPhysicsPosition(
this.characterBehavior._getPhysicsPosition(
_sharedData.getRVec3(0, 0, 0)
)
);
@@ -1732,7 +1759,7 @@ namespace gdjs {
if (!character) {
return;
}
const shape = behavior.createShape();
const shape = behavior.createShapeWithoutMassCenterOffset();
const isShapeValid = character.SetShape(
shape,
Number.MAX_VALUE,

View File

@@ -26,6 +26,7 @@ declare namespace Jolt {
size(): number;
}
class ArrayVec3 {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): Vec3;
@@ -36,6 +37,7 @@ declare namespace Jolt {
data(): Vec3MemRef;
}
class ArrayQuat {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): Quat;
@@ -46,6 +48,7 @@ declare namespace Jolt {
data(): QuatMemRef;
}
class ArrayMat44 {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): Mat44;
@@ -56,6 +59,7 @@ declare namespace Jolt {
data(): Mat44MemRef;
}
class ArrayBodyID {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): BodyID;
@@ -66,6 +70,7 @@ declare namespace Jolt {
data(): BodyIDMemRef;
}
class ArrayBodyPtr {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): Body;
@@ -431,6 +436,13 @@ declare namespace Jolt {
function _emscripten_enum_SoftBodySharedSettings_ELRAType_SoftBodySharedSettings_ELRAType_None(): SoftBodySharedSettings_ELRAType;
function _emscripten_enum_SoftBodySharedSettings_ELRAType_SoftBodySharedSettings_ELRAType_EuclideanDistance(): SoftBodySharedSettings_ELRAType;
function _emscripten_enum_SoftBodySharedSettings_ELRAType_SoftBodySharedSettings_ELRAType_GeodesicDistance(): SoftBodySharedSettings_ELRAType;
const MeshShapeSettings_EBuildQuality_FavorRuntimePerformance: number;
const MeshShapeSettings_EBuildQuality_FavorBuildSpeed: number;
type MeshShapeSettings_EBuildQuality =
| typeof MeshShapeSettings_EBuildQuality_FavorRuntimePerformance
| typeof MeshShapeSettings_EBuildQuality_FavorBuildSpeed;
function _emscripten_enum_MeshShapeSettings_EBuildQuality_MeshShapeSettings_EBuildQuality_FavorRuntimePerformance(): MeshShapeSettings_EBuildQuality;
function _emscripten_enum_MeshShapeSettings_EBuildQuality_MeshShapeSettings_EBuildQuality_FavorBuildSpeed(): MeshShapeSettings_EBuildQuality;
class Vec3MemRef {}
class QuatMemRef {}
class Mat44MemRef {}
@@ -444,6 +456,7 @@ declare namespace Jolt {
constructor(inV: Float3);
constructor(inX: number, inY: number, inZ: number);
sZero(): Vec3;
sOne(): Vec3;
sAxisX(): Vec3;
sAxisY(): Vec3;
sAxisZ(): Vec3;
@@ -505,6 +518,7 @@ declare namespace Jolt {
constructor();
constructor(inX: number, inY: number, inZ: number);
sZero(): RVec3;
sOne(): RVec3;
sAxisX(): RVec3;
sAxisY(): RVec3;
sAxisZ(): RVec3;
@@ -552,6 +566,7 @@ declare namespace Jolt {
constructor(inV: Vec3, inW: number);
constructor(inX: number, inY: number, inZ: number, inW: number);
sZero(): Vec4;
sOne(): Vec4;
sReplicate(inV: number): Vec4;
sMin(inLHS: Vec4, inRHS: Vec4): Vec4;
sMax(inLHS: Vec4, inRHS: Vec4): Vec4;
@@ -1427,6 +1442,9 @@ declare namespace Jolt {
get_mPerTriangleUserData(): boolean;
set_mPerTriangleUserData(mPerTriangleUserData: boolean): void;
mPerTriangleUserData: boolean;
get_mBuildQuality(): MeshShapeSettings_EBuildQuality;
set_mBuildQuality(mBuildQuality: MeshShapeSettings_EBuildQuality): void;
mBuildQuality: MeshShapeSettings_EBuildQuality;
}
class MeshShape extends Shape {
GetTriangleUserData(inSubShapeID: SubShapeID): number;
@@ -2523,6 +2541,8 @@ declare namespace Jolt {
GetGravityFactor(inBodyID: BodyID): number;
SetUseManifoldReduction(inBodyID: BodyID, inUseReduction: boolean): void;
GetUseManifoldReduction(inBodyID: BodyID): boolean;
SetCollisionGroup(inBodyID: BodyID, inCollisionGroup: CollisionGroup): void;
GetCollisionGroup(inBodyID: BodyID): CollisionGroup;
AddForce(
inBodyID: BodyID,
inForce: Vec3,
@@ -2624,9 +2644,9 @@ declare namespace Jolt {
get_mLinearCastMaxPenetration(): number;
set_mLinearCastMaxPenetration(mLinearCastMaxPenetration: number): void;
mLinearCastMaxPenetration: number;
get_mManifoldToleranceSq(): number;
set_mManifoldToleranceSq(mManifoldToleranceSq: number): void;
mManifoldToleranceSq: number;
get_mManifoldTolerance(): number;
set_mManifoldTolerance(mManifoldTolerance: number): void;
mManifoldTolerance: number;
get_mMaxPenetrationDistance(): number;
set_mMaxPenetrationDistance(mMaxPenetrationDistance: number): void;
mMaxPenetrationDistance: number;
@@ -2983,6 +3003,7 @@ declare namespace Jolt {
AddHit(inResult: number): void;
}
class ArrayRayCastResult {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): RayCastResult;
@@ -3040,6 +3061,7 @@ declare namespace Jolt {
AddHit(inResult: number): void;
}
class ArrayCollidePointResult {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): CollidePointResult;
@@ -3114,6 +3136,7 @@ declare namespace Jolt {
AddHit(inResult: number): void;
}
class ArrayCollideShapeResult {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): CollideShapeResult;
@@ -3188,6 +3211,7 @@ declare namespace Jolt {
AddHit(inResult: number): void;
}
class ArrayShapeCastResult {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): ShapeCastResult;
@@ -3618,6 +3642,7 @@ declare namespace Jolt {
mMaxDistance: number;
}
class ArraySoftBodySharedSettingsVertex {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): SoftBodySharedSettingsVertex;
@@ -3627,6 +3652,7 @@ declare namespace Jolt {
clear(): void;
}
class ArraySoftBodySharedSettingsFace {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): SoftBodySharedSettingsFace;
@@ -3636,6 +3662,7 @@ declare namespace Jolt {
clear(): void;
}
class ArraySoftBodySharedSettingsEdge {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): SoftBodySharedSettingsEdge;
@@ -3645,6 +3672,7 @@ declare namespace Jolt {
clear(): void;
}
class ArraySoftBodySharedSettingsDihedralBend {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): SoftBodySharedSettingsDihedralBend;
@@ -3654,6 +3682,7 @@ declare namespace Jolt {
clear(): void;
}
class ArraySoftBodySharedSettingsVolume {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): SoftBodySharedSettingsVolume;
@@ -3663,6 +3692,7 @@ declare namespace Jolt {
clear(): void;
}
class ArraySoftBodySharedSettingsInvBind {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): SoftBodySharedSettingsInvBind;
@@ -3672,6 +3702,7 @@ declare namespace Jolt {
clear(): void;
}
class ArraySoftBodySharedSettingsSkinned {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): SoftBodySharedSettingsSkinned;
@@ -3681,6 +3712,7 @@ declare namespace Jolt {
clear(): void;
}
class ArraySoftBodySharedSettingsLRA {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): SoftBodySharedSettingsLRA;
@@ -3708,6 +3740,7 @@ declare namespace Jolt {
mLRAMaxDistanceMultiplier: number;
}
class ArraySoftBodySharedSettingsVertexAttributes {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): SoftBodySharedSettingsVertexAttributes;
@@ -3856,6 +3889,7 @@ declare namespace Jolt {
readonly mVelocityOffset: number;
}
class ArraySoftBodyVertex {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): SoftBodyVertex;
@@ -3923,8 +3957,18 @@ declare namespace Jolt {
set_mShape(mShape: Shape): void;
mShape: Shape;
}
class CharacterID {
constructor();
GetValue(): number;
IsInvalid(): boolean;
sNextCharacterID(): CharacterID;
sSetNextCharacterID(inNextValue: number): void;
}
class CharacterVirtualSettings extends CharacterBaseSettings {
constructor();
get_mID(): CharacterID;
set_mID(mID: CharacterID): void;
mID: CharacterID;
get_mMass(): number;
set_mMass(mMass: number): void;
mMass: number;
@@ -3967,6 +4011,9 @@ declare namespace Jolt {
get_mInnerBodyShape(): Shape;
set_mInnerBodyShape(mInnerBodyShape: Shape): void;
mInnerBodyShape: Shape;
get_mInnerBodyIDOverride(): BodyID;
set_mInnerBodyIDOverride(mInnerBodyIDOverride: BodyID): void;
mInnerBodyIDOverride: BodyID;
get_mInnerBodyLayer(): number;
set_mInnerBodyLayer(mInnerBodyLayer: number): void;
mInnerBodyLayer: number;
@@ -4008,6 +4055,19 @@ declare namespace Jolt {
inContactNormal: number,
ioSettings: number
): void;
OnContactPersisted(
inCharacter: number,
inBodyID2: number,
inSubShapeID2: number,
inContactPosition: number,
inContactNormal: number,
ioSettings: number
): void;
OnContactRemoved(
inCharacter: number,
inBodyID2: number,
inSubShapeID2: number
): void;
OnCharacterContactAdded(
inCharacter: number,
inOtherCharacter: number,
@@ -4016,6 +4076,19 @@ declare namespace Jolt {
inContactNormal: number,
ioSettings: number
): void;
OnCharacterContactPersisted(
inCharacter: number,
inOtherCharacter: number,
inSubShapeID2: number,
inContactPosition: number,
inContactNormal: number,
ioSettings: number
): void;
OnCharacterContactRemoved(
inCharacter: number,
inOtherCharacter: number,
inSubShapeID2: number
): void;
OnContactSolve(
inCharacter: number,
inBodyID2: number,
@@ -4091,9 +4164,9 @@ declare namespace Jolt {
get_mBodyB(): BodyID;
set_mBodyB(mBodyB: BodyID): void;
mBodyB: BodyID;
get_mCharacterB(): CharacterVirtual;
set_mCharacterB(mCharacterB: CharacterVirtual): void;
mCharacterB: CharacterVirtual;
get_mCharacterIDB(): CharacterID;
set_mCharacterIDB(mCharacterIDB: CharacterID): void;
mCharacterIDB: CharacterID;
get_mSubShapeIDB(): SubShapeID;
set_mSubShapeIDB(mSubShapeIDB: SubShapeID): void;
mSubShapeIDB: SubShapeID;
@@ -4103,6 +4176,9 @@ declare namespace Jolt {
get_mIsSensorB(): boolean;
set_mIsSensorB(mIsSensorB: boolean): void;
mIsSensorB: boolean;
get_mCharacterB(): CharacterVirtual;
set_mCharacterB(mCharacterB: CharacterVirtual): void;
mCharacterB: CharacterVirtual;
get_mUserData(): number;
set_mUserData(mUserData: number): void;
mUserData: number;
@@ -4120,6 +4196,7 @@ declare namespace Jolt {
mCanPushCharacter: boolean;
}
class ArrayCharacterVirtualContact {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): CharacterVirtualContact;
@@ -4234,6 +4311,7 @@ declare namespace Jolt {
inRotation: Quat,
inSystem: PhysicsSystem
);
GetID(): CharacterID;
SetListener(inListener: CharacterContactListener): void;
SetCharacterVsCharacterCollision(
inCharacterVsCharacterCollision: CharacterVsCharacterCollision
@@ -4265,6 +4343,8 @@ declare namespace Jolt {
GetUserData(): number;
SetUserData(inUserData: number): void;
GetInnerBodyID(): BodyID;
StartTrackingContactChanges(): void;
FinishTrackingContactChanges(): void;
CancelVelocityTowardsSteepSlopes(inDesiredVelocity: Vec3): Vec3;
Update(
inDeltaTime: number,
@@ -4326,6 +4406,7 @@ declare namespace Jolt {
SetInnerBodyShape(inShape: Shape): void;
GetTransformedShape(): TransformedShape;
HasCollidedWith(inBodyID: BodyID): boolean;
HasCollidedWithCharacterID(inCharacterID: CharacterID): boolean;
HasCollidedWithCharacter(inCharacter: CharacterVirtual): boolean;
GetActiveContacts(): ArrayCharacterVirtualContact;
}
@@ -4340,6 +4421,7 @@ declare namespace Jolt {
GetValue(inX: number): number;
}
class ArrayFloat {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): number;
@@ -4350,6 +4432,7 @@ declare namespace Jolt {
data(): FloatMemRef;
}
class ArrayUint {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): number;
@@ -4360,6 +4443,7 @@ declare namespace Jolt {
data(): UintMemRef;
}
class ArrayUint8 {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): number;
@@ -4370,6 +4454,7 @@ declare namespace Jolt {
data(): Uint8MemRef;
}
class ArrayVehicleAntiRollBar {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): VehicleAntiRollBar;
@@ -4378,6 +4463,7 @@ declare namespace Jolt {
clear(): void;
}
class ArrayWheelSettings {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): WheelSettings;
@@ -4386,6 +4472,7 @@ declare namespace Jolt {
clear(): void;
}
class ArrayVehicleDifferentialSettings {
constructor();
empty(): boolean;
size(): number;
at(inIndex: number): VehicleDifferentialSettings;
@@ -4457,6 +4544,7 @@ declare namespace Jolt {
inWheelRight: Vec3,
inWheelUp: Vec3
): RMat44;
GetAntiRollBars(): ArrayVehicleAntiRollBar;
SetNumStepsBetweenCollisionTestActive(inSteps: number): void;
GetNumStepsBetweenCollisionTestActive(): number;
SetNumStepsBetweenCollisionTestInactive(inSteps: number): void;
@@ -4819,9 +4907,6 @@ declare namespace Jolt {
}
class VehicleControllerSettings {}
class VehicleController {
GetRefCount(): number;
AddRef(): void;
Release(): void;
GetConstraint(): VehicleConstraint;
}
class WheeledVehicleController extends VehicleController {

File diff suppressed because it is too large Load Diff

View File

@@ -23,7 +23,9 @@ void DeclarePlatformBehaviorExtension(gd::PlatformExtension& extension) {
"held, customizable gravity... It can be used for the player, but "
"also for other objects moving on platforms. In this case though, "
"it's recommended to first check if there is a simpler behavior that "
"could be used.",
"could be used. Default controls for keyboards are included. For "
"touch or gamepads, use the \"Multitouch Joystick\" objects and the "
"associated \"mapper\" behaviors.",
"Florian Rival",
"Open source (MIT License)")
.SetCategory("Movement")
@@ -33,16 +35,16 @@ void DeclarePlatformBehaviorExtension(gd::PlatformExtension& extension) {
.SetIcon("CppPlatform/Extensions/platformerobjecticon.png");
{
gd::BehaviorMetadata& aut = extension.AddBehavior(
"PlatformerObjectBehavior",
_("Platformer character"),
"PlatformerObject",
_("Jump and run on platforms."),
"",
"CppPlatform/Extensions/platformerobjecticon.png",
"PlatformerObjectBehavior",
std::make_shared<PlatformerObjectBehavior>(),
std::make_shared<gd::BehaviorsSharedData>());
gd::BehaviorMetadata& aut =
extension.AddBehavior("PlatformerObjectBehavior",
_("Platformer character"),
"PlatformerObject",
_("Jump and run on platforms."),
"",
"CppPlatform/Extensions/platformerobjecticon.png",
"PlatformerObjectBehavior",
std::make_shared<PlatformerObjectBehavior>(),
std::make_shared<gd::BehaviorsSharedData>());
// Deprecated, use IsMovingEvenALittle instead
aut.AddCondition("IsMoving",
@@ -59,14 +61,15 @@ void DeclarePlatformBehaviorExtension(gd::PlatformExtension& extension) {
.MarkAsSimple()
.SetFunctionName("IsMoving");
aut.AddScopedCondition("IsMovingEvenALittle",
_("Is moving"),
_("Check if the object is moving (whether it is on the "
"floor or in the air)."),
_("_PARAM0_ is moving"),
_("Platformer state"),
"CppPlatform/Extensions/platformerobjecticon.png",
"CppPlatform/Extensions/platformerobjecticon.png")
aut.AddScopedCondition(
"IsMovingEvenALittle",
_("Is moving"),
_("Check if the object is moving (whether it is on the "
"floor or in the air)."),
_("_PARAM0_ is moving"),
_("Platformer state"),
"CppPlatform/Extensions/platformerobjecticon.png",
"CppPlatform/Extensions/platformerobjecticon.png")
.AddParameter("object", _("Object"))
.AddParameter("behavior", _("Behavior"), "PlatformerObjectBehavior")
.MarkAsSimple();
@@ -525,14 +528,14 @@ void DeclarePlatformBehaviorExtension(gd::PlatformExtension& extension) {
.MarkAsAdvanced()
.SetFunctionName("SimulateLadderKey");
aut.AddAction(
"SimulateReleaseLadderKey",
_("Simulate release ladder key press"),
_("Simulate a press of the Release Ladder key (used to get off a ladder)."),
_("Simulate pressing Release Ladder key for _PARAM0_"),
_("Platformer controls"),
"res/conditions/keyboard24.png",
"res/conditions/keyboard.png")
aut.AddAction("SimulateReleaseLadderKey",
_("Simulate release ladder key press"),
_("Simulate a press of the Release Ladder key (used to get "
"off a ladder)."),
_("Simulate pressing Release Ladder key for _PARAM0_"),
_("Platformer controls"),
"res/conditions/keyboard24.png",
"res/conditions/keyboard.png")
.AddParameter("object", _("Object"))
.AddParameter("behavior", _("Behavior"), "PlatformerObjectBehavior")
.MarkAsAdvanced();
@@ -550,7 +553,8 @@ void DeclarePlatformBehaviorExtension(gd::PlatformExtension& extension) {
aut.AddAction("SimulateReleasePlatformKey",
_("Simulate release platform key press"),
_("Simulate a press of the release platform key (used when grabbing a "
_("Simulate a press of the release platform key (used when "
"grabbing a "
"platform ledge)."),
_("Simulate pressing Release Platform key for _PARAM0_"),
_("Platformer controls"),
@@ -561,7 +565,8 @@ void DeclarePlatformBehaviorExtension(gd::PlatformExtension& extension) {
.SetFunctionName("SimulateReleasePlatformKey");
// Support for deprecated names:
aut.AddDuplicatedAction("SimulateReleaseKey", "SimulateReleasePlatformKey").SetHidden();
aut.AddDuplicatedAction("SimulateReleaseKey", "SimulateReleasePlatformKey")
.SetHidden();
aut.AddAction("SimulateControl",
_("Simulate control"),
@@ -574,23 +579,27 @@ void DeclarePlatformBehaviorExtension(gd::PlatformExtension& extension) {
.AddParameter("object", _("Object"))
.AddParameter("behavior", _("Behavior"), "PlatformerObjectBehavior")
.AddParameter("stringWithSelector",
_("Key"),
"[\"Left\", \"Right\", \"Jump\", \"Ladder\", \"Release Ladder\", \"Up\", \"Down\"]")
_("Key"),
"[\"Left\", \"Right\", \"Jump\", \"Ladder\", \"Release "
"Ladder\", \"Up\", \"Down\"]")
.MarkAsAdvanced()
.SetFunctionName("SimulateControl");
aut.AddScopedCondition("IsUsingControl",
_("Control pressed or simulated"),
_("A control was applied from a default control or simulated by an action."),
_("_PARAM0_ has the _PARAM2_ key pressed or simulated"),
_("Platformer state"),
"res/conditions/keyboard24.png",
"res/conditions/keyboard.png")
aut.AddScopedCondition(
"IsUsingControl",
_("Control pressed or simulated"),
_("A control was applied from a default control or simulated by an "
"action."),
_("_PARAM0_ has the _PARAM2_ key pressed or simulated"),
_("Platformer state"),
"res/conditions/keyboard24.png",
"res/conditions/keyboard.png")
.AddParameter("object", _("Object"))
.AddParameter("behavior", _("Behavior"), "PlatformerObjectBehavior")
.AddParameter("stringWithSelector",
_("Key"),
"[\"Left\", \"Right\", \"Jump\", \"Ladder\", \"Release Ladder\", \"Up\", \"Down\"]")
_("Key"),
"[\"Left\", \"Right\", \"Jump\", \"Ladder\", \"Release "
"Ladder\", \"Up\", \"Down\"]")
.MarkAsAdvanced();
aut.AddAction("IgnoreDefaultControls",
@@ -792,59 +801,65 @@ void DeclarePlatformBehaviorExtension(gd::PlatformExtension& extension) {
.AddParameter("behavior", _("Behavior"), "PlatformerObjectBehavior")
.SetFunctionName("GetJumpSpeed");
aut.AddExpression("JumpSustainTime",
_("Jump sustain time"),
_("Return the jump sustain time of the object (in seconds)."
"This is the time during which keeping the jump button held "
"allow the initial jump speed to be maintained."),
_("Platformer configuration"),
"CppPlatform/Extensions/platformerobjecticon.png")
aut.AddExpression(
"JumpSustainTime",
_("Jump sustain time"),
_("Return the jump sustain time of the object (in seconds)."
"This is the time during which keeping the jump button held "
"allow the initial jump speed to be maintained."),
_("Platformer configuration"),
"CppPlatform/Extensions/platformerobjecticon.png")
.AddParameter("object", _("Object"))
.AddParameter("behavior", _("Behavior"), "PlatformerObjectBehavior");
aut.AddExpression("CurrentFallSpeed",
_("Current fall speed"),
_("Return the current fall speed of the object "
"(in pixels per second). Its value is always positive."),
_("Platformer state"),
"CppPlatform/Extensions/platformerobjecticon.png")
aut.AddExpression(
"CurrentFallSpeed",
_("Current fall speed"),
_("Return the current fall speed of the object "
"(in pixels per second). Its value is always positive."),
_("Platformer state"),
"CppPlatform/Extensions/platformerobjecticon.png")
.AddParameter("object", _("Object"))
.AddParameter("behavior", _("Behavior"), "PlatformerObjectBehavior")
.SetFunctionName("GetCurrentFallSpeed");
aut.AddExpression("CurrentSpeed",
_("Current horizontal speed"),
_("Return the current horizontal speed of the object "
"(in pixels per second). The object moves to the left "
"with negative values and to the right with positive ones"),
_("Platformer state"),
"CppPlatform/Extensions/platformerobjecticon.png")
aut.AddExpression(
"CurrentSpeed",
_("Current horizontal speed"),
_("Return the current horizontal speed of the object "
"(in pixels per second). The object moves to the left "
"with negative values and to the right with positive ones"),
_("Platformer state"),
"CppPlatform/Extensions/platformerobjecticon.png")
.AddParameter("object", _("Object"))
.AddParameter("behavior", _("Behavior"), "PlatformerObjectBehavior")
.SetFunctionName("GetCurrentSpeed");
aut.AddExpression("CurrentJumpSpeed",
_("Current jump speed"),
_("Return the current jump speed of the object "
"(in pixels per second). Its value is always positive."),
_("Platformer state"),
"CppPlatform/Extensions/platformerobjecticon.png")
aut.AddExpression(
"CurrentJumpSpeed",
_("Current jump speed"),
_("Return the current jump speed of the object "
"(in pixels per second). Its value is always positive."),
_("Platformer state"),
"CppPlatform/Extensions/platformerobjecticon.png")
.AddParameter("object", _("Object"))
.AddParameter("behavior", _("Behavior"), "PlatformerObjectBehavior")
.SetFunctionName("GetCurrentJumpSpeed");
}
{
gd::BehaviorMetadata& aut = extension.AddBehavior(
"PlatformBehavior",
_("Platform"),
"Platform",
_("Flag objects as being platforms which characters can run on."),
"",
"CppPlatform/Extensions/platformicon.png",
"PlatformBehavior",
std::make_shared<PlatformBehavior>(),
std::make_shared<gd::BehaviorsSharedData>())
.SetQuickCustomizationVisibility(gd::QuickCustomization::Hidden);
gd::BehaviorMetadata& aut =
extension
.AddBehavior("PlatformBehavior",
_("Platform"),
"Platform",
_("Flag objects as being platforms which characters "
"can run on."),
"",
"CppPlatform/Extensions/platformicon.png",
"PlatformBehavior",
std::make_shared<PlatformBehavior>(),
std::make_shared<gd::BehaviorsSharedData>())
.SetQuickCustomizationVisibility(gd::QuickCustomization::Hidden);
aut.AddAction("ChangePlatformType",
_("Platform type"),
@@ -857,21 +872,23 @@ void DeclarePlatformBehaviorExtension(gd::PlatformExtension& extension) {
.AddParameter("object", _("Object"))
.AddParameter("behavior", _("Behavior"), "PlatformBehavior")
.AddParameter("stringWithSelector",
_("Platform type"),
"[\"Platform\",\"Jumpthru\",\"Ladder\"]")
_("Platform type"),
"[\"Platform\",\"Jumpthru\",\"Ladder\"]")
.MarkAsAdvanced()
.SetFunctionName("ChangePlatformType");
}
extension.AddCondition("IsObjectOnGivenFloor",
_("Character is on given platform"),
_("Check if a platformer character is on a given platform."),
_("_PARAM0_ is on platform _PARAM2_"),
_("Collision"),
"CppPlatform/Extensions/platformicon.png",
"CppPlatform/Extensions/platformicon.png")
.AddParameter("objectList", _("Object"), "", false)
.AddParameter("behavior", _("Behavior"), "PlatformerObjectBehavior")
.AddParameter("objectList", _("Platforms"), "", false)
.AddCodeOnlyParameter("conditionInverted", "");
extension
.AddCondition(
"IsObjectOnGivenFloor",
_("Character is on given platform"),
_("Check if a platformer character is on a given platform."),
_("_PARAM0_ is on platform _PARAM2_"),
_("Collision"),
"CppPlatform/Extensions/platformicon.png",
"CppPlatform/Extensions/platformicon.png")
.AddParameter("objectList", _("Object"), "", false)
.AddParameter("behavior", _("Behavior"), "PlatformerObjectBehavior")
.AddParameter("objectList", _("Platforms"), "", false)
.AddCodeOnlyParameter("conditionInverted", "");
}

View File

@@ -146,7 +146,7 @@ describe('gdjs.TextInputRuntimeObject (using a PixiJS RuntimeGame with DOM eleme
expect(gameDomElementContainer.querySelector('input')).not.to.be(null);
expect(gameDomElementContainer.querySelector('textarea')).to.be(null);
object.deleteFromScene(runtimeScene);
object.deleteFromScene();
runtimeScene.renderAndStep(1000 / 60);
expect(gameDomElementContainer.querySelector('input')).to.be(null);
expect(gameDomElementContainer.querySelector('textarea')).to.be(null);

View File

@@ -98,7 +98,7 @@ namespace gdjs {
}
updatePosition(): void {
if (this._object.isWrapping()) {
if (this._object.isWrapping() && this._text.width !== 0) {
const alignmentX =
this._object._textAlign === 'right'
? 1
@@ -117,7 +117,6 @@ namespace gdjs {
this._text.position.x = this._object.x + this._text.width / 2;
this._text.anchor.x = 0.5;
}
this._text.position.y = this._object.y + this._text.height / 2;
const alignmentY =
this._object._verticalTextAlignment === 'bottom'

View File

@@ -89,7 +89,7 @@ namespace gdjs {
}
private _deleteFromScene() {
this.owner.deleteFromScene(this.owner.getInstanceContainer());
this.owner.deleteFromScene();
}
/**

View File

@@ -105,7 +105,14 @@ namespace gdjs {
return;
}
let usedVariantData: EventsBasedObjectVariantData = eventsBasedObjectData;
if (!eventsBasedObjectData.defaultVariant) {
eventsBasedObjectData.defaultVariant = {
...eventsBasedObjectData,
name: '',
};
}
let usedVariantData: EventsBasedObjectVariantData =
eventsBasedObjectData.defaultVariant;
if (customObjectData.variant) {
for (
let variantIndex = 0;
@@ -199,13 +206,13 @@ namespace gdjs {
}
}
override onDeletedFromScene(parent: gdjs.RuntimeInstanceContainer): void {
override onDeletedFromScene(): void {
// Let subclasses do something before the object is destroyed.
this.onDestroy(parent);
this.onDestroy(this._runtimeScene);
// Let behaviors do something before the object is destroyed.
super.onDeletedFromScene(parent);
super.onDeletedFromScene();
// Destroy the children.
this._instanceContainer.onDestroyFromScene(parent);
this._instanceContainer.onDestroyFromScene(this._runtimeScene);
}
override update(parent: gdjs.RuntimeInstanceContainer): void {

View File

@@ -80,7 +80,11 @@ namespace gdjs {
++i
) {
const childObjectData = eventsBasedObjectVariantData.objects[i];
if (customObjectData.childrenContent) {
// The children configuration override only applies to the default variant.
if (
customObjectData.childrenContent &&
!eventsBasedObjectVariantData.name
) {
this.registerObject({
...childObjectData,
// The custom object overrides its events-based object configuration.
@@ -183,7 +187,7 @@ namespace gdjs {
const allInstancesList = this.getAdhocListOfAllInstances();
for (let i = 0, len = allInstancesList.length; i < len; ++i) {
const object = allInstancesList[i];
object.onDeletedFromScene(this);
object.onDeletedFromScene();
// The object can free all its resource directly...
object.onDestroyed();
}

View File

@@ -678,7 +678,7 @@ namespace gdjs {
}
// Notify the object it was removed from the container
obj.onDeletedFromScene(this);
obj.onDeletedFromScene();
// Notify the global callbacks
for (let j = 0; j < gdjs.callbacksObjectDeletedFromScene.length; ++j) {

View File

@@ -1376,7 +1376,7 @@ namespace gdjs {
) {
// Instance was deleted (or object name changed, in which case it will be re-created later)
if (runtimeObject) {
runtimeObject.deleteFromScene(runtimeInstanceContainer);
runtimeObject.deleteFromScene();
}
} else {
}

View File

@@ -224,8 +224,7 @@ namespace gdjs {
let yOffset = 0;
if (anticipateMove && !object.hasNoForces()) {
const objectAverageForce = object.getAverageForce();
const elapsedTimeInSeconds =
object.getElapsedTime(instanceContainer) / 1000;
const elapsedTimeInSeconds = object.getElapsedTime() / 1000;
xOffset = objectAverageForce.getX() * elapsedTimeInSeconds;
yOffset = objectAverageForce.getY() * elapsedTimeInSeconds;
}

View File

@@ -382,10 +382,8 @@ namespace gdjs {
* in milliseconds, for the object.
*
* Objects can have different elapsed time if they are on layers with different time scales.
*
* @param instanceContainer The instance container the object belongs to (deprecated - can be omitted).
*/
getElapsedTime(instanceContainer?: gdjs.RuntimeInstanceContainer): float {
getElapsedTime(): float {
const theLayer = this._runtimeScene.getLayer(this.layer);
return theLayer.getElapsedTime();
}
@@ -599,11 +597,10 @@ namespace gdjs {
* Remove an object from a scene.
*
* Do not change/redefine this method. Instead, redefine the onDestroyFromScene method.
* @param instanceContainer The container owning the object.
*/
deleteFromScene(instanceContainer: gdjs.RuntimeInstanceContainer): void {
deleteFromScene(): void {
if (this._livingOnScene) {
instanceContainer.markObjectForDeletion(this);
this._runtimeScene.markObjectForDeletion(this);
this._livingOnScene = false;
}
}
@@ -620,11 +617,9 @@ namespace gdjs {
* 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);`).
*
* @param instanceContainer The container owning the object.
*/
onDeletedFromScene(instanceContainer: gdjs.RuntimeInstanceContainer): void {
const theLayer = instanceContainer.getLayer(this.layer);
onDeletedFromScene(): void {
const theLayer = this._runtimeScene.getLayer(this.layer);
const rendererObject = this.getRendererObject();
if (rendererObject) {
theLayer.getRenderer().removeRendererObject(rendererObject);
@@ -797,12 +792,7 @@ namespace gdjs {
return this.getY();
}
rotateTowardPosition(
x: float,
y: float,
speed: float,
scene: gdjs.RuntimeScene
): void {
rotateTowardPosition(x: float, y: float, speed: float): void {
this.rotateTowardAngle(
gdjs.toDegrees(
Math.atan2(
@@ -810,21 +800,15 @@ namespace gdjs {
x - (this.getDrawableX() + this.getCenterX())
)
),
speed,
scene
speed
);
}
/**
* @param angle The targeted direction angle.
* @param speed The rotation speed.
* @param instanceContainer The container the object belongs to (deprecated - can be omitted).
*/
rotateTowardAngle(
angle: float,
speed: float,
instanceContainer?: gdjs.RuntimeInstanceContainer
): void {
rotateTowardAngle(angle: float, speed: float): void {
if (speed === 0) {
this.setAngle(angle);
return;
@@ -863,10 +847,7 @@ namespace gdjs {
* @param speed The speed, in degrees per second.
* @param instanceContainer The container the object belongs to (deprecated - can be omitted).
*/
rotate(
speed: float,
instanceContainer?: gdjs.RuntimeInstanceContainer
): void {
rotate(speed: float): void {
this.setAngle(this.getAngle() + (speed * this.getElapsedTime()) / 1000);
}

View File

@@ -284,7 +284,7 @@ namespace gdjs {
const allInstancesList = this.getAdhocListOfAllInstances();
for (let i = 0, len = allInstancesList.length; i < len; ++i) {
const object = allInstancesList[i];
object.onDeletedFromScene(this);
object.onDeletedFromScene();
object.onDestroyed();
}

View File

@@ -945,18 +945,16 @@ namespace gdjs {
//Other :
/**
* @param obj The target object
* @param scene The scene containing the object
* @deprecated
*/
turnTowardObject(obj: gdjs.RuntimeObject | null, scene: gdjs.RuntimeScene) {
turnTowardObject(obj: gdjs.RuntimeObject | null) {
if (obj === null) {
return;
}
this.rotateTowardPosition(
obj.getDrawableX() + obj.getCenterX(),
obj.getDrawableY() + obj.getCenterY(),
0,
scene
0
);
}
}

View File

@@ -212,6 +212,9 @@ declare interface EventsBasedObjectData
name: string;
isInnerAreaFollowingParentSize: boolean;
variants: Array<EventsBasedObjectVariantData>;
/** Added at runtime to have the default variant with an empty name instead
* of the events-based object name. */
defaultVariant?: EventsBasedObjectVariantData;
}
declare interface EventsBasedObjectVariantData extends InstanceContainerData {

View File

@@ -1196,6 +1196,7 @@ interface MeasurementUnit {
[Const, Ref] MeasurementUnit STATIC_GetPixel();
[Const, Ref] MeasurementUnit STATIC_GetPixelSpeed();
[Const, Ref] MeasurementUnit STATIC_GetPixelAcceleration();
[Const, Ref] MeasurementUnit STATIC_GetAngularSpeed();
[Const, Ref] MeasurementUnit STATIC_GetNewton();
long STATIC_GetDefaultMeasurementUnitsCount();

View File

@@ -830,6 +830,7 @@ typedef ExtensionAndMetadata<ExpressionMetadata> ExtensionAndExpressionMetadata;
#define STATIC_GetPixel GetPixel
#define STATIC_GetPixelSpeed GetPixelSpeed
#define STATIC_GetPixelAcceleration GetPixelAcceleration
#define STATIC_GetAngularSpeed GetAngularSpeed
#define STATIC_GetNewton GetNewton
#define STATIC_GetDefaultMeasurementUnitsCount GetDefaultMeasurementUnitsCount
#define STATIC_GetDefaultMeasurementUnitAtIndex GetDefaultMeasurementUnitAtIndex

View File

@@ -388,7 +388,8 @@ class VariablesContainer {
}
class RuntimeObject {
constructor(runtimeScene, objectData) {
constructor(instanceContainer, objectData) {
this._runtimeScene = instanceContainer;
this.name = objectData.name || '';
this._variables = new VariablesContainer(objectData.variables);
this._livingOnScene = true;
@@ -466,10 +467,9 @@ class RuntimeObject {
array.pushValue(value);
}
/** @param {RuntimeScene} runtimeScene */
deleteFromScene(runtimeScene) {
deleteFromScene() {
if (this._livingOnScene) {
runtimeScene.markObjectForDeletion(this);
this._runtimeScene.markObjectForDeletion(this);
this._livingOnScene = false;
}
}

View File

@@ -1153,7 +1153,7 @@ describe('libGD.js - GDJS Async Code Generation integration tests', function ()
);
// Delete an object while the task is running.
myObjectA1.deleteFromScene(runtimeScene);
myObjectA1.deleteFromScene();
// Process the tasks (after faking it's finished).
runtimeScene.getAsyncTasksManager().markAllFakeAsyncTasksAsFinished();
@@ -1175,8 +1175,8 @@ describe('libGD.js - GDJS Async Code Generation integration tests', function ()
);
// Delete other objects while the task is running.
myObjectA3.deleteFromScene(runtimeScene);
myObjectB1.deleteFromScene(runtimeScene);
myObjectA3.deleteFromScene();
myObjectB1.deleteFromScene();
// Process the tasks again (after faking it's finished).
runtimeScene.getAsyncTasksManager().markAllFakeAsyncTasksAsFinished();
@@ -1291,7 +1291,7 @@ describe('libGD.js - GDJS Async Code Generation integration tests', function ()
);
// Delete an object while the task is running.
myObjectA1.deleteFromScene(runtimeScene);
myObjectA1.deleteFromScene();
// Process the tasks (after faking it's finished).
runtimeScene.getAsyncTasksManager().markAllFakeAsyncTasksAsFinished();
@@ -1315,8 +1315,8 @@ describe('libGD.js - GDJS Async Code Generation integration tests', function ()
);
// Delete other objects while the task is running.
myObjectA3.deleteFromScene(runtimeScene);
myObjectB1.deleteFromScene(runtimeScene);
myObjectA3.deleteFromScene();
myObjectB1.deleteFromScene();
// Process the tasks again (after faking it's finished).
runtimeScene.getAsyncTasksManager().markAllFakeAsyncTasksAsFinished();
@@ -1632,7 +1632,7 @@ describe('libGD.js - GDJS Async Code Generation integration tests', function ()
);
// Delete an object while the task is running.
myObjectA1.deleteFromScene(runtimeScene);
myObjectA1.deleteFromScene();
// Process the tasks (after faking it's finished).
runtimeScene.getAsyncTasksManager().markAllFakeAsyncTasksAsFinished();
@@ -1656,8 +1656,8 @@ describe('libGD.js - GDJS Async Code Generation integration tests', function ()
);
// Delete other objects while the task is running.
myObjectA3.deleteFromScene(runtimeScene);
myObjectB1.deleteFromScene(runtimeScene);
myObjectA3.deleteFromScene();
myObjectB1.deleteFromScene();
// Process the tasks again (after faking it's finished).
runtimeScene.getAsyncTasksManager().markAllFakeAsyncTasksAsFinished();
@@ -2132,8 +2132,8 @@ describe('libGD.js - GDJS Async Code Generation integration tests', function ()
const newMyObjectA = runtimeScene.getObjects('MyObjectA')[3];
// Delete some objects while the second Wait task is running.
myObjectA1.deleteFromScene(runtimeScene);
myObjectB1.deleteFromScene(runtimeScene);
myObjectA1.deleteFromScene();
myObjectB1.deleteFromScene();
// Process the tasks again (after faking it's finished).
runtimeScene.getAsyncTasksManager().markAllFakeAsyncTasksAsFinished();
@@ -2285,9 +2285,9 @@ describe('libGD.js - GDJS Async Code Generation integration tests', function ()
const newMyObjectA2 = runtimeScene.getObjects('MyObjectA')[4];
// Delete some objects while the second Wait task is running.
myObjectA1.deleteFromScene(runtimeScene);
myObjectB1.deleteFromScene(runtimeScene);
newMyObjectA1.deleteFromScene(runtimeScene);
myObjectA1.deleteFromScene();
myObjectB1.deleteFromScene();
newMyObjectA1.deleteFromScene();
// Process the tasks again (after faking it's finished).
runtimeScene.getAsyncTasksManager().markAllFakeAsyncTasksAsFinished();

View File

@@ -987,6 +987,7 @@ export class MeasurementUnit extends EmscriptenObject {
static getPixel(): MeasurementUnit;
static getPixelSpeed(): MeasurementUnit;
static getPixelAcceleration(): MeasurementUnit;
static getAngularSpeed(): MeasurementUnit;
static getNewton(): MeasurementUnit;
static getDefaultMeasurementUnitsCount(): number;
static getDefaultMeasurementUnitAtIndex(index: number): MeasurementUnit;

View File

@@ -17,6 +17,7 @@ declare class gdMeasurementUnit {
static getPixel(): gdMeasurementUnit;
static getPixelSpeed(): gdMeasurementUnit;
static getPixelAcceleration(): gdMeasurementUnit;
static getAngularSpeed(): gdMeasurementUnit;
static getNewton(): gdMeasurementUnit;
static getDefaultMeasurementUnitsCount(): number;
static getDefaultMeasurementUnitAtIndex(index: number): gdMeasurementUnit;

Binary file not shown.

Before

Width:  |  Height:  |  Size: 779 KiB

After

Width:  |  Height:  |  Size: 819 KiB

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="14" height="14" version="1.1" viewBox="0 0 14 14" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"><path d="m7 0-6 3.5v7l6 3.5 6-3.5v-7z" fill="#55b1e0" style="paint-order:normal"/><path d="m7.001 0.289 5.75 3.355v6.711l-5.75 3.355-5.75-3.355v-6.711z" fill="#2e388a" style="paint-order:normal"/><path d="m9.595 4.129c-0.075-0.2212-0.285-0.3788-0.5325-0.3788h-4.125c-0.2475 0-0.4538 0.1575-0.5325 0.3788l-0.78 2.246v3c0 0.2062 0.1688 0.375 0.375 0.375h0.375c0.2062 0 0.375-0.1688 0.375-0.375v-0.375h4.5v0.375c0 0.2062 0.1688 0.375 0.375 0.375h0.375c0.2062 0 0.375-0.1688 0.375-0.375v-3zm-4.658 3.746c-0.3112 0-0.5625-0.2512-0.5625-0.5625s0.2512-0.5625 0.5625-0.5625 0.5625 0.2512 0.5625 0.5625-0.2512 0.5625-0.5625 0.5625zm4.125 0c-0.3112 0-0.5625-0.2512-0.5625-0.5625s0.2512-0.5625 0.5625-0.5625 0.5625 0.2512 0.5625 0.5625-0.2512 0.5625-0.5625 0.5625zm-4.688-1.875 0.5625-1.688h4.125l0.5625 1.688z" fill="#55b1e0" stroke-width=".375"/></svg>

After

Width:  |  Height:  |  Size: 1001 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 777 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -3,8 +3,9 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
<link rel="apple-touch-icon" href="%PUBLIC_URL%/apple-touch-icon.png">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon-256.png">
<link rel="apple-touch-icon" sizes="180x180" href="%PUBLIC_URL%/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="%PUBLIC_URL%/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="%PUBLIC_URL%/favicon-16x16.png">
<title>GDevelop 5</title>
<meta name="title" content="GDevelop game making app" />

View File

@@ -3,24 +3,14 @@
"name": "GDevelop",
"icons": [
{
"src": "favicon-512.png",
"src": "/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "favicon-256.png",
"sizes": "256x256",
"type": "image/png"
},
{
"src": "apple-touch-icon.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "favicon.ico",
"sizes": "128x128",
"type": "image/png"
}
],
"screenshots": [

View File

@@ -18,6 +18,7 @@ import {
installRequiredExtensions,
installPublicAsset,
type RequiredExtensionInstallation,
complyVariantsToEventsBasedObjectOf,
} from './InstallAsset';
import EventsFunctionsExtensionsContext from '../EventsFunctionsExtensionsLoader/EventsFunctionsExtensionsContext';
import { showErrorBox } from '../UI/Messages/MessageBox';
@@ -226,6 +227,7 @@ const AssetPackInstallDialog = ({
const createdObjects = results
.map(result => result.createdObjects)
.flat();
complyVariantsToEventsBasedObjectOf(project, createdObjects);
onAssetsAdded(createdObjects);
} catch (error) {
setAreAssetsBeingInstalled(false);

View File

@@ -600,3 +600,21 @@ export const checkRequiredExtensionsUpdateForAssets = async ({
return checkRequiredExtensionsUpdate({ requiredExtensions, project });
};
export const complyVariantsToEventsBasedObjectOf = (
project: gdProject,
createdObjects: Array<gdObject>
) => {
const installedVariantObjectTypes = new Set<string>();
for (const createdObject of createdObjects) {
if (project.hasEventsBasedObject(createdObject.getType())) {
installedVariantObjectTypes.add(createdObject.getType());
}
}
for (const installedVariantObjectType of installedVariantObjectTypes) {
gd.EventsBasedObjectVariantHelper.complyVariantsToEventsBasedObject(
project,
project.getEventsBasedObject(installedVariantObjectType)
);
}
};

View File

@@ -20,6 +20,7 @@ import {
checkRequiredExtensionsUpdate,
checkRequiredExtensionsUpdateForAssets,
type InstallAssetOutput,
complyVariantsToEventsBasedObjectOf,
} from './InstallAsset';
import {
type Asset,
@@ -217,6 +218,10 @@ export const useInstallAsset = ({
openedAssetPack && openedAssetPack.id ? openedAssetPack.id : null,
assetPackKind: isPrivate ? 'private' : 'public',
});
complyVariantsToEventsBasedObjectOf(
project,
installOutput.createdObjects
);
await resourceManagementProps.onFetchNewlyAddedResources();
return installOutput;

View File

@@ -17,7 +17,7 @@ const gd: libGDevelop = global.gd;
type Props = BehaviorEditorProps;
const areAdvancedPropertiesModified = (behavior: gdBehavior) => {
export const areAdvancedPropertiesModified = (behavior: gdBehavior) => {
const behaviorMetadata = gd.MetadataProvider.getBehaviorMetadata(
gd.JsPlatform.get(),
behavior.getTypeName()

View File

@@ -16,6 +16,12 @@ import useForceUpdate from '../../../Utils/UseForceUpdate';
import Button from '@material-ui/core/Button';
import ButtonGroup from '@material-ui/core/ButtonGroup';
import { NumericProperty, UnitAdornment } from '../Physics2Editor';
import {
Accordion,
AccordionHeader,
AccordionBody,
} from '../../../UI/Accordion';
import { areAdvancedPropertiesModified } from '../BehaviorPropertiesEditor';
type Props = BehaviorEditorProps;
@@ -57,6 +63,11 @@ const Physics3DEditor = (props: Props) => {
const { behavior, onBehaviorUpdated } = props;
const forceUpdate = useForceUpdate();
const areAdvancedPropertiesExpandedByDefault = React.useMemo(
() => areAdvancedPropertiesModified(behavior),
[behavior]
);
const updateBehaviorProperty = React.useCallback(
(property, value) => {
behavior.updateProperty(property, value);
@@ -244,6 +255,18 @@ const Physics3DEditor = (props: Props) => {
)
}
/>
<NumericProperty
id="physics3d-parameter-mass-override"
properties={properties}
propertyName={'massOverride'}
step={0.1}
onUpdate={newValue =>
updateBehaviorProperty(
'massOverride',
parseFloat(newValue) > 0 ? newValue : '0'
)
}
/>
<NumericProperty
properties={properties}
propertyName={'gravityScale'}
@@ -356,6 +379,72 @@ const Physics3DEditor = (props: Props) => {
disabled={isStatic}
/>
</Line>
<Accordion
defaultExpanded={areAdvancedPropertiesExpandedByDefault}
noMargin
>
<AccordionHeader noMargin>
<Text size="sub-title">
<Trans>Advanced properties</Trans>
</Text>
</AccordionHeader>
<AccordionBody disableGutters>
<Column expand noMargin>
<ResponsiveLineStackLayout>
<NumericProperty
properties={properties}
propertyName={'shapeOffsetX'}
step={1}
onUpdate={newValue =>
updateBehaviorProperty('shapeOffsetX', newValue)
}
/>
<NumericProperty
properties={properties}
propertyName={'shapeOffsetY'}
step={1}
onUpdate={newValue =>
updateBehaviorProperty('shapeOffsetY', newValue)
}
/>
<NumericProperty
properties={properties}
propertyName={'shapeOffsetZ'}
step={1}
onUpdate={newValue =>
updateBehaviorProperty('shapeOffsetZ', newValue)
}
/>
</ResponsiveLineStackLayout>
<ResponsiveLineStackLayout>
<NumericProperty
properties={properties}
propertyName={'massCenterOffsetX'}
step={1}
onUpdate={newValue =>
updateBehaviorProperty('massCenterOffsetX', newValue)
}
/>
<NumericProperty
properties={properties}
propertyName={'massCenterOffsetY'}
step={1}
onUpdate={newValue =>
updateBehaviorProperty('massCenterOffsetY', newValue)
}
/>
<NumericProperty
properties={properties}
propertyName={'massCenterOffsetZ'}
step={1}
onUpdate={newValue =>
updateBehaviorProperty('massCenterOffsetZ', newValue)
}
/>
</ResponsiveLineStackLayout>
</Column>
</AccordionBody>
</Accordion>
</Column>
);
};

View File

@@ -1,5 +1,5 @@
// @flow
import { roundPosition } from '../Utils/GridHelpers';
import { roundPositionsToGrid } from '../Utils/GridHelpers';
import { unserializeFromJSObject } from '../Utils/Serializer';
import { type InstancesEditorSettings } from './InstancesEditorSettings';
const gd: libGDevelop = global.gd;
@@ -9,29 +9,6 @@ type Props = {|
instancesEditorSettings: InstancesEditorSettings,
|};
const roundPositionsToGrid = (
pos: [number, number],
instancesEditorSettings: InstancesEditorSettings
): [number, number] => {
const newPos = pos;
if (instancesEditorSettings.grid && instancesEditorSettings.snap) {
roundPosition(
newPos,
instancesEditorSettings.gridWidth,
instancesEditorSettings.gridHeight,
instancesEditorSettings.gridOffsetX,
instancesEditorSettings.gridOffsetY,
instancesEditorSettings.gridType
);
} else {
newPos[0] = Math.round(newPos[0]);
newPos[1] = Math.round(newPos[1]);
}
return newPos;
};
/**
* Allow to add instances on the scene. Supports "temporary" instances,
* which are real instances but can be deleted as long as they are not "committed".
@@ -56,14 +33,12 @@ export default class InstancesAdder {
position,
copyReferential,
serializedInstances,
preventSnapToGrid = false,
addInstancesInTheForeground = false,
doesObjectExistInContext,
}: {|
position: [number, number],
copyReferential: [number, number],
serializedInstances: Array<Object>,
preventSnapToGrid?: boolean,
addInstancesInTheForeground?: boolean,
doesObjectExistInContext: string => boolean,
|}): Array<gdInitialInstance> => {
@@ -78,18 +53,8 @@ export default class InstancesAdder {
const instance = new gd.InitialInstance();
unserializeFromJSObject(instance, serializedInstance);
if (!doesObjectExistInContext(instance.getObjectName())) return null;
const desiredPosition = [
instance.getX() - copyReferential[0] + position[0],
instance.getY() - copyReferential[1] + position[1],
];
const newPos = preventSnapToGrid
? desiredPosition
: roundPositionsToGrid(
desiredPosition,
this._instancesEditorSettings
);
instance.setX(newPos[0]);
instance.setY(newPos[1]);
instance.setX(instance.getX() - copyReferential[0] + position[0]);
instance.setY(instance.getY() - copyReferential[1] + position[1]);
if (addInstancesInTheForeground) {
if (
addedInstancesLowestZOrder === null ||

View File

@@ -1,5 +1,5 @@
// @flow
import { roundPosition } from '../Utils/GridHelpers';
import { roundPositionsToGrid } from '../Utils/GridHelpers';
import Rectangle from '../Utils/Rectangle';
import { type InstancesEditorSettings } from './InstancesEditorSettings';
import { type InstanceMeasurer } from './InstancesRenderer';
@@ -106,30 +106,15 @@ export default class InstancesMover {
const magnetPosition = this._temporaryPoint;
magnetPosition[0] = initialMagnetX + this.totalDeltaX;
magnetPosition[1] = initialMagnetY + this.totalDeltaY;
if (
this.instancesEditorSettings.snap &&
this.instancesEditorSettings.grid &&
!noGridSnap
) {
roundPosition(
magnetPosition,
this.instancesEditorSettings.gridWidth,
this.instancesEditorSettings.gridHeight,
this.instancesEditorSettings.gridOffsetX,
this.instancesEditorSettings.gridOffsetY,
this.instancesEditorSettings.gridType
);
} else {
// Without a grid, the position is still rounded to the nearest pixel.
// The size of the instance (or selection of instances) might not be round,
// so the magnet corner is still relevant.
magnetPosition[0] = Math.round(magnetPosition[0]);
magnetPosition[1] = Math.round(magnetPosition[1]);
}
roundPositionsToGrid(
magnetPosition,
this.instancesEditorSettings,
noGridSnap
);
const roundedTotalDeltaX = magnetPosition[0] - initialMagnetX;
const roundedTotalDeltaY = magnetPosition[1] - initialMagnetY;
for (var i = 0; i < nonLockedInstances.length; i++) {
for (let i = 0; i < nonLockedInstances.length; i++) {
const selectedInstance = nonLockedInstances[i];
let initialPosition = this.instancePositions[selectedInstance.ptr];
@@ -170,6 +155,16 @@ export default class InstancesMover {
this.totalDeltaY = 0;
}
snapSelection(instances: gdInitialInstance[]): void {
// The snapping doesn't work well on 3D model objects because their default
// dimensions and origin change when the model is loaded from an async call.
this.endMove();
// Force magnet from selection top left corner.
this.startMove(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY);
this.moveBy(instances, 0, 0, false, false);
this.endMove();
}
isMoving() {
return !!this._initialSelectionAABB;
}

View File

@@ -770,13 +770,16 @@ export default class InstancesEditor extends Component<Props, State> {
position: [number, number],
copyReferential: [number, number],
serializedInstances: Array<Object>,
preventSnapToGrid?: boolean,
addInstancesInTheForeground?: boolean,
doesObjectExistInContext: string => boolean,
|}): Array<gdInitialInstance> => {
return this._instancesAdder.addSerializedInstances(options);
};
snapSelection = (instances: gdInitialInstance[]) => {
this.instancesMover.snapSelection(instances);
};
/**
* Immediately add instances for the specified objects at the given
* position (in scene coordinates) given their names.

View File

@@ -191,6 +191,16 @@ const jsExtensions = [
},
];
const getExpectedNumberOfJSExtensionModules = ({
filterExamples,
}: {|
filterExamples: boolean,
|}): number => {
return jsExtensions.filter(
({ name }) => !filterExamples || !name.includes('Example')
).length;
};
type MakeExtensionsLoaderArguments = {|
objectsEditorService: typeof ObjectsEditorService,
objectsRenderingService: typeof ObjectsRenderingService,
@@ -210,52 +220,57 @@ export default function makeExtensionsLoader({
return {
loadAllExtensions(
_: TranslationFunction
): Promise<
Array<{ extensionModulePath: string, result: ExtensionLoadingResult }>
> {
return Promise.resolve(
jsExtensions
.filter(({ name }) => !filterExamples || !name.includes('Example'))
.map(({ name, extensionModule, objectsRenderingServiceModules }) => {
if (
objectsEditorService &&
extensionModule.registerEditorConfigurations
) {
extensionModule.registerEditorConfigurations(
objectsEditorService
);
}
): Promise<{|
results: Array<{|
extensionModulePath: string,
result: ExtensionLoadingResult,
|}>,
expectedNumberOfJSExtensionModulesLoaded: number,
|}> {
const results = jsExtensions
.filter(({ name }) => !filterExamples || !name.includes('Example'))
.map(({ name, extensionModule, objectsRenderingServiceModules }) => {
if (
objectsEditorService &&
extensionModule.registerEditorConfigurations
) {
extensionModule.registerEditorConfigurations(objectsEditorService);
}
if (objectsRenderingService) {
if (objectsRenderingServiceModules) {
for (const requirePath in objectsRenderingServiceModules) {
objectsRenderingService.registerModule(
requirePath,
objectsRenderingServiceModules[requirePath]
);
}
}
if (extensionModule.registerInstanceRenderers) {
extensionModule.registerInstanceRenderers(
objectsRenderingService
if (objectsRenderingService) {
if (objectsRenderingServiceModules) {
for (const requirePath in objectsRenderingServiceModules) {
objectsRenderingService.registerModule(
requirePath,
objectsRenderingServiceModules[requirePath]
);
}
if (extensionModule.registerClearCache) {
extensionModule.registerClearCache(objectsRenderingService);
}
}
if (extensionModule.registerInstanceRenderers) {
extensionModule.registerInstanceRenderers(
objectsRenderingService
);
}
if (extensionModule.registerClearCache) {
extensionModule.registerClearCache(objectsRenderingService);
}
}
return {
extensionModulePath: 'internal-extension://' + name,
result: loadExtension(
_,
gd,
gd.JsPlatform.get(),
extensionModule
),
};
})
return {
extensionModulePath: 'internal-extension://' + name,
result: loadExtension(_, gd, gd.JsPlatform.get(), extensionModule),
};
});
const expectedNumberOfJSExtensionModulesLoaded = getExpectedNumberOfJSExtensionModules(
{
filterExamples,
}
);
return Promise.resolve({
results,
expectedNumberOfJSExtensionModulesLoaded,
});
},
};
}

View File

@@ -17,8 +17,23 @@ type MakeExtensionsLoaderArguments = {|
filterExamples: boolean,
onFindGDJS?: ?() => Promise<{gdjsRoot: string}>
|};
type GetExpectedNumberOfJSExtensionModulesArguments = {|
filterExamples: boolean,
|};
*/
// This value is hardcoded to allow raising an error if the number of JS extensions
// loaded is different from the expected one, which may lead
// to projects corruption in the future if the app is still used.
// If a new extension is added, update this value.
// Also remember to add the extension in the list of extensions in BrowserJsExtensionsLoader.js
function getExpectedNumberOfJSExtensionModules(
{ filterExamples } /*: GetExpectedNumberOfJSExtensionModulesArguments*/
) /*:number*/ {
return 28 + (filterExamples ? 0 : 1);
}
/**
* Loader that will find all JS extensions declared in GDJS/Runtime/Extensions/xxx/JsExtension.js.
* If you add a new extension and also want it to be available for the web-app version, add it in
@@ -97,7 +112,14 @@ module.exports = function makeExtensionsLoader(
),
};
})
);
).then(results => {
return {
results,
expectedNumberOfJSExtensionModulesLoaded: getExpectedNumberOfJSExtensionModules(
{ filterExamples }
),
};
});
},
err => {
console.error(`Unable to find JS extensions modules`);

View File

@@ -10,17 +10,18 @@ export type JsExtensionModule = {
runExtensionSanityTests(gd: any, extension: gdPlatformExtension): Array<string>,
};
export type ExtensionLoadingResult = {
export type ExtensionLoadingResult = {|
error: boolean,
message: string,
dangerous?: boolean,
rawError?: any,
};
|};
export interface JsExtensionsLoader {
loadAllExtensions(_: TranslationFunction): Promise<
Array<{ extensionModulePath: string, result: ExtensionLoadingResult }>
>,
loadAllExtensions(_: TranslationFunction): Promise<{|
results: Array<{| extensionModulePath: string, result: ExtensionLoadingResult |}>,
expectedNumberOfJSExtensionModulesLoaded: number,
|}>,
}
*/

View File

@@ -116,7 +116,9 @@ export const create = (authentication: Authentication) => {
filterExamples: !isDev,
})}
initialFileMetadataToOpen={initialFileMetadataToOpen}
initialExampleSlugToOpen={appArguments['create-from-example'] || null}
initialExampleSlugToOpen={
appArguments['create-from-example'] || null
}
/>
)}
</ProjectStorageProviders>

View File

@@ -188,18 +188,19 @@ export const AiRequestChat = React.forwardRef<Props, AiRequestChatInterface>(
)
}
recommendedPlanIdIfNoSubscription="gdevelop_gold"
canHide
>
<Line>
<Column noMargin>
<Text noMargin>
{increaseQuotaOffering === 'subscribe' ? (
<Trans>
Get more free AI requests with a GDevelop premium plan.
Unlock AI requests included with a GDevelop premium plan.
</Trans>
) : (
<Trans>
Upgrade to another premium plan to get more free AI
requests.
Get even more AI requests included with a higher premium
plan.
</Trans>
)}
</Text>
@@ -232,45 +233,56 @@ export const AiRequestChat = React.forwardRef<Props, AiRequestChatInterface>(
<Trans>What do you want to make?</Trans>
</Text>
</Column>
<Column noMargin alignItems="stretch" justifyContent="stretch">
<CompactTextAreaField
maxLength={6000}
value={userRequestText}
disabled={isLaunchingAiRequest}
onChange={userRequestText =>
setUserRequestText(userRequestText)
}
placeholder={newChatPlaceholder}
rows={5}
/>
</Column>
<Line noMargin>
<ResponsiveLineStackLayout
noMargin
alignItems="flex-start"
justifyContent="space-between"
expand
>
{!isMobile && errorOrQuotaOrCreditsExplanation}
<Line noMargin justifyContent="flex-end">
<LeftLoader reserveSpace isLoading={isLaunchingAiRequest}>
<RaisedButton
color="primary"
label={<Trans>Send</Trans>}
style={{ flexShrink: 0 }}
disabled={isLaunchingAiRequest}
onClick={() => {
onSendUserRequest(userRequestText);
}}
/>
</LeftLoader>
<form
onSubmit={() => {
onSendUserRequest(userRequestText);
}}
>
<ColumnStackLayout justifyContent="center" noMargin>
<Column noMargin alignItems="stretch" justifyContent="stretch">
<CompactTextAreaField
maxLength={6000}
value={userRequestText}
disabled={isLaunchingAiRequest}
onChange={userRequestText =>
setUserRequestText(userRequestText)
}
onSubmit={() => {
onSendUserRequest(userRequestText);
}}
placeholder={newChatPlaceholder}
rows={5}
/>
</Column>
<Line noMargin>
<ResponsiveLineStackLayout
noMargin
alignItems="flex-start"
justifyContent="space-between"
expand
>
{!isMobile && errorOrQuotaOrCreditsExplanation}
<Line noMargin justifyContent="flex-end">
<LeftLoader reserveSpace isLoading={isLaunchingAiRequest}>
<RaisedButton
color="primary"
label={<Trans>Send</Trans>}
style={{ flexShrink: 0 }}
disabled={isLaunchingAiRequest || !userRequestText}
onClick={() => {
onSendUserRequest(userRequestText);
}}
/>
</LeftLoader>
</Line>
{isMobile && errorOrQuotaOrCreditsExplanation}
</ResponsiveLineStackLayout>
</Line>
{isMobile && errorOrQuotaOrCreditsExplanation}
</ResponsiveLineStackLayout>
</Line>
</ColumnStackLayout>
</form>
{subscriptionBanner}
</ColumnStackLayout>
<Column justifyContent="center" noMargin>
<Column justifyContent="center">
<Text size="body-small" color="secondary" align="center" noMargin>
<Trans>
The AI is experimental and still being improved.{' '}
@@ -458,37 +470,52 @@ export const AiRequestChat = React.forwardRef<Props, AiRequestChatInterface>(
) : (
subscriptionBanner
)}
<CompactTextAreaField
maxLength={6000}
value={userRequestText}
disabled={isLaunchingAiRequest}
onChange={userRequestText => setUserRequestText(userRequestText)}
placeholder={t`Ask a follow up question`}
rows={2}
/>
<Column noMargin alignItems="flex-end">
<ResponsiveLineStackLayout
<form
onSubmit={() => {
onSendUserRequest(userRequestText);
}}
>
<ColumnStackLayout
justifyContent="stretch"
alignItems="stretch"
noMargin
alignItems="flex-start"
justifyContent="space-between"
expand
>
{!isMobile && errorOrQuotaOrCreditsExplanation}
<Line noMargin justifyContent="flex-end">
<LeftLoader reserveSpace isLoading={isLaunchingAiRequest}>
<RaisedButton
color="primary"
disabled={aiRequest.status === 'working'}
label={<Trans>Send</Trans>}
onClick={() => {
onSendUserRequest(userRequestText);
}}
/>
</LeftLoader>
</Line>
{isMobile && errorOrQuotaOrCreditsExplanation}
</ResponsiveLineStackLayout>
</Column>
<CompactTextAreaField
maxLength={6000}
value={userRequestText}
disabled={isLaunchingAiRequest}
onChange={userRequestText => setUserRequestText(userRequestText)}
placeholder={t`Ask a follow up question`}
rows={2}
onSubmit={() => {
onSendUserRequest(userRequestText);
}}
/>
<Column noMargin alignItems="flex-end">
<ResponsiveLineStackLayout
noMargin
alignItems="flex-start"
justifyContent="space-between"
expand
>
{!isMobile && errorOrQuotaOrCreditsExplanation}
<Line noMargin justifyContent="flex-end">
<LeftLoader reserveSpace isLoading={isLaunchingAiRequest}>
<RaisedButton
color="primary"
disabled={aiRequest.status === 'working'}
label={<Trans>Send</Trans>}
onClick={() => {
onSendUserRequest(userRequestText);
}}
/>
</LeftLoader>
</Line>
{isMobile && errorOrQuotaOrCreditsExplanation}
</ResponsiveLineStackLayout>
</Column>
</ColumnStackLayout>
</form>
{dislikeFeedbackDialogOpenedFor && (
<DislikeFeedbackDialog
open

View File

@@ -59,6 +59,7 @@ export type AskAiEditorInterface = {|
scene: gdLayout,
objectWithContext: ObjectWithContext
) => void,
onSceneObjectsDeleted: (scene: gdLayout) => void,
|};
const noop = () => {};
@@ -109,6 +110,7 @@ export const AskAi = React.memo<Props>(
forceUpdateEditor: noop,
onEventsBasedObjectChildrenEdited: noop,
onSceneObjectEdited: noop,
onSceneObjectsDeleted: noop,
}));
const aiRequestChatRef = React.useRef<AiRequestChatInterface | null>(

View File

@@ -151,6 +151,7 @@ export type RenderEditorContainerProps = {|
scene: gdLayout,
objectWithContext: ObjectWithContext
) => void,
onSceneObjectsDeleted: (scene: gdLayout) => void,
onExtractAsExternalLayout: (name: string) => void,
onExtractAsEventBasedObject: (

View File

@@ -237,9 +237,15 @@ export class CustomObjectEditorContainer extends React.Component<RenderEditorCon
onObjectEdited={() =>
this.props.onEventsBasedObjectChildrenEdited(eventsBasedObject)
}
onObjectsDeleted={() =>
this.props.onEventsBasedObjectChildrenEdited(eventsBasedObject)
}
onObjectGroupEdited={() =>
this.props.onEventsBasedObjectChildrenEdited(eventsBasedObject)
}
onObjectGroupsDeleted={() =>
this.props.onEventsBasedObjectChildrenEdited(eventsBasedObject)
}
onEventsBasedObjectChildrenEdited={
this.props.onEventsBasedObjectChildrenEdited
}

View File

@@ -57,6 +57,10 @@ export class DebuggerEditorContainer extends React.Component<
// No thing to be done.
}
onSceneObjectsDeleted(scene: gdLayout) {
// No thing to be done.
}
// To be updated, see https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops.
UNSAFE_componentWillReceiveProps() {
this._checkUserHasSubscription();

View File

@@ -53,6 +53,10 @@ export class EventsEditorContainer extends React.Component<RenderEditorContainer
// No thing to be done.
}
onSceneObjectsDeleted(scene: gdLayout) {
// No thing to be done.
}
getLayout(): ?gdLayout {
const { project, projectItemName } = this.props;
if (

View File

@@ -46,6 +46,10 @@ export class EventsFunctionsExtensionEditorContainer extends React.Component<Ren
// No thing to be done.
}
onSceneObjectsDeleted(scene: gdLayout) {
// No thing to be done.
}
shouldComponentUpdate(nextProps: RenderEditorContainerProps) {
// We stop updates when the component is inactive.
// If it's active, was active or becoming active again we let update propagate.

View File

@@ -90,6 +90,10 @@ export class ExternalEventsEditorContainer extends React.Component<
// No thing to be done.
}
onSceneObjectsDeleted(scene: gdLayout) {
// No thing to be done.
}
getExternalEvents(): ?gdExternalEvents {
const { project, projectItemName } = this.props;
if (!project || !projectItemName) return null;

View File

@@ -138,6 +138,20 @@ export class ExternalLayoutEditorContainer extends React.Component<
}
}
onSceneObjectsDeleted(scene: gdLayout) {
const { editor } = this;
const externalLayout = this.getExternalLayout();
if (!externalLayout) {
return;
}
if (externalLayout.getAssociatedLayout() !== scene.getName()) {
return;
}
if (editor) {
editor.forceUpdateObjectsList();
}
}
getExternalLayout(): ?gdExternalLayout {
const { project, projectItemName } = this.props;
if (!project || !projectItemName) return null;
@@ -266,8 +280,10 @@ export class ExternalLayoutEditorContainer extends React.Component<
onObjectEdited={objectWithContext =>
this.props.onSceneObjectEdited(layout, objectWithContext)
}
onObjectsDeleted={() => this.props.onSceneObjectsDeleted(layout)}
// It's only used to refresh events-based object variants.
onObjectGroupEdited={() => {}}
onObjectGroupsDeleted={() => {}}
// Nothing to do as events-based objects can't have external layout.
onEventsBasedObjectChildrenEdited={() => {}}
onExtensionInstalled={this.props.onExtensionInstalled}

View File

@@ -47,21 +47,17 @@ const GamesPlatformFrame = ({ initialGameId, loaded, visible }: Props) => {
const url = new URL(
gameId.current
? `/app-embedded/${gamesPlatformEmbeddedVersion}/games/${gameId.current}`
: isMobile
? // On mobile, go directly to a random game if none is specified.
`/app-embedded/${gamesPlatformEmbeddedVersion}/games/random`
: // On desktop, access the homepage.
`/app-embedded/${gamesPlatformEmbeddedVersion}/${paletteType}`,
: `/app-embedded/${gamesPlatformEmbeddedVersion}/${paletteType}`,
gdGamesHost
);
if (gameId.current || isMobile) url.searchParams.set('theme', paletteType);
if (gameId.current) url.searchParams.set('theme', paletteType);
const src = loaded ? url.toString() : '';
React.useEffect(
() => {
if (!loaded && initialGameId) {
// Every time the frame is unloaded on a gameId, we reset it for the next load.
if (!loaded) {
// Every time the frame is unloaded, we reset it for the next load.
gameId.current = initialGameId;
}
},

View File

@@ -169,6 +169,7 @@ export type HomePageEditorInterface = {|
scene: gdLayout,
objectWithContext: ObjectWithContext
) => void,
onSceneObjectsDeleted: (scene: gdLayout) => void,
|};
export const HomePage = React.memo<Props>(
@@ -482,12 +483,17 @@ export const HomePage = React.memo<Props>(
[]
);
const onSceneObjectsDeleted = React.useCallback((scene: gdLayout) => {
// No thing to be done.
}, []);
React.useImperativeHandle(ref, () => ({
getProject,
updateToolbar,
forceUpdateEditor,
onEventsBasedObjectChildrenEdited,
onSceneObjectEdited,
onSceneObjectsDeleted,
}));
const onUserSurveyStarted = React.useCallback(() => {

View File

@@ -41,6 +41,10 @@ export class ResourcesEditorContainer extends React.Component<RenderEditorContai
// No thing to be done.
}
onSceneObjectsDeleted(scene: gdLayout) {
// No thing to be done.
}
componentDidUpdate(prevProps: RenderEditorContainerProps) {
if (
this.editor &&

View File

@@ -79,6 +79,20 @@ export class SceneEditorContainer extends React.Component<RenderEditorContainerP
}
}
onSceneObjectsDeleted(scene: gdLayout) {
const layout = this.getLayout();
if (!layout) {
return;
}
if (layout !== scene) {
return;
}
const { editor } = this;
if (editor) {
editor.forceUpdateObjectsList();
}
}
getLayout(): ?gdLayout {
const { project, projectItemName } = this.props;
if (
@@ -160,8 +174,10 @@ export class SceneEditorContainer extends React.Component<RenderEditorContainerP
onObjectEdited={objectWithContext =>
this.props.onSceneObjectEdited(layout, objectWithContext)
}
onObjectsDeleted={() => this.props.onSceneObjectsDeleted(layout)}
// It's only used to refresh events-based object variants.
onObjectGroupEdited={() => {}}
onObjectGroupsDeleted={() => {}}
// Nothing to do as scenes are not events-based objects.
onEventsBasedObjectChildrenEdited={() => {}}
/>

View File

@@ -203,6 +203,7 @@ import useHomepageWitchForRouting from './UseHomepageWitchForRouting';
import RobotIcon from '../ProjectCreation/RobotIcon';
import PublicProfileContext from '../Profile/PublicProfileContext';
import { useGamesPlatformFrame } from './EditorContainers/HomePage/PlaySection/UseGamesPlatformFrame';
import { useExtensionLoadErrorDialog } from '../Utils/UseExtensionLoadErrorDialog';
const GD_STARTUP_TIMES = global.GD_STARTUP_TIMES || [];
@@ -371,9 +372,10 @@ const MainFrame = (props: Props) => {
chooseResourceOptions,
setChooseResourceOptions,
] = React.useState<?ChooseResourceOptions>(null);
const [onResourceChosen, setOnResourceChosen] = React.useState<?(
Array<gdResource>
) => void>(null);
const [onResourceChosen, setOnResourceChosen] = React.useState<?({|
selectedResources: Array<gdResource>,
selectedSourceName: string,
|}) => void>(null);
const _previewLauncher = React.useRef((null: ?PreviewLauncherInterface));
const forceUpdate = useForceUpdate();
const [isLoadingProject, setIsLoadingProject] = React.useState<boolean>(
@@ -551,6 +553,12 @@ const MainFrame = (props: Props) => {
gamesList,
});
const {
setExtensionLoadingResults,
hasExtensionLoadErrors,
renderExtensionLoadErrorDialog,
} = useExtensionLoadErrorDialog();
/**
* This reference is useful to get the current opened project,
* even in the callback of a hook/promise - without risking to read "stale" data.
@@ -808,36 +816,26 @@ const MainFrame = (props: Props) => {
return extensionsLoader
.loadAllExtensions(getNotNullTranslationFunction(i18n))
.then(loadingResults => {
const successLoadingResults = loadingResults.filter(
loadingResult => !loadingResult.result.error
);
const failLoadingResults = loadingResults.filter(
loadingResult =>
loadingResult.result.error && !loadingResult.result.dangerous
);
const dangerousLoadingResults = loadingResults.filter(
loadingResult =>
loadingResult.result.error && loadingResult.result.dangerous
);
console.info(`Loaded ${successLoadingResults.length} JS extensions.`);
if (failLoadingResults.length) {
console.error(
`⚠️ Unable to load ${
failLoadingResults.length
} JS extensions. Please check these errors:`,
failLoadingResults
.then(
({
expectedNumberOfJSExtensionModulesLoaded,
results: loadingResults,
}) => {
const successLoadingResults = loadingResults.filter(
loadingResult => !loadingResult.result.error
);
}
if (dangerousLoadingResults.length) {
console.error(
`💣 Dangerous exceptions while loading ${
dangerousLoadingResults.length
} JS extensions. 🔥 Please check these errors as they will CRASH GDevelop:`,
dangerousLoadingResults
console.info(
`Loaded ${
successLoadingResults.length
}/${expectedNumberOfJSExtensionModulesLoaded} JS extensions.`
);
setExtensionLoadingResults({
expectedNumberOfJSExtensionModulesLoaded,
results: loadingResults,
});
}
});
);
};
useDiscordRichPresence(currentProject);
@@ -2352,6 +2350,18 @@ const MainFrame = (props: Props) => {
[state.editorTabs]
);
const onSceneObjectsDeleted = React.useCallback(
(scene: gdLayout) => {
for (const editor of state.editorTabs.editors) {
const { editorRef } = editor;
if (editorRef) {
editorRef.onSceneObjectsDeleted(scene);
}
}
},
[state.editorTabs]
);
const _onProjectItemModified = () => {
triggerUnsavedChanges();
forceUpdate();
@@ -2715,6 +2725,9 @@ const MainFrame = (props: Props) => {
|}
) => {
if (!currentProject) return;
// Prevent saving if there are errors in the extension modules, as
// this can lead to corrupted projects.
if (hasExtensionLoadErrors) return;
saveUiSettings(state.editorTabs);
@@ -2933,6 +2946,7 @@ const MainFrame = (props: Props) => {
showAlert,
showConfirmation,
gamesList,
hasExtensionLoadErrors,
]
);
@@ -2944,6 +2958,9 @@ const MainFrame = (props: Props) => {
if (!canSaveProjectAs) {
return;
}
// Prevent saving if there are errors in the extension modules, as
// this can lead to corrupted projects.
if (hasExtensionLoadErrors) return;
if (cloudProjectRecoveryOpenedVersionId && !cloudProjectSaveChoiceOpen) {
setCloudProjectSaveChoiceOpen(true);
@@ -2970,12 +2987,17 @@ const MainFrame = (props: Props) => {
cloudProjectRecoveryOpenedVersionId,
cloudProjectSaveChoiceOpen,
canSaveProjectAs,
hasExtensionLoadErrors,
]
);
const saveProject = React.useCallback(
async () => {
if (!currentProject) return;
// Prevent saving if there are errors in the extension modules, as
// this can lead to corrupted projects.
if (hasExtensionLoadErrors) return;
if (!currentFileMetadata) {
return saveProjectAs();
}
@@ -3135,6 +3157,7 @@ const MainFrame = (props: Props) => {
showConfirmation,
checkedOutVersionStatus,
gamesList,
hasExtensionLoadErrors,
]
);
@@ -3321,9 +3344,11 @@ const MainFrame = (props: Props) => {
(options: ChooseResourceOptions) => {
return new Promise(resolve => {
setChooseResourceOptions(options);
const onResourceChosenSetter: () => (
Promise<Array<gdResource>> | Array<gdResource>
) => void = () => resolve;
const onResourceChosenSetter: () => ({|
selectedResources: Array<gdResource>,
selectedSourceName: string,
|}) => void = () => resolve;
setOnResourceChosen(onResourceChosenSetter);
});
},
@@ -4035,6 +4060,7 @@ const MainFrame = (props: Props) => {
onDeleteEventsBasedObjectVariant: deleteEventsBasedObjectVariant,
onEventsBasedObjectChildrenEdited: onEventsBasedObjectChildrenEdited,
onSceneObjectEdited: onSceneObjectEdited,
onSceneObjectsDeleted: onSceneObjectsDeleted,
onExtensionInstalled: onExtensionInstalled,
gamesList,
gamesPlatformFrameTools,
@@ -4098,15 +4124,18 @@ const MainFrame = (props: Props) => {
getStorageProvider={getStorageProvider}
i18n={i18n}
resourceSources={resourceSources}
onChooseResources={resources => {
onChooseResources={resourcesOptions => {
setOnResourceChosen(null);
setChooseResourceOptions(null);
onResourceChosen(resources);
onResourceChosen(resourcesOptions);
}}
onClose={() => {
setOnResourceChosen(null);
setChooseResourceOptions(null);
onResourceChosen([]);
onResourceChosen({
selectedResources: [],
selectedSourceName: '',
});
}}
options={chooseResourceOptions}
/>
@@ -4198,6 +4227,7 @@ const MainFrame = (props: Props) => {
{renderResourceFetcherDialog()}
{renderVersionHistoryPanel()}
{renderSaveReminder()}
{renderExtensionLoadErrorDialog()}
<CloseConfirmDialog
shouldPrompt={!!state.currentProject}
i18n={props.i18n}

View File

@@ -233,8 +233,9 @@ const Cube3DEditor = ({
!hasLight(layout) && (
<AlertMessage kind="error">
<Trans>
Make sure to set up a light in the effects of the layer or chose
"No lighting effect" - otherwise the object will appear black.
Make sure to set up a light in the effects of the layer or
choose "No lighting effect" - otherwise the object will appear
black.
</Trans>
</AlertMessage>
)}

View File

@@ -79,7 +79,7 @@ const getVariantName = (
? customObjectConfiguration.getVariantName()
: '';
const getVariant = (
export const getVariant = (
eventBasedObject: gdEventsBasedObject,
customObjectConfiguration: gdCustomObjectConfiguration
): gdEventsBasedObjectVariant => {

View File

@@ -442,34 +442,41 @@ const AnimationList = React.forwardRef<
);
const importImages = React.useCallback(
async (resourceSource: ResourceSource) => {
const resources = await resourceManagementProps.onChooseResource({
initialSourceName: resourceSource.name,
async (initialResourceSource: ResourceSource) => {
const {
selectedResources,
selectedSourceName,
} = await resourceManagementProps.onChooseResource({
initialSourceName: initialResourceSource.name,
multiSelection: true,
resourceKind: 'image',
});
if (resources.length === 0) {
return;
}
if (resourceSource.shouldCreateResource) {
resources.forEach(resource => {
if (!selectedResources.length) return;
const selectedResourceSource = resourceSources.find(
source => source.name === selectedSourceName
);
if (!selectedResourceSource) return;
if (selectedResourceSource.shouldCreateResource) {
selectedResources.forEach(resource => {
applyResourceDefaults(project, resource);
project.getResourcesManager().addResource(resource);
});
const resourcesByAnimation = resourceSource.shouldGuessAnimationsFromName
? groupResourcesByAnimations(resources)
const resourcesByAnimation = selectedResourceSource.shouldGuessAnimationsFromName
? groupResourcesByAnimations(selectedResources)
: new Map<string, Array<gdResource>>();
addAnimations(resourcesByAnimation);
// Important, we are responsible for deleting the resources that were given to us.
// Otherwise we have a memory leak, as calling addResource is making a copy of the resource.
resources.forEach(resource => resource.delete());
selectedResources.forEach(resource => resource.delete());
await resourceManagementProps.onFetchNewlyAddedResources();
} else {
const resourcesByAnimation = new Map<string, Array<gdResource>>();
resourcesByAnimation.set('default', resources);
resourcesByAnimation.set('default', selectedResources);
addAnimations(resourcesByAnimation);
}
@@ -485,6 +492,7 @@ const AnimationList = React.forwardRef<
adaptCollisionMaskIfNeeded,
onObjectUpdated,
project,
resourceSources,
]
);

View File

@@ -300,6 +300,15 @@ const SpritesList = ({
const forceUpdate = useForceUpdate();
const { showConfirmation } = useAlertDialog();
const storageProvider = resourceManagementProps.getStorageProvider();
const resourceSources = resourceManagementProps.resourceSources
.filter(source => source.kind === 'image')
.filter(
({ onlyForStorageProvider }) =>
!onlyForStorageProvider ||
onlyForStorageProvider === storageProvider.internalName
);
const updateSelectionIndexesAfterMoveUp = React.useCallback(
(oldIndex: number, newIndex: number, wasMovedItemSelected: boolean) => {
for (let i = oldIndex; i <= newIndex; ++i) {
@@ -385,16 +394,25 @@ const SpritesList = ({
);
const onAddSprite = React.useCallback(
async (resourceSource: ResourceSource) => {
async (initialResourceSource: ResourceSource) => {
const directionSpritesCountBeforeAdding = direction.getSpritesCount();
const resources = await resourceManagementProps.onChooseResource({
initialSourceName: resourceSource.name,
const {
selectedResources,
selectedSourceName,
} = await resourceManagementProps.onChooseResource({
initialSourceName: initialResourceSource.name,
multiSelection: true,
resourceKind: 'image',
});
if (resourceSource.shouldCreateResource) {
resources.forEach(resource => {
if (!selectedResources.length) return;
const selectedResourceSource = resourceSources.find(
source => source.name === selectedSourceName
);
if (!selectedResourceSource) return;
if (selectedResourceSource.shouldCreateResource) {
selectedResources.forEach(resource => {
applyResourceDefaults(project, resource);
project.getResourcesManager().addResource(resource);
});
@@ -402,10 +420,12 @@ const SpritesList = ({
if (
directionSpritesCountBeforeAdding === 0 &&
resources.length > 1 &&
resourceSource.shouldGuessAnimationsFromName
selectedResources.length > 1 &&
selectedResourceSource.shouldGuessAnimationsFromName
) {
const resourcesByAnimation = groupResourcesByAnimations(resources);
const resourcesByAnimation = groupResourcesByAnimations(
selectedResources
);
if (resourcesByAnimation.size > 1) {
addAnimations(resourcesByAnimation);
} else {
@@ -417,22 +437,22 @@ const SpritesList = ({
}
}
} else {
for (const resource of resources) {
for (const resource of selectedResources) {
addAnimationFrame(animations, direction, resource, onSpriteAdded);
}
}
if (resourceSource.shouldCreateResource) {
if (selectedResourceSource.shouldCreateResource) {
// Important, we are responsible for deleting the resources that were given to us.
// Otherwise we have a memory leak, as calling addResource is making a copy of the resource.
resources.forEach(resource => resource.delete());
selectedResources.forEach(resource => resource.delete());
}
forceUpdate();
await resourceManagementProps.onFetchNewlyAddedResources();
if (resources.length && onSpriteUpdated) onSpriteUpdated();
if (selectedResources.length && onSpriteUpdated) onSpriteUpdated();
if (directionSpritesCountBeforeAdding === 0 && onFirstSpriteUpdated) {
// If there was no sprites before, we can assume the first sprite was added.
onFirstSpriteUpdated();
@@ -448,6 +468,7 @@ const SpritesList = ({
addAnimations,
animations,
onSpriteAdded,
resourceSources,
]
);
@@ -561,15 +582,6 @@ const SpritesList = ({
[selectUniqueSprite]
);
const storageProvider = resourceManagementProps.getStorageProvider();
const resourceSources = resourceManagementProps.resourceSources
.filter(source => source.kind === 'image')
.filter(
({ onlyForStorageProvider }) =>
!onlyForStorageProvider ||
onlyForStorageProvider === storageProvider.internalName
);
return (
<ColumnStackLayout noMargin>
<DirectionTools
@@ -590,12 +602,11 @@ const SpritesList = ({
resourcesLoader={resourcesLoader}
direction={direction}
project={project}
onSortEnd={onSortEnd}
onAddSprite={onAddSprite}
resourceManagementProps={resourceManagementProps}
selectedSprites={selectedSprites.current}
onSelectSprite={addSpriteToSelection}
onOpenSpriteContextMenu={openSpriteContextMenu}
onSortEnd={onSortEnd}
helperClass="sortable-helper"
lockAxis="x"
axis="x"

View File

@@ -19,6 +19,7 @@ import {
import { type ObjectEditorTab } from '../ObjectEditor/ObjectEditorDialog';
import type { ObjectWithContext } from '../ObjectsList/EnumerateObjects';
import { type HTMLDataset } from '../Utils/HTMLDataset';
import { getVariant } from '../ObjectEditor/Editors/CustomObjectPropertiesEditor';
const gd: libGDevelop = global.gd;
@@ -370,6 +371,11 @@ export class ObjectTreeViewItemContent implements TreeViewItemContent {
project.hasEventsBasedObject(object.getType())
? {
label: i18n._(t`Edit children`),
enabled:
getVariant(
project.getEventsBasedObject(object.getType()),
gd.asCustomObjectConfiguration(object.getConfiguration())
).getAssetStoreAssetId() === '',
click: () => {
const customObjectConfiguration = gd.asCustomObjectConfiguration(
object.getConfiguration()

View File

@@ -195,20 +195,29 @@ export default class RenderedCustomObjectInstance extends Rendered3DInstance
let renderedInstance = this.renderedInstances.get(instance.ptr);
if (!renderedInstance) {
// No renderer associated yet, the instance must have been just created!...
const customObjectConfiguration = gd.asCustomObjectConfiguration(
this._associatedObjectConfiguration
);
let childObjectConfiguration = null;
const variant = this.getVariant();
if (variant) {
const childObjects = variant.getObjects();
if (childObjects.hasObjectNamed(instance.getObjectName())) {
const childObject = childObjects.getObject(instance.getObjectName());
childObjectConfiguration = childObject.getConfiguration();
childObjectConfiguration =
this.eventBasedObject &&
customObjectConfiguration.isMarkedAsOverridingEventsBasedObjectChildrenConfiguration() &&
variant === this.eventBasedObject.getDefaultVariant()
? customObjectConfiguration.getChildObjectConfiguration(
instance.getObjectName()
)
: childObject.getConfiguration();
}
}
// Apply property mapping rules on the child instance.
const childPropertyOverridings = new Map<string, string>();
const customObjectConfiguration = gd.asCustomObjectConfiguration(
this._associatedObjectConfiguration
);
const customObjectProperties = customObjectConfiguration.getProperties();
for (const propertyMappingRule of this._propertyMappingRules) {
if (propertyMappingRule.targetChild !== instance.getObjectName()) {

View File

@@ -192,7 +192,7 @@ export default class RenderedTextInstance extends RenderedInstance {
this._styleFontDirty = false;
}
if (this._instance.hasCustomSize()) {
if (this._instance.hasCustomSize() && this._pixiObject.width !== 0) {
const alignmentX =
this._textAlignment === 'right'
? 1

View File

@@ -14,8 +14,11 @@ import CrownShining from '../../UI/CustomSvgIcons/CrownShining';
import { useResponsiveWindowSize } from '../../UI/Responsive/ResponsiveWindowMeasurer';
import AuthenticatedUserContext from '../AuthenticatedUserContext';
import { hasValidSubscriptionPlan } from '../../Utils/GDevelopServices/Usage';
import IconButton from '../../UI/IconButton';
import Cross from '../../UI/CustomSvgIcons/Cross';
const styles = {
topRightHideButton: { position: 'absolute', right: 1, top: 1 },
paper: {
zIndex: 2, // Make sure the paper is above the background for the border effect.
flex: 1,
@@ -49,6 +52,7 @@ type Props = {|
| 'gdevelop_gold'
| 'gdevelop_startup'
| 'gdevelop_education',
canHide?: boolean,
|};
const GetSubscriptionCard = ({
@@ -61,7 +65,9 @@ const GetSubscriptionCard = ({
forceColumnLayout,
filter,
recommendedPlanIdIfNoSubscription,
canHide,
}: Props) => {
const [isHidden, setIsHidden] = React.useState(false);
const { subscription } = React.useContext(AuthenticatedUserContext);
const actualPlanIdToRecommend = hasValidSubscriptionPlan(subscription)
? // If the user already has a subscription, show the original subscription dialog.
@@ -72,6 +78,9 @@ const GetSubscriptionCard = ({
);
const { isMobile } = useResponsiveWindowSize();
const columnLayout = forceColumnLayout || isMobile;
if (isHidden) return null;
return (
<div className={classes.premiumContainer}>
<Paper style={styles.paper} background="medium">
@@ -117,6 +126,19 @@ const GetSubscriptionCard = ({
</ResponsiveLineStackLayout>
</Column>
</Line>
{canHide && (
<div style={styles.topRightHideButton}>
<IconButton
aria-label="hide"
onClick={() => {
setIsHidden(true);
}}
size="small"
>
<Cross fontSize="small" />
</IconButton>
</div>
)}
</Paper>
</div>
);

View File

@@ -292,7 +292,7 @@ const propertyKeywordCouples: Array<Array<string>> = [
['Width', 'Height', 'Depth'],
['Top', 'Bottom'],
['Left', 'Right'],
['Front', 'Back'],
['Back', 'Front'],
['Up', 'Down'],
['Min', 'Max'],
['Low', 'High'],
@@ -305,6 +305,12 @@ const propertyKeywordCouples: Array<Array<string>> = [
['JumpSpeed', 'JumpSustainTime'],
['XGrabTolerance', 'YGrabOffset'],
['MaxSpeed', 'SlopeMaxAngle'],
['Beginning', 'End'],
['Start', 'End'],
['Rear', 'Front'],
['1', '2'],
['3', '4'],
['5', '6'],
];
const uncapitalize = str => {

View File

@@ -61,30 +61,6 @@ const ResourcePropertiesEditor = React.forwardRef<
const forceUpdate = useForceUpdate();
React.useImperativeHandle(ref, () => ({ forceUpdate }));
const chooseResourcePath = React.useCallback(
async (resourceSource: ResourceSource) => {
const resource = resources[0];
const newResources = await resourceManagementProps.onChooseResource({
initialSourceName: resourceSource.name,
multiSelection: false,
resourceKind: resource.getKind(),
});
if (!newResources.length) return; // No path was chosen by the user.
resource.setFile(newResources[0].getFile());
// Important, we are responsible for deleting the resources that were given to us.
// Otherwise we have a memory leak.
newResources.forEach(resource => resource.delete());
onResourcePathUpdated();
forceUpdate();
await resourceManagementProps.onFetchNewlyAddedResources();
},
[resourceManagementProps, resources, onResourcePathUpdated, forceUpdate]
);
const resourceSources = React.useMemo(
() => {
const storageProvider = resourceManagementProps.getStorageProvider();
@@ -102,6 +78,44 @@ const ResourcePropertiesEditor = React.forwardRef<
[resourceManagementProps, resources]
);
const chooseResourcePath = React.useCallback(
async (initialResourceSource: ResourceSource) => {
const resource = resources[0];
const {
selectedResources,
selectedSourceName,
} = await resourceManagementProps.onChooseResource({
initialSourceName: initialResourceSource.name,
multiSelection: false,
resourceKind: resource.getKind(),
});
if (!selectedResources.length) return; // No path was chosen by the user.
const selectedResourceSource = resourceSources.find(
source => source.name === selectedSourceName
);
if (!selectedResourceSource) return;
resource.setFile(selectedResources[0].getFile());
// Important, we are responsible for deleting the resources that were given to us.
// Otherwise we have a memory leak.
selectedResources.forEach(resource => resource.delete());
onResourcePathUpdated();
forceUpdate();
await resourceManagementProps.onFetchNewlyAddedResources();
},
[
resourceManagementProps,
resources,
onResourcePathUpdated,
forceUpdate,
resourceSources,
]
);
const schema: Schema = React.useMemo(
() => [
{

View File

@@ -176,33 +176,42 @@ export const UrlChooser = ({
};
const browserResourceSources: Array<ResourceSource> = [
...allResourceKindsAndMetadata.map(({ kind, createNewResource }) => ({
name: `upload-${kind}`,
displayName: t`File(s) from your device`,
displayTab: 'import',
shouldCreateResource: true,
shouldGuessAnimationsFromName: true,
kind,
renderComponent: (props: ResourceSourceComponentProps) => (
<FileToCloudProjectResourceUploader
createNewResource={createNewResource}
onChooseResources={props.onChooseResources}
options={props.options}
fileMetadata={props.fileMetadata}
getStorageProvider={props.getStorageProvider}
key={`url-chooser-${kind}`}
automaticallyOpenInput={!!props.automaticallyOpenIfPossible}
/>
),
})),
...allResourceKindsAndMetadata.map(({ kind, createNewResource }) => {
const sourceName = `upload-${kind}`;
return {
name: sourceName,
displayName: t`File(s) from your device`,
displayTab: 'import',
shouldCreateResource: true,
shouldGuessAnimationsFromName: true,
kind,
renderComponent: (props: ResourceSourceComponentProps) => (
<FileToCloudProjectResourceUploader
createNewResource={createNewResource}
onChooseResources={(resources: Array<gdResource>) =>
props.onChooseResources({
selectedResources: resources,
selectedSourceName: sourceName,
})
}
options={props.options}
fileMetadata={props.fileMetadata}
getStorageProvider={props.getStorageProvider}
key={`url-chooser-${kind}`}
automaticallyOpenInput={!!props.automaticallyOpenIfPossible}
/>
),
};
}),
...resourcesKindSupportedByResourceStore
.map(kind => {
const source = allResourceKindsAndMetadata.find(
resourceSource => resourceSource.kind === kind
);
if (!source) return null;
const sourceName = `resource-store-${kind}`;
return {
name: `resource-store-${kind}`,
name: sourceName,
displayName: t`Choose from asset store`,
displayTab: 'standalone',
shouldCreateResource: true,
@@ -246,70 +255,87 @@ const browserResourceSources: Array<ResourceSource> = [
newResource.setName(resourceCleanedName);
newResource.setOrigin('gdevelop-asset-store', chosenResourceUrl);
onChooseResources([newResource]);
onChooseResources({
selectedResources: [newResource],
selectedSourceName: sourceName,
});
}}
/>
),
};
})
.filter(Boolean),
...allResourceKindsAndMetadata.map(({ kind, createNewResource }) => ({
name: `project-resources-${kind}`,
displayName: t`Project resources`,
displayTab: 'standalone',
shouldCreateResource: false,
shouldGuessAnimationsFromName: false,
hideInResourceEditor: true,
kind,
renderComponent: (props: ResourceSourceComponentProps) => (
<ProjectResourcesChooser
project={props.project}
onResourcesSelected={props.onResourcesSelected}
resourceKind={kind}
key={`project-resources-${kind}`}
multiSelection={props.options.multiSelection}
/>
),
renderPrimaryAction: ({
selectedResources,
onChooseResources,
}: ResourceSourceComponentPrimaryActionProps) => (
<DialogPrimaryButton
primary
key="select-resources"
label={
!selectedResources ||
!selectedResources.length ||
selectedResources.length === 1 ? (
<Trans>Select resource</Trans>
) : (
<Trans>Select {selectedResources.length} resources</Trans>
)
}
disabled={!selectedResources || !selectedResources.length}
onClick={() => {
if (!selectedResources || !selectedResources.length) return;
onChooseResources(selectedResources);
}}
/>
),
})),
...allResourceKindsAndMetadata.map(({ kind, createNewResource }) => ({
name: `url-chooser-${kind}`,
displayName: t`Use a public URL`,
displayTab: 'import-advanced',
shouldCreateResource: true,
shouldGuessAnimationsFromName: false,
kind,
renderComponent: (props: ResourceSourceComponentProps) => (
<UrlChooser
createNewResource={createNewResource}
onChooseResources={props.onChooseResources}
options={props.options}
key={`url-chooser-${kind}`}
/>
),
})),
...allResourceKindsAndMetadata.map(({ kind, createNewResource }) => {
const sourceName = `project-resources-${kind}`;
return {
name: sourceName,
displayName: t`Project resources`,
displayTab: 'standalone',
shouldCreateResource: false,
shouldGuessAnimationsFromName: false,
hideInResourceEditor: true,
kind,
renderComponent: (props: ResourceSourceComponentProps) => (
<ProjectResourcesChooser
project={props.project}
onResourcesSelected={props.onResourcesSelected}
resourceKind={kind}
key={`project-resources-${kind}`}
multiSelection={props.options.multiSelection}
/>
),
renderPrimaryAction: ({
selectedResources,
onChooseResources,
}: ResourceSourceComponentPrimaryActionProps) => (
<DialogPrimaryButton
primary
key="select-resources"
label={
!selectedResources ||
!selectedResources.length ||
selectedResources.length === 1 ? (
<Trans>Select resource</Trans>
) : (
<Trans>Select {selectedResources.length} resources</Trans>
)
}
disabled={!selectedResources || !selectedResources.length}
onClick={() => {
if (!selectedResources || !selectedResources.length) return;
onChooseResources({
selectedResources,
selectedSourceName: sourceName,
});
}}
/>
),
};
}),
...allResourceKindsAndMetadata.map(({ kind, createNewResource }) => {
const sourceName = `url-chooser-${kind}`;
return {
name: sourceName,
displayName: t`Use a public URL`,
displayTab: 'import-advanced',
shouldCreateResource: true,
shouldGuessAnimationsFromName: false,
kind,
renderComponent: (props: ResourceSourceComponentProps) => (
<UrlChooser
createNewResource={createNewResource}
onChooseResources={(resources: Array<gdResource>) =>
props.onChooseResources({
selectedResources: resources,
selectedSourceName: sourceName,
})
}
options={props.options}
key={`url-chooser-${kind}`}
/>
),
};
}),
];
export default browserResourceSources;

View File

@@ -56,6 +56,15 @@ export const CompactResourceSelectorWithThumbnail = ({
const displayThumbnail = resourcesKindsWithThumbnail.includes(resourceKind);
const idToUse = React.useRef<string>(id || makeTimestampedId());
const storageProvider = resourceManagementProps.getStorageProvider();
const resourceSources = resourceManagementProps.resourceSources
.filter(source => source.kind === resourceKind)
.filter(
({ onlyForStorageProvider }) =>
!onlyForStorageProvider ||
onlyForStorageProvider === storageProvider.internalName
);
// TODO: move in a hook?
const { showConfirmation } = useAlertDialog();
const abortControllerRef = React.useRef<?AbortController>(null);
@@ -72,22 +81,30 @@ export const CompactResourceSelectorWithThumbnail = ({
// TODO: move in a hook?
const addFrom = React.useCallback(
async (source: ResourceSource) => {
async (initialResourceSource: ResourceSource) => {
try {
if (!source) return;
if (!initialResourceSource) return;
const resources = await resourceManagementProps.onChooseResource({
initialSourceName: source.name,
const {
selectedResources,
selectedSourceName,
} = await resourceManagementProps.onChooseResource({
initialSourceName: initialResourceSource.name,
multiSelection: false,
resourceKind: resourceKind,
});
if (!resources.length) return;
const resource = resources[0];
if (!selectedResources.length) return;
const selectedResourceSource = resourceSources.find(
source => source.name === selectedSourceName
);
if (!selectedResourceSource) return;
const resource = selectedResources[0];
const resourceName: string = resource.getName();
if (source.shouldCreateResource) {
if (selectedResourceSource.shouldCreateResource) {
applyResourceDefaults(project, resource);
// addResource will check if a resource with the same name exists, and if it is
@@ -96,7 +113,7 @@ export const CompactResourceSelectorWithThumbnail = ({
// Important, we are responsible for deleting the resources that were given to us.
// Otherwise we have a memory leak, as calling addResource is making a copy of the resource.
resources.forEach(resource => resource.delete());
selectedResources.forEach(resource => resource.delete());
await resourceManagementProps.onFetchNewlyAddedResources();
triggerResourcesHaveChanged();
@@ -114,6 +131,7 @@ export const CompactResourceSelectorWithThumbnail = ({
resourceKind,
onChange,
triggerResourcesHaveChanged,
resourceSources,
]
);
@@ -215,17 +233,6 @@ export const CompactResourceSelectorWithThumbnail = ({
externalEditor => externalEditor.kind === resourceKind
);
const storageProvider = resourceManagementProps.getStorageProvider();
// TODO: move in a hook?
const resourceSources = resourceManagementProps.resourceSources
.filter(source => source.kind === resourceKind)
.filter(
({ onlyForStorageProvider }) =>
!onlyForStorageProvider ||
onlyForStorageProvider === storageProvider.internalName
);
const isResourceSetButInvalid =
resourceName && !project.getResourcesManager().hasResource(resourceName);

View File

@@ -22,14 +22,14 @@ import Paper from '../UI/Paper';
import GDevelopThemeContext from '../UI/Theme/GDevelopThemeContext';
import RaisedButton from '../UI/RaisedButton';
type FileToCloudProjectResourceUploaderProps = {
type FileToCloudProjectResourceUploaderProps = {|
options: ChooseResourceOptions,
fileMetadata: ?FileMetadata,
getStorageProvider: () => StorageProvider,
onChooseResources: (resources: Array<gdResource>) => void,
createNewResource: () => gdResource,
automaticallyOpenInput: boolean,
};
|};
const resourceKindToInputAcceptedMimes = {
audio: ['audio/aac', 'audio/x-wav', 'audio/mpeg', 'audio/mp3', 'audio/ogg'],

View File

@@ -207,8 +207,10 @@ const localResourceSources: Array<ResourceSource> = [
});
};
const sourceName = 'local-file-opener-' + kind;
return {
name: 'local-file-opener-' + kind,
name: sourceName,
displayName: t`File(s) from your device`,
displayTab: 'import',
onlyForStorageProvider: 'LocalFile',
@@ -228,7 +230,7 @@ const localResourceSources: Array<ResourceSource> = [
)
}
onClick={async () => {
const resources = await selectLocalFileResources({
const selectedResources = await selectLocalFileResources({
i18n: props.i18n,
project: props.project,
fileMetadata: props.fileMetadata,
@@ -240,7 +242,10 @@ const localResourceSources: Array<ResourceSource> = [
props.resourcesImporationBehavior,
});
props.onChooseResources(resources);
props.onChooseResources({
selectedResources,
selectedSourceName: sourceName,
});
}}
/>
</Line>
@@ -248,34 +253,43 @@ const localResourceSources: Array<ResourceSource> = [
};
}
),
...allResourceKindsAndMetadata.map(({ kind, createNewResource }) => ({
name: `upload-${kind}`,
displayName: t`File(s) from your device`,
shouldCreateResource: true,
shouldGuessAnimationsFromName: true,
displayTab: 'import',
onlyForStorageProvider: 'Cloud',
kind,
renderComponent: (props: ResourceSourceComponentProps) => (
<FileToCloudProjectResourceUploader
createNewResource={createNewResource}
onChooseResources={props.onChooseResources}
options={props.options}
fileMetadata={props.fileMetadata}
getStorageProvider={props.getStorageProvider}
key={`url-chooser-${kind}`}
automaticallyOpenInput={!!props.automaticallyOpenIfPossible}
/>
),
})),
...allResourceKindsAndMetadata.map(({ kind, createNewResource }) => {
const sourceName = `upload-${kind}`;
return {
name: sourceName,
displayName: t`File(s) from your device`,
shouldCreateResource: true,
shouldGuessAnimationsFromName: true,
displayTab: 'import',
onlyForStorageProvider: 'Cloud',
kind,
renderComponent: (props: ResourceSourceComponentProps) => (
<FileToCloudProjectResourceUploader
createNewResource={createNewResource}
onChooseResources={(resources: Array<gdResource>) =>
props.onChooseResources({
selectedResources: resources,
selectedSourceName: sourceName,
})
}
options={props.options}
fileMetadata={props.fileMetadata}
getStorageProvider={props.getStorageProvider}
key={`url-chooser-${kind}`}
automaticallyOpenInput={!!props.automaticallyOpenIfPossible}
/>
),
};
}),
...resourcesKindSupportedByResourceStore
.map(kind => {
const source = allResourceKindsAndMetadata.find(
resourceSource => resourceSource.kind === kind
);
if (!source) return null;
const sourceName = 'resource-store-' + kind;
return {
name: `resource-store-${kind}`,
name: sourceName,
displayName: t`Choose from asset store`,
displayTab: 'standalone',
kind,
@@ -312,54 +326,63 @@ const localResourceSources: Array<ResourceSource> = [
newResource.setName(path.basename(chosenResourceUrl));
newResource.setOrigin('gdevelop-asset-store', chosenResourceUrl);
onChooseResources([newResource]);
onChooseResources({
selectedResources: [newResource],
selectedSourceName: sourceName,
});
}}
/>
),
};
})
.filter(Boolean),
...allResourceKindsAndMetadata.map(({ kind, createNewResource }) => ({
name: `project-resources-${kind}`,
displayName: t`Project resources`,
displayTab: 'standalone',
shouldCreateResource: false,
shouldGuessAnimationsFromName: false,
hideInResourceEditor: true,
kind,
renderComponent: (props: ResourceSourceComponentProps) => (
<ProjectResourcesChooser
project={props.project}
onResourcesSelected={props.onResourcesSelected}
resourceKind={kind}
key={`project-resources-${kind}`}
multiSelection={props.options.multiSelection}
/>
),
renderPrimaryAction: ({
selectedResources,
onChooseResources,
}: ResourceSourceComponentPrimaryActionProps) => (
<DialogPrimaryButton
primary
key="select-resources"
label={
!selectedResources ||
!selectedResources.length ||
selectedResources.length === 1 ? (
<Trans>Select resource</Trans>
) : (
<Trans>Select {selectedResources.length} resources</Trans>
)
}
disabled={!selectedResources || !selectedResources.length}
onClick={() => {
if (!selectedResources || !selectedResources.length) return;
onChooseResources(selectedResources);
}}
/>
),
})),
...allResourceKindsAndMetadata.map(({ kind, createNewResource }) => {
const sourceName = `project-resources-${kind}`;
return {
name: sourceName,
displayName: t`Project resources`,
displayTab: 'standalone',
shouldCreateResource: false,
shouldGuessAnimationsFromName: false,
hideInResourceEditor: true,
kind,
renderComponent: (props: ResourceSourceComponentProps) => (
<ProjectResourcesChooser
project={props.project}
onResourcesSelected={props.onResourcesSelected}
resourceKind={kind}
key={`project-resources-${kind}`}
multiSelection={props.options.multiSelection}
/>
),
renderPrimaryAction: ({
selectedResources,
onChooseResources,
}: ResourceSourceComponentPrimaryActionProps) => (
<DialogPrimaryButton
primary
key="select-resources"
label={
!selectedResources ||
!selectedResources.length ||
selectedResources.length === 1 ? (
<Trans>Select resource</Trans>
) : (
<Trans>Select {selectedResources.length} resources</Trans>
)
}
disabled={!selectedResources || !selectedResources.length}
onClick={() => {
if (!selectedResources || !selectedResources.length) return;
onChooseResources({
selectedResources,
selectedSourceName: sourceName,
});
}}
/>
),
};
}),
];
export default localResourceSources;

View File

@@ -26,7 +26,10 @@ type Props = {|
options: ChooseResourceOptions,
resourceSources: Array<ResourceSource>,
onClose: () => void,
onChooseResources: (resources: Array<gdResource>) => void,
onChooseResources: ({|
selectedResources: Array<gdResource>,
selectedSourceName: string,
|}) => void,
|};
export const NewResourceDialog = ({
@@ -113,10 +116,16 @@ export const NewResourceDialog = ({
resourcesImporationBehavior:
preferences.values.resourcesImporationBehavior,
});
onChooseResources(resources);
onChooseResources({
selectedResources: resources,
selectedSourceName: initialSource.name,
});
} catch (error) {
console.error('Unexpected error from a resource source:', error);
onChooseResources([]);
onChooseResources({
selectedResources: [],
selectedSourceName: initialSource.name,
});
}
})();
},

View File

@@ -9,15 +9,10 @@ import { getDefaultResourceThumbnail } from '..';
import { getPixelatedImageRendering } from '../../Utils/CssHelpers';
import { isProjectImageResourceSmooth } from '../ResourcePreview/ImagePreview';
import Model3DPreview from '../ResourcePreview/Model3DPreview';
import CheckeredBackground from '../CheckeredBackground';
const paddingSize = 10;
const styles = {
previewContainer: {
display: 'flex',
position: 'relative',
justifyContent: 'center',
alignItems: 'center',
},
previewImage: {
position: 'relative',
objectFit: 'contain',
@@ -74,17 +69,22 @@ const ImagePreview = ({ resource, project }: ImagePreviewProps) => {
resourceName
);
return (
<CorsAwareImage
key={resourceName}
style={{
...styles.previewImage,
maxWidth: 128 - 2 * paddingSize,
maxHeight: 128 - 2 * paddingSize,
...(!isImageResourceSmooth ? styles.previewImagePixelated : undefined),
}}
src={resourceThumbnail}
alt={resourceName}
/>
<>
<CheckeredBackground />
<CorsAwareImage
key={resourceName}
style={{
...styles.previewImage,
maxWidth: 128 - 2 * paddingSize,
maxHeight: 128 - 2 * paddingSize,
...(!isImageResourceSmooth
? styles.previewImagePixelated
: undefined),
}}
src={resourceThumbnail}
alt={resourceName}
/>
</>
);
};

View File

@@ -13,14 +13,6 @@ const styles = {
alignItems: 'stretch',
minHeight: 0,
},
background: {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
background: 'url("res/transparentback.png") repeat',
},
screenshot: {
position: 'relative',
objectFit: 'contain',

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