Dataset Viewer
Auto-converted to Parquet Duplicate
before_code
stringlengths
14
465k
reviewer_comment
stringlengths
16
25.5k
after_code
stringlengths
13
467k
diff_context
stringlengths
0
97k
file_path
stringlengths
5
226
comment_line
int32
0
26
language
stringclasses
36 values
quality_score
float32
0.07
1
comment_type
stringclasses
9 values
comment_length
int32
16
25.5k
before_lines
int32
1
14.6k
after_lines
int32
1
12.1k
is_negative
bool
2 classes
pr_title
stringlengths
1
308
pr_number
int32
1
183k
repo_name
stringclasses
326 values
repo_stars
int64
321
419k
repo_language
stringclasses
25 values
reviewer_username
stringlengths
0
39
author_username
stringlengths
2
39
this.owner.setHeight(bottom - top); } if (this._leftEdgeAnchor !== HorizontalAnchor.None) { this.owner.setX( left + this.owner.getX() - this.owner.getDrawableX() ); } if (this._topEdgeAnchor !== VerticalAnchor.None) { this.owner.setY( top + this.owner.getY() - this.owner.getDrawableY() ); } } // End of compatibility code else { // Resize if right and left anchors are set if ( this._rightEdgeAnchor !== HorizontalAnchor.None && this._leftEdgeAnchor !== HorizontalAnchor.None ) { const width = right - left; this.owner.setX( left + ((this.owner.getX() - this.owner.getDrawableX()) * width) / this.owner.getWidth() ); this.owner.setWidth(width); } else { if (this._leftEdgeAnchor !== HorizontalAnchor.None) { this.owner.setX( left + this.owner.getX() - this.owner.getDrawableX() ); } if (this._rightEdgeAnchor !== HorizontalAnchor.None) { this.owner.setX( right + this.owner.getX() - this.owner.getDrawableX() - this.owner.getWidth() ); } } // Resize if top and bottom anchors are set if ( this._bottomEdgeAnchor !== VerticalAnchor.None && this._topEdgeAnchor !== VerticalAnchor.None ) { const height = bottom - top; this.owner.setY( top + ((this.owner.getY() - this.owner.getDrawableY()) * height) /
Should we had `if (this.owner.getX() === this.owner.getDrawableX())` to avoid extra computations 90% of the time at the cost of the `if`?
this.owner.setHeight(bottom - top); } if (this._leftEdgeAnchor !== HorizontalAnchor.None) { this.owner.setX( left + this.owner.getX() - this.owner.getDrawableX() ); } if (this._topEdgeAnchor !== VerticalAnchor.None) { this.owner.setY( top + this.owner.getY() - this.owner.getDrawableY() ); } } // End of compatibility code else { // Resize if right and left anchors are set if ( this._rightEdgeAnchor !== HorizontalAnchor.None && this._leftEdgeAnchor !== HorizontalAnchor.None ) { const width = right - left; this.owner.setX( this.owner.getX() === this.owner.getDrawableX() ? left : left + ((this.owner.getX() - this.owner.getDrawableX()) * width) / this.owner.getWidth() ); this.owner.setWidth(width); } else { if (this._leftEdgeAnchor !== HorizontalAnchor.None) { this.owner.setX( left + this.owner.getX() - this.owner.getDrawableX() ); } if (this._rightEdgeAnchor !== HorizontalAnchor.None) { this.owner.setX( right + this.owner.getX() - this.owner.getDrawableX() - this.owner.getWidth() ); } } // Resize if top and bottom anchors are set if ( this._bottomEdgeAnchor !== VerticalAnchor.None && this._topEdgeAnchor !== VerticalAnchor.None ) { const height = bottom - top; this.owner.setY(
@@ -270,8 +270,13 @@ namespace gdjs { this._rightEdgeAnchor !== HorizontalAnchor.None && this._leftEdgeAnchor !== HorizontalAnchor.None ) { - this.owner.setWidth(right - left); - this.owner.setX(left); + const width = right - left; + this.owner.setX( + left + + ((this.owner.getX() - this.owner.getDrawableX()) * width) / + this.owner.getWidth() + );
Extensions/AnchorBehavior/anchorruntimebehavior.ts
26
TypeScript
0.571
question
137
51
51
false
Fix anchor behavior when objects has custom origin
6,970
4ian/GDevelop
10,154
JavaScript
D8H
D8H
} setCustomCenter(customCenterX, customCenterY) { this._customCenterX = customCenterX; this._customCenterY = customCenterY; this.invalidateHitboxes(); } getRendererObject() { return null; } getWidth() { return this._customWidth; } getHeight() { return this._customHeight; } setWidth(width) { this._customWidth = width; } setHeight(height) { return this._customHeight = height; } getCenterX() { if (this._customCenterX === null) return super.getCenterX(); return this._customCenterX; } getCenterY() { if (this._customCenterY === null) return super.getCenterY(); return this._customCenterY; } }; gdjs.registerObject('TestSpriteObject::TestSpriteObject', gdjs.TestSpriteRuntimeObject);
```suggestion this._customHeight = height; ```
} setCustomCenter(customCenterX, customCenterY) { this._customCenterX = customCenterX; this._customCenterY = customCenterY; this.invalidateHitboxes(); } getRendererObject() { return null; } getWidth() { return this._customWidth; } getHeight() { return this._customHeight; } setWidth(width) { this._customWidth = width; } setHeight(height) { this._customHeight = height; } getCenterX() { if (this._customCenterX === null) return super.getCenterX(); return this._customCenterX; } getCenterY() { if (this._customCenterY === null) return super.getCenterY(); return this._customCenterY; } }; gdjs.registerObject('TestSpriteObject::TestSpriteObject', gdjs.TestSpriteRuntimeObject);
@@ -62,6 +62,14 @@ return this._customHeight; } + setWidth(width) { + this._customWidth = width; + } + + setHeight(height) { + return this._customHeight = height;
GDJS/tests/tests/Extensions/testspriteruntimeobject.js
26
JavaScript
0.571
suggestion
51
41
41
false
Fix anchor behavior when objects has custom origin
6,970
4ian/GDevelop
10,154
JavaScript
4ian
D8H
* sub-expression that a given node represents. */ static const gd::String GetType(const gd::Platform &platform, const gd::ProjectScopedContainers &projectScopedContainers, const gd::String &rootType, gd::ExpressionNode& node) { gd::ExpressionTypeFinder typeFinder( platform, projectScopedContainers, rootType); node.Visit(typeFinder); return typeFinder.GetType(); } virtual ~ExpressionTypeFinder(){}; protected: ExpressionTypeFinder(const gd::Platform &platform_, const gd::ProjectScopedContainers &projectScopedContainers_, const gd::String &rootType_) : platform(platform_), projectScopedContainers(projectScopedContainers_), rootType(rootType_), type(ExpressionTypeFinder::unknownType), child(nullptr) {}; const gd::String &GetType() { return gd::ParameterMetadata::GetExpressionValueType(type); }; void OnVisitSubExpressionNode(SubExpressionNode& node) override { VisitParent(node); } void OnVisitOperatorNode(OperatorNode& node) override { VisitParent(node); } void OnVisitUnaryOperatorNode(UnaryOperatorNode& node) override { VisitParent(node); } void OnVisitNumberNode(NumberNode& node) override { type = ExpressionTypeFinder::numberType; } void OnVisitTextNode(TextNode& node) override { type = ExpressionTypeFinder::stringType; } void OnVisitVariableNode(VariableNode& node) override { VisitParent(node); } void OnVisitVariableAccessorNode(VariableAccessorNode& node) override { VisitParent(node); } void OnVisitIdentifierNode(IdentifierNode& node) override { VisitParent(node);
This doesn't change anything. It's just to navigate more easily without going through deprecated functions.
* sub-expression that a given node represents. */ static const gd::String GetType(const gd::Platform &platform, const gd::ProjectScopedContainers &projectScopedContainers, const gd::String &rootType, gd::ExpressionNode& node) { gd::ExpressionTypeFinder typeFinder( platform, projectScopedContainers, rootType); node.Visit(typeFinder); return typeFinder.GetType(); } virtual ~ExpressionTypeFinder(){}; protected: ExpressionTypeFinder(const gd::Platform &platform_, const gd::ProjectScopedContainers &projectScopedContainers_, const gd::String &rootType_) : platform(platform_), projectScopedContainers(projectScopedContainers_), rootType(rootType_), type(ExpressionTypeFinder::unknownType), child(nullptr) {}; const gd::String &GetType() { return gd::ValueTypeMetadata::GetExpressionPrimitiveValueType(type); }; void OnVisitSubExpressionNode(SubExpressionNode& node) override { VisitParent(node); } void OnVisitOperatorNode(OperatorNode& node) override { VisitParent(node); } void OnVisitUnaryOperatorNode(UnaryOperatorNode& node) override { VisitParent(node); } void OnVisitNumberNode(NumberNode& node) override { type = ExpressionTypeFinder::numberType; } void OnVisitTextNode(TextNode& node) override { type = ExpressionTypeFinder::stringType; } void OnVisitVariableNode(VariableNode& node) override { VisitParent(node); } void OnVisitVariableAccessorNode(VariableAccessorNode& node) override { VisitParent(node); } void OnVisitIdentifierNode(IdentifierNode& node) override { VisitParent(node);
@@ -72,7 +72,7 @@ class GD_CORE_API ExpressionTypeFinder : public ExpressionParser2NodeWorker { child(nullptr) {}; const gd::String &GetType() { - return gd::ParameterMetadata::GetExpressionValueType(type); + return gd::ValueTypeMetadata::GetExpressionPrimitiveValueType(type);
Core/GDCore/IDE/Events/ExpressionTypeFinder.h
26
C/C++
0.429
suggestion
107
51
51
false
Fix mouse and key parameters for event-functions
7,052
4ian/GDevelop
10,154
JavaScript
D8H
D8H
case 'RotateCamera': case 'ZoomCamera': case 'FixCamera': case 'CentreCamera': return ['smooth-camera-movement']; case 'ChangeTimeScale': return ['pause-menu']; case 'EcrireFichierExp': case 'EcrireFichierTxt': case 'LireFichierExp': case 'LireFichierTxt': case 'ReadNumberFromStorage': case 'ReadStringFromStorage': return ['intermediate-storage']; case 'PlatformBehavior::SimulateJumpKey': return ['simple-trampoline-platformer']; case 'AjoutObjConcern': case 'PickNearest': case 'AjoutHasard': return ['intermediate-object-picking']; case 'ToggleObjectVariableAsBoolean': case 'ToggleGlobalVariableAsBoolean': case 'ToggleSceneVariableAsBoolean': case 'SetBooleanObjectVariable': case 'SetBooleanVariable': return ['iIntermediate-toggle-states-with-variable']; case 'Scene': case 'PushScene': case 'PopScene': return ['intermediate-level-select-menu']; case 'Animation': case 'AnimationName': case 'ChangeAnimation': case 'ChangeAnimationName': case 'AnimatableCapability::AnimatableBehavior::Index': case 'AnimatableCapability::AnimatableBehavior::Name': case 'AnimatableCapability::AnimatableBehavior::SetIndex': case 'AnimatableCapability::AnimatableBehavior::SetName': return ['intermediate-changing-animations']; case 'PopStartedTouch': case 'MouseButtonPressed': case 'HasAnyTouchOrMouseStarted': case 'HasTouchEnded': return ['intermediate-touchscreen-controls']; default: return []; } };
```suggestion return ['intermediate-toggle-states-with-variable']; ```
case 'RotateCamera': case 'ZoomCamera': case 'FixCamera': case 'CentreCamera': return ['smooth-camera-movement']; case 'ChangeTimeScale': return ['pause-menu']; case 'EcrireFichierExp': case 'EcrireFichierTxt': case 'LireFichierExp': case 'LireFichierTxt': case 'ReadNumberFromStorage': case 'ReadStringFromStorage': return ['intermediate-storage']; case 'PlatformBehavior::SimulateJumpKey': return ['simple-trampoline-platformer']; case 'AjoutObjConcern': case 'PickNearest': case 'AjoutHasard': return ['intermediate-object-picking']; case 'ToggleObjectVariableAsBoolean': case 'ToggleGlobalVariableAsBoolean': case 'ToggleSceneVariableAsBoolean': case 'SetBooleanObjectVariable': case 'SetBooleanVariable': return ['intermediate-toggle-states-with-variable']; case 'Scene': case 'PushScene': case 'PopScene': return ['intermediate-level-select-menu']; case 'Animation': case 'AnimationName': case 'ChangeAnimation': case 'ChangeAnimationName': case 'AnimatableCapability::AnimatableBehavior::Index': case 'AnimatableCapability::AnimatableBehavior::Name': case 'AnimatableCapability::AnimatableBehavior::SetIndex': case 'AnimatableCapability::AnimatableBehavior::SetName': return ['intermediate-changing-animations']; case 'PopStartedTouch': case 'MouseButtonPressed': case 'HasAnyTouchOrMouseStarted': case 'HasTouchEnded': return ['intermediate-touchscreen-controls']; default: return []; } };
@@ -124,6 +126,8 @@ export const getInstructionTutorialIds = (type: string): Array<string> => { case 'ToggleObjectVariableAsBoolean': case 'ToggleGlobalVariableAsBoolean': case 'ToggleSceneVariableAsBoolean': + case 'SetBooleanObjectVariable': + case 'SetBooleanVariable': return ['iIntermediate-toggle-states-with-variable'];
newIDE/app/src/Utils/GDevelopServices/Tutorial.js
26
JavaScript
0.571
suggestion
78
49
49
false
Add tutorial bubbles on actions replacing deprecated ones
7,077
4ian/GDevelop
10,154
JavaScript
AlexandreSi
D8H
// @flow export default function getObjectByName( globalObjectsContainer: gdObjectsContainer | null, objectsContainer?: ?gdObjectsContainer, objectName: string ): ?gdObject { if (objectsContainer && objectsContainer.hasObjectNamed(objectName)) return objectsContainer.getObject(objectName); else if ( globalObjectsContainer && globalObjectsContainer.hasObjectNamed(objectName) ) return globalObjectsContainer.getObject(objectName); return null; } export const hasObjectWithName = ( globalObjectsContainer: gdObjectsContainer | null, objectsContainer?: ?gdObjectsContainer, objectName: string ): boolean => { if (objectsContainer && objectsContainer.hasObjectNamed(objectName)) return true; else if ( globalObjectsContainer && globalObjectsContainer.hasObjectNamed(objectName) ) return true; return false; };
`ObjectsContainersList` should be used instead. You can pass a `ProjectScopedContainersAccessor` to your component.
// @flow export default function getObjectByName( globalObjectsContainer: gdObjectsContainer | null, objectsContainer?: ?gdObjectsContainer, objectName: string ): ?gdObject { if (objectsContainer && objectsContainer.hasObjectNamed(objectName)) return objectsContainer.getObject(objectName); else if ( globalObjectsContainer && globalObjectsContainer.hasObjectNamed(objectName) ) return globalObjectsContainer.getObject(objectName); return null; }
@@ -15,3 +15,18 @@ export default function getObjectByName( return null; } + +export const hasObjectWithName = ( + globalObjectsContainer: gdObjectsContainer | null, + objectsContainer?: ?gdObjectsContainer, + objectName: string +): boolean => {
newIDE/app/src/Utils/GetObjectByName.js
23
JavaScript
0.571
suggestion
115
33
18
false
Fix instances paste from a scene to another
7,105
4ian/GDevelop
10,154
JavaScript
D8H
AlexandreSi
> <QuickPublish project={testProject.project} gameAndBuildsManager={fakeEmptyGameAndBuildsManager} isSavingProject={false} isRequiredToSaveAsNewCloudProject={() => // Indicates that the project is already saved, there will be // no need to save it as a new cloud project. false } onSaveProject={async () => {}} onlineWebExporter={onlineWebExporter} setIsNavigationDisabled={() => {}} onClose={action('onClose')} onContinueQuickCustomization={action('onContinueQuickCustomization')} onTryAnotherGame={action('onTryAnotherGame')} /> </AuthenticatedUserContext.Provider> </Template> ); }; export const AuthenticatedAndLoadingUserCloudProjects = () => { return ( <Template> <AuthenticatedUserContext.Provider value={{ ...fakeAuthenticatedUserWithNoSubscriptionAndCredits, cloudProjects: null, }} > <QuickPublish project={testProject.project} gameAndBuildsManager={fakeEmptyGameAndBuildsManager} isSavingProject={false} isRequiredToSaveAsNewCloudProject={() => true} onSaveProject={async () => {}} onlineWebExporter={onlineWebExporter} setIsNavigationDisabled={() => {}} onClose={action('onClose')} onContinueQuickCustomization={action('onContinueQuickCustomization')} onTryAnotherGame={action('onTryAnotherGame')} /> </AuthenticatedUserContext.Provider> </Template> ); }; export const AuthenticatedAndFails = () => { return ( <Template>
I feel like this comment should be next to the props type in QuickPublish. I was not sure what it meant before reading this comment
onClose={action('onClose')} onContinueQuickCustomization={action('onContinueQuickCustomization')} onTryAnotherGame={action('onTryAnotherGame')} /> </AuthenticatedUserContext.Provider> </Template> ); }; export const AuthenticatedWithCloudProjectsMaximumReachedButSavedAlready = () => { return ( <Template> <AuthenticatedUserContext.Provider value={{ ...fakeAuthenticatedUserWithNoSubscriptionAndCredits, // We have more projects than the maximum allowed, but the project is already saved // so there are no problems. cloudProjects: tenCloudProjects, }} > <QuickPublish project={testProject.project} gameAndBuildsManager={fakeGameAndBuildsManager} isSavingProject={false} isRequiredToSaveAsNewCloudProject={() => // Indicates that the project is already saved, there will be // no need to save it as a new cloud project. false } onSaveProject={async () => {}} onlineWebExporter={onlineWebExporter} setIsNavigationDisabled={() => {}} onClose={action('onClose')} onContinueQuickCustomization={action('onContinueQuickCustomization')} onTryAnotherGame={action('onTryAnotherGame')} /> </AuthenticatedUserContext.Provider> </Template> ); }; export const AuthenticatedAndLoadingUserCloudProjects = () => { return ( <Template> <AuthenticatedUserContext.Provider value={{ ...fakeAuthenticatedUserWithNoSubscriptionAndCredits, cloudProjects: null, }} > <QuickPublish
@@ -119,6 +124,39 @@ export const AuthenticatedWithTooManyCloudProjects = () => { </Template> ); }; + +export const AuthenticatedWithCloudProjectsMaximumReachedButSavedAlready = () => { + return ( + <Template> + <AuthenticatedUserContext.Provider + value={{ + ...fakeAuthenticatedUserWithNoSubscriptionAndCredits, + // We have more projects than the maximum allowed, but the project is already saved + // so there are no problems. + cloudProjects: tenCloudProjects, + }} + > + <QuickPublish + project={testProject.project} + gameAndBuildsManager={fakeEmptyGameAndBuildsManager} + isSavingProject={false} + isRequiredToSaveAsNewCloudProject={() => + // Indicates that the project is already saved, there will be
newIDE/app/src/stories/componentStories/QuickCustomization/QuickPublish.stories.js
26
JavaScript
0.571
suggestion
131
51
51
false
Fix issues when reworking a quick customization project
7,109
4ian/GDevelop
10,154
JavaScript
AlexandreSi
4ian
if (!selectedItem) return; if (selectedItem.content.isDescendantOf(item.content)) { selectObjectFolderOrObjectWithContext(null); } }, [selectObjectFolderOrObjectWithContext, selectedItems] ); // Force List component to be mounted again if project or objectsContainer // has been changed. Avoid accessing to invalid objects that could // crash the app. const listKey = project.ptr + ';' + objectsContainer.ptr; const initiallyOpenedNodeIds = [ globalObjectsRootFolder && globalObjectsRootFolder.getChildrenCount() > 0 ? globalObjectsRootFolderId : null, sceneObjectsRootFolderId, ].filter(Boolean); const arrowKeyNavigationProps = React.useMemo( () => ({ onGetItemInside: (item: TreeViewItem): ?TreeViewItem => { if (item.isPlaceholder || item.isRoot) return null; const objectFolderOrObject = item.content.getObjectFolderOrObject(); if (!objectFolderOrObject) return null; if (!objectFolderOrObject.isFolder()) return null; else { if (objectFolderOrObject.getChildrenCount() === 0) return null; return createTreeViewItem({ objectFolderOrObject: objectFolderOrObject.getChildAt(0), isGlobal: item.content.isGlobal(), objectFolderTreeViewItemProps, objectTreeViewItemProps, }); } }, onGetItemOutside: (item: TreeViewItem): ?TreeViewItem => { if (item.isPlaceholder || item.isRoot) return null; const objectFolderOrObject = item.content.getObjectFolderOrObject(); if (!objectFolderOrObject) return null; const parent = objectFolderOrObject.getParent(); if (parent.isRootFolder()) return null; return createTreeViewItem({ objectFolderOrObject: parent, isGlobal: item.content.isGlobal(), objectFolderTreeViewItemProps, objectTreeViewItemProps, }); }, }), [objectFolderTreeViewItemProps, objectTreeViewItemProps]
Removing the column, you removed the margin, you should maybe remove the `noMargin` in the child Column
* does not stay selected and not visible to the user. */ const onCollapseItem = React.useCallback( (item: TreeViewItem) => { if (!selectedItems || selectedItems.length !== 1) return; const selectedItem = selectedItems[0]; if (!selectedItem) return; if (selectedItem.content.isDescendantOf(item.content)) { selectObjectFolderOrObjectWithContext(null); } }, [selectObjectFolderOrObjectWithContext, selectedItems] ); // Force List component to be mounted again if project or objectsContainer // has been changed. Avoid accessing to invalid objects that could // crash the app. const listKey = project.ptr + ';' + objectsContainer.ptr; const initiallyOpenedNodeIds = [ globalObjectsRootFolder && globalObjectsRootFolder.getChildrenCount() > 0 ? globalObjectsRootFolderId : null, sceneObjectsRootFolderId, ].filter(Boolean); const arrowKeyNavigationProps = React.useMemo( () => ({ onGetItemInside: (item: TreeViewItem): ?TreeViewItem => { if (item.isPlaceholder || item.isRoot) return null; const objectFolderOrObject = item.content.getObjectFolderOrObject(); if (!objectFolderOrObject) return null; if (!objectFolderOrObject.isFolder()) return null; else { if (objectFolderOrObject.getChildrenCount() === 0) return null; return createTreeViewItem({ objectFolderOrObject: objectFolderOrObject.getChildAt(0), isGlobal: item.content.isGlobal(), objectFolderTreeViewItemProps, objectTreeViewItemProps, }); } }, onGetItemOutside: (item: TreeViewItem): ?TreeViewItem => { if (item.isPlaceholder || item.isRoot) return null; const objectFolderOrObject = item.content.getObjectFolderOrObject(); if (!objectFolderOrObject) return null; const parent = objectFolderOrObject.getParent(); if (parent.isRootFolder()) return null; return createTreeViewItem({ objectFolderOrObject: parent, isGlobal: item.content.isGlobal(),
@@ -1363,28 +1393,16 @@ const ObjectsList = React.forwardRef<Props, ObjectsListInterface>( return ( <Background maxWidth> - <Column>
newIDE/app/src/ObjectsList/index.js
26
JavaScript
0.571
suggestion
103
51
51
false
Replace the "add folder" button by a drop-down menu action
7,117
4ian/GDevelop
10,154
JavaScript
AlexandreSi
D8H
this._injectExternalLayout ); this._watermark.displayAtStartup(); //Uncomment to profile the first x frames of the game. // var x = 500; // var startTime = Date.now(); // console.profile("Stepping for " + x + " frames") // for(var i = 0; i < x; ++i) { // this._sceneStack.step(16); // } // console.profileEnd(); // var time = Date.now() - startTime; // logger.log("Took", time, "ms"); // return; this._setupGameVisibilityEvents(); // The standard game loop let accumulatedElapsedTime = 0; this._hasJustResumed = false; this._renderer.startGameLoop((lastCallElapsedTime) => { try { if (this._isDisposed) { return false; } if (this._paused) { return true; } // Skip the frame if we rendering frames too fast accumulatedElapsedTime += lastCallElapsedTime; if ( this._maxFPS > 0 && 1000.0 / accumulatedElapsedTime > this._maxFPS + 7 ) { // Only skip frame if the framerate is 7 frames above the maximum framerate. // Most browser/engines will try to run at slightly more than 60 frames per second. // If game is set to have a maximum FPS to 60, then one out of two frames will be dropped. // Hence, we use a 7 frames margin to ensure that we're not skipping frames too much. return true; } const elapsedTime = accumulatedElapsedTime; accumulatedElapsedTime = 0; // Manage resize events. if (this._notifyScenesForGameResolutionResize) { this._sceneStack.onGameResolutionResized(); this._notifyScenesForGameResolutionResize = false; }
This check should not exist, you should stop gameLoop before disposing of the renderer.
? firstSceneName : // There is always at least a scene this.getSceneAndExtensionsData()!.sceneData.name; } /** * Start the game loop, to be called once assets are loaded. */ startGameLoop() { this._throwIfDisposed(); try { if (!this.hasScene()) { logger.error('The game has no scene.'); return; } this._forceGameResolutionUpdate(); // Load the first scene this._sceneStack.push( this._getFirstSceneName(), this._injectExternalLayout ); this._watermark.displayAtStartup(); //Uncomment to profile the first x frames of the game. // var x = 500; // var startTime = Date.now(); // console.profile("Stepping for " + x + " frames") // for(var i = 0; i < x; ++i) { // this._sceneStack.step(16); // } // console.profileEnd(); // var time = Date.now() - startTime; // logger.log("Took", time, "ms"); // return; this._setupGameVisibilityEvents(); // The standard game loop let accumulatedElapsedTime = 0; this._hasJustResumed = false; this._renderer.startGameLoop((lastCallElapsedTime) => { try { if (this._paused) { return true; } // Skip the frame if we rendering frames too fast accumulatedElapsedTime += lastCallElapsedTime; if ( this._maxFPS > 0 &&
@@ -888,6 +889,10 @@ namespace gdjs { this._hasJustResumed = false; this._renderer.startGameLoop((lastCallElapsedTime) => { try { + if (this._isDisposed) { + return false; + }
GDJS/Runtime/runtimegame.ts
26
TypeScript
0.286
suggestion
87
51
51
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
? !!navigator.maxTouchPoints && navigator.maxTouchPoints > 2 : false, supportedCompressionMethods: getSupportedCompressionMethods(), }; }; _setupGameVisibilityEvents() { if (typeof navigator !== 'undefined' && typeof document !== 'undefined') { document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') { this._hasJustResumed = true; } }); window.addEventListener( 'resume', () => { this._hasJustResumed = true; }, false ); } } /** * Register a new session for the game, and set up listeners to follow the session * time. */ _setupSessionMetrics() { if (this._isDisposed) { return; } if (this._sessionMetricsInitialized) { return; } if (this._disableMetrics) { return; } if (this.isPreview()) { return; } if (typeof fetch === 'undefined') { return; } if (!this._data.properties.projectUuid) { return; } const baseUrl = 'https://api.gdevelop-app.com/analytics'; this._playerId = this._makePlayerUuid(); /** * The duration that is already sent to the service
Remove this check, and clear the interval instead.
enableMetrics(enable: boolean): void { this._disableMetrics = !enable; if (enable) { this._setupSessionMetrics(); } } /** * Helper function to get information about the platform running the game. */ getPlatformInfo = () => { return { // @ts-ignore isCordova: !!window.cordova, devicePlatform: // @ts-ignore typeof device !== 'undefined' ? device.platform || '' : '', navigatorPlatform: typeof navigator !== 'undefined' ? navigator.platform : '', hasTouch: typeof navigator !== 'undefined' ? !!navigator.maxTouchPoints && navigator.maxTouchPoints > 2 : false, supportedCompressionMethods: getSupportedCompressionMethods(), }; }; _setupGameVisibilityEvents() { if (typeof navigator !== 'undefined' && typeof document !== 'undefined') { document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') { this._hasJustResumed = true; } }); window.addEventListener( 'resume', () => { this._hasJustResumed = true; }, false ); } } /** * Register a new session for the game, and set up listeners to follow the session * time. */ _setupSessionMetrics() { if (this._sessionMetricsInitialized) { return;
@@ -989,6 +1005,10 @@ namespace gdjs { * time. */ _setupSessionMetrics() { + if (this._isDisposed) { + return; + }
GDJS/Runtime/runtimegame.ts
26
TypeScript
0.286
refactor
50
51
51
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
} catch (e) { if (this._debuggerClient) this._debuggerClient.onUncaughtException(e); throw e; } }); setTimeout(() => { this._setupSessionMetrics(); }, 4000); } catch (e) { if (this._debuggerClient) this._debuggerClient.onUncaughtException(e); throw e; } } dispose(): void { if (this._isDisposed) { return; } this._isDisposed = true; this._sceneStack.dispose(); this._renderer.dispose(); this._resourcesLoader.dispose(); } /** * Set if the session should be registered. */ enableMetrics(enable: boolean): void { this._disableMetrics = !enable; if (enable) { this._setupSessionMetrics(); } } /** * Helper function to get information about the platform running the game. */ getPlatformInfo = () => { return { // @ts-ignore isCordova: !!window.cordova, devicePlatform: // @ts-ignore typeof device !== 'undefined' ? device.platform || '' : '', navigatorPlatform: typeof navigator !== 'undefined' ? navigator.platform : '', hasTouch:
What is the aim of this check? Calling the dispose method once is the responsibility of whoever created the game.
const elapsedTime = accumulatedElapsedTime; accumulatedElapsedTime = 0; // Manage resize events. if (this._notifyScenesForGameResolutionResize) { this._sceneStack.onGameResolutionResized(); this._notifyScenesForGameResolutionResize = false; } // Render and step the scene. if (this._sceneStack.step(elapsedTime)) { this.getInputManager().onFrameEnded(); this._hasJustResumed = false; return true; } return false; } catch (e) { if (this._debuggerClient) this._debuggerClient.onUncaughtException(e); throw e; } }); setTimeout(() => { this._setupSessionMetrics(); }, 4000); if (this._captureManager) { this._captureManager.setupCaptureOptions(this._isPreview); } } catch (e) { if (this._debuggerClient) this._debuggerClient.onUncaughtException(e); throw e; } } /** * Stop game loop, unload all scenes, dispose renderer and resources. * After calling this method, the RuntimeGame should not be used anymore. */ dispose(): void { this._renderer.stopGameLoop(); this._sceneStack.dispose(); this._renderer.dispose(); this._resourcesLoader.dispose(); this._wasDisposed = true; } /** * Set if the session should be registered.
@@ -937,6 +942,17 @@ namespace gdjs { } } + dispose(): void { + if (this._isDisposed) { + return; + } + + this._isDisposed = true;
GDJS/Runtime/runtimegame.ts
26
TypeScript
0.357
question
113
51
51
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
newScene.networkId = sceneSyncData.networkId; } hasMadeChangeToStack = true; // Continue to the next scene in the stack received from the host. continue; } // The scene is in the stack and has the right networkId. // Nothing to do, just continue to the next scene in the stack received from the host. } // Pop any scene not on the host. // In the future, we could avoid to pop scenes if they are not set to be synchronized. if (this._stack.length > sceneStackSyncData.length) { const popCount = this._stack.length - sceneStackSyncData.length; this.pop(popCount); hasMadeChangeToStack = true; } return hasMadeChangeToStack; } dispose(): void { for (let i = 0; i < this._stack.length; ++i) { this._stack[i].unloadScene(); } this._stack.length = 0; } } }
Use `for...of` or `forEach` because there is no logic with `i` involved.
debugLogger.info( `Scene at position ${i} and name ${sceneAtThisPositionInOurStack.getName()} has a different networkId ${ sceneAtThisPositionInOurStack.networkId } than the expected ${sceneSyncData.networkId}, replacing.` ); // The scene is in the stack but has a different networkId // This can happen if the host has restarted the scene // We can't just update the networkId of the scene in the stack // We need to replace it with a new scene const newScene = this.replace( sceneSyncData.name, false // Don't clear the stack ); if (newScene) { newScene.networkId = sceneSyncData.networkId; } hasMadeChangeToStack = true; // Continue to the next scene in the stack received from the host. continue; } // The scene is in the stack and has the right networkId. // Nothing to do, just continue to the next scene in the stack received from the host. } // Pop any scene not on the host. // In the future, we could avoid to pop scenes if they are not set to be synchronized. if (this._stack.length > sceneStackSyncData.length) { const popCount = this._stack.length - sceneStackSyncData.length; this.pop(popCount); hasMadeChangeToStack = true; } return hasMadeChangeToStack; } /** * Unload all the scenes and clear the stack. */ dispose(): void { for (const item of this._stack) { item.unloadScene(); } this._stack.length = 0; this._wasDisposed = true; } private _throwIfDisposed(): void { if (this._wasDisposed) { throw 'The scene stack has been disposed and should not be used anymore.';
@@ -354,5 +354,12 @@ namespace gdjs { return hasMadeChangeToStack; } + + dispose(): void { + for (let i = 0; i < this._stack.length; ++i) { + this._stack[i].unloadScene(); + }
GDJS/Runtime/scenestack.ts
26
TypeScript
0.429
suggestion
72
31
51
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
logger.error('Window closing failed. See error:', error); } } } else { if ( typeof navigator !== 'undefined' && // @ts-ignore navigator.app && // @ts-ignore navigator.app.exitApp ) { // @ts-ignore navigator.app.exitApp(); } } // HTML5 games on mobile/browsers don't have a way to close their window/page. } dispose() { this._pixiRenderer?.destroy(true); this._pixiRenderer = null; this._threeRenderer = null; this._gameCanvas = null; this._domElementsContainer = null; } /** * Get the canvas DOM element. */ getCanvas(): HTMLCanvasElement | null { return this._gameCanvas; } /** * Check if the device supports WebGL. * @returns true if WebGL is supported */ isWebGLSupported(): boolean { return ( !!this._pixiRenderer && this._pixiRenderer.type === PIXI.RENDERER_TYPE.WEBGL ); } /** * Get the electron module, if running as a electron renderer process. */ getElectron() { if (typeof require === 'function') { return require('electron'); }
Call `this._threeRenderer?.dispose();`.
} /** * Close the game, if applicable. */ stopGame() { // Try to detect the environment to use the most adapted // way of closing the app const remote = this.getElectronRemote(); if (remote) { const browserWindow = remote.getCurrentWindow(); if (browserWindow) { try { browserWindow.close(); } catch (error) { logger.error('Window closing failed. See error:', error); } } } else { if ( typeof navigator !== 'undefined' && // @ts-ignore navigator.app && // @ts-ignore navigator.app.exitApp ) { // @ts-ignore navigator.app.exitApp(); } } // HTML5 games on mobile/browsers don't have a way to close their window/page. } /** * Dispose PixiRenderer, ThreeRenderer and remove canvas from DOM. */ dispose() { this._pixiRenderer?.destroy(true); this._threeRenderer?.dispose(); this._pixiRenderer = null; this._threeRenderer = null; this._gameCanvas = null; this._domElementsContainer = null; this._wasDisposed = true; } /** * Get the canvas DOM element. */ getCanvas(): HTMLCanvasElement | null { return this._gameCanvas;
@@ -924,6 +924,14 @@ namespace gdjs { // HTML5 games on mobile/browsers don't have a way to close their window/page. } + dispose() { + this._pixiRenderer?.destroy(true); + this._pixiRenderer = null; + this._threeRenderer = null;
GDJS/Runtime/pixi-renderers/runtimegame-pixi-renderer.ts
26
TypeScript
0.214
suggestion
39
51
51
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
} } } else { if ( typeof navigator !== 'undefined' && // @ts-ignore navigator.app && // @ts-ignore navigator.app.exitApp ) { // @ts-ignore navigator.app.exitApp(); } } // HTML5 games on mobile/browsers don't have a way to close their window/page. } dispose() { this._pixiRenderer?.destroy(true); this._pixiRenderer = null; this._threeRenderer = null; this._gameCanvas = null; this._domElementsContainer = null; } /** * Get the canvas DOM element. */ getCanvas(): HTMLCanvasElement | null { return this._gameCanvas; } /** * Check if the device supports WebGL. * @returns true if WebGL is supported */ isWebGLSupported(): boolean { return ( !!this._pixiRenderer && this._pixiRenderer.type === PIXI.RENDERER_TYPE.WEBGL ); } /** * Get the electron module, if running as a electron renderer process. */ getElectron() { if (typeof require === 'function') { return require('electron'); } return null;
Remove gameCanvas and domElementsContainer from the parent element.
/** * Close the game, if applicable. */ stopGame() { // Try to detect the environment to use the most adapted // way of closing the app const remote = this.getElectronRemote(); if (remote) { const browserWindow = remote.getCurrentWindow(); if (browserWindow) { try { browserWindow.close(); } catch (error) { logger.error('Window closing failed. See error:', error); } } } else { if ( typeof navigator !== 'undefined' && // @ts-ignore navigator.app && // @ts-ignore navigator.app.exitApp ) { // @ts-ignore navigator.app.exitApp(); } } // HTML5 games on mobile/browsers don't have a way to close their window/page. } /** * Dispose PixiRenderer, ThreeRenderer and remove canvas from DOM. */ dispose() { this._pixiRenderer?.destroy(true); this._threeRenderer?.dispose(); this._pixiRenderer = null; this._threeRenderer = null; this._gameCanvas = null; this._domElementsContainer = null; this._wasDisposed = true; } /** * Get the canvas DOM element. */ getCanvas(): HTMLCanvasElement | null { return this._gameCanvas; }
@@ -924,6 +924,14 @@ namespace gdjs { // HTML5 games on mobile/browsers don't have a way to close their window/page. } + dispose() { + this._pixiRenderer?.destroy(true); + this._pixiRenderer = null; + this._threeRenderer = null; + this._gameCanvas = null;
GDJS/Runtime/pixi-renderers/runtimegame-pixi-renderer.ts
26
TypeScript
0.286
suggestion
67
51
51
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
/* * GDevelop JS Platform * Copyright 2013-2023 Florian Rival ([email protected]). All rights reserved. * This project is released under the MIT License. */ namespace gdjs { /** * A resource managers that download and remember downloaded content for one * kind of resource. */ export interface ResourceManager { /** * Load the specified resource. * * This method will be run during the game. It should only do light tasks * like file downloading. */ loadResource(resourceName: string): Promise<void>; /** * Process the specified resource. * * This method will only be run while loading screen is shown. It can do * heavy tasks like parsing data. */ processResource(resourceName: string): Promise<void>; /** * Return the kind of resources handled by this manager. */ getResourceKinds(): Array<ResourceKind>; dispose(): void; } }
Please, add jsdoc description.
/** * Load the specified resource. * * This method will be run during the game. It should only do light tasks * like file downloading. */ loadResource(resourceName: string): Promise<void>; /** * Process the specified resource. * * This method will only be run while loading screen is shown. It can do * heavy tasks like parsing data. */ processResource(resourceName: string): Promise<void>; /** * Return the kind of resources handled by this manager. */ getResourceKinds(): Array<ResourceKind>; /** * Should clear all resources, data, loaders stored by this manager. * Using the manager after calling this method is undefined behavior. */ dispose(): void; } }
@@ -29,5 +29,7 @@ namespace gdjs { * Return the kind of resources handled by this manager. */ getResourceKinds(): Array<ResourceKind>; + + dispose(): void;
GDJS/Runtime/ResourceManager.ts
26
TypeScript
0.071
suggestion
30
36
29
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
xhr.send(); } /** * Check if the given json resource was loaded (preloaded or loaded with `loadJson`). * @param resourceName The name of the json resource. * @returns true if the content of the json resource is loaded. false otherwise. */ isJsonLoaded(resourceName: string): boolean { return !!this._loadedJsons.getFromName(resourceName); } /** * Get the object for the given resource that is already loaded (preloaded or loaded with `loadJson`). * If the resource is not loaded, `null` will be returned. * * @param resourceName The name of the json resource. * @returns the content of the json resource, if loaded. `null` otherwise. */ getLoadedJson(resourceName: string): Object | null { return this._loadedJsons.getFromName(resourceName) || null; } dispose(): void { this._loadedJsons.clear(); this._callbacks.clear } } }
Do not forget to call the function.
xhr.send(); } /** * Check if the given json resource was loaded (preloaded or loaded with `loadJson`). * @param resourceName The name of the json resource. * @returns true if the content of the json resource is loaded. false otherwise. */ isJsonLoaded(resourceName: string): boolean { return !!this._loadedJsons.getFromName(resourceName); } /** * Get the object for the given resource that is already loaded (preloaded or loaded with `loadJson`). * If the resource is not loaded, `null` will be returned. * * @param resourceName The name of the json resource. * @returns the content of the json resource, if loaded. `null` otherwise. */ getLoadedJson(resourceName: string): Object | null { return this._loadedJsons.getFromName(resourceName) || null; } /** * To be called when the game is disposed. * Clear the JSONs loaded in this manager. */ dispose(): void { this._loadedJsons.clear(); this._callbacks.clear(); } } }
@@ -200,5 +200,10 @@ namespace gdjs { getLoadedJson(resourceName: string): Object | null { return this._loadedJsons.getFromName(resourceName) || null; } + + dispose(): void { + this._loadedJsons.clear(); + this._callbacks.clear
GDJS/Runtime/jsonmanager.ts
26
TypeScript
0.071
suggestion
35
30
34
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
'include' : // For other resources, use "same-origin" as done by default by fetch. 'same-origin', } ); const fontData = await response.text(); this._loadedFontsData.set(resource, fontData); } catch (error) { logger.error( "Can't fetch the bitmap font file " + resource.file + ', error: ' + error ); } } dispose(): void { for (const bitmapFontInstallKey in this._pixiBitmapFontsInUse) { PIXI.BitmapFont.uninstall(bitmapFontInstallKey); } for (const bitmapFontInstallKey of this._pixiBitmapFontsToUninstall) { PIXI.BitmapFont.uninstall(bitmapFontInstallKey); } this._pixiBitmapFontsInUse = {}; this._pixiBitmapFontsToUninstall = []; this._loadedFontsData.clear(); } } // Register the class to let the engine use it. export const BitmapFontManager = gdjs.PixiBitmapFontManager; export type BitmapFontManager = gdjs.PixiBitmapFontManager; }
Might be: `this._pixiBitmapFontsToUninstall.length = 0;`
'include' : // For other resources, use "same-origin" as done by default by fetch. 'same-origin', } ); const fontData = await response.text(); this._loadedFontsData.set(resource, fontData); } catch (error) { logger.error( "Can't fetch the bitmap font file " + resource.file + ', error: ' + error ); } } /** * To be called when the game is disposed. * Uninstall all the fonts from memory and clear cache of loaded fonts. */ dispose(): void { for (const bitmapFontInstallKey in this._pixiBitmapFontsInUse) { PIXI.BitmapFont.uninstall(bitmapFontInstallKey); } for (const bitmapFontInstallKey of this._pixiBitmapFontsToUninstall) { PIXI.BitmapFont.uninstall(bitmapFontInstallKey); } this._pixiBitmapFontsInUse = {}; this._pixiBitmapFontsToUninstall.length = 0; this._loadedFontsData.clear(); } } // Register the class to let the engine use it. export const BitmapFontManager = gdjs.PixiBitmapFontManager; export type BitmapFontManager = gdjs.PixiBitmapFontManager; }
@@ -289,6 +289,18 @@ namespace gdjs { ); } } + + dispose(): void { + for (const bitmapFontInstallKey in this._pixiBitmapFontsInUse) { + PIXI.BitmapFont.uninstall(bitmapFontInstallKey); + } + for (const bitmapFontInstallKey of this._pixiBitmapFontsToUninstall) { + PIXI.BitmapFont.uninstall(bitmapFontInstallKey); + } + this._pixiBitmapFontsInUse = {}; + this._pixiBitmapFontsToUninstall = [];
GDJS/Runtime/pixi-renderers/pixi-bitmapfont-manager.ts
26
TypeScript
0.357
suggestion
56
35
41
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
this._loadedTextures.clear(); const threeTextures: THREE.Texture[] = []; this._loadedThreeTextures.values(threeTextures); this._loadedThreeTextures.clear(); for (const threeTexture of threeTextures) { threeTexture.dispose(); } const threeMaterials: THREE.Material[] = []; this._loadedThreeMaterials.values(threeMaterials); this._loadedThreeMaterials.clear(); for (const threeMaterial of threeMaterials) { threeMaterial.dispose(); } const diskPixiTextures = [...this._diskTextures.values()]; this._diskTextures.clear(); for (const pixiTexture of diskPixiTextures) { if (pixiTexture.destroyed) { continue; } pixiTexture.destroy(); } const rectanglePixiTextures = [...this._rectangleTextures.values()]; this._rectangleTextures.clear(); for (const pixiTexture of rectanglePixiTextures) { if (pixiTexture.destroyed) { continue; } pixiTexture.destroy(); } const scaledPixiTextures = [...this._scaledTextures.values()]; this._scaledTextures.clear(); for (const pixiTexture of scaledPixiTextures) { if (pixiTexture.destroyed) { continue; } pixiTexture.destroy(); } } } //Register the class to let the engine use it. export const ImageManager = gdjs.PixiImageManager; export type ImageManager = gdjs.PixiImageManager;
Will this work? ``` for (const pixiTexture of this._diskTextures.values()) { if (pixiTexture.destroyed) { continue; } pixiTexture.destroy(); } this._diskTextures.clear(); ``` Minus new array creation.
* To be called when the game is disposed. * Clear caches of loaded textures and materials. */ dispose(): void { this._loadedTextures.clear(); const threeTextures: THREE.Texture[] = []; this._loadedThreeTextures.values(threeTextures); this._loadedThreeTextures.clear(); for (const threeTexture of threeTextures) { threeTexture.dispose(); } const threeMaterials: THREE.Material[] = []; this._loadedThreeMaterials.values(threeMaterials); this._loadedThreeMaterials.clear(); for (const threeMaterial of threeMaterials) { threeMaterial.dispose(); } for (const pixiTexture of this._diskTextures.values()) { if (pixiTexture.destroyed) { continue; } pixiTexture.destroy(); } this._diskTextures.clear(); for (const pixiTexture of this._rectangleTextures.values()) { if (pixiTexture.destroyed) { continue; } pixiTexture.destroy(); } this._rectangleTextures.clear(); for (const pixiTexture of this._scaledTextures.values()) { if (pixiTexture.destroyed) { continue; } pixiTexture.destroy(); } this._scaledTextures.clear(); } } //Register the class to let the engine use it. export const ImageManager = gdjs.PixiImageManager;
@@ -463,6 +463,54 @@ namespace gdjs { } return particleTexture; } + + dispose(): void { + this._loadedTextures.clear(); + + const threeTextures: THREE.Texture[] = []; + this._loadedThreeTextures.values(threeTextures); + this._loadedThreeTextures.clear(); + for (const threeTexture of threeTextures) { + threeTexture.dispose(); + } + + const threeMaterials: THREE.Material[] = []; + this._loadedThreeMaterials.values(threeMaterials); + this._loadedThreeMaterials.clear(); + for (const threeMaterial of threeMaterials) { + threeMaterial.dispose(); + } + + const diskPixiTextures = [...this._diskTextures.values()]; + this._diskTextures.clear(); + for (const pixiTexture of diskPixiTextures) { + if (pixiTexture.destroyed) { + continue; + } + + pixiTexture.destroy(); + }
GDJS/Runtime/pixi-renderers/pixi-image-manager.ts
26
TypeScript
0.786
suggestion
262
51
51
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
/** * @brief Return the scene variables of the current scene or the current * extension. It allows legacy "scenevar" parameters to accept extension * variables. */ const gd::VariablesContainer &GetLegacySceneVariables() const { return legacySceneVariables; }; const gd::PropertiesContainersList &GetPropertiesContainersList() const { return propertiesContainersList; }; const std::vector<const ParameterMetadataContainer *> &GetParametersVectorsList() const { return parametersVectorsList; }; /** Do not use - should be private but accessible to let Emscripten create a * temporary. */ ProjectScopedContainers(){}; private: gd::ObjectsContainersList objectsContainersList; gd::VariablesContainersList variablesContainersList; gd::VariablesContainer legacyGlobalVariables; gd::VariablesContainer legacySceneVariables; gd::PropertiesContainersList propertiesContainersList; std::vector<const ParameterMetadataContainer *> parametersVectorsList; }; } // namespace gd
These are not references/pointers but values, meaning that ProjectScopedContainers moved from "I'm just a set of lists pointing to things in your project" to "I actually hold stuff, and you will have a bad time if you destroyed me and kept references to things".
/** * @brief Return the scene variables of the current scene or the current * extension. It allows legacy "scenevar" parameters to accept extension * variables. */ const gd::VariablesContainer *GetLegacySceneVariables() const { return legacySceneVariables; }; const gd::PropertiesContainersList &GetPropertiesContainersList() const { return propertiesContainersList; }; const std::vector<const ParameterMetadataContainer *> &GetParametersVectorsList() const { return parametersVectorsList; }; /** Do not use - should be private but accessible to let Emscripten create a * temporary. */ ProjectScopedContainers(){}; private: gd::ObjectsContainersList objectsContainersList; gd::VariablesContainersList variablesContainersList; const gd::VariablesContainer *legacyGlobalVariables; const gd::VariablesContainer *legacySceneVariables; gd::PropertiesContainersList propertiesContainersList; std::vector<const ParameterMetadataContainer *> parametersVectorsList; }; } // namespace gd
@@ -236,6 +230,8 @@ class ProjectScopedContainers { private: gd::ObjectsContainersList objectsContainersList; gd::VariablesContainersList variablesContainersList; + gd::VariablesContainer legacyGlobalVariables; + gd::VariablesContainer legacySceneVariables;
Core/GDCore/Project/ProjectScopedContainers.h
26
C/C++
0.5
suggestion
262
31
31
false
Allow legacy scene variable parameters to use extension variables
7,121
4ian/GDevelop
10,154
JavaScript
4ian
D8H
auto &initialInstances = eventsBasedObject.GetInitialInstances(); initialInstances.InsertNewInitialInstance().SetLayer("My layer"); initialInstances.InsertNewInitialInstance().SetLayer("My layer"); initialInstances.InsertNewInitialInstance().SetLayer("My layer"); initialInstances.InsertNewInitialInstance().SetLayer(""); initialInstances.InsertNewInitialInstance().SetLayer(""); initialInstances.InsertNewInitialInstance().SetLayer("My other layer"); REQUIRE(initialInstances.GetInstancesCount() == 6); REQUIRE(initialInstances.GetLayerInstancesCount("My layer") == 3); gd::WholeProjectRefactorer::MergeLayersInEventsBasedObject( eventsBasedObject, "My layer", ""); // No instance was removed. REQUIRE(initialInstances.GetInstancesCount() == 6); // No instance remain in "My layer". REQUIRE(initialInstances.GetLayerInstancesCount("My layer") == 0); // Other layers from the same layout are untouched. REQUIRE(initialInstances.GetLayerInstancesCount("My other layer") == 1); } SECTION("Can find and rename leaderboards in a project") { gd::Project project; gd::Platform platform; SetupProjectWithDummyPlatform(project, platform); auto &layout = project.InsertNewLayout("My layout", 0); gd::StandardEvent &event = dynamic_cast<gd::StandardEvent &>( layout.GetEvents().InsertNewEvent(project, "BuiltinCommonInstructions::Standard")); gd::Instruction action; action.SetType("MyExtension::DisplayLeaderboard"); action.SetParametersCount(1); action.SetParameter(0, gd::Expression("\"12345678-9abc-def0-1234-56789abcdef0\"")); event.GetActions().Insert(action); std::set<gd::String> allLeaderboardIds = gd::WholeProjectRefactorer::FindAllLeaderboardIds(project); REQUIRE(allLeaderboardIds.size() == 1); REQUIRE(allLeaderboardIds.count("12345678-9abc-def0-1234-56789abcdef0") == 1); std::map<gd::String, gd::String> leaderboardIdMap; leaderboardIdMap["12345678-9abc-def0-1234-56789abcdef0"] = "87654321-9abc-def0-1234-56789abcdef0"; gd::WholeProjectRefactorer::RenameLeaderboards(project, leaderboardIdMap); REQUIRE(GetEventFirstActionFirstParameterString(layout.GetEvents().GetEvent(0)) == "\"87654321-9abc-def0-1234-56789abcdef0\"");
The previous description better fit what the test actually covers.
auto &initialInstances = eventsBasedObject.GetInitialInstances(); initialInstances.InsertNewInitialInstance().SetLayer("My layer"); initialInstances.InsertNewInitialInstance().SetLayer("My layer"); initialInstances.InsertNewInitialInstance().SetLayer("My layer"); initialInstances.InsertNewInitialInstance().SetLayer(""); initialInstances.InsertNewInitialInstance().SetLayer(""); initialInstances.InsertNewInitialInstance().SetLayer("My other layer"); REQUIRE(initialInstances.GetInstancesCount() == 6); REQUIRE(initialInstances.GetLayerInstancesCount("My layer") == 3); gd::WholeProjectRefactorer::MergeLayersInEventsBasedObject( eventsBasedObject, "My layer", ""); // No instance was removed. REQUIRE(initialInstances.GetInstancesCount() == 6); // No instance remain in "My layer". REQUIRE(initialInstances.GetLayerInstancesCount("My layer") == 0); // Other layers from the same layout are untouched. REQUIRE(initialInstances.GetLayerInstancesCount("My other layer") == 1); } // TODO: ideally, a test should also cover objects having `leaderboardId` as property. SECTION("Can rename a leaderboard in scene events") { gd::Project project; gd::Platform platform; SetupProjectWithDummyPlatform(project, platform); auto &layout = project.InsertNewLayout("My layout", 0); gd::StandardEvent &event = dynamic_cast<gd::StandardEvent &>( layout.GetEvents().InsertNewEvent(project, "BuiltinCommonInstructions::Standard")); gd::Instruction action; action.SetType("MyExtension::DisplayLeaderboard"); action.SetParametersCount(1); action.SetParameter(0, gd::Expression("\"12345678-9abc-def0-1234-56789abcdef0\"")); event.GetActions().Insert(action); std::set<gd::String> allLeaderboardIds = gd::WholeProjectRefactorer::FindAllLeaderboardIds(project); REQUIRE(allLeaderboardIds.size() == 1); REQUIRE(allLeaderboardIds.count("12345678-9abc-def0-1234-56789abcdef0") == 1); std::map<gd::String, gd::String> leaderboardIdMap; leaderboardIdMap["12345678-9abc-def0-1234-56789abcdef0"] = "87654321-9abc-def0-1234-56789abcdef0"; gd::WholeProjectRefactorer::RenameLeaderboards(project, leaderboardIdMap); REQUIRE(GetEventFirstActionFirstParameterString(layout.GetEvents().GetEvent(0)) ==
@@ -4452,13 +4452,13 @@ TEST_CASE("MergeLayers", "[common]") { REQUIRE(initialInstances.GetLayerInstancesCount("My other layer") == 1); } - SECTION("Can rename a leaderboard in scene events") { + SECTION("Can find and rename leaderboards in a project") {
Core/tests/WholeProjectRefactorer.cpp
26
C++
0.286
suggestion
66
51
51
false
Fix leaderboards not properly replaced in projects using them in custom objects
7,131
4ian/GDevelop
10,154
JavaScript
D8H
4ian
} onInstructionTypeChanged={onInstructionTypeChanged} /> {editorOpen && project && !objectGroup && ( <ObjectVariablesDialog project={project} projectScopedContainersAccessor={projectScopedContainersAccessor} objectName={objectName} variablesContainer={variablesContainers[0]} open onCancel={() => setEditorOpen(null)} onApply={onVariableEditorApply} preventRefactoringToDeleteInstructions initiallySelectedVariableName={editorOpen.variableName} shouldCreateInitiallySelectedVariable={editorOpen.shouldCreate} onComputeAllVariableNames={onComputeAllVariableNames} hotReloadPreviewButtonProps={null} /> )} {editorOpen && project && objectGroup && ( <ObjectGroupVariablesDialog project={project} projectScopedContainersAccessor={projectScopedContainersAccessor} globalObjectsContainer={globalObjectsContainer} objectsContainer={objectsContainer} objectGroup={objectGroup} onCancel={() => setEditorOpen(null)} onApply={onVariableEditorApply} open initiallySelectedVariableName={editorOpen.variableName} shouldCreateInitiallySelectedVariable={editorOpen.shouldCreate} onComputeAllVariableNames={onComputeAllVariableNames} /> )} </React.Fragment> ); } ); export const renderInlineObjectVariable = ( props: ParameterInlineRendererProps ) => renderVariableWithIcon(props, 'object variable', ObjectVariableIcon);
Sounds suspicious as not used then?
} onInstructionTypeChanged={onInstructionTypeChanged} /> {editorOpen && project && !!variablesContainers.length && !objectGroup && ( <ObjectVariablesDialog project={project} projectScopedContainersAccessor={projectScopedContainersAccessor} objectName={objectName} variablesContainer={variablesContainers[0]} open onCancel={() => setEditorOpen(null)} onApply={onVariableEditorApply} preventRefactoringToDeleteInstructions initiallySelectedVariableName={editorOpen.variableName} shouldCreateInitiallySelectedVariable={editorOpen.shouldCreate} onComputeAllVariableNames={onComputeAllVariableNames} hotReloadPreviewButtonProps={null} /> )} {editorOpen && project && objectGroup && !!variablesContainers.length && ( <ObjectGroupVariablesDialog project={project} projectScopedContainersAccessor={projectScopedContainersAccessor} globalObjectsContainer={globalObjectsContainer} objectsContainer={objectsContainer} objectGroup={objectGroup} onCancel={() => setEditorOpen(null)} onApply={onVariableEditorApply} open initiallySelectedVariableName={editorOpen.variableName} shouldCreateInitiallySelectedVariable={editorOpen.shouldCreate} onComputeAllVariableNames={onComputeAllVariableNames} /> )} </React.Fragment> ); } ); export const renderInlineObjectVariable = ( props: ParameterInlineRendererProps ) => renderVariableWithIcon(props, 'object variable', ObjectVariableIcon);
@@ -188,37 +188,43 @@ export default React.forwardRef<ParameterFieldProps, ParameterFieldInterface>( } onInstructionTypeChanged={onInstructionTypeChanged} /> - {editorOpen && project && !objectGroup && ( - <ObjectVariablesDialog - project={project} - projectScopedContainersAccessor={projectScopedContainersAccessor} - objectName={objectName} - variablesContainer={variablesContainers[0]} - open - onCancel={() => setEditorOpen(null)} - onApply={onVariableEditorApply} - preventRefactoringToDeleteInstructions - initiallySelectedVariableName={editorOpen.variableName} - shouldCreateInitiallySelectedVariable={editorOpen.shouldCreate} - onComputeAllVariableNames={onComputeAllVariableNames} - hotReloadPreviewButtonProps={null} - /> - )} - {editorOpen && project && objectGroup && ( - <ObjectGroupVariablesDialog - project={project} - projectScopedContainersAccessor={projectScopedContainersAccessor} - globalObjectsContainer={globalObjectsContainer} - objectsContainer={objectsContainer} - objectGroup={objectGroup} - onCancel={() => setEditorOpen(null)} - onApply={onVariableEditorApply} - open - initiallySelectedVariableName={editorOpen.variableName} - shouldCreateInitiallySelectedVariable={editorOpen.shouldCreate} - onComputeAllVariableNames={onComputeAllVariableNames} - /> - )} + {editorOpen && + project && + !!variablesContainers.length && + !objectGroup && ( + <ObjectVariablesDialog + project={project} + projectScopedContainersAccessor={projectScopedContainersAccessor} + objectName={objectName} + variablesContainer={variablesContainers[0]} + open + onCancel={() => setEditorOpen(null)} + onApply={onVariableEditorApply} + preventRefactoringToDeleteInstructions + initiallySelectedVariableName={editorOpen.variableName} + shouldCreateInitiallySelectedVariable={editorOpen.shouldCreate} + onComputeAllVariableNames={onComputeAllVariableNames} + hotReloadPreviewButtonProps={null} + /> + )} + {editorOpen && + project && + objectGroup && + !!variablesContainers.length && (
newIDE/app/src/EventsSheet/ParameterFields/ObjectVariableField.js
26
JavaScript
0.143
question
35
43
49
false
Prevent opening variables dialog for objects & groups if there is no object
7,132
4ian/GDevelop
10,154
JavaScript
4ian
ClementPasteau
// We could pass it a string, but lets do it right this.removeJoint(parseInt(jId, 10)); } } } } // Remove the joint this.world.DestroyJoint(joint); delete this.joints[jointId]; } } } gdjs.registerRuntimeSceneUnloadedCallback(function (runtimeScene) { if ( // @ts-ignore runtimeScene.physics2SharedData && // @ts-ignore runtimeScene.physics2SharedData.world ) { // @ts-ignore Box2D.destroy(runtimeScene.physics2SharedData.world); } }); export class Physics2RuntimeBehavior extends gdjs.RuntimeBehavior { bodyType: string; bullet: boolean; fixedRotation: boolean; canSleep: boolean; shape: string; shapeDimensionA: any; shapeDimensionB: any; shapeOffsetX: float; shapeOffsetY: float; polygonOrigin: string; polygon: gdjs.Polygon | null; density: float; friction: float; restitution: float; linearDamping: float; angularDamping: float; gravityScale: float; layers: integer; masks: integer; shapeScale: number = 1; /** * Array containing the beginning of contacts reported by onContactBegin. Each contact * should be unique to avoid recording glitches where the object loses and regain * contact between two frames. The array is updated each time the method
In the future, a `destroy()` method on the shared data would be I think safer (in the sense: it's part of the class, so there is less chance you forget to update it when needed) and we we should probably made the "shared data" something first class that is handled by the runtime scene (rather than something that is manually handled by the behavior like now).
if ( this.joints[jId].GetType() === Box2D.e_gearJoint && (Box2D.getPointer( (this.joints[jId] as Box2D.b2GearJoint).GetJoint1() ) === Box2D.getPointer(joint) || Box2D.getPointer( (this.joints[jId] as Box2D.b2GearJoint).GetJoint2() ) === Box2D.getPointer(joint)) ) { // We could pass it a string, but lets do it right this.removeJoint(parseInt(jId, 10)); } } } } // Remove the joint this.world.DestroyJoint(joint); delete this.joints[jointId]; } } } gdjs.registerRuntimeSceneUnloadedCallback(function (runtimeScene) { const physics2SharedData = runtimeScene.physics2SharedData; if (physics2SharedData && physics2SharedData.world) { Box2D.destroy(physics2SharedData.world); Box2D.destroy(physics2SharedData._tempb2Vec2); Box2D.destroy(physics2SharedData._tempb2Vec2Sec); } }); export class Physics2RuntimeBehavior extends gdjs.RuntimeBehavior { bodyType: string; bullet: boolean; fixedRotation: boolean; canSleep: boolean; shape: string; shapeDimensionA: any; shapeDimensionB: any; shapeOffsetX: float; shapeOffsetY: float; polygonOrigin: string; polygon: gdjs.Polygon | null; density: float; friction: float; restitution: float; linearDamping: float; angularDamping: float; gravityScale: float; layers: integer; masks: integer;
@@ -300,14 +309,11 @@ namespace gdjs { } } gdjs.registerRuntimeSceneUnloadedCallback(function (runtimeScene) { - if ( - // @ts-ignore - runtimeScene.physics2SharedData && - // @ts-ignore - runtimeScene.physics2SharedData.world - ) { - // @ts-ignore - Box2D.destroy(runtimeScene.physics2SharedData.world); + const physics2SharedData = runtimeScene.physics2SharedData; + if (physics2SharedData && physics2SharedData.world) { + Box2D.destroy(physics2SharedData.world);
Extensions/Physics2Behavior/physics2runtimebehavior.ts
26
TypeScript
0.786
suggestion
360
51
51
false
[Physics2] Fix a memory leak on object instances
7,136
4ian/GDevelop
10,154
JavaScript
4ian
D8H
// we need to relay the ownership change to others, // and expect an acknowledgment from them. if (gdjs.multiplayer.isCurrentPlayerHost()) { const connectedPeerIds = gdjs.multiplayerPeerJsHelper.getAllPeers(); // We don't need to send the message to the player who sent the ownership change message. const otherPeerIds = connectedPeerIds.filter( (peerId) => peerId !== messageSender ); if (!otherPeerIds.length) { // No one else to relay the message to. return; } addExpectedMessageAcknowledgement({ originalMessageName: messageName, originalData: messageData, expectedMessageName: variableOwnerChangedMessageName, otherPeerIds, // As we are the host, we do not cancel the message if it times out. shouldCancelMessageIfTimesOut: false, }); for (const peerId of otherPeerIds) { debugLogger.info( `Relaying ownership change of variable with Id ${variableNetworkId} to ${peerId}.` ); sendDataTo(otherPeerIds, messageName, messageData); } } }); }); }; const getRegexFromAckMessageName = (messageName: string) => { if (messageName.startsWith(instanceDestroyedMessageNamePrefix)) { return instanceDestroyedMessageNameRegex; } else if ( messageName.startsWith(instanceOwnerChangedMessageNamePrefix) ) { return instanceOwnerChangedMessageNameRegex; } else if ( messageName.startsWith(variableOwnerChangedMessageNamePrefix) ) { return variableOwnerChangedMessageNameRegex; } else if (messageName.startsWith(customMessageAcknowledgePrefix)) { return customMessageAcknowledgeRegex; } return null; }; const isMessageAcknowledgement = (messageName: string) => { return (
So this was sending too many messages!
// we need to relay the ownership change to others, // and expect an acknowledgment from them. if (gdjs.multiplayer.isCurrentPlayerHost()) { const connectedPeerIds = gdjs.multiplayerPeerJsHelper.getAllPeers(); // We don't need to send the message to the player who sent the ownership change message. const otherPeerIds = connectedPeerIds.filter( (peerId) => peerId !== messageSender ); if (!otherPeerIds.length) { // No one else to relay the message to. return; } addExpectedMessageAcknowledgement({ originalMessageName: messageName, originalData: messageData, expectedMessageName: variableOwnerChangedMessageName, otherPeerIds, // As we are the host, we do not cancel the message if it times out. shouldCancelMessageIfTimesOut: false, }); debugLogger.info( `Relaying ownership change of variable with Id ${variableNetworkId} to ${otherPeerIds.join( ', ' )}.` ); sendDataTo(otherPeerIds, messageName, messageData); } }); }); }; const getRegexFromAckMessageName = (messageName: string) => { if (messageName.startsWith(instanceDestroyedMessageNamePrefix)) { return instanceDestroyedMessageNameRegex; } else if ( messageName.startsWith(instanceOwnerChangedMessageNamePrefix) ) { return instanceOwnerChangedMessageNameRegex; } else if ( messageName.startsWith(variableOwnerChangedMessageNamePrefix) ) { return variableOwnerChangedMessageNameRegex; } else if (messageName.startsWith(customMessageAcknowledgePrefix)) { return customMessageAcknowledgeRegex; } return null; }; const isMessageAcknowledgement = (messageName: string) => { return (
@@ -917,12 +917,12 @@ namespace gdjs { // As we are the host, we do not cancel the message if it times out. shouldCancelMessageIfTimesOut: false, }); - for (const peerId of otherPeerIds) { - debugLogger.info( - `Relaying ownership change of variable with Id ${variableNetworkId} to ${peerId}.` - ); - sendDataTo(otherPeerIds, messageName, messageData);
Extensions/Multiplayer/messageManager.ts
26
TypeScript
0.071
suggestion
38
51
51
false
Fix destroying an object even if flagged as "DoNothing" in the multiplayer behavior
7,137
4ian/GDevelop
10,154
JavaScript
4ian
ClementPasteau
} catch (error) { console.error('Error while login:', error); throw error; } } async loginOrSignupWithProvider({ provider, signal, }: {| provider: IdentityProvider, signal?: AbortSignal, |}) { if (signal && signal.aborted) { return Promise.reject( new UserCancellationError( 'Login or Signup with provider already aborted.' ) ); } const promise = new Promise((resolve, reject) => { // Listen for abort event on signal if (signal) { signal.addEventListener('abort', () => { terminateWebSocket(); }); } setupAuthenticationWebSocket({ onConnectionEstablished: connectionId => { if (signal && signal.aborted) return; const url = new URL(authenticationPortalUrl); url.searchParams.set('connection-id', connectionId); url.searchParams.set('provider', provider); url.searchParams.set('env', isDev ? 'dev' : 'live'); Window.openExternalURL(url.toString()); }, onTokenReceived: async ({ provider, data, }: {| provider: 'apple' | 'google' | 'github', data: any, |}) => { if (signal && signal.aborted) return; try { const credential = provider === 'google' ? GoogleAuthProvider.credential(data.credential) : provider === 'github' ? GithubAuthProvider.credential(data.accessToken) : new OAuthProvider('apple.com').credential({
this seemed duplicated in this file and the browser one. This was always causing an error in the console because the signal always aborts (we trigger it when we close the dialog) I don't think this deserves to raise an error as it's the expected path?
} catch (error) { console.error('Error while login:', error); throw error; } } async loginOrSignupWithProvider({ provider, signal, }: {| provider: IdentityProvider, signal?: AbortSignal, |}) { if (signal && signal.aborted) { return Promise.reject( new UserCancellationError( 'Login or Signup with provider already aborted.' ) ); } const promise = new Promise((resolve, reject) => { // Listen for abort event on signal if (signal) { signal.addEventListener('abort', () => { terminateWebSocket(); reject( new UserCancellationError( 'Login or Signup with provider already aborted.' ) ); }); } setupAuthenticationWebSocket({ onConnectionEstablished: connectionId => { if (signal && signal.aborted) return; const url = new URL(authenticationPortalUrl); url.searchParams.set('connection-id', connectionId); url.searchParams.set('provider', provider); url.searchParams.set('env', isDev ? 'dev' : 'live'); Window.openExternalURL(url.toString()); }, onTokenReceived: async ({ provider, data, }: {| provider: 'apple' | 'google' | 'github', data: any, |}) => { if (signal && signal.aborted) return; try { const credential =
@@ -61,11 +61,6 @@ class LocalLoginProvider implements LoginProvider, FirebaseBasedLoginProvider { if (signal) { signal.addEventListener('abort', () => { terminateWebSocket(); - reject(
newIDE/app/src/LoginProvider/LocalLoginProvider.js
26
JavaScript
0.643
refactor
253
51
51
false
Fix infinite loading when canceling login with provider
7,138
4ian/GDevelop
10,154
JavaScript
ClementPasteau
ClementPasteau
}, }); } } this.setState({ createAccountInProgress: false, loginInProgress: false, authenticatedUser: { ...this.state.authenticatedUser, creatingOrLoggingInAccount: false, }, }); this._automaticallyUpdateUserProfile = true; }; _cancelLoginOrSignUp = () => { if (this._abortController) { this._abortController.abort(); this._abortController = null; } this.setState({ loginInProgress: false, createAccountInProgress: false, authenticatedUser: { ...this.state.authenticatedUser, creatingOrLoggingInAccount: false, }, }); }; _doLogin = async (form: LoginForm) => { const { authentication } = this.props; if (!authentication) return; this.setState({ loginInProgress: true, apiCallError: null, authenticatedUser: { ...this.state.authenticatedUser, creatingOrLoggingInAccount: true, authenticationError: null, }, }); this._automaticallyUpdateUserProfile = false; try { await authentication.login(form); await this._fetchUserProfileWithoutThrowingErrors({ resetState: true }); this.openLoginDialog(false); this._showLoginSnackbar(this.state.authenticatedUser); } catch (apiCallError) { this.setState({
I don't like doing this here. It looks like we're trying to "finish a process". But the process is already there: <img width="776" alt="image" src="https://github.com/user-attachments/assets/6fe5b8b4-8d4c-4124-b83a-34f6d90bbd83"> There is already a catch (ensuring that an exception will never stop the end to run) and at the end we set the boolean back to false.
}, }); } } this.setState({ createAccountInProgress: false, loginInProgress: false, authenticatedUser: { ...this.state.authenticatedUser, creatingOrLoggingInAccount: false, }, }); this._automaticallyUpdateUserProfile = true; }; _cancelLoginOrSignUp = () => { if (this._abortController) { this._abortController.abort(); this._abortController = null; } }; _doLogin = async (form: LoginForm) => { const { authentication } = this.props; if (!authentication) return; this.setState({ loginInProgress: true, apiCallError: null, authenticatedUser: { ...this.state.authenticatedUser, creatingOrLoggingInAccount: true, authenticationError: null, }, }); this._automaticallyUpdateUserProfile = false; try { await authentication.login(form); await this._fetchUserProfileWithoutThrowingErrors({ resetState: true }); this.openLoginDialog(false); this._showLoginSnackbar(this.state.authenticatedUser); } catch (apiCallError) { this.setState({ apiCallError, authenticatedUser: { ...this.state.authenticatedUser, authenticationError: apiCallError, }, }); } this.setState({
@@ -996,11 +996,19 @@ export default class AuthenticatedUserProvider extends React.Component< this._automaticallyUpdateUserProfile = true; }; - _cancelLogin = () => { + _cancelLoginOrSignUp = () => { if (this._abortController) { this._abortController.abort(); this._abortController = null; } + this.setState({ + loginInProgress: false, + createAccountInProgress: false, + authenticatedUser: { + ...this.state.authenticatedUser, + creatingOrLoggingInAccount: false,
newIDE/app/src/Profile/AuthenticatedUserProvider.js
26
JavaScript
0.643
suggestion
369
51
51
false
Fix infinite loading when canceling login with provider
7,138
4ian/GDevelop
10,154
JavaScript
4ian
ClementPasteau
Props, State > { state = { eventsFunction: null, extensionName: '', createNewExtension: false, }; _projectScopedContainersAccessor: ProjectScopedContainersAccessor | null = null; componentDidMount() { const { project, scope, globalObjectsContainer, objectsContainer, serializedEvents, } = this.props; // This is only used to check parameter for name conflict. // TODO Update it according to the chosen extension. this._projectScopedContainersAccessor = new ProjectScopedContainersAccessor( { project } ); // Set up the function const eventsFunction = new gd.EventsFunction(); setupFunctionFromEvents({ project, scope, globalObjectsContainer, objectsContainer, serializedEvents, eventsFunction, }); this.setState({ eventsFunction, }); // Prepopulate the form const eventsFunctionsExtensions = enumerateEventsFunctionsExtensions( project ); if (eventsFunctionsExtensions.length === 0) { this.setState({ createNewExtension: true, }); } } componentWillUnmount() {
This is kind of regression as it will forbid to use the same name as global variables and global objects for a parameter. We should probably use a new blank project instead.
Props, State > { state = { eventsFunction: null, extensionName: '', createNewExtension: false, }; _projectScopedContainersAccessor: ProjectScopedContainersAccessor | null = null; componentDidMount() { const { project, scope, globalObjectsContainer, objectsContainer, serializedEvents, } = this.props; // This is only used to check parameter for name conflict,but the parameter // editor is locked so users can't actually change parameter names. // Thus, it's fine to use the wrong scope. this._projectScopedContainersAccessor = new ProjectScopedContainersAccessor( { project } ); // Set up the function const eventsFunction = new gd.EventsFunction(); setupFunctionFromEvents({ project, scope, globalObjectsContainer, objectsContainer, serializedEvents, eventsFunction, }); this.setState({ eventsFunction, }); // Prepopulate the form const eventsFunctionsExtensions = enumerateEventsFunctionsExtensions( project ); if (eventsFunctionsExtensions.length === 0) { this.setState({ createNewExtension: true, }); } }
@@ -65,6 +67,12 @@ export default class EventsFunctionExtractorDialog extends React.Component< serializedEvents, } = this.props; + // This is only used to check parameter for name conflict. + // TODO Update it according to the chosen extension. + this._projectScopedContainersAccessor = new ProjectScopedContainersAccessor( + { project } + );
newIDE/app/src/EventsSheet/EventsFunctionExtractor/EventsFunctionExtractorDialog.js
26
JavaScript
0.429
suggestion
174
51
51
false
Reduce the risk of name collisions between objects, variables, parameters and properties
7,148
4ian/GDevelop
10,154
JavaScript
D8H
D8H
preferences.values.openDiagnosticReportAutomatically, onLaunchPreviewWithDiagnosticReport, previewState.overridenPreviewLayoutName, previewState.overridenPreviewExternalLayoutName, previewState.isPreviewOverriden, previewState.previewExternalLayoutName, previewState.previewLayoutName, setPreviewOverride, ] ); // Create a separate function to avoid the button passing its event as // the first argument. const onShareClick = React.useCallback( () => { openShareDialog(); }, [openShareDialog] ); return ( <LineStackLayout noMargin> <FlatButtonWithSplitMenu primary onClick={ !hasPreviewsRunning && preferences.values.takeScreenshotOnPreview // Take a screenshot on first preview. ? onLaunchPreviewWithScreenshot : onHotReloadPreview } disabled={!isPreviewEnabled} icon={hasPreviewsRunning ? <UpdateIcon /> : <PreviewIcon />} label={ !isMobile ? ( hasPreviewsRunning ? ( <Trans>Update</Trans> ) : ( <Trans>Preview</Trans> ) ) : null } id="toolbar-preview-button" splitMenuButtonId="toolbar-preview-split-menu-button" buildMenuTemplate={previewBuildMenuTemplate} /> <ResponsiveRaisedButton primary onClick={onShareClick} disabled={!isSharingEnabled} icon={<PublishIcon />} label={<Trans>Share</Trans>} // This ID is used for guided lessons, let's keep it stable.
wondering if we should also take a screenshot only if: - you don't have a thumbnailUrl already set (but the screenshots might be useful) - you haven't taken a screenshot recently (to avoid taking one on every preview) - like every x minutes ?
previewState.overridenPreviewLayoutName, previewState.overridenPreviewExternalLayoutName, previewState.isPreviewOverriden, previewState.previewExternalLayoutName, previewState.previewLayoutName, setPreviewOverride, ] ); // Create a separate function to avoid the button passing its event as // the first argument. const onShareClick = React.useCallback( () => { openShareDialog(); }, [openShareDialog] ); return ( <LineStackLayout noMargin> <FlatButtonWithSplitMenu primary onClick={onHotReloadPreview} disabled={!isPreviewEnabled} icon={hasPreviewsRunning ? <UpdateIcon /> : <PreviewIcon />} label={ !isMobile ? ( hasPreviewsRunning ? ( <Trans>Update</Trans> ) : ( <Trans>Preview</Trans> ) ) : null } id="toolbar-preview-button" splitMenuButtonId="toolbar-preview-split-menu-button" buildMenuTemplate={previewBuildMenuTemplate} /> <ResponsiveRaisedButton primary onClick={onShareClick} disabled={!isSharingEnabled} icon={<PublishIcon />} label={<Trans>Share</Trans>} // This ID is used for guided lessons, let's keep it stable. id="toolbar-publish-button" /> </LineStackLayout> ); } );
@@ -185,7 +187,11 @@ const PreviewAndShareButtons = React.memo<PreviewAndShareButtonsProps>( <LineStackLayout noMargin> <FlatButtonWithSplitMenu primary - onClick={onHotReloadPreview} + onClick={ + !hasPreviewsRunning && preferences.values.takeScreenshotOnPreview // Take a screenshot on first preview.
newIDE/app/src/MainFrame/Toolbar/PreviewAndShareButtons.js
26
JavaScript
0.5
question
244
51
51
false
Take a screenshot on preview
7,156
4ian/GDevelop
10,154
JavaScript
ClementPasteau
ClementPasteau
preferences.getIsMenuBarHiddenInPreview, preferences.getIsAlwaysOnTopInPreview, preferences.values.openDiagnosticReportAutomatically, currentlyRunningInAppTutorial, getAuthenticatedPlayerForPreview, quickCustomizationDialogOpenedFromGameId, onCaptureFinished, createCaptureOptionsForPreview, ] ); const launchPreview = addCreateBadgePreHookIfNotClaimed( authenticatedUser, TRIVIAL_FIRST_PREVIEW, _launchPreview ); const launchNewPreview = React.useCallback( async options => { const numberOfWindows = options ? options.numberOfWindows : 1; await launchPreview({ networkPreview: false, numberOfWindows }); }, [launchPreview] ); const launchPreviewWithScreenshot = React.useCallback( () => launchPreview({ networkPreview: false, hotReload: false, launchCaptureOptions: { screenshots: [ { delayTimeInSeconds: 3000 }, // Take only 1 screenshot per preview. ], }, }), [launchPreview] ); const launchHotReloadPreview = React.useCallback( () => launchPreview({ networkPreview: false, hotReload: true, }), [launchPreview] ); const launchNetworkPreview = React.useCallback( () => launchPreview({ networkPreview: true, hotReload: false }), [launchPreview]
Consider not adding yet-another-way-to-launch-preview and instead: - Make the logic related to the timing inside the existing function. - delayTimeInSeconds can also be in the function - forcing a screenshot, bypassing the check for timing, is "just" a "forceScreenshot: true". But this is only used for quick customization. For normal previews, the buttons are unchanged.
preferences.getIsMenuBarHiddenInPreview, preferences.getIsAlwaysOnTopInPreview, preferences.values.openDiagnosticReportAutomatically, currentlyRunningInAppTutorial, getAuthenticatedPlayerForPreview, quickCustomizationDialogOpenedFromGameId, onCaptureFinished, createCaptureOptionsForPreview, ] ); const launchPreview = addCreateBadgePreHookIfNotClaimed( authenticatedUser, TRIVIAL_FIRST_PREVIEW, _launchPreview ); const launchNewPreview = React.useCallback( async options => { const numberOfWindows = options ? options.numberOfWindows : 1; await launchPreview({ networkPreview: false, numberOfWindows }); }, [launchPreview] ); const launchHotReloadPreview = React.useCallback( async () => { const launchCaptureOptions = currentProject ? getHotReloadPreviewLaunchCaptureOptions( currentProject.getProjectUuid() ) : undefined; await launchPreview({ networkPreview: false, hotReload: true, launchCaptureOptions, }); }, [currentProject, launchPreview, getHotReloadPreviewLaunchCaptureOptions] ); const launchNetworkPreview = React.useCallback( () => launchPreview({ networkPreview: true, hotReload: false }), [launchPreview] ); const launchPreviewWithDiagnosticReport = React.useCallback( () => launchPreview({ forceDiagnosticReport: true }), [launchPreview] );
@@ -1723,13 +1724,31 @@ const MainFrame = (props: Props) => { const launchNewPreview = React.useCallback( async options => { const numberOfWindows = options ? options.numberOfWindows : 1; - launchPreview({ networkPreview: false, numberOfWindows }); + await launchPreview({ networkPreview: false, numberOfWindows }); }, [launchPreview] ); + const launchPreviewWithScreenshot = React.useCallback(
newIDE/app/src/MainFrame/index.js
26
JavaScript
0.5
suggestion
375
51
51
false
Take a screenshot on preview
7,156
4ian/GDevelop
10,154
JavaScript
4ian
ClementPasteau
// (because the target is in the scope), replace or remove it: RenameOrRemovePropertyOfTargetPropertyContainer(node.name); } if (node.child) node.child->Visit(*this); }); } void OnVisitVariableAccessorNode(VariableAccessorNode& node) override { if (node.child) node.child->Visit(*this); } void OnVisitVariableBracketAccessorNode( VariableBracketAccessorNode& node) override { node.expression->Visit(*this); if (node.child) node.child->Visit(*this); } void OnVisitIdentifierNode(IdentifierNode& node) override { auto& propertiesContainersList = projectScopedContainers.GetPropertiesContainersList(); // Match the potential *new* name of the property, because refactorings are // done after changes in the variables container. projectScopedContainers.MatchIdentifierWithName<void>( GetPotentialNewName(node.identifierName), [&]() { // Do nothing, it's an object variable. }, [&]() { // Do nothing, it's a variable. }, [&]() { // This is a property, check if it's coming from the target container with // properties to replace. if (propertiesContainersList.HasPropertiesContainer( targetPropertiesContainer)) { // The node represents a property, that can come from the target // (because the target is in the scope), replace or remove it: RenameOrRemovePropertyOfTargetPropertyContainer(node.identifierName); } }, [&]() { // Do nothing, it's a parameter. }, [&]() { // This is something else - potentially a deleted property. // Check if it's coming from the target container with // properties to replace. if (propertiesContainersList.HasPropertiesContainer( targetPropertiesContainer)) { // The node represents a property, that can come from the target // (because the target is in the scope), replace or remove it: RenameOrRemovePropertyOfTargetPropertyContainer(node.identifierName); } }); } void OnVisitObjectFunctionNameNode(ObjectFunctionNameNode& node) override {}
I don't understand why this "MatchIdentifierWithName" is not doing its job? If it's a variable, it should match it (and so do nothing), no?
}, [&]() { // Do nothing, it's something else. if (node.child) node.child->Visit(*this); }); } void OnVisitVariableAccessorNode(VariableAccessorNode& node) override { if (node.child) node.child->Visit(*this); } void OnVisitVariableBracketAccessorNode( VariableBracketAccessorNode& node) override { bool isGrandParentTypeAVariable = isParentTypeAVariable; isParentTypeAVariable = false; node.expression->Visit(*this); isParentTypeAVariable = isGrandParentTypeAVariable; if (node.child) node.child->Visit(*this); } void OnVisitIdentifierNode(IdentifierNode& node) override { if (isParentTypeAVariable) { // Do nothing, it's a variable. return; } auto& propertiesContainersList = projectScopedContainers.GetPropertiesContainersList(); projectScopedContainers.MatchIdentifierWithName<void>( // The property name is changed after the refactor operation node.identifierName, [&]() { // Do nothing, it's an object variable. }, [&]() { // Do nothing, it's a variable. }, [&]() { // This is a property, check if it's coming from the target container with // properties to replace. if (propertiesContainersList.HasPropertiesContainer( targetPropertiesContainer)) { // The node represents a property, that can come from the target // (because the target is in the scope), replace or remove it: RenameOrRemovePropertyOfTargetPropertyContainer(node.identifierName); } }, [&]() { // Do nothing, it's a parameter. }, [&]() { // Do nothing, it's something else. }); } void OnVisitObjectFunctionNameNode(ObjectFunctionNameNode& node) override {} void OnVisitFunctionCallNode(FunctionCallNode &node) override { bool isGrandParentTypeAVariable = isParentTypeAVariable; for (auto &parameter : node.parameters) {
@@ -118,17 +116,24 @@ class GD_CORE_API ExpressionPropertyReplacer } void OnVisitVariableBracketAccessorNode( VariableBracketAccessorNode& node) override { + bool isGrandParentTypeAVariable = isParentTypeAVariable; + isParentTypeAVariable = false; node.expression->Visit(*this); + isParentTypeAVariable = isGrandParentTypeAVariable; if (node.child) node.child->Visit(*this); } void OnVisitIdentifierNode(IdentifierNode& node) override { + if (isParentTypeAVariable) { + // Do nothing, it's a variable. + return; + } + auto& propertiesContainersList = projectScopedContainers.GetPropertiesContainersList(); - // Match the potential *new* name of the property, because refactorings are - // done after changes in the variables container. projectScopedContainers.MatchIdentifierWithName<void>(
Core/GDCore/IDE/Events/EventsPropertyReplacer.cpp
26
C++
0.429
question
139
51
51
false
Fix variables from being renamed with a property
7,186
4ian/GDevelop
10,154
JavaScript
4ian
D8H
for (std::size_t c = 0; c < GetCameraCount(); ++c) { SerializerElement& cameraElement = camerasElement.AddChild("camera"); cameraElement.SetAttribute("defaultSize", GetCamera(c).UseDefaultSize()); cameraElement.SetAttribute("width", GetCamera(c).GetWidth()); cameraElement.SetAttribute("height", GetCamera(c).GetHeight()); cameraElement.SetAttribute("defaultViewport", GetCamera(c).UseDefaultViewport()); cameraElement.SetAttribute("viewportLeft", GetCamera(c).GetViewportX1()); cameraElement.SetAttribute("viewportTop", GetCamera(c).GetViewportY1()); cameraElement.SetAttribute("viewportRight", GetCamera(c).GetViewportX2()); cameraElement.SetAttribute("viewportBottom", GetCamera(c).GetViewportY2()); } SerializerElement& effectsElement = element.AddChild("effects"); effectsContainer.SerializeTo(effectsElement); } /** * \brief Unserialize the layer. */ void Layer::UnserializeFrom(const SerializerElement& element) { SetName(element.GetStringAttribute("name", "", "Name")); SetRenderingType(element.GetStringAttribute("renderingType", "")); SetCameraType(element.GetStringAttribute("cameraType", "perspective")); SetDefaultCameraBehavior(element.GetStringAttribute("defaultCameraBehavior", "keep-top-left-fixed-if-never-moved")); SetVisibility(element.GetBoolAttribute("visibility", true, "Visibility")); SetLocked(element.GetBoolAttribute("isLocked", false)); SetLightingLayer(element.GetBoolAttribute("isLightingLayer", false)); SetFollowBaseLayerCamera( element.GetBoolAttribute("followBaseLayerCamera", false)); SetAmbientLightColor(element.GetIntAttribute("ambientLightColorR", 200), element.GetIntAttribute("ambientLightColorG", 200), element.GetIntAttribute("ambientLightColorB", 200)); SetCamera3DNearPlaneDistance(element.GetDoubleAttribute( "camera3DNearPlaneDistance", 0.1, "threeDNearPlaneDistance")); SetCamera3DFarPlaneDistance(element.GetDoubleAttribute( "camera3DFarPlaneDistance", 10000, "threeDFarPlaneDistance")); SetCamera3DFieldOfView(element.GetDoubleAttribute( "camera3DFieldOfView", 45, "threeDFieldOfView")); cameras.clear(); SerializerElement& camerasElement = element.GetChild("cameras"); camerasElement.ConsiderAsArrayOf("camera"); for (std::size_t i = 0; i < camerasElement.GetChildrenCount(); ++i) { const SerializerElement& cameraElement = camerasElement.GetChild(i); Camera camera; camera.SetUseDefaultSize( cameraElement.GetBoolAttribute("defaultSize", true)); camera.SetSize(cameraElement.GetDoubleAttribute("width"),
to make it a bit shorter ```suggestion SetDefaultCameraBehavior(element.GetStringAttribute("defaultCameraBehavior", "top-left-anchored-if-never-moved")); ```
for (std::size_t c = 0; c < GetCameraCount(); ++c) { SerializerElement& cameraElement = camerasElement.AddChild("camera"); cameraElement.SetAttribute("defaultSize", GetCamera(c).UseDefaultSize()); cameraElement.SetAttribute("width", GetCamera(c).GetWidth()); cameraElement.SetAttribute("height", GetCamera(c).GetHeight()); cameraElement.SetAttribute("defaultViewport", GetCamera(c).UseDefaultViewport()); cameraElement.SetAttribute("viewportLeft", GetCamera(c).GetViewportX1()); cameraElement.SetAttribute("viewportTop", GetCamera(c).GetViewportY1()); cameraElement.SetAttribute("viewportRight", GetCamera(c).GetViewportX2()); cameraElement.SetAttribute("viewportBottom", GetCamera(c).GetViewportY2()); } SerializerElement& effectsElement = element.AddChild("effects"); effectsContainer.SerializeTo(effectsElement); } /** * \brief Unserialize the layer. */ void Layer::UnserializeFrom(const SerializerElement& element) { SetName(element.GetStringAttribute("name", "", "Name")); SetRenderingType(element.GetStringAttribute("renderingType", "")); SetCameraType(element.GetStringAttribute("cameraType", "perspective")); SetDefaultCameraBehavior(element.GetStringAttribute("defaultCameraBehavior", "top-left-anchored-if-never-moved")); SetVisibility(element.GetBoolAttribute("visibility", true, "Visibility")); SetLocked(element.GetBoolAttribute("isLocked", false)); SetLightingLayer(element.GetBoolAttribute("isLightingLayer", false)); SetFollowBaseLayerCamera( element.GetBoolAttribute("followBaseLayerCamera", false)); SetAmbientLightColor(element.GetIntAttribute("ambientLightColorR", 200), element.GetIntAttribute("ambientLightColorG", 200), element.GetIntAttribute("ambientLightColorB", 200)); SetCamera3DNearPlaneDistance(element.GetDoubleAttribute( "camera3DNearPlaneDistance", 0.1, "threeDNearPlaneDistance")); SetCamera3DFarPlaneDistance(element.GetDoubleAttribute( "camera3DFarPlaneDistance", 10000, "threeDFarPlaneDistance")); SetCamera3DFieldOfView(element.GetDoubleAttribute( "camera3DFieldOfView", 45, "threeDFieldOfView")); cameras.clear(); SerializerElement& camerasElement = element.GetChild("cameras"); camerasElement.ConsiderAsArrayOf("camera"); for (std::size_t i = 0; i < camerasElement.GetChildrenCount(); ++i) { const SerializerElement& cameraElement = camerasElement.GetChild(i); Camera camera; camera.SetUseDefaultSize( cameraElement.GetBoolAttribute("defaultSize", true)); camera.SetSize(cameraElement.GetDoubleAttribute("width"),
@@ -80,6 +84,7 @@ void Layer::UnserializeFrom(const SerializerElement& element) { SetName(element.GetStringAttribute("name", "", "Name")); SetRenderingType(element.GetStringAttribute("renderingType", "")); SetCameraType(element.GetStringAttribute("cameraType", "perspective")); + SetDefaultCameraBehavior(element.GetStringAttribute("defaultCameraBehavior", "keep-top-left-fixed-if-never-moved"));
Core/GDCore/Project/Layer.cpp
26
C++
0.786
suggestion
164
51
51
false
Fix anchor behavior and add option to center layer or keep top-left fixed when resized
7,188
4ian/GDevelop
10,154
JavaScript
D8H
4ian
_cameraX: float; _cameraY: float; _cameraZ: float = 0; /** * `_cameraZ` is dirty when the zoom factor is set last. */ _isCameraZDirty: boolean = true; /** * @param layerData The data used to initialize the layer * @param instanceContainer The container in which the layer is used */ constructor( layerData: LayerData, instanceContainer: gdjs.RuntimeInstanceContainer ) { super(layerData, instanceContainer); if ( this._defaultCameraBehavior === gdjs.RuntimeLayerDefaultCameraBehavior .KEEP_TOP_LEFT_FIXED_IF_NEVER_MOVED ) { // If top-left must stay in the top-left corner, this means we center the camera on the current size. this._cameraX = this._runtimeScene.getViewportWidth() / 2; this._cameraY = this._runtimeScene.getViewportHeight() / 2; } else { // Otherwise, the default camera position is the center of the initial viewport. this._cameraX = (this._runtimeScene.getInitialUnrotatedViewportMinX() + this._runtimeScene.getInitialUnrotatedViewportMaxX()) / 2; this._cameraY = (this._runtimeScene.getInitialUnrotatedViewportMinY() + this._runtimeScene.getInitialUnrotatedViewportMaxY()) / 2; } if (this.getCameraType() === gdjs.RuntimeLayerCameraType.ORTHOGRAPHIC) { this._cameraZ = (this._initialCamera3DFarPlaneDistance + this._initialCamera3DNearPlaneDistance) / 2; } // Let the renderer do its final set up: this._renderer.onCreated(); } /** * Called by the RuntimeScene whenever the game resolution size is changed. * Updates the layer width/height and position.
Should this use `getViewportOriginX/Y` to handle the fact that custom objects don't necessarily have the top-left corner at (0 ; 0) (even if it probably doesn't matter here as it's a scene layer)?
_cameraX: float; _cameraY: float; _cameraZ: float = 0; /** * `_cameraZ` is dirty when the zoom factor is set last. */ _isCameraZDirty: boolean = true; /** * @param layerData The data used to initialize the layer * @param instanceContainer The container in which the layer is used */ constructor( layerData: LayerData, instanceContainer: gdjs.RuntimeInstanceContainer ) { super(layerData, instanceContainer); if ( this._defaultCameraBehavior === gdjs.RuntimeLayerDefaultCameraBehavior.TOP_LEFT_ANCHORED_IF_NEVER_MOVED ) { // If top-left must stay in the top-left corner, this means we center the camera on the current size. this._cameraX = this._runtimeScene.getViewportOriginX(); this._cameraY = this._runtimeScene.getViewportOriginY(); } else { // Otherwise, the default camera position is the center of the initial viewport. this._cameraX = (this._runtimeScene.getInitialUnrotatedViewportMinX() + this._runtimeScene.getInitialUnrotatedViewportMaxX()) / 2; this._cameraY = (this._runtimeScene.getInitialUnrotatedViewportMinY() + this._runtimeScene.getInitialUnrotatedViewportMaxY()) / 2; } if (this.getCameraType() === gdjs.RuntimeLayerCameraType.ORTHOGRAPHIC) { this._cameraZ = (this._initialCamera3DFarPlaneDistance + this._initialCamera3DNearPlaneDistance) / 2; } // Let the renderer do its final set up: this._renderer.onCreated(); } /** * Called by the RuntimeScene whenever the game resolution size is changed. * Updates the layer width/height and position. */
@@ -28,8 +28,25 @@ namespace gdjs { ) { super(layerData, instanceContainer); - this._cameraX = this.getWidth() / 2; - this._cameraY = this.getHeight() / 2; + if ( + this._defaultCameraBehavior === + gdjs.RuntimeLayerDefaultCameraBehavior + .KEEP_TOP_LEFT_FIXED_IF_NEVER_MOVED + ) { + // If top-left must stay in the top-left corner, this means we center the camera on the current size. + this._cameraX = this._runtimeScene.getViewportWidth() / 2; + this._cameraY = this._runtimeScene.getViewportHeight() / 2;
GDJS/Runtime/layer.ts
26
TypeScript
0.714
question
196
51
51
false
Fix anchor behavior and add option to center layer or keep top-left fixed when resized
7,188
4ian/GDevelop
10,154
JavaScript
D8H
4ian
// Handle scale mode. if (this._game.getScaleMode() === 'nearest') { gameCanvas.style['image-rendering'] = '-moz-crisp-edges'; gameCanvas.style['image-rendering'] = '-webkit-optimize-contrast'; gameCanvas.style['image-rendering'] = '-webkit-crisp-edges'; gameCanvas.style['image-rendering'] = 'pixelated'; } // Handle pixels rounding. if (this._game.getPixelsRounding()) { PIXI.settings.ROUND_PIXELS = true; } // Handle resize: immediately adjust the game canvas (and dom element container) // and notify the game (that may want to adjust to the new size of the window). window.addEventListener('resize', () => { this._game.onWindowInnerSizeChanged(); this._resizeCanvas(); }); // Focus the canvas when created. gameCanvas.focus(); } useCanvas(gameCanvas: HTMLCanvasElement): void { if (typeof THREE !== "undefined") { this._threeRenderer = new THREE.WebGLRenderer({ canvas: gameCanvas, antialias: this._game.getAntialiasingMode() !== "none" && (this._game.isAntialisingEnabledOnMobile() || !gdjs.evtTools.common.isMobile()), preserveDrawingBuffer: true, // Keep to true to allow screenshots. }); this._threeRenderer.useLegacyLights = true; this._threeRenderer.autoClear = false; this._threeRenderer.setSize(this._game.getGameResolutionWidth(), this._game.getGameResolutionHeight()); // Create a PixiJS renderer that use the same GL context as Three.js // so that both can render to the canvas and even have PixiJS rendering // reused in Three.js (by using a RenderTexture and the same internal WebGL texture). this._pixiRenderer = new PIXI.Renderer({ width: this._game.getGameResolutionWidth(), height: this._game.getGameResolutionHeight(), view: gameCanvas, // @ts-ignore - reuse the context from Three.js. context: this._threeRenderer.getContext(), clearBeforeRender: false, preserveDrawingBuffer: true, // Keep to true to allow screenshots. antialias: false, backgroundAlpha: 0,
There is a lot of copy from the `createStandardCanvas` function. Could you rework `createStandardCanvas` so that it's using `useCanvas` under the hood? Also, the name is probably not showing this is an important operation enough, that just can't be redone a second time. So I think it should be called `initializeForCanvas`
// Prevent magnifying glass on iOS with a long press. // Note that there are related bugs on iOS 15 (see https://bugs.webkit.org/show_bug.cgi?id=231161) // but it seems not to affect us as the `domElementsContainer` has `pointerEvents` set to `none`. domElementsContainer.style['-webkit-user-select'] = 'none'; gameCanvas.parentNode?.appendChild(domElementsContainer); this._domElementsContainer = domElementsContainer; this._resizeCanvas(); // Handle scale mode. if (this._game.getScaleMode() === 'nearest') { gameCanvas.style['image-rendering'] = '-moz-crisp-edges'; gameCanvas.style['image-rendering'] = '-webkit-optimize-contrast'; gameCanvas.style['image-rendering'] = '-webkit-crisp-edges'; gameCanvas.style['image-rendering'] = 'pixelated'; } // Handle pixels rounding. if (this._game.getPixelsRounding()) { PIXI.settings.ROUND_PIXELS = true; } // Handle resize: immediately adjust the game canvas (and dom element container) // and notify the game (that may want to adjust to the new size of the window). window.addEventListener('resize', () => { this._game.onWindowInnerSizeChanged(); this._resizeCanvas(); }); // Focus the canvas when created. gameCanvas.focus(); } static getWindowInnerWidth() { return typeof window !== 'undefined' ? window.innerWidth : 800; } static getWindowInnerHeight() { return typeof window !== 'undefined' ? window.innerHeight : 800; } /** * Update the game renderer size according to the "game resolution". * Called when game resolution changes. * * Note that if the canvas is fullscreen, it won't be resized, but when going back to * non fullscreen mode, the requested size will be used. */ updateRendererSize(): void {
@@ -189,6 +189,120 @@ namespace gdjs { gameCanvas.focus(); } + useCanvas(gameCanvas: HTMLCanvasElement): void {
GDJS/Runtime/pixi-renderers/runtimegame-pixi-renderer.ts
26
TypeScript
0.643
suggestion
326
51
51
false
Add external canvas usage to RuntimeGamePixiRenderer
7,199
4ian/GDevelop
10,154
JavaScript
4ian
danvervlad
} else { outputObjectsContainer.InsertNewObject( project, parameter.GetExtraInfo(), objectName, outputObjectsContainer.GetObjectsCount()); } // Memorize the last object name. By convention, parameters that require // an object (mainly, "objectvar" and "behavior") should be placed after // the object in the list of parameters (if possible, just after). // Search "lastObjectName" in the codebase for other place where this // convention is enforced. lastObjectName = objectName; } else if (gd::ParameterMetadata::IsBehavior(parameter.GetType())) { if (!lastObjectName.empty()) { if (outputObjectsContainer.HasObjectNamed(lastObjectName)) { const gd::String& behaviorName = parameter.GetName(); const gd::String& behaviorType = parameter.GetExtraInfo(); gd::Object& object = outputObjectsContainer.GetObject(lastObjectName); allObjectBehaviorNames[lastObjectName].insert(behaviorName); // Check if we can keep the existing behavior. if (object.HasBehaviorNamed(behaviorName)) { if (object.GetBehavior(behaviorName).GetTypeName() != behaviorType) { // Behavior type has changed, remove it so it is re-created. object.RemoveBehavior(behaviorName); } } if (!object.HasBehaviorNamed(behaviorName)) { object.AddNewBehavior( project, parameter.GetExtraInfo(), behaviorName); } } } } } // Remove objects that are not in the parameters anymore. std::set<gd::String> objectNamesInContainer = outputObjectsContainer.GetAllObjectNames(); for (const auto& objectName : objectNamesInContainer) { if (allObjectNames.find(objectName) == allObjectNames.end()) { outputObjectsContainer.RemoveObject(objectName); } } // Remove behaviors of objects that are not in the parameters anymore.
I wonder if the name can be confusing because a free function could have an object parameter without object type and the following behavior parameters be some capabilities (default behavior). It also won't be "all" the behaviors of the actual objects. I guess it's kind of the required behavior for objects passed in parameter, but "required" may be confusing as it's already used for behavior properties. ```suggestion objectAdditionnalBehaviorNames[lastObjectName].insert(behaviorName); ```
// are all present (and no more than required by the object type). // Non default behaviors coming from parameters will be added or removed later. project.EnsureObjectDefaultBehaviors(outputObjectsContainer.GetObject(objectName)); } else { // Create a new object (and its default behaviors) if needed. outputObjectsContainer.InsertNewObject( project, objectType, objectName, outputObjectsContainer.GetObjectsCount()); } // Memorize the last object name. By convention, parameters that require // an object (mainly, "objectvar" and "behavior") should be placed after // the object in the list of parameters (if possible, just after). // Search "lastObjectName" in the codebase for other place where this // convention is enforced. lastObjectName = objectName; } else if (gd::ParameterMetadata::IsBehavior(parameter.GetType())) { if (!lastObjectName.empty()) { if (outputObjectsContainer.HasObjectNamed(lastObjectName)) { const gd::String& behaviorName = parameter.GetName(); const gd::String& behaviorType = parameter.GetExtraInfo(); gd::Object& object = outputObjectsContainer.GetObject(lastObjectName); allObjectNonDefaultBehaviorNames[lastObjectName].insert(behaviorName); // Check if we can keep the existing behavior. if (object.HasBehaviorNamed(behaviorName)) { if (object.GetBehavior(behaviorName).GetTypeName() != behaviorType) { // Behavior type has changed, remove it so it is re-created. object.RemoveBehavior(behaviorName); } } if (!object.HasBehaviorNamed(behaviorName)) { object.AddNewBehavior( project, parameter.GetExtraInfo(), behaviorName); } } } } } // Remove objects that are not in the parameters anymore. std::set<gd::String> objectNamesInContainer = outputObjectsContainer.GetAllObjectNames(); for (const auto& objectName : objectNamesInContainer) { if (allObjectNames.find(objectName) == allObjectNames.end()) { outputObjectsContainer.RemoveObject(objectName);
@@ -71,7 +75,7 @@ void ParameterMetadataTools::ParametersToObjectsContainer( const gd::String& behaviorType = parameter.GetExtraInfo(); gd::Object& object = outputObjectsContainer.GetObject(lastObjectName); - allObjectBehaviorNames[lastObjectName].insert(behaviorName); + allObjectNonDefaultBehaviorNames[lastObjectName].insert(behaviorName);
Core/GDCore/Extensions/Metadata/ParameterMetadataTools.cpp
26
C++
1
suggestion
510
51
51
false
Fix default behaviors not added properly to objects in functions
7,206
4ian/GDevelop
10,154
JavaScript
D8H
4ian
parameters.removeParameter('MySpriteObject2'); expect(parameters.getParametersCount()).toBe(7); objectsContainer = new gd.ObjectsContainer(gd.ObjectsContainer.Function); gd.ParameterMetadataTools.parametersToObjectsContainer( project, parameters, objectsContainer ); // Check that object parameters are considered as objects in the objects container. expect(objectsContainer.getObjectsCount()).toBe(2); expect(objectsContainer.hasObjectNamed('MyObjectWithoutType')).toBe(true); expect(objectsContainer.hasObjectNamed('MySpriteObject')).toBe(true); const objectWithoutType = objectsContainer.getObject('MyObjectWithoutType'); expect(objectWithoutType.getType()).toBe( '' ); const mySpriteObject = objectsContainer.getObject('MySpriteObject'); expect(objectsContainer.getObject('MySpriteObject').getType()).toBe( 'Sprite' ); // Check that behaviors were also added. expect(objectsContainer.getObject('MySpriteObject').getAllBehaviorNames().toJSArray()).toEqual( ['MyFirstBehavior', 'MySecondBehavior'] ); // Call a second time and verify no changes. gd.ParameterMetadataTools.parametersToObjectsContainer( project, parameters, objectsContainer ); expect(objectsContainer.getObjectsCount()).toBe(2); expect(objectsContainer.hasObjectNamed('MyObjectWithoutType')).toBe(true); expect(objectsContainer.hasObjectNamed('MySpriteObject')).toBe(true); expect(objectsContainer.getObject('MySpriteObject').getAllBehaviorNames().toJSArray()).toEqual( ['MyFirstBehavior', 'MySecondBehavior'] ); // Verify that objects are even stable in memory. expect(objectWithoutType).toBe(objectsContainer.getObject('MyObjectWithoutType')); expect(gd.getPointer(objectWithoutType)).toBe(gd.getPointer(objectsContainer.getObject('MyObjectWithoutType'))); expect(mySpriteObject).toBe(objectsContainer.getObject('MySpriteObject')); expect(gd.getPointer(mySpriteObject)).toBe(gd.getPointer(objectsContainer.getObject('MySpriteObject'))); // Change an object type, rename a behavior and add a new object. parameters.getParameter("MyObjectWithoutType").setExtraInfo('Sprite');
Maybe `ObjectMetadata::AddDefaultBehavior` can be used to simulate a change of capability in a custom object.
parameters.removeParameter('MySpriteObject2'); expect(parameters.getParametersCount()).toBe(7); objectsContainer = new gd.ObjectsContainer(); gd.ParameterMetadataTools.parametersToObjectsContainer( project, parameters, objectsContainer ); // Check that object parameters are considered as objects in the objects container. expect(objectsContainer.getObjectsCount()).toBe(2); expect(objectsContainer.hasObjectNamed('MyObjectWithoutType')).toBe(true); expect(objectsContainer.hasObjectNamed('MySpriteObject')).toBe(true); const objectWithoutType = objectsContainer.getObject( 'MyObjectWithoutType' ); expect(objectWithoutType.getType()).toBe(''); const mySpriteObject = objectsContainer.getObject('MySpriteObject'); expect(objectsContainer.getObject('MySpriteObject').getType()).toBe( 'Sprite' ); // Check that behaviors were also added AND that default behaviors are also present. expect( objectsContainer .getObject('MySpriteObject') .getAllBehaviorNames() .toJSArray() ).toEqual([ 'Animation', 'Effect', 'Flippable', 'MyFirstBehavior', 'MySecondBehavior', 'Opacity', 'Resizable', 'Scale', ]); expect( objectsContainer .getObject('MyObjectWithoutType') .getAllBehaviorNames() .toJSArray() ).toEqual([]); // Call a second time and verify no changes. gd.ParameterMetadataTools.parametersToObjectsContainer( project,
@@ -4295,19 +4295,37 @@ describe('libGD.js', function () { expect(objectsContainer.hasObjectNamed('MyObjectWithoutType')).toBe(true); expect(objectsContainer.hasObjectNamed('MySpriteObject')).toBe(true); - const objectWithoutType = objectsContainer.getObject('MyObjectWithoutType'); - expect(objectWithoutType.getType()).toBe( - '' + const objectWithoutType = objectsContainer.getObject( + 'MyObjectWithoutType' ); + expect(objectWithoutType.getType()).toBe(''); const mySpriteObject = objectsContainer.getObject('MySpriteObject'); expect(objectsContainer.getObject('MySpriteObject').getType()).toBe( 'Sprite' ); - // Check that behaviors were also added. - expect(objectsContainer.getObject('MySpriteObject').getAllBehaviorNames().toJSArray()).toEqual( - ['MyFirstBehavior', 'MySecondBehavior'] - ); + // Check that behaviors were also added AND that default behaviors are also present.
GDevelop.js/__tests__/Core.js
26
JavaScript
0.571
suggestion
109
51
51
false
Fix default behaviors not added properly to objects in functions
7,206
4ian/GDevelop
10,154
JavaScript
D8H
4ian
std::set<gd::String> objectNamesInContainer = outputObjectsContainer.GetAllObjectNames(); for (const auto& objectName : objectNamesInContainer) { if (allObjectNames.find(objectName) == allObjectNames.end()) { outputObjectsContainer.RemoveObject(objectName); } } // Remove behaviors of objects that are not in the parameters anymore. for (const auto& objectName : allObjectNames) { if (!outputObjectsContainer.HasObjectNamed(objectName)) { // Should not happen. continue; } auto& object = outputObjectsContainer.GetObject(objectName); for (const auto& behaviorName : object.GetAllBehaviorNames()) { const auto& allBehaviorNames = allObjectBehaviorNames[objectName]; if (allBehaviorNames.find(behaviorName) == allBehaviorNames.end()) { object.RemoveBehavior(behaviorName); } } } } void ParameterMetadataTools::ForEachParameterMatchingSearch( const std::vector<const ParameterMetadataContainer*>& parametersVectorsList, const gd::String& search, std::function<void(const gd::ParameterMetadata&)> cb) { for (auto it = parametersVectorsList.rbegin(); it != parametersVectorsList.rend(); ++it) { const ParameterMetadataContainer* parametersVector = *it; for (const auto &parameterMetadata : parametersVector->GetInternalVector()) { if (parameterMetadata->GetName().FindCaseInsensitive(search) != gd::String::npos) cb(*parameterMetadata); } } } bool ParameterMetadataTools::Has( const std::vector<const ParameterMetadataContainer*>& parametersVectorsList, const gd::String& parameterName) { for (auto it = parametersVectorsList.rbegin(); it != parametersVectorsList.rend(); ++it) { const ParameterMetadataContainer* parametersVector = *it;
Actually, I think it's legit to add behavior parameters to require capabilities on an object without any specified type.
} } // Remove objects that are not in the parameters anymore. std::set<gd::String> objectNamesInContainer = outputObjectsContainer.GetAllObjectNames(); for (const auto& objectName : objectNamesInContainer) { if (allObjectNames.find(objectName) == allObjectNames.end()) { outputObjectsContainer.RemoveObject(objectName); } } // Remove behaviors of objects that are not in the parameters anymore. for (const auto& objectName : allObjectNames) { if (!outputObjectsContainer.HasObjectNamed(objectName)) { // Should not happen. continue; } auto& object = outputObjectsContainer.GetObject(objectName); const auto& allBehaviorNames = allObjectNonDefaultBehaviorNames[objectName]; for (const auto& behaviorName : object.GetAllBehaviorNames()) { if (object.GetBehavior(behaviorName).IsDefaultBehavior()) { // Default behaviors are already ensured to be all present // (and no more than required by the object type). continue; } if (allBehaviorNames.find(behaviorName) == allBehaviorNames.end()) { object.RemoveBehavior(behaviorName); } } } } void ParameterMetadataTools::ForEachParameterMatchingSearch( const std::vector<const ParameterMetadataContainer*>& parametersVectorsList, const gd::String& search, std::function<void(const gd::ParameterMetadata&)> cb) { for (auto it = parametersVectorsList.rbegin(); it != parametersVectorsList.rend(); ++it) { const ParameterMetadataContainer* parametersVector = *it; for (const auto &parameterMetadata : parametersVector->GetInternalVector()) { if (parameterMetadata->GetName().FindCaseInsensitive(search) != gd::String::npos) cb(*parameterMetadata); }
@@ -108,8 +112,14 @@ void ParameterMetadataTools::ParametersToObjectsContainer( } auto& object = outputObjectsContainer.GetObject(objectName); + const auto& allBehaviorNames = allObjectNonDefaultBehaviorNames[objectName]; for (const auto& behaviorName : object.GetAllBehaviorNames()) { - const auto& allBehaviorNames = allObjectBehaviorNames[objectName]; + if (object.GetBehavior(behaviorName).IsDefaultBehavior()) { + // Default behaviors are already ensured to be all present + // (and no more than required by the object type). + continue;
Core/GDCore/Extensions/Metadata/ParameterMetadataTools.cpp
26
C++
0.5
suggestion
120
51
51
false
Fix default behaviors not added properly to objects in functions
7,206
4ian/GDevelop
10,154
JavaScript
D8H
4ian
behavior->SetDefaultBehavior(true); }; auto &objectMetadata = gd::MetadataProvider::GetObjectMetadata(platform, objectType); if (!MetadataProvider::IsBadObjectMetadata(objectMetadata)) { for (auto &behaviorType : objectMetadata.GetDefaultBehaviors()) { addDefaultBehavior(behaviorType); } } // During project deserialization, event-based object metadata are not yet // generated. Default behaviors will be added by // MetadataDeclarationHelper::UpdateCustomObjectDefaultBehaviors else if (!project.HasEventsBasedObject(objectType)) { gd::LogWarning("Object: " + name + " has an unknown type: " + objectType); } return std::move(object); } std::unique_ptr<gd::ObjectConfiguration> Project::CreateObjectConfiguration( const gd::String& type) const { if (Project::HasEventsBasedObject(type)) { return gd::make_unique<CustomObjectConfiguration>(*this, type); } else { // Create a base object if the type can't be found in the platform. return currentPlatform->CreateObjectConfiguration(type); } } bool Project::HasEventsBasedObject(const gd::String& type) const { const auto separatorIndex = type.find(PlatformExtension::GetNamespaceSeparator()); if (separatorIndex == std::string::npos) { return false; } gd::String extensionName = type.substr(0, separatorIndex); if (!Project::HasEventsFunctionsExtensionNamed(extensionName)) { return false; } auto& extension = Project::GetEventsFunctionsExtension(extensionName); gd::String objectTypeName = type.substr(separatorIndex + 2); return extension.GetEventsBasedObjects().Has(objectTypeName); } gd::EventsBasedObject& Project::GetEventsBasedObject(const gd::String& type) { const auto separatorIndex = type.find(PlatformExtension::GetNamespaceSeparator()); gd::String extensionName = type.substr(0, separatorIndex); gd::String objectTypeName = type.substr(separatorIndex + 2);
It's probably not a big issue, but instance stability won't be ensured for capabilities required for an object without any type. Unless capabilities from parameters are not marked as default behavior?
const auto& behavior = object.GetBehavior(behaviorName); if (!behavior.IsDefaultBehavior() || behavior.GetTypeName() != behaviorType) { // Behavior type has changed, remove it so it is re-created. object.RemoveBehavior(behaviorName); } } if (!object.HasBehaviorNamed(behaviorName)) { auto* behavior = object.AddNewBehavior( project, behaviorType, behaviorName); behavior->SetDefaultBehavior(true); } }; auto &objectMetadata = gd::MetadataProvider::GetObjectMetadata(platform, objectType); if (!MetadataProvider::IsBadObjectMetadata(objectMetadata)) { // Add all default behaviors. const auto& defaultBehaviorTypes = objectMetadata.GetDefaultBehaviors(); for (auto &behaviorType : defaultBehaviorTypes) { addDefaultBehavior(behaviorType); } // Ensure there are no default behaviors that would not be required left on the object. for (const auto& behaviorName : object.GetAllBehaviorNames()) { auto& behavior = object.GetBehavior(behaviorName); if (!behavior.IsDefaultBehavior()) { // Non default behaviors are not handled by this function. continue; } if (defaultBehaviorTypes.find(behavior.GetTypeName()) == defaultBehaviorTypes.end()) { object.RemoveBehavior(behaviorName); } } } // During project deserialization, event-based object metadata are not yet // generated. Default behaviors will be added by // MetadataDeclarationHelper::UpdateCustomObjectDefaultBehaviors else if (!project.HasEventsBasedObject(objectType)) { gd::LogWarning("Object: " + name + " has an unknown type: " + objectType); } } std::unique_ptr<gd::Object> Project::CreateObject( const gd::String& objectType, const gd::String& name) const { std::unique_ptr<gd::Object> object = gd::make_unique<Object>( name, objectType, CreateObjectConfiguration(objectType)); EnsureObjectDefaultBehaviors(*object);
@@ -97,24 +95,62 @@ std::unique_ptr<gd::Object> Project::CreateObject( " has an unknown default behavior: " + behaviorType); return; } - auto* behavior = object->AddNewBehavior( - project, behaviorType, behaviorMetadata.GetDefaultName()); - behavior->SetDefaultBehavior(true); + + const gd::String& behaviorName = behaviorMetadata.GetDefaultName(); + + // Check if we can keep a behavior that would have been already set up on the object. + if (object.HasBehaviorNamed(behaviorName)) { + const auto& behavior = object.GetBehavior(behaviorName); + + if (!behavior.IsDefaultBehavior() || behavior.GetTypeName() != behaviorType) { + // Behavior type has changed, remove it so it is re-created. + object.RemoveBehavior(behaviorName); + } + } + + if (!object.HasBehaviorNamed(behaviorName)) { + auto* behavior = object.AddNewBehavior( + project, behaviorType, behaviorName); + behavior->SetDefaultBehavior(true); + } }; auto &objectMetadata = gd::MetadataProvider::GetObjectMetadata(platform, objectType); if (!MetadataProvider::IsBadObjectMetadata(objectMetadata)) { - for (auto &behaviorType : objectMetadata.GetDefaultBehaviors()) { + // Add all default behaviors. + const auto& defaultBehaviorTypes = objectMetadata.GetDefaultBehaviors(); + for (auto &behaviorType : defaultBehaviorTypes) { addDefaultBehavior(behaviorType); } + + // Ensure there are no default behaviors that would not be required left on the object. + for (const auto& behaviorName : object.GetAllBehaviorNames()) {
Core/GDCore/Project/Project.cpp
26
C++
0.571
question
201
51
51
false
Fix default behaviors not added properly to objects in functions
7,206
4ian/GDevelop
10,154
JavaScript
D8H
4ian
import { getRelativeOrAbsoluteDisplayDate } from '../Utils/DateDisplay'; const electron = optionalRequire('electron'); const path = optionalRequire('path'); export const getThumbnailWidth = ({ isMobile }: {| isMobile: boolean |}) => isMobile ? undefined : Math.min(245, Math.max(130, window.innerWidth / 4)); export const getProjectDisplayDate = (i18n: I18nType, date: number) => getRelativeOrAbsoluteDisplayDate({ i18n, dateAsNumber: date, sameDayFormat: 'todayAndHour', dayBeforeFormat: 'yesterdayAndHour', relativeLimit: 'currentWeek', sameWeekFormat: 'thisWeek', }); export const getDetailedProjectDisplayDate = (i18n: I18nType, date: number) => i18n.date(date, { dateStyle: 'short', timeStyle: 'short', }); const getNoProjectAlertMessage = () => { if (!electron) { // Trying to open a local project from the web app of the mobile app. return t`Looks like your project isn't there!${'\n\n'}Your project is surely stored on your computer.`; } else { return t`We couldn't find your project.${'\n\n'}If your project is stored on a different computer, launch GDevelop on that computer.${'\n'}Otherwise, use the "Open project" button and find it in your filesystem.`; } }; const styles = { tooltipButtonContainer: { display: 'flex', flexDirection: 'column', alignItems: 'stretch', }, buttonsContainer: { display: 'flex', flexShrink: 0, flexDirection: 'column', justifyContent: 'center', }, iconAndText: { display: 'flex', gap: 2, alignItems: 'flex-start' }, title: { ...textEllipsisStyle, overflowWrap: 'break-word', }, projectFilesButton: { minWidth: 32 }, fileIcon: { width: 16,
I'd rather say `Your project must be stored on your computer` rather than surely, it feels more english
import { getRelativeOrAbsoluteDisplayDate } from '../Utils/DateDisplay'; const electron = optionalRequire('electron'); const path = optionalRequire('path'); export const getThumbnailWidth = ({ isMobile }: {| isMobile: boolean |}) => isMobile ? undefined : Math.min(245, Math.max(130, window.innerWidth / 4)); export const getProjectDisplayDate = (i18n: I18nType, date: number) => getRelativeOrAbsoluteDisplayDate({ i18n, dateAsNumber: date, sameDayFormat: 'todayAndHour', dayBeforeFormat: 'yesterdayAndHour', relativeLimit: 'currentWeek', sameWeekFormat: 'thisWeek', }); export const getDetailedProjectDisplayDate = (i18n: I18nType, date: number) => i18n.date(date, { dateStyle: 'short', timeStyle: 'short', }); const getNoProjectAlertMessage = () => { if (!electron) { // Trying to open a local project from the web app of the mobile app. return t`Looks like your project isn't there!${'\n\n'}Your project must be stored on your computer.`; } else { return t`We couldn't find your project.${'\n\n'}If your project is stored on a different computer, launch GDevelop on that computer.${'\n'}Otherwise, use the "Open project" button and find it in your filesystem.`; } }; const styles = { tooltipButtonContainer: { display: 'flex', flexDirection: 'column', alignItems: 'stretch', }, buttonsContainer: { display: 'flex', flexShrink: 0, flexDirection: 'column', justifyContent: 'center', }, iconAndText: { display: 'flex', gap: 2, alignItems: 'flex-start' }, title: { ...textEllipsisStyle, overflowWrap: 'break-word', }, projectFilesButton: { minWidth: 32 }, fileIcon: { width: 16,
@@ -50,13 +51,37 @@ import PreferencesContext from '../MainFrame/Preferences/PreferencesContext'; import { textEllipsisStyle } from '../UI/TextEllipsis'; import FileWithLines from '../UI/CustomSvgIcons/FileWithLines'; import TextButton from '../UI/TextButton'; -import { Tooltip } from '@material-ui/core'; +import { getRelativeOrAbsoluteDisplayDate } from '../Utils/DateDisplay'; const electron = optionalRequire('electron'); const path = optionalRequire('path'); export const getThumbnailWidth = ({ isMobile }: {| isMobile: boolean |}) => isMobile ? undefined : Math.min(245, Math.max(130, window.innerWidth / 4)); +export const getProjectDisplayDate = (i18n: I18nType, date: number) => + getRelativeOrAbsoluteDisplayDate({ + i18n, + dateAsNumber: date, + sameDayFormat: 'todayAndHour', + dayBeforeFormat: 'yesterdayAndHour', + relativeLimit: 'currentWeek', + sameWeekFormat: 'thisWeek', + }); +export const getDetailedProjectDisplayDate = (i18n: I18nType, date: number) => + i18n.date(date, { + dateStyle: 'short', + timeStyle: 'short', + }); + +const getNoProjectAlertMessage = () => { + if (!electron) { + // Trying to open a local project from the web app of the mobile app. + return t`Looks like your project isn't there!${'\n\n'}Your project is surely stored on your computer.`;
newIDE/app/src/GameDashboard/GameDashboardCard.js
26
JavaScript
0.5
suggestion
103
51
51
false
Polishing the new Create tab
7,236
4ian/GDevelop
10,154
JavaScript
ClementPasteau
AlexandreSi
export const getDetailedProjectDisplayDate = (i18n: I18nType, date: number) => i18n.date(date, { dateStyle: 'short', timeStyle: 'short', }); const getNoProjectAlertMessage = () => { if (!electron) { // Trying to open a local project from the web app of the mobile app. return t`Looks like your project isn't there!${'\n\n'}Your project is surely stored on your computer.`; } else { return t`We couldn't find your project.${'\n\n'}If your project is stored on a different computer, launch GDevelop on that computer.${'\n'}Otherwise, use the "Open project" button and find it in your filesystem.`; } }; const styles = { tooltipButtonContainer: { display: 'flex', flexDirection: 'column', alignItems: 'stretch', }, buttonsContainer: { display: 'flex', flexShrink: 0, flexDirection: 'column', justifyContent: 'center', }, iconAndText: { display: 'flex', gap: 2, alignItems: 'flex-start' }, title: { ...textEllipsisStyle, overflowWrap: 'break-word', }, projectFilesButton: { minWidth: 32 }, fileIcon: { width: 16, height: 16, }, }; const locateProjectFile = (file: FileMetadataAndStorageProviderName) => { if (!electron) return; electron.shell.showItemInFolder( path.resolve(file.fileMetadata.fileIdentifier) ); }; const getFileNameWithoutExtensionFromPath = (path: string) => { // Normalize path separators for cross-platform compatibility const normalizedPath = path.replace(/\\/g, '/'); // Extract file name
maybe double check landscape/mobile/etc...
export const getDetailedProjectDisplayDate = (i18n: I18nType, date: number) => i18n.date(date, { dateStyle: 'short', timeStyle: 'short', }); const getNoProjectAlertMessage = () => { if (!electron) { // Trying to open a local project from the web app of the mobile app. return t`Looks like your project isn't there!${'\n\n'}Your project must be stored on your computer.`; } else { return t`We couldn't find your project.${'\n\n'}If your project is stored on a different computer, launch GDevelop on that computer.${'\n'}Otherwise, use the "Open project" button and find it in your filesystem.`; } }; const styles = { tooltipButtonContainer: { display: 'flex', flexDirection: 'column', alignItems: 'stretch', }, buttonsContainer: { display: 'flex', flexShrink: 0, flexDirection: 'column', justifyContent: 'center', }, iconAndText: { display: 'flex', gap: 2, alignItems: 'flex-start' }, title: { ...textEllipsisStyle, overflowWrap: 'break-word', }, projectFilesButton: { minWidth: 32 }, fileIcon: { width: 16, height: 16, }, }; const locateProjectFile = (file: FileMetadataAndStorageProviderName) => { if (!electron) return; electron.shell.showItemInFolder( path.resolve(file.fileMetadata.fileIdentifier) ); }; const getFileNameWithoutExtensionFromPath = (path: string) => { // Normalize path separators for cross-platform compatibility const normalizedPath = path.replace(/\\/g, '/'); // Extract file name
@@ -67,7 +92,7 @@ const styles = { display: 'flex', flexShrink: 0, flexDirection: 'column', - justifyContent: 'flex-end', + justifyContent: 'center',
newIDE/app/src/GameDashboard/GameDashboardCard.js
26
JavaScript
0.071
suggestion
43
51
51
false
Polishing the new Create tab
7,236
4ian/GDevelop
10,154
JavaScript
ClementPasteau
AlexandreSi
newSaveAsOptions = saveAsOptions; } if (canFileMetadataBeSafelySavedAs && currentFileMetadata) { const canProjectBeSafelySavedAs = await canFileMetadataBeSafelySavedAs( currentFileMetadata, { showAlert, showConfirmation, } ); if (!canProjectBeSafelySavedAs) return; } let originalProjectUuid = null; if (newSaveAsOptions && newSaveAsOptions.generateNewProjectUuid) { originalProjectUuid = currentProject.getProjectUuid(); currentProject.resetProjectUuid(); } let originalProjectName = null; const newProjectName = newSaveAsLocation && newSaveAsLocation.name ? newSaveAsLocation.name : null; if (newProjectName) { originalProjectName = currentProject.getName(); currentProject.setName(newProjectName); } const { wasSaved, fileMetadata } = await onSaveProjectAs( currentProject, newSaveAsLocation, { onStartSaving: () => _replaceSnackMessage(i18n._(t`Saving...`), null), onMoveResources: async ({ newFileMetadata }) => { if (currentFileMetadata) await ensureResourcesAreMoved({ project: currentProject, newFileMetadata, newStorageProvider, newStorageProviderOperations, oldFileMetadata: currentFileMetadata, oldStorageProvider, oldStorageProviderOperations, authenticatedUser, }); }, } );
just double checking this will not affect the initial project? I assume not as we're not saving that project
// ... or if the project is opened from a URL. oldStorageProvider.internalName !== 'UrlStorageProvider', }); if (!saveAsLocation) { return; // Save as was cancelled. } newSaveAsLocation = saveAsLocation; newSaveAsOptions = saveAsOptions; } if (canFileMetadataBeSafelySavedAs && currentFileMetadata) { const canProjectBeSafelySavedAs = await canFileMetadataBeSafelySavedAs( currentFileMetadata, { showAlert, showConfirmation, } ); if (!canProjectBeSafelySavedAs) return; } let originalProjectUuid = null; if (newSaveAsOptions && newSaveAsOptions.generateNewProjectUuid) { originalProjectUuid = currentProject.getProjectUuid(); currentProject.resetProjectUuid(); } let originalProjectName = null; const newProjectName = newSaveAsLocation && newSaveAsLocation.name ? newSaveAsLocation.name : null; if (newProjectName) { originalProjectName = currentProject.getName(); currentProject.setName(newProjectName); } const { wasSaved, fileMetadata } = await onSaveProjectAs( currentProject, newSaveAsLocation, { onStartSaving: () => _replaceSnackMessage(i18n._(t`Saving...`), null), onMoveResources: async ({ newFileMetadata }) => { if (currentFileMetadata) await ensureResourcesAreMoved({ project: currentProject, newFileMetadata, newStorageProvider, newStorageProviderOperations, oldFileMetadata: currentFileMetadata,
@@ -2627,6 +2633,21 @@ const MainFrame = (props: Props) => { if (!canProjectBeSafelySavedAs) return; } + let originalProjectUuid = null; + if (newSaveAsOptions && newSaveAsOptions.generateNewProjectUuid) { + originalProjectUuid = currentProject.getProjectUuid(); + currentProject.resetProjectUuid();
newIDE/app/src/MainFrame/index.js
26
JavaScript
0.357
suggestion
109
51
51
false
When duplicating a project, ask for the new name and if link with game should be kept
7,253
4ian/GDevelop
10,154
JavaScript
ClementPasteau
AlexandreSi
|}) => async ({ project, fileMetadata, }: {| project: gdProject, fileMetadata: ?FileMetadata, |}): Promise<{| saveAsLocation: ?SaveAsLocation, saveAsOptions: ?SaveAsOptions, |}> => { if (!authenticatedUser.authenticated) { return { saveAsLocation: null, saveAsOptions: null }; } const options = await new Promise(resolve => { setDialog(() => ( <SaveAsOptionsDialog onCancel={() => { closeDialog(); resolve(null); }} nameMaxLength={CLOUD_PROJECT_NAME_MAX_LENGTH} nameSuggestion={ fileMetadata ? `${project.getName()} - Copy` : project.getName() } shouldAskForGameLinkRemoval={!!fileMetadata && !!fileMetadata.gameId} onSave={options => { closeDialog(); resolve(options); }} /> )); }); if (!options) return { saveAsLocation: null, saveAsOptions: null }; // Save was cancelled. return { saveAsLocation: { name: options.name, }, saveAsOptions: { generateNewProjectUuid: options.generateNewProjectUuid, }, }; }; export const generateOnSaveProjectAs = ( authenticatedUser: AuthenticatedUser, setDialog: (() => React.Node) => void, closeDialog: () => void ) => async (
maybe name this prop `shouldAskForNewProjectUuid` to be consistent with the props you use in the component?
|}) => async ({ project, fileMetadata, displayOptionToGenerateNewProjectUuid, }: {| project: gdProject, fileMetadata: ?FileMetadata, displayOptionToGenerateNewProjectUuid: boolean, |}): Promise<{| saveAsLocation: ?SaveAsLocation, saveAsOptions: ?SaveAsOptions, |}> => { if (!authenticatedUser.authenticated) { return { saveAsLocation: null, saveAsOptions: null }; } const options = await new Promise(resolve => { setDialog(() => ( <SaveAsOptionsDialog onCancel={() => { closeDialog(); resolve(null); }} nameMaxLength={CLOUD_PROJECT_NAME_MAX_LENGTH} nameSuggestion={ fileMetadata ? `${project.getName()} - Copy` : project.getName() } displayOptionToGenerateNewProjectUuid={ displayOptionToGenerateNewProjectUuid } onSave={options => { closeDialog(); resolve(options); }} /> )); }); if (!options) return { saveAsLocation: null, saveAsOptions: null }; // Save was cancelled. return { saveAsLocation: { name: options.name, }, saveAsOptions: { generateNewProjectUuid: options.generateNewProjectUuid, }, }; }; export const generateOnSaveProjectAs = (
@@ -189,33 +190,40 @@ export const generateOnChooseSaveProjectAsLocation = ({ fileMetadata: ?FileMetadata, |}): Promise<{| saveAsLocation: ?SaveAsLocation, + saveAsOptions: ?SaveAsOptions, |}> => { if (!authenticatedUser.authenticated) { - return { saveAsLocation: null }; + return { saveAsLocation: null, saveAsOptions: null }; } - const name = await new Promise(resolve => { + const options = await new Promise(resolve => { setDialog(() => ( - <CloudSaveAsDialog + <SaveAsOptionsDialog onCancel={() => { closeDialog(); resolve(null); }} - nameSuggestion={project.getName()} - onSave={(newName: string) => { + nameMaxLength={CLOUD_PROJECT_NAME_MAX_LENGTH} + nameSuggestion={ + fileMetadata ? `${project.getName()} - Copy` : project.getName() + } + shouldAskForGameLinkRemoval={!!fileMetadata && !!fileMetadata.gameId}
newIDE/app/src/ProjectsStorage/CloudStorageProvider/CloudProjectWriter.js
26
JavaScript
0.571
question
107
51
51
false
When duplicating a project, ask for the new name and if link with game should be kept
7,253
4ian/GDevelop
10,154
JavaScript
ClementPasteau
AlexandreSi
return { saveAsLocation: { name: options.name, }, saveAsOptions: { generateNewProjectUuid: options.generateNewProjectUuid, }, }; }; export const generateOnSaveProjectAs = ( authenticatedUser: AuthenticatedUser, setDialog: (() => React.Node) => void, closeDialog: () => void ) => async ( project: gdProject, saveAsLocation: ?SaveAsLocation, options: {| onStartSaving: () => void, onMoveResources: ({| newFileMetadata: FileMetadata, |}) => Promise<void>, |} ) => { if (!saveAsLocation) throw new Error('A location was not chosen before saving as.'); const { name } = saveAsLocation; if (!name) throw new Error('A name was not chosen before saving as.'); if (!authenticatedUser.authenticated) { return { wasSaved: false, fileMetadata: null }; } options.onStartSaving(); const gameId = project.getProjectUuid(); try { // Create a new cloud project. const cloudProject = await createCloudProject(authenticatedUser, { name, gameId, }); if (!cloudProject) throw new Error('No cloud project was returned from creation api call.'); const cloudProjectId = cloudProject.id; const fileMetadata: FileMetadata = { fileIdentifier: cloudProjectId, gameId, }; // Move the resources to the new project.
why this change? was this not used?
}); if (!options) return { saveAsLocation: null, saveAsOptions: null }; // Save was cancelled. return { saveAsLocation: { name: options.name, }, saveAsOptions: { generateNewProjectUuid: options.generateNewProjectUuid, }, }; }; export const generateOnSaveProjectAs = ( authenticatedUser: AuthenticatedUser, setDialog: (() => React.Node) => void, closeDialog: () => void ) => async ( project: gdProject, saveAsLocation: ?SaveAsLocation, options: {| onStartSaving: () => void, onMoveResources: ({| newFileMetadata: FileMetadata, |}) => Promise<void>, |} ) => { if (!saveAsLocation) throw new Error('A location was not chosen before saving as.'); const { name } = saveAsLocation; if (!name) throw new Error('A name was not chosen before saving as.'); if (!authenticatedUser.authenticated) { return { wasSaved: false, fileMetadata: null }; } options.onStartSaving(); const gameId = project.getProjectUuid(); try { // Create a new cloud project. const cloudProject = await createCloudProject(authenticatedUser, { name, gameId, }); if (!cloudProject) throw new Error('No cloud project was returned from creation api call.'); const cloudProjectId = cloudProject.id; const fileMetadata: FileMetadata = { fileIdentifier: cloudProjectId,
@@ -243,7 +251,7 @@ export const generateOnSaveProjectAs = ( } options.onStartSaving(); - const gameId = saveAsLocation.gameId || project.getProjectUuid();
newIDE/app/src/ProjectsStorage/CloudStorageProvider/CloudProjectWriter.js
26
JavaScript
0.143
question
35
51
51
false
When duplicating a project, ask for the new name and if link with game should be kept
7,253
4ian/GDevelop
10,154
JavaScript
ClementPasteau
AlexandreSi
|}> => { const options = await new Promise(resolve => { setDialog(() => ( <SaveAsOptionsDialog onCancel={() => { closeDialog(); resolve(null); }} nameSuggestion={ fileMetadata ? `${project.getName()} - Copy` : project.getName() } mainActionLabel={<Trans>Continue</Trans>} shouldAskForGameLinkRemoval={!!fileMetadata && !!fileMetadata.gameId} onSave={options => { closeDialog(); resolve(options); }} /> )); }); if (!options) return { saveAsLocation: null, saveAsOptions: null }; // Save was cancelled. let defaultPath = fileMetadata ? fileMetadata.fileIdentifier : ''; if (path && defaultPath) { defaultPath = path.join(path.dirname(defaultPath), `${options.name}.json`); } const browserWindow = remote.getCurrentWindow(); const saveDialogOptions = { defaultPath, filters: [{ name: 'GDevelop 5 project', extensions: ['json'] }], }; if (!dialog) { throw new Error('Unsupported'); } const filePath = dialog.showSaveDialogSync(browserWindow, saveDialogOptions); if (!filePath) { return { saveAsLocation: null, saveAsOptions: null }; } return { saveAsLocation: { name: options.name, fileIdentifier: filePath, }, saveAsOptions: { generateNewProjectUuid: options.generateNewProjectUuid, }, };
any risk the `options.name` results in a filename that is not compatible with path? like with '/' in it?
saveAsLocation: ?SaveAsLocation, // This is the newly chosen location (or null if cancelled). saveAsOptions: ?SaveAsOptions, |}> => { const options = await new Promise(resolve => { setDialog(() => ( <SaveAsOptionsDialog onCancel={() => { closeDialog(); resolve(null); }} nameSuggestion={ fileMetadata ? `${project.getName()} - Copy` : project.getName() } mainActionLabel={<Trans>Continue</Trans>} displayOptionToGenerateNewProjectUuid={ displayOptionToGenerateNewProjectUuid } onSave={options => { closeDialog(); resolve(options); }} /> )); }); if (!options) return { saveAsLocation: null, saveAsOptions: null }; // Save was cancelled. let defaultPath = fileMetadata ? fileMetadata.fileIdentifier : ''; const { name } = options; if (path && defaultPath && name) { const safeFilename = name.replace(/[<>:"/\\|?*]/g, '_'); defaultPath = path.join(path.dirname(defaultPath), `${safeFilename}.json`); } const browserWindow = remote.getCurrentWindow(); const saveDialogOptions = { defaultPath, filters: [{ name: 'GDevelop 5 project', extensions: ['json'] }], }; if (!dialog) { throw new Error('Unsupported'); } const filePath = dialog.showSaveDialogSync(browserWindow, saveDialogOptions); if (!filePath) { return { saveAsLocation: null, saveAsOptions: null }; } return { saveAsLocation: { name: options.name,
@@ -180,16 +185,49 @@ export const onSaveProject = async ( }; }; -export const onChooseSaveProjectAsLocation = async ({ +export const generateOnChooseSaveProjectAsLocation = ({ + setDialog, + closeDialog, +}: { + setDialog: (() => React.Node) => void, + closeDialog: () => void, +}) => async ({ project, fileMetadata, }: {| project: gdProject, fileMetadata: ?FileMetadata, // This is the current location. |}): Promise<{| saveAsLocation: ?SaveAsLocation, // This is the newly chosen location (or null if cancelled). + saveAsOptions: ?SaveAsOptions, |}> => { - const defaultPath = fileMetadata ? fileMetadata.fileIdentifier : ''; + const options = await new Promise(resolve => { + setDialog(() => ( + <SaveAsOptionsDialog + onCancel={() => { + closeDialog(); + resolve(null); + }} + nameSuggestion={ + fileMetadata ? `${project.getName()} - Copy` : project.getName() + } + mainActionLabel={<Trans>Continue</Trans>} + shouldAskForGameLinkRemoval={!!fileMetadata && !!fileMetadata.gameId} + onSave={options => { + closeDialog(); + resolve(options); + }} + /> + )); + }); + + if (!options) return { saveAsLocation: null, saveAsOptions: null }; // Save was cancelled. + + let defaultPath = fileMetadata ? fileMetadata.fileIdentifier : ''; + if (path && defaultPath) { + defaultPath = path.join(path.dirname(defaultPath), `${options.name}.json`);
newIDE/app/src/ProjectsStorage/LocalFileStorageProvider/LocalProjectWriter.js
26
JavaScript
0.5
question
104
51
51
false
When duplicating a project, ask for the new name and if link with game should be kept
7,253
4ian/GDevelop
10,154
JavaScript
ClementPasteau
AlexandreSi
) : ( <Text> <Trans>You don't have any feedback for this game.</Trans> </Text> )} </> )} {displayedFeedbacksArray.length !== 0 && ( <ColumnStackLayout expand noMargin> {Object.keys(displayedFeedbacks).map((key, index) => { const title = sortByDate ? key : getBuildNameTitle(key); return ( <ColumnStackLayout key={key} noMargin> <Line justifyContent="space-between" alignItems="center" > <Column> <Text size="block-title"> {title} {title ? ' - ' : ' '} {displayedFeedbacks[key].length === 1 ? ( <Trans>1 review</Trans> ) : ( <Trans> {displayedFeedbacks[key].length} reviews </Trans> )} </Text> </Column> {index === 0 && ( <Column justifyContent="center"> <IconButton disabled={isMarkingAllAsProcessed} onClick={event => openOptionsContextMenu(event)} > {!isMarkingAllAsProcessed ? ( <Options fontSize="small" /> ) : ( <CircularProgress size={20} /> )} </IconButton> </Column> )} </Line> {displayedFeedbacks[key].map( (comment: Comment, index: number) => ( <FeedbackCard key={comment.id} comment={comment} buildProperties={getBuildPropertiesForComment(
I don't think that's useful, let's not do it
value={''} label={t`All exports`} /> <SelectOption key={'game-only'} value={'game-only'} label={t`On game page only`} /> {Object.keys(buildsByIds).map(buildId => { return ( <SelectOption key={buildId} value={buildId} label={getBuildNameOption(buildId)} /> ); })} </SelectField> </div> </Line> </Column> )} </ResponsiveLineStackLayout> <ColumnStackLayout expand noMargin> {!!feedbacks && feedbacks.length > 0 && ( // TODO: Should it display the data for the filtered pieces of feedback only? <FeedbackAverageCard feedbacks={feedbacks} /> )} </ColumnStackLayout> {displayedFeedbacks.length === 0 && ( <> {showProcessed ? ( <LineStackLayout alignItems="center" justifyContent="center" > <EmptyMessage> {isShowingCommentsForASpecificBuild ? ( <Trans> You don't have any unread feedback for this export. </Trans> ) : ( <Trans> You don't have any unread feedback for this game. </Trans> )} </EmptyMessage> <FlatButton onClick={() => setShowProcessed(false)} label={<Trans>Show all feedbacks</Trans>} />
@@ -374,89 +419,154 @@ const GameFeedback = ({ i18n, authenticatedUser, game }: Props) => { </ResponsiveLineStackLayout> <ColumnStackLayout expand noMargin> {!!feedbacks && feedbacks.length > 0 && ( + // TODO: Should it display the data for the filtered pieces of feedback only?
newIDE/app/src/GameDashboard/Feedbacks/GameFeedback.js
26
JavaScript
0.143
suggestion
44
51
51
false
Paginate feedbacks
7,259
4ian/GDevelop
10,154
JavaScript
4ian
AlexandreSi
// - The normal keeps the same length (as the normal is included in the 2D space) this._slopeClimbingMinNormalZ = Math.min( Math.cos(gdjs.toRad(slopeMaxAngle)), 1 - 1 / 1024 ); } getStairHeightMax(): float { return this._stairHeightMax; } setStairHeightMax(stairHeightMax: float): void { const { extendedUpdateSettings } = this.getPhysics3D(); this._stairHeightMax = stairHeightMax; console.log(stairHeightMax); const walkStairsStepUp = stairHeightMax * this._sharedData.worldInvScale; extendedUpdateSettings.mWalkStairsStepUp = this.getVec3( 0, 0, walkStairsStepUp ); // Use default values proportionally; extendedUpdateSettings.mWalkStairsMinStepForward = (0.02 / 0.4) * walkStairsStepUp; extendedUpdateSettings.mWalkStairsStepForwardTest = (0.15 / 0.4) * walkStairsStepUp; } /** * Get the gravity of the Character. * @returns The current gravity. */ getGravity(): float { return this._gravity; } /** * Set the gravity of the Character. * @param gravity The new gravity. */ setGravity(gravity: float): void { this._gravity = gravity; } /** * Get the maximum falling speed of the Character. * @returns The maximum falling speed. */ getMaxFallingSpeed(): float { return this._maxFallingSpeed; }
Is there an explanation for those factors?
// - The normal keeps the same length (as the normal is included in the 2D space) this._slopeClimbingMinNormalZ = Math.min( Math.cos(gdjs.toRad(slopeMaxAngle)), 1 - 1 / 1024 ); } getStairHeightMax(): float { return this._stairHeightMax; } setStairHeightMax(stairHeightMax: float): void { const { extendedUpdateSettings } = this.getPhysics3D(); this._stairHeightMax = stairHeightMax; const walkStairsStepUp = stairHeightMax * this._sharedData.worldInvScale; extendedUpdateSettings.mWalkStairsStepUp = this.getVec3( 0, 0, walkStairsStepUp ); // Use default values proportionally; // "The factors are arbitrary but works well when tested in a game." extendedUpdateSettings.mWalkStairsMinStepForward = (0.02 / 0.4) * walkStairsStepUp; extendedUpdateSettings.mWalkStairsStepForwardTest = (0.15 / 0.4) * walkStairsStepUp; } /** * Get the gravity of the Character. * @returns The current gravity. */ getGravity(): float { return this._gravity; } /** * Set the gravity of the Character. * @param gravity The new gravity. */ setGravity(gravity: float): void { this._gravity = gravity; } /** * Get the maximum falling speed of the Character. * @returns The maximum falling speed. */ getMaxFallingSpeed(): float { return this._maxFallingSpeed; }
@@ -783,6 +791,27 @@ namespace gdjs { ); } + getStairHeightMax(): float { + return this._stairHeightMax; + } + + setStairHeightMax(stairHeightMax: float): void { + const { extendedUpdateSettings } = this.getPhysics3D(); + this._stairHeightMax = stairHeightMax; + console.log(stairHeightMax); + const walkStairsStepUp = stairHeightMax * this._sharedData.worldInvScale; + extendedUpdateSettings.mWalkStairsStepUp = this.getVec3( + 0, + 0, + walkStairsStepUp + ); + // Use default values proportionally; + extendedUpdateSettings.mWalkStairsMinStepForward = + (0.02 / 0.4) * walkStairsStepUp; + extendedUpdateSettings.mWalkStairsStepForwardTest = + (0.15 / 0.4) * walkStairsStepUp;
Extensions/Physics3DBehavior/PhysicsCharacter3DRuntimeBehavior.ts
26
TypeScript
0.071
question
42
51
51
false
Add a property to choose the maximum stair height a 3D character can walk
7,265
4ian/GDevelop
10,154
JavaScript
AlexandreSi
D8H
End of preview. Expand in Data Studio

Code Review Diffs

A large-scale dataset of (before_code, reviewer_comment, after_code) triplets extracted from merged pull requests on top GitHub repositories, including negative examples of clean code that received no reviewer comments.

Dataset Description

Each row captures a moment where a human code reviewer left an inline comment on a pull request, and the author subsequently modified the code in response. The dataset also includes negative examples — code from the same PRs that passed review without comments — to help models learn when code is acceptable.

This provides a natural signal for training models to:

  • Generate code review comments given a code diff
  • Apply review feedback by modifying code based on reviewer suggestions
  • Understand code quality patterns across languages and projects
  • Know when not to comment — recognizing clean code that needs no changes

Key Features

  • 118K+ positive triplets from 562 top GitHub repositories
  • Negative examples (~30% ratio) of clean code labeled "No issues found."
  • 20+ programming languages (Python, TypeScript, Go, C++, Rust, JavaScript, C#, Java, Kotlin, Swift, and more)
  • Quality-filtered: bot comments, noise ("LGTM", "+1"), and auto-generated content removed
  • Chunk-focused: ~50 lines of context around the reviewed code, not entire files
  • Permissive licenses only: all source repos use MIT, Apache-2.0, BSD, or similar licenses
  • Verified changes: only includes triplets where the code chunk actually changed after the review

Schema

Column Type Description
before_code string ~50 lines of code around the comment, before the fix
reviewer_comment string The inline review comment text (or "No issues found." for negatives)
after_code string ~50 lines of code around the comment, after the fix
diff_context string The PR diff hunk where the comment was placed
file_path string File path within the repo
comment_line int Line number where the comment was placed (0 for negatives)
language string Programming language
quality_score float Comment quality score (0.0-1.0; 1.0 for negatives)
comment_type string Category: suggestion, question, nitpick, bug, refactor, style, security, performance, none
comment_length int Character count of reviewer comment
before_lines int Line count of before code
after_lines int Line count of after code
is_negative bool True if this is a negative example (no reviewer comment)
pr_title string Pull request title
pr_number int PR number
repo_name string Full repo name (owner/repo)
repo_stars int GitHub stars
repo_language string Primary repo language
reviewer_username string Reviewer's GitHub username
author_username string PR author's GitHub username

Usage

from datasets import load_dataset

ds = load_dataset("ronantakizawa/github-codereview")

# Get a training example
example = ds["train"][0]
print(f"Review comment: {example['reviewer_comment']}")
print(f"Language: {example['language']}")
print(f"Before:\n{example['before_code'][:200]}")
print(f"After:\n{example['after_code'][:200]}")

Filter by language

python_reviews = ds["train"].filter(lambda x: x["language"] == "Python")

Filter by quality

high_quality = ds["train"].filter(lambda x: x["quality_score"] >= 0.5)

Positive examples only

positives = ds["train"].filter(lambda x: not x["is_negative"])

Negative examples only

negatives = ds["train"].filter(lambda x: x["is_negative"])

Collection Methodology

  1. Repo selection: Top 10,000 GitHub repos by stars with permissive licenses from ronantakizawa/github-top-projects
  2. PR discovery: Paginate merged PRs, filter bot authors, fetch inline review comments
  3. Comment filtering: Remove bots, noise patterns, auto-generated comments, non-English text, non-code files, reply comments
  4. Triplet extraction: Fetch file contents at the review commit (before) and PR head (after), extract focused chunks around the comment line
  5. Change verification: Only keep triplets where the code chunk around the comment actually changed
  6. Negative extraction: For each reviewed PR, identify source code files that were changed but received no review comments; extract a ~50-line chunk as a negative example labeled "No issues found."

Quality Filters Applied

  • Bot authors excluded (dependabot, renovate, codecov, etc.)
  • Comments < 30 characters excluded
  • Noise patterns excluded (LGTM, +1, emoji-only, etc.)
  • Auto-generated comments excluded (coverage reports, CI output)
  • Non-English comments excluded (ASCII ratio < 70%)
  • Non-source-code files excluded
  • Reply comments excluded (only top-level review comments)
  • Files > 512 KB excluded
  • PRs with < 10 or > 500 changed lines excluded

Splits

Split Percentage Description
train 90% Training data
test 5% Test data
validation 5% Validation data

Splits are deterministic by repository — all examples from the same repo appear in the same split.

Limitations

  • Review comments may address style/formatting rather than substantive logic changes
  • The "after" code may include changes unrelated to the specific review comment
  • Line number alignment may be imprecise when multiple commits occur between review and merge
  • Some original_commit_id SHAs may be unavailable due to force-pushes; in these cases, the PR merge base is used as the "before" state
  • Negative examples assume that uncommented code was acceptable, though reviewers may have simply not reviewed certain files

Citation

If you use this dataset, please cite:

@dataset{takizawa2026codereviewdiffs,
  title={Code Review Diffs: A Large-Scale Dataset of Review-Driven Code Changes},
  author={Takizawa, Ronan},
  year={2026},
  publisher={Hugging Face},
  url={https://huggingface.co/datasets/ronantakizawa/github-codereview}
}
Downloads last month
-