A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
chore: the Cocos project importer and the cc compatibility layer are held on the cocos-import branch and are not part of this release
yhh2973611798f3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 330ab0999..32a7643d5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,23 +23,11 @@ published separately; it ships inside the editor.- **Scroll areas can be pulled past an end and spring back.** A scroll area whose movement is Elastic now does what the setting always said: a drag past an end is stiffer the further out it goes, letting go returns the content, and a flick that reaches an end bounces off it. It is opt-in per area (`ScrollMovement.Elastic`; Clamped, the default, behaves as before), and the gesture model (`ScrollMotion`, with `ScrollContainer.dragTo` and `getOverscroll`) is exported for scrolling anything else the same way.- **More easing curves.** Sine, quart, quint, expo and circ (each in, out and in-out), bounce in and in-out, and smoothstep and smootherstep join the quad, cubic, back, elastic and out-bounce curves. They are new `EasingType` members after the existing ones, so a saved tween keeps its curve, and they ease the same in a C++ tween and a script value tween.- **World content has a rectangle: `ContentRect`.** A size and the pivot the entity's transform sits on, which the `Sprite` and `Text` on the entity follow and which a `UIMask` on it clips to — no `UINode` needed, so a clipping region or a scroll viewport can stand in the world. `contentRectContains` tests a world point against it.-- **Edited Cocos documents move to RectAnchors.** A converted document the creator edited is left as it is on re-import, except that its `Cocos.Widget` components become the engine `RectAnchors` (same fields, no `target`), so a project converted before the change keeps its alignment.- **RectAnchors: world content that follows its parent.** A new engine component pins content placed by its `Transform` and sized by a `ContentRect` to the edges or centre of its parent rectangle (stretch, pin to an edge, centre with an offset, margins in units or as a fraction), or, with no parent rectangle, to the screen, which is centred on the world origin. An engine system aligns parents before the children that depend on them, in the editor edit mode as well as in play, on ONCE / ON_RESIZE / ALWAYS. The Cocos `Widget` is now a view on it, and a converted project carries `RectAnchors` instead of a compatibility-layer component, so a scene is laid out where the editor shows it. The visible area of the Cocos layer is centred on the origin, as the engine screen is.-- **A converted Cocos project fits the screen as the game does.** The Cocos design fit (fit width, fit height) becomes the project camera scale mode (fixed width, fixed height), so a UI laid out in design units comes out the same size on every screen instead of being drawn at the window pixel size. `cc.profiler` (`showStats`, `hideStats`) is accepted by the compatibility layer.-- **A Cocos node layer is its renderers layer.** The sprites, texts, shapes, spine, particles and meshes of a converted node are put in the layer the node had in Cocos (its bit index), which is what a camera culling mask selects among. A UI camera that draws only layer 25 used to draw none of the sprites left in layer 0, so the converted game launch scene was black.-- **A converted Cocos project starts as the game does.** The project opens at the Cocos launch scene (not the starter empty scene) and its design size, scripts that only define globals (the game configuration) run before the ones scenes name, and the editor built-in assets a scene names by uuid (the default progress bar images) are read from the Creator install, which took the missing sprite frames of the client from 385 to 15.-- **Cocos layer components survive a replay.** The components the layer declares (Widget, Button, ProgressBar, ScrollView and the rest) are counted among the engine own, so clearing the registry for a replay no longer drops them, and the host walks its script query before running scripts, so a script that switches nodes on in `start` does not meet a walked query.-- **A material colour is the renderer tint.** The engine keeps a mesh colour on the renderer, not in a shader parameter, so `mainColor`, `albedo`, `baseColor` and `color` set on a renderer own material instance write its tint and read back from it.-- **Mesh renderers and materials in the Cocos layer.** `MeshRenderer` is a view on the engine mesh renderer: `getSharedMaterial`, `getMaterialInstance` (the engine own per-renderer instance, made once), `material`, `setMaterial`, and `Material.setProperty` / `getProperty` writing through to the engine material (colours 0..255 become 0..1). `ModelRenderer` and `UIMeshRenderer` exist, and `cc.geometry` has `AABB`, `Ray`, `Plane` and the box, ray and plane tests.-- **More of `cc`.** `js` (class names and lookup, `isChildClassOf`, `mixin`, `addon`, property definers), `ccenum` and `NodePool` (put a node away, get it back, with the handler component told `unuse` and `reuse`) are in the Cocos compatibility layer.- **The script bundle is not rebuilt for nothing.** The project-script bundle is stamped with every file it read (size and modification time) and the build tool that made it, and Play builds it again only when one of those changed: a project of thousands of scripts goes from a multi-second build at every Play to a check of a few hundred milliseconds.-- **Two Cocos classes with one name.** Cocos tells classes apart by their script, so two scripts may write the same `@ccclass` name. The converted project gives the second its own component name (`Name_2`, in path order), writes which script that was beside the entry, and the bundler writes the new name into that script decorator.- **Large projects open faster.** The asset dependency scan no longer asks the path index about every string in every document (names, types and labels cannot be paths), which took the open of a 5000-document project from 17 s to under 5 s, and the Cocos script rewrite makes two passes over a file instead of one per declaration.-- **A model texture the project does not have is left off.** A model whose material names a texture file that is not there is imported without it, with a warning, instead of keeping a reference that fails to load on every use.+- **A model texture the project does not have is left off.** A model whose material names a texture file that is not there is imported without it, with a warning, instead of keeping a reference that fails to load on every use. A texture the model names by a path on the artist's machine is looked for by its file name beside the model first.- **An unlit mesh variant with tangents links.** The fragment stage declared the tangent varying wherever a mesh had tangents, though the vertex stage wrote it only when lit, so an unlit variant failed to link.-- **Cocos scripts load one by one.** Each script of a converted project loads on its own, so one whose module throws no longer stops the rest from registering their components. A part of the `cc` module the layer does not provide is a stand-in that survives being read, called and constructed (and says once that it is missing) rather than `undefined`. `Director` is a class scripts can patch, `AssetManager.Cache` exists, and `input._registerEventDispatcher` is accepted.-- **A converted Cocos project links its images.** The source images, fonts and spine files are hard-linked into the converted project (copied only across drives), so a multi-gigabyte art folder is neither copied nor stored twice, and a re-import skips what is already linked. The project reads those files and never writes into them.-- **A Cocos conversion shows its progress.** The importer reports the stage it is in and how far through it is, and the editor runs the conversion on a thread of its own with a progress bar over the window, instead of freezing until it ends.- **Bursts on a schedule.** `ParticleEmitter.bursts` is a list of `{ time, count }`: each releases its particles once the emitter has been emitting for `time` seconds, and a looping emitter repeats the list every `duration`. It runs beside `burstCount`, which still repeats one burst on an interval.- **A 3D collider can sit off its entity.** `BoxCollider3D`, `SphereCollider3D` and `CapsuleCollider3D` take an optional `center`, the shape's place from the entity origin in world units. The body stays at the entity, so a dynamic body turns about its origin and the shape swings round it.- **Text can underline, and a box can grow to its text.** `Text.underline` draws a bar under each line, taken from the font's own underscore. `TextOverflow.ResizeHeight` keeps every line and sets the entity's `ContentRect` height to the height they take, so what sits below a paragraph can follow it.@@ -49,8 +37,6 @@ published separately; it ships inside the editor.- **An emitter can start late.** `ParticleEmitter.startDelay` holds back emission for that many seconds after the emitter starts playing; the duration of a non-looping emitter is counted from the end of the delay. Zero, the default, is the behaviour before.- **Particles can be stretched along their velocity.** `ParticleEmitter.renderMode` is `Billboard` (as before) or `Stretched`, which turns each particle's quad so its Y axis runs along the particle's velocity and makes it `size * lengthScale + speed * velocityScale` long: sparks, rain and streaks. A particle at rest keeps its own rotation. It is drawn by the CPU simulation; an emitter simulated on the GPU still draws as a billboard.- **Fade a whole group of world content with one value: `GroupOpacity`.** On an entity it fades that entity and everything under it; the opacities multiply down the hierarchy into each descendant's own alpha, as `UINode.opacity` does for a UI subtree. Sprites, text, shapes, trails and tilemap layers follow it. It is not a composited layer, so children that overlap show through one another while the group is partly faded.-- **Open a Cocos Creator project from the editor.** Choosing a Cocos Creator 3.x folder in Open Project (recognised by the Creator version in its `package.json`) offers to convert its scenes and prefabs into a new Estella project beside it, `<name>-estella`, and opens that; the Cocos folder is only read. Opening the same folder again opens the converted project instead of converting twice.-- **Re-import a Cocos project without losing your edits.** Run Re-import Cocos Project in a project converted from Cocos Creator and the scenes and prefabs changed on the Cocos side are brought across, new ones are added, and a document you edited here is left as it is and counted in the result. After the first conversion a message lists the components that did not come across (their data is kept on the entity, but nothing runs), most used first.- **A held pointer reports where it goes, and a hold can be given up.** `pointer_move` goes to the entity a pointer is holding for as long as it is held, `press_cancel` to one whose hold was taken away (`UIControlPointers.cancelHold`, optionally handing the gesture to another entity, so a scroll area can take a drag from the button under it), and every pointer event now says which pointer it was and where, in the world and on the surface. An entity that is only a `ContentRect` with an `Interactable` can be the one pressed.- **The engine's runtime tuning is a project setting.** Project Settings → Game → Runtime sets how a scene switch fades (duration and colour), how far one frame may advance the game and how many fixed steps it may catch up, how long an asset may take to load and how soon a failed one is tried again, how much memory the texture, audio and device-loss caches keep, the text canvas size and the default font family. They were reachable only from code (`RuntimeConfig`) and no project file could carry them. The project holds `features.runtime` with only what differs from the engine's own values (`RUNTIME_BUILD_DEFAULTS`), a build ships the same block, and `initRuntime` applies it before the first asset loads on the web, desktop, native, mini-game and playable targets and in Play. The edit viewport keeps the engine's values.- **Rows for the choices that could only be written into the project file.** Under Rendering: compile shaders in the background, warm them up behind the loading screen and how long to wait, draw only changing frames and how many frames to keep after a change, each level's anti-aliasing (MSAA or temporal; the MSAA count is hidden where temporal ignores it) and its depth pre-pass. Under Game → Display: the render resolution (screen, design resolution or integer multiple). Under the web build: the servers the page may connect to, each checked by the parser the export uses. `check-project-settings` now reads the keys of `QualityConfig`, `QualityProfile` and `RuntimeBuildConfig` and fails a key that has no row and no stated reason, which is how these went unnoticed behind the one row the block had.@@ -74,12 +60,7 @@ published separately; it ships inside the editor.- **Virtual prefab instances.** A prefab instance marked virtual (the Virtual toggle in the prefab bar of Details, or the outliner's context menu; `deferred` in its metadata) is shown and edited whole in the editor, but a running scene makes only its root and builds the rest when it is opened, so a screen of many pages does not pay for the ones nobody opens; `UIPages` registers such instances as pages. An instance that adds, removes or re-parents parts is made whole. `?expand-virtual` in the page address makes every virtual instance whole at boot, for a harness that expects every node, leaving out one marked as another layout, and `deferredEntities` and `deferredRecord` are exported for a game that keeps two layouts this way.- **The loading screens say how far they are.** One bar, a line per step with its count and time, and the time so far; the engine step says which step of the boot it is in, and the asset scan reports how many documents it has read of how many.- **A material can read a mesh's second uv set.** In a mesh variant that carries one (`MESH_LIGHTMAP`), the vertex stage hands the material the mesh's second uv set as authored, `v_texCoord1`, beside the lightmap coordinates, for a mask or a dissolve map.-- **Cocos scripts drive scenes as the game does.** `director.loadScene` runs a project scene through the engine's scene manager (the scenes are in the manifest, and a persistent root is `SceneOwner.persistent`), a scene's components start in one phase before the frame's updates, and `director` has a scheduler and fires its frame events. A node's scripts load and enable as it joins an active parent or is switched on, not a frame later, and a node made between frames joins the running world. `setSiblingIndex` reorders through the engine's entity order, `getComponent` finds a component by a base class it derives from or by its `cc.` name, and `Component.EventHandler`, `Node.getParent` and `Camera.screenPointToRay` exist. Sprites, labels and graphics accept the rebuild requests scripts send, and the design resolution is known to scripts before they run. A Play that follows another in the same script runtime gets the layer's systems again and none of what the last one loaded.-- **Cocos scripts load assets by path.** `resources.load` gives images, sprite frames and audio by path, and finds an image's `spriteFrame` and `texture` by the end of the path; `Sprite` takes a `spriteFrame`. A directory load leaves out what the layer cannot load instead of failing, `loadAny` takes a uuid, a loaded asset is named for its file and counts its holders, and `assetManager` has a downloader and a factory.-- **A converted project's scripts are components the editor knows.** The converted project declares the component classes of every script, since a game opens its views by class name, and they reach the inspector; the script entry leaves out Cocos's own editor scripts, and the scripts bundle past the gaps Cocos tolerates (missing `cc` names, a reassigned `const`, package files outside `exports`, imports used only in preview).-- **A Cocos project's own effects are converted.** An effect becomes an Estella shader and material, so a sprite, a mesh or a particle that wore it keeps its look: its chunks are included, its vertex program is carried into the fragment, a vertex displacement becomes the material's vertex hook with a derived WebGPU twin, and each macro combination is one shader, compiled and given its WebGPU twin before it is written. The sprite texture is not made a material parameter, a blend state the material does not set is the effect's, and the import progress has a stage for checking the converted effects.-- **Converted Cocos UI looks as it does in Cocos.** The UI layer is painted in hierarchy order, so a popup covers the text of the view under it. A root pinned to the screen is stored where the engine places it in the design box, so the document and the viewport agree, and the Cocos `Layout` runs between the engine's two anchor passes instead of keeping a second copy of the alignment. A Label with no overflow rule does not wrap and is laid out from its anchor, a Label takes a game's replaced string setter, and an EditBox becomes the engine's text field with its two labels folded in, showing its text label while it holds text. An inactive node becomes the `Disabled` tag, so its subtree goes with it instead of being stranded; enums are the engine's numbers; and a bitmap font's page ships at its full size with its meta, not halved by the default 2048 cap.-- **A converted Cocos project is brought up to date when it is opened.** The importer records its revision in the project, and a project written by an older importer is converted again when the editor opens it.+- **Paste textures onto a blank texture: `TextureCanvas`.** `TextureCanvas.create(width, height)` gives a canvas whose `draw(source, x, y, width?, height?)` pastes a texture at a pixel position, in the order you call it, and whose `texture` a `Sprite` shows. Where `TextureAtlas.pack` lays textures out for you, this puts each one where you say.### Changed@@ -108,6 +89,11 @@ published separately; it ships inside the editor.- **A project script bundle that throws while it loads is reported.** Play logged nothing and ran as though the project had no scripts; the error is now logged.- **A playable far over its size cap is built at once and says its size.** The search for a smaller page built the whole page, a base64 copy of every asset, for each candidate encoding, so a game of 140 images never finished; the size is now worked out from the parts, the search is skipped when what no encoder can shrink is already over the cap, each stage reports itself, and a page over the network's limit is a warning with its size instead of a failed build. A 57 MB game went from no answer to 4 s.- **The status strip fits a narrow window.** Each readout keeps to one line, and when the strip is short of room it drops the long message and the least useful readouts instead of wrapping.+- **A texture keeps the colour under its clear texels when it is made smaller or read back.** A texture that stores numbers in its colour where it is clear (a terrain weight map) came out black after a Max Size resize or a read back through a 2D canvas, which keeps what it holds premultiplied. The resize and the read back now keep the colour.+- **A camera that clears no colour is drawn over the main view.** A full-frame camera that only clears depth (a UI camera) competed with the world camera to be the main view and hid its picture; it is now drawn over it.+- **Stopping Play closes the connections the game opened.** The play window is kept between plays, and a socket the last play opened stayed connected, so a game that logs in as the same account on the next play was told it had signed in somewhere else.+- **A drop on an Outliner row lands.** A drop that arrived before the hover had been drawn was lost; the drop now asks for its own answer when the one it holds is for another row.+- **A play that cannot start says why.** Every compile error of the project scripts is printed to the output log, and the status line gives the reason instead of only saying it failed.## [0.96.0] - 2026-10-27diff --git a/desktop b/desktopindex c993e8c86..c4682f6b8 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit c993e8c86b481a759ba6da5e63dde6aba1bbd01d+Subproject commit c4682f6b81920520744b14496a61356e860515c4diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjsindex 8fdde02fa..1411a6fd2 100644--- a/docs/astro/astro.config.mjs+++ b/docs/astro/astro.config.mjs@@ -170,7 +170,6 @@ export default defineConfig({{ label: 'Play in the Editor', translations: { 'zh-CN': '编辑器内运行' }, slug: 'editor/play' },{ label: 'Asset Editors', translations: { 'zh-CN': '专用编辑器' }, slug: 'editor/asset-editors' },{ label: 'Project Settings', translations: { 'zh-CN': '项目设置' }, slug: 'editor/settings' },- { label: 'Importing a Cocos Project', translations: { 'zh-CN': '导入 Cocos 项目' }, slug: 'editor/cocos-import' },{ label: 'History, Scatter & Health', translations: { 'zh-CN': '历史、散布与健康' }, slug: 'editor/history-scatter-health' },{ label: 'Keyboard Shortcuts', translations: { 'zh-CN': '键盘快捷键' }, slug: 'editor/shortcuts' },],diff --git a/docs/astro/src/content/docs/assets/models.mdx b/docs/astro/src/content/docs/assets/models.mdxindex 65d3ef12c..d330b3ca7 100644--- a/docs/astro/src/content/docs/assets/models.mdx+++ b/docs/astro/src/content/docs/assets/models.mdx@@ -19,8 +19,8 @@ That import is the subject of this page. For the component that draws the result## Built-in primitivesSeven shapes need no import and no file. **+ Add → Create entity… → Cube** (or Sphere, Capsule, Cylinder,-Cone, Plane, Cocos Plane, Quad) makes an entity whose `MeshRenderer.mesh` holds a `builtin:` ref, and the-same eight appear at the top of the picker on any `MeshRenderer.mesh` field.+Cone, Plane, Quad) makes an entity whose `MeshRenderer.mesh` holds a `builtin:` ref, and the+same seven appear at the top of the picker on any `MeshRenderer.mesh` field.| Ref | Shape ||---|---|@@ -30,7 +30,6 @@ same eight appear at the top of the picker on any `MeshRenderer.mesh` field.| `builtin:cylinder` | 100-unit upright cylinder, flat caps || `builtin:cone` | 100-unit cone standing on its base || `builtin:plane` | 100-unit square in XZ, facing up — a ground |-| `builtin:cocos-plane` | the ground square of Cocos Creator: 10 units across, the v of its texture running along +z as a map's does — what an effect written against Cocos's plane reads || `builtin:quad` | 100-unit square in XY, facing the camera — a backdrop |They are built in code at load time, so they cost no bytes in a package and a scene thatdiff --git a/docs/astro/src/content/docs/editor/cocos-import.mdx b/docs/astro/src/content/docs/editor/cocos-import.mdxdeleted file mode 100644index 7336fff44..000000000--- a/docs/astro/src/content/docs/editor/cocos-import.mdx+++ /dev/null@@ -1,108 +0,0 @@-----title: Importing a Cocos Creator project-description: "Open a Cocos Creator 3.x project in the editor, what the conversion carries over, how re-import keeps your edits, and the cc compatibility layer that runs the project's scripts."------import { Aside } from '@astrojs/starlight/components';--The editor can bring a **Cocos Creator 3.x** project across: its scenes, prefabs, scripts and-assets become an Estella project that you keep editing here. The Cocos folder is only ever read.--## Open a Cocos project--Choose a Cocos Creator folder in **Open Project**. The editor recognises it by the Creator-version in its `package.json` and offers to convert it into a new project beside it, named-`<name>-estella`, and then opens that. Opening the same Cocos folder again opens the converted-project instead of converting twice.--The conversion shows its progress: the stage it is in and how far through it is, in a bar over the-window. It runs off the editor's main thread, so the window does not freeze.--- **Images, fonts and spine files are linked, not copied.** They are hard-linked into the converted- project (copied only across drives), so a multi-gigabyte art folder is neither duplicated nor- stored twice. The project reads those files and never writes into them.-- **The project starts as the game does.** It opens at the Cocos launch scene with the Cocos- design size, and scripts that only define globals (the game configuration) run before the ones- scenes name. Editor built-in assets that a scene names by uuid, such as the default progress bar- images, are read from your Creator install.-- **Components that did not come across are listed.** After the first conversion, a message lists- the components that have no counterpart, most used first. Their data is kept on the entity, but- nothing runs for them.-- **The Cocos project's own effects are converted** into Estella shaders and materials, so a sprite,- mesh or particle that used one keeps its look.--## What the conversion keeps--**Screen fit.** The Cocos design fit (fit width, fit height) becomes the project camera's scale-mode (fixed width, fixed height), so a UI laid out in design units comes out the same size on every-screen. See [Screen & Design Resolution](/docs/core-concepts/screen/).--**Layers.** A node's Cocos layer becomes the layer of its sprites, texts, shapes, spine, particles and-meshes (the layer's bit index), which is what a camera's culling mask selects among. A UI camera-that draws only one layer therefore draws what it did in Cocos.--**UI.** Converted UI behaves as it does in Cocos:--- The UI layer is painted in hierarchy order, so a popup covers the text of the view under it- (see [hierarchy-order layers](/docs/graphics/sprites/#hierarchy-order-layers)).-- `Widget` becomes the engine's [`RectAnchors`](/docs/ui/overview/#rectanchors--world-content-that-follows-its-parent)- on a [`ContentRect`](/docs/ui/overview/#contentrect--a-rectangle-for-world-content), so the scene is- laid out in the editor where it will run. A root pinned to the screen is stored where the engine- places it in the design box. The Cocos `Layout` runs between the engine's two anchor passes.-- A Label with no overflow rule does not wrap and is laid out from its anchor.-- An `EditBox` becomes the engine's text field with its two labels folded in.-- An inactive node becomes the `Disabled` tag, and its subtree goes with it.-- Bitmap font pages keep their full size.--**Scripts.** Each script's component classes are declared to the editor, so they reach the-Inspector. Scripts are bundled with Cocos's tolerated gaps (missing `cc` names, a reassigned-`const`, package files outside `exports`, imports used only in preview). Two scripts that write the-same `@ccclass` name are told apart: the second gets its own component name (`Name_2`, in path-order), the converter writes which script that was beside the entry, and the bundler writes the new-name into that script's decorator. The script bundle is rebuilt on Play only when a file it read-changed.--## Re-import without losing your edits--Run **Re-import Cocos Project** in a project converted from Cocos Creator. Scenes and prefabs that-changed on the Cocos side are brought across and new ones are added. A document you edited here is-left as it is and counted in the result, for example *3 new, 2 updated, 5 kept because you edited-them*. The one exception is `Cocos.Widget` components on an edited document, which are turned into-`RectAnchors` (same fields), so a project converted by an older importer keeps its alignment.--A converted project records the importer's revision. When the editor opens a project written by an-older importer, it is converted again.--Running the command in a project that did not come from Cocos tells you so and changes nothing.--## The `cc` compatibility layer--Cocos scripts keep working because the project's scripts are built with `cc` resolved to the-engine's Cocos layer (`esengine/cocos`). A `Node` there is an entity and a `Component` subclass is an-Estella component. Parts of Cocos with no counterpart are not simulated: a part of the `cc` module the-layer does not provide is a stand-in that survives being read, called and constructed, and says-once that it is missing, rather than `undefined`. Each script of a converted project loads on its-own, so one whose module throws does not stop the others from registering.--What is covered:--| Area | Provided |-|---|---|-| Scenes and `director` | `director.loadScene` runs a project scene through the engine's scene manager (a persistent root is `SceneOwner.persistent`). A scene's components start in one phase before the frame's updates. `director` has a scheduler and fires its frame events, and is a class scripts can patch. A node's scripts load and enable as it joins an active parent or is switched on, and a node made between frames joins the running world. |-| Nodes and components | `setSiblingIndex` reorders through the engine's entity order. `getComponent` finds a component by a base class it derives from, or by its `cc.` name. `Component.EventHandler`, `Node.getParent` and `Camera.screenPointToRay` exist. The design resolution is known to scripts before they run. |-| Loading assets | `resources.load` gives images, sprite frames and audio by path, and finds an image's `spriteFrame` and `texture` by the end of the path. A directory load leaves out what the layer cannot load instead of failing. `loadAny` takes a uuid. A loaded asset is named for its file and counts its holders. `assetManager` has a downloader, a factory and `AssetManager.Cache`. |-| Meshes and materials | `MeshRenderer` is a view on the engine's mesh renderer: `getSharedMaterial`, `getMaterialInstance` (the per-renderer instance, made once), `material`, `setMaterial`. `Material.setProperty` / `getProperty` write through to the engine material (colours 0..255 become 0..1); `mainColor`, `albedo`, `baseColor` and `color` write the renderer's tint. `ModelRenderer`, `UIMeshRenderer` and `cc.geometry` (`AABB`, `Ray`, `Plane` and the box, ray and plane tests) exist. |-| Utilities | `js` (class names and lookup, `isChildClassOf`, `mixin`, `addon`, property definers), `ccenum`, `NodePool` (the handler component is told `unuse` and `reuse`), `cc.profiler` (`showStats`, `hideStats`). |-| UI components | Widget, Layout, Button, Toggle (a toggle belongs to the container its parent holds; assigning `isChecked` switches the others of its group off), ProgressBar, ScrollView, Label, Sprite, EditBox and the rest of the layer. Sprites, labels and graphics accept the rebuild requests scripts send. |--<Aside type="note">- Where two pressable things overlap at the same depth and layer, a press goes to the one drawn- later by its place in the hierarchy, so a node taken from a pool and added under a panel does not- take presses meant for what covers it.-</Aside>--## See also--- [Prefabs](/docs/world/prefabs/) — virtual instances, which keep a screen of many pages cheap.-- [UI overview](/docs/ui/overview/) — `ContentRect`, `RectAnchors` and `UIPages`.-- [Screen & Design Resolution](/docs/core-concepts/screen/)diff --git a/docs/astro/src/content/docs/zh-cn/assets/models.mdx b/docs/astro/src/content/docs/zh-cn/assets/models.mdxindex f075cafb0..4d011a70e 100644--- a/docs/astro/src/content/docs/zh-cn/assets/models.mdx+++ b/docs/astro/src/content/docs/zh-cn/assets/models.mdx@@ -15,8 +15,8 @@ import { Aside } from '@astrojs/starlight/components';## 内置图元-有八个形状不需要导入、也不需要文件。**+ 添加 → 创建实体… → Cube**(以及 Sphere、Capsule、Cylinder、-Cone、Plane、Cocos Plane、Quad)建出的实体,其 `MeshRenderer.mesh` 里放的是一个 `builtin:` 引用;同样这八个+有七个形状不需要导入、也不需要文件。**+ 添加 → 创建实体… → Cube**(以及 Sphere、Capsule、Cylinder、+Cone、Plane、Quad)建出的实体,其 `MeshRenderer.mesh` 里放的是一个 `builtin:` 引用;同样这七个也排在任何 `MeshRenderer.mesh` 字段选择器的最前面。| 引用 | 形状 |@@ -27,10 +27,9 @@ Cone、Plane、Cocos Plane、Quad)建出的实体,其 `MeshRenderer.mesh`| `builtin:cylinder` | 100 单位的竖直圆柱,平顶平底 || `builtin:cone` | 100 单位的圆锥,立在底面上 || `builtin:plane` | XZ 平面上 100 单位的方块,朝上 —— 一块地面 |-| `builtin:cocos-plane` | Cocos Creator 的地面方块:宽 10 单位,贴图的 v 沿 +z 方向,和地图一样 —— 按 Cocos 的平面写的效果读的就是它 || `builtin:quad` | XY 平面上 100 单位的方块,正对相机 —— 一块背板 |-它们在加载时由代码生成,所以在包里不占任何字节,引用了它的场景也不因此多出依赖。八个都+它们在加载时由代码生成,所以在包里不占任何字节,引用了它的场景也不因此多出依赖。七个都和新建的 `ShapeRenderer` 一样大,所以往场景里放一个不用先缩放就看得见;要多大,通过Transform 给,和导入的模型一样。diff --git a/docs/astro/src/content/docs/zh-cn/editor/cocos-import.mdx b/docs/astro/src/content/docs/zh-cn/editor/cocos-import.mdxdeleted file mode 100644index e2da18fd8..000000000--- a/docs/astro/src/content/docs/zh-cn/editor/cocos-import.mdx+++ /dev/null@@ -1,91 +0,0 @@-----title: 导入 Cocos Creator 项目-description: "在编辑器里打开 Cocos Creator 3.x 项目、转换带过来什么、重新导入如何保留你的修改,以及运行项目脚本的 cc 兼容层。"------import { Aside } from '@astrojs/starlight/components';--编辑器可以把一个 **Cocos Creator 3.x** 项目整个带过来:它的场景、预制体、脚本和资源会变成一个-Estella 项目,你可以在这里继续编辑。Cocos 文件夹只会被读取,不会被修改。--## 打开 Cocos 项目--在**打开项目**里选择一个 Cocos Creator 文件夹。编辑器通过其 `package.json` 里的 Creator 版本识别它,-并询问是否把它转换成旁边的新项目 `<名字>-estella`,然后打开那个项目。再次打开同一个 Cocos 文件夹-会直接打开已转换的项目,而不会转换两次。--转换会显示进度:当前所处阶段和完成程度,以进度条覆盖在窗口上。转换跑在独立线程里,窗口不会卡住。--- **图片、字体和 spine 文件是链接而不是复制。** 它们以硬链接放进转换后的项目(只有跨盘才复制),- 数 GB 的美术目录既不会被复制,也不会存两份。项目只读这些文件,从不往里写。-- **项目像游戏一样启动。** 它直接打开 Cocos 的启动场景,使用 Cocos 的设计尺寸;只定义全局变量的脚本- (游戏配置)先于场景点名的脚本运行。场景按 uuid 引用的编辑器内置资源(例如默认的进度条图片)- 从你安装的 Creator 里读取。-- **没能带过来的组件会列出来。** 首次转换后会有一条消息,按使用量从多到少列出没有对应物的组件。- 它们的数据保留在实体上,但不会有任何逻辑运行。-- **Cocos 项目自己的 effect 会被转换**成 Estella 的着色器和材质,用了它的精灵、网格或粒子保持原来的外观。--## 转换保留了什么--**屏幕适配。** Cocos 的设计适配(适配宽度、适配高度)变成项目相机的缩放模式(固定宽度、固定高度),-所以按设计单位布局的 UI 在每种屏幕上大小一致。见[屏幕与设计分辨率](/docs/zh-cn/core-concepts/screen/)。--**层。** 节点在 Cocos 里的层(层序号)会成为它的精灵、文本、图形、spine、粒子和网格所在的层,-相机的剔除掩码就是在这些层之间选择。所以只画某一层的 UI 相机,画出的内容和在 Cocos 里一致。--**UI。** 转换后的 UI 表现与 Cocos 一致:--- UI 层按层级顺序绘制,所以弹窗会盖住下面视图的文字- (见[层级顺序层](/docs/zh-cn/graphics/sprites/#层级顺序层))。-- `Widget` 变成引擎的 [`RectAnchors`](/docs/zh-cn/ui/overview/#rectanchors--跟随父级的世界内容),配合- [`ContentRect`](/docs/zh-cn/ui/overview/#contentrect--世界内容的矩形),所以场景在编辑器里就按运行时的- 位置排好。钉在屏幕上的根节点存放在引擎在设计框里放置它的位置。Cocos 的 `Layout` 在引擎的两遍锚点对齐之间运行。-- 没有溢出规则的 Label 不换行,从它的锚点开始排版。-- `EditBox` 变成引擎的输入框,两个标签折叠进去。-- 未激活的节点变成 `Disabled` 标签,整个子树跟着一起关。-- 位图字体的页保持完整尺寸。--**脚本。** 每个脚本的组件类都会声明给编辑器,因此出现在检查器里。脚本打包时容忍 Cocos 容忍的那些缺口-(缺少的 `cc` 名字、被重新赋值的 `const`、`exports` 之外的包文件、只在预览里用到的 import)。两个脚本写了-同一个 `@ccclass` 名字时会被区分开:第二个得到自己的组件名(`Name_2`,按路径顺序),转换器在入口旁写明-是哪个脚本,打包器把新名字写进那个脚本的装饰器。运行时只有当它读过的文件变了,脚本包才会重新构建。--## 重新导入而不丢失你的修改--在由 Cocos Creator 转换来的项目里执行**重新导入 Cocos 项目**。Cocos 一侧改动过的场景和预制体会被带过来,-新增的会被加入;你在这里编辑过的文档保持原样,并计入结果,例如“新增 3,更新 2,5 个因你改过而保留”。-唯一的例外是被编辑过的文档里的 `Cocos.Widget` 组件,它们会变成 `RectAnchors`(字段相同),-这样由旧版导入器转换的项目也能保留对齐。--转换后的项目会记录导入器的修订号;编辑器打开由更旧导入器写出的项目时,会重新转换一次。--在不是由 Cocos 转换来的项目里执行该命令,只会提示这一点,不会改动任何东西。--## `cc` 兼容层--Cocos 脚本之所以能继续工作,是因为项目脚本构建时 `cc` 被解析到引擎的 Cocos 层(`esengine/cocos`)。-那里的 `Node` 就是实体,`Component` 子类就是 Estella 组件。Cocos 中没有对应物的部分不做模拟:`cc` 模块里-这一层没有提供的部分是一个可以被读取、调用、构造的占位,并只提示一次它缺失,而不是 `undefined`。-转换后项目的每个脚本各自加载,所以某个模块抛错不会阻止其他脚本注册。--已覆盖的内容:--| 方面 | 提供的能力 |-|---|---|-| 场景与 `director` | `director.loadScene` 通过引擎的场景管理器运行项目场景(常驻根是 `SceneOwner.persistent`)。场景的组件在帧更新之前的同一阶段启动。`director` 有调度器并触发帧事件,而且是脚本可以打补丁的类。节点的脚本在它加入已激活的父级或被打开时就加载并启用,帧与帧之间创建的节点会加入运行中的世界。 |-| 节点与组件 | `setSiblingIndex` 通过引擎的实体顺序重排。`getComponent` 可按它派生自的基类或 `cc.` 名字查找组件。`Component.EventHandler`、`Node.getParent`、`Camera.screenPointToRay` 都有。设计分辨率在脚本运行前就已知。 |-| 加载资源 | `resources.load` 按路径给出图片、精灵帧和音频,并按路径末尾找到图片的 `spriteFrame` 和 `texture`。目录加载会略过这一层加载不了的东西,而不是失败。`loadAny` 接受 uuid。加载的资源以文件名命名并统计持有者。`assetManager` 有下载器、工厂和 `AssetManager.Cache`。 |-| 网格与材质 | `MeshRenderer` 是引擎网格渲染器的视图:`getSharedMaterial`、`getMaterialInstance`(每个渲染器一个实例,只创建一次)、`material`、`setMaterial`。`Material.setProperty` / `getProperty` 直接写穿到引擎材质(颜色 0..255 变成 0..1);`mainColor`、`albedo`、`baseColor`、`color` 写的是渲染器的色调。还有 `ModelRenderer`、`UIMeshRenderer` 和 `cc.geometry`(`AABB`、`Ray`、`Plane` 以及盒、射线、平面的相交测试)。 |-| 工具 | `js`(类名与查找、`isChildClassOf`、`mixin`、`addon`、属性定义器)、`ccenum`、`NodePool`(处理组件会收到 `unuse` 和 `reuse`)、`cc.profiler`(`showStats`、`hideStats`)。 |-| UI 组件 | Widget、Layout、Button、Toggle(Toggle 属于其父级持有的容器;给 `isChecked` 赋值会关掉同组的其他项)、ProgressBar、ScrollView、Label、Sprite、EditBox 等。精灵、标签和图形接受脚本发出的重建请求。 |--<Aside type="note">- 两个可点击的东西在同一深度和层上重叠时,点击交给层级位置上后绘制的那个,所以从对象池取出、- 加到面板下的节点不会抢走本该给覆盖它的东西的点击。-</Aside>--## 另请参阅--- [预制体](/docs/zh-cn/world/prefabs/) —— 虚拟实例,让包含很多页面的界面保持轻量。-- [UI 总览](/docs/zh-cn/ui/overview/) —— `ContentRect`、`RectAnchors` 和 `UIPages`。-- [屏幕与设计分辨率](/docs/zh-cn/core-concepts/screen/)diff --git a/pipeline/bin/estella.mjs b/pipeline/bin/estella.mjsindex 2a5396c01..8492f9ce6 100644--- a/pipeline/bin/estella.mjs+++ b/pipeline/bin/estella.mjs@@ -24,8 +24,6 @@ const USAGE = `usage: node pipeline/bin/estella.mjs create <template> <dir> [--n[--project <dir>] [--scale <n>][--specular-map color|orm] [--lightmap-uv] [--lods <0-3>]node pipeline/bin/estella.mjs import-hdr <file.hdr> [outDir] [--face-size <n>]- node pipeline/bin/estella.mjs import-cocos <cocosProjectDir> <estellaProjectDir>- [--only <assets/ subpath>]... [--into <folder>] [--dry-run]node pipeline/bin/estella.mjs bake-scene <scene.esscene> [--check]node pipeline/bin/estella.mjs package-openpaas <exportDir> --config <local.json> --out <game.sp>@@ -77,16 +75,6 @@ editor), unwrapping one where the source's second set is too sparse to bake intotriangles) as <mesh>_lod<n>.esmesh and a LODGroup that swaps them in (GenerateLODs in the editor); skinned and morphing meshes keep one level.-import-cocos takes a Cocos Creator 3.x project into an Estella project without touching-it: the source is only read, and an output folder inside it is refused. Prefabs and scenes-become \`.esprefab\` / \`.esscene\` under assets/<into> (default cocos), keeping the source's-folder layout; a prefab instance stays a nested prefab whose changes are overrides. Only the-textures and fonts the converted documents use are copied. Components with a counterpart-(Node, Sprite, Label, RichText, Camera) are mapped; every other component is kept verbatim-under the entity's metadata.cocos and counted. assets/<into>/import-report.json says what-was mapped, approximated and left out, and --dry-run writes nothing but still prints it.---only restricts the documents converted to those under the given assets/ subpath(s).-import-hdr bakes an equirectangular panorama into the two things a renderer asksan environment for: nine irradiance coefficients (in the \`.esenv\`) and oneprefiltered octahedral atlas beside it, which the document names as a sibling.@@ -146,20 +134,6 @@ function parseArgs(argv) {}return { command, source: path.resolve(projectDir), config: path.resolve(rest[config + 1]), out: path.resolve(rest[out + 1]) };}- if (command === 'import-cocos') {- const target = rest.find((a, i) => !a.startsWith('--') && rest[i - 1] !== '--only' && rest[i - 1] !== '--into');- if (!projectDir || !target) {- console.error(USAGE);- process.exit(2);- }- const only = [];- for (let i = 0; i < rest.length; i++) if (rest[i] === '--only' && rest[i + 1]) only.push(rest[i + 1].replace(/^\/+/, ''));- const into = rest.indexOf('--into');- return {- command, source: path.resolve(projectDir), out: path.resolve(target), only,- into: into >= 0 ? rest[into + 1] : undefined, dryRun: rest.includes('--dry-run'),- };- }if (command === 'import-model' || command === 'import-gltf' || command === 'import-hdr') {if (!projectDir) {console.error(USAGE);@@ -819,21 +793,6 @@ if (opts.command === 'package-openpaas') {process.exit(process.exitCode ?? 0);}-if (opts.command === 'import-cocos') {- const { mod, cleanup } = await loadPipeline(path.join(PIPELINE, 'src', 'import', 'cocos', 'index.ts'), 'cocosImport.mjs');- try {- const report = await mod.importCocosProject({- source: opts.source, out: opts.out, only: opts.only, dryRun: opts.dryRun, ...(opts.into ? { into: opts.into } : {}),- });- console.log(JSON.stringify(report, null, 2));- process.exitCode = report.documents.failed.length ? 1 : 0;- } catch (e) {- console.error(e instanceof Error ? e.message : String(e));- process.exitCode = 1;- } finally { cleanup(); }- process.exit(process.exitCode ?? 0);-}-// `import-gltf` is the name this command shipped under; it reads any of the// model sources now, and the old spelling keeps working.if (opts.command === 'import-model' || opts.command === 'import-gltf') {diff --git a/pipeline/src/bundle/buildScripts.ts b/pipeline/src/bundle/buildScripts.tsindex 1c71b1602..baa1695ea 100644--- a/pipeline/src/bundle/buildScripts.ts+++ b/pipeline/src/bundle/buildScripts.ts@@ -19,7 +19,6 @@ import path from 'node:path';import { loadEsbuild } from './esbuildRuntime';import { explainBundleErrors, type BundleMessage } from './bundleDiagnostics';import { officialPackagesPlugin } from './officialPackages';-import { COCOS_COMPAT_VERSION, cocosCompatPlugin } from './cocosCompat';/** esengine and any subpath import are left for the realm's import map to resolve. */const EXTERNAL = ['esengine', 'esengine/*'];@@ -44,7 +43,6 @@ const STAMP = 'scripts.stamp.json';/** What a bundle was built from: enough to know, without building, whether building again would give the same bytes. */interface BuildStamp {version: number;- compat: number;esbuild: string;entry: string;packagesDir: string;@@ -78,7 +76,7 @@ async function currentStamp(stampPath: string, outputPath: string, want: Omit<Bu} catch {return null;}- if (stamp.version !== want.version || stamp.compat !== want.compat || stamp.esbuild !== want.esbuild+ if (stamp.version !== want.version || stamp.esbuild !== want.esbuild|| stamp.entry !== want.entry || stamp.packagesDir !== want.packagesDir) return null;const files = Object.entries(stamp.inputs);// in slices, so a project of thousands of scripts does not open thousands of files at once@@ -112,7 +110,7 @@ export async function buildProjectScripts(const stampPath = path.join(root, CACHE_DIR, STAMP);try {const esbuild = await loadEsbuild();- const want = { version: STAMP_VERSION, compat: COCOS_COMPAT_VERSION, esbuild: esbuild.version, entry: entryPath, packagesDir: opts.packagesDir };+ const want = { version: STAMP_VERSION, esbuild: esbuild.version, entry: entryPath, packagesDir: opts.packagesDir };const fresh = await currentStamp(stampPath, outputPath, want);if (fresh) return { ok: true, outputPath, errors: [], warnings: fresh.warnings };@@ -123,7 +121,7 @@ export async function buildProjectScripts(platform: 'browser',target: 'es2020',external: EXTERNAL,- plugins: [officialPackagesPlugin(opts.packagesDir), cocosCompatPlugin()],+ plugins: [officialPackagesPlugin(opts.packagesDir)],outfile: outputPath,sourcemap: true,write: true,diff --git a/pipeline/src/bundle/cocosCompat.ts b/pipeline/src/bundle/cocosCompat.tsdeleted file mode 100644index 4b148ebd3..000000000--- a/pipeline/src/bundle/cocosCompat.ts+++ /dev/null@@ -1,179 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file Scripts written for Cocos Creator build against the engine, in every bundle a project's scripts go into.- *- * Two things a Cocos script assumes that a plain bundle does not give it:- *- * - `import { Component } from 'cc'` (and `'cc/env'` for its build flags). Both name the compatibility layer, `esengine/cocos`.- * The import is handed back to the bundler as that specifier, so it resolves however the build resolves `esengine/*`:- * left external for the page's import map, or aliased and inlined.- * - Legacy (`experimentalDecorators`) decorators, with fields assigned by the constructor rather than defined. Cocos scripts are- * written for that, the layer's `@ccclass` / `@property` have that signature, and esbuild's default for a file whose nearest- * tsconfig says nothing is the newer standard form, under which every decorator in the project would run with the wrong- * arguments. A Cocos project's own tsconfig usually extends a file the editor generates and the checkout lacks, so it cannot- * be relied on to say it.- *- * A package's file by its path (`long/umd/index.js`) even where the package's `exports` map does not list it: Cocos resolves- * files the way node did before `exports`, and the generated protobuf code of a project asks for exactly that.- *- * A third, smaller one: Cocos compiles scripts that esbuild refuses. A `const` that is assigned to later is a TypeScript error Cocos- * builds through (its output is `var`, where the assignment simply works), and esbuild stops the whole bundle on it. Such a- * declaration is read as `let`, which is what the script meant.- *- * Only files that import `cc` are touched: a script that does not is not a Cocos script, and keeps whatever its own tsconfig says.- * The project's files are read, never written.- */-import { existsSync, readFileSync, statSync } from 'node:fs';-import { readFile } from 'node:fs/promises';-import path from 'node:path';-import type { Plugin, PluginBuild } from 'esbuild';-import { BUNDLER_RESOLVES } from './bundlerResolve';-import { loadEsbuild } from './esbuildRuntime';--/** Changes whenever what this plugin does to a script changes, so a bundle built by an older one is not taken for current. */-export const COCOS_COMPAT_VERSION = 4;--/** What `cc` and `cc/env` resolve to. */-export const COCOS_LAYER = 'esengine/cocos';--const CC = /^cc(\/env)?$/;-const IMPORTS_CC = /(?:from|import)\s*\(?\s*['"]cc(?:\/env)?['"]/;-const TS = /\.tsx?$/;--const PACKAGE_FILE = /^(?:@[^/]+\/[^/]+|[^@./][^/]*)\/.+/;--/** `<dir>/node_modules/<specifier>` for the nearest dir upward that has it, as a file. */-function packageFileFrom(dir: string, specifier: string): string | undefined {- for (let d = dir; ; d = path.dirname(d)) {- const candidate = path.join(d, 'node_modules', specifier);- if (existsSync(candidate) && statSync(candidate).isFile()) return candidate;- if (path.dirname(d) === d) return undefined;- }-}--const CONST_DECL = /\bconst\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]+)?=/g;-/** An assignment statement: the name at the start of a statement, then `=` that is not `==` or `=>`, or a compound operator. */-const ASSIGNMENT = /(?:^|[;{}\n])\s*([A-Za-z_$][\w$]*)\s*(?:[-+*/%&|^]|\*\*|<<|>>>?|&&|\|\||\?\?)?=(?![=>])/g;--const NAMED_CC_IMPORT = /^[ \t]*import\s*\{([^}]*)\}\s*from\s*(['"])(cc(?:\/env)?)\2\s*;?/gm;--/**- * `import { A, B as C } from 'cc'` as a read of the layer's namespace. The layer provides part of the Creator API, and Cocos hands a- * script the rest as `undefined` where a bundler would stop at the first name that is not exported. A name the layer lacks is- * `undefined` here too, and the script finds out only if it gets as far as using it.- */-export function readNamedImportsThroughNamespace(source: string): string {- let n = 0;- const reads: string[] = [];- const rest = source.replace(NAMED_CC_IMPORT, (all, list: string, quote: string, from: string) => {- const bindings = list.split(',').map((x) => x.trim()).filter((x) => x && !/^type\s/.test(x))- .map((x) => { const [name, alias] = x.split(/\s+as\s+/); return { name: name!.trim(), local: (alias ?? name)!.trim() }; });- if (bindings.length > 0) {- const ns = '__cc' + n++;- // a name the layer lacks is a stand-in that survives being used, so a script that reaches into it while its module loads does not stop the rest- const each = bindings.map((b) => b.local + ' = ' + ns + '.' + b.name + ' ?? ' + ns + '.unsupported(' + JSON.stringify(b.name) + ')').join(', ');- reads.push('import * as ' + ns + ' from ' + quote + from + quote + '; const ' + each + ';');- }- // the statement leaves its lines behind, so what follows keeps its line numbers- return all.replace(/[^\n]/g, '');- });- // an import is hoisted: a script may use a name above the line that imports it, so the bindings go first, on the first line- return reads.length > 0 ? reads.join(' ') + ' ' + rest : rest;-}--/**- * The source with every `const` that the script assigns to again read as `let`; the source itself when there is none. Two passes over the text, not- * one per declaration: a project's scripts are thousands of files, and this runs on every build, on the editor's main thread.- */-export function letTheReassignedConsts(source: string): string {- if (!source.includes('const ')) return source;- const assigned = new Set<string>();- for (const m of source.matchAll(ASSIGNMENT)) assigned.add(m[1]!);- if (assigned.size === 0) return source;- // a name assigned anywhere makes every const of that name a let: harmless where the assignment was to another variable of the same name- return source.replace(CONST_DECL, (all: string, name: string) => (assigned.has(name) ? all.replace('const', 'let') : all));-}--/** The script classes a converted project renamed, from the file the import wrote beside the project's entry; empty when there is none. */-function readClassNames(build: PluginBuild): Map<string, { from: string; to: string }> {- const options = build.initialOptions;- const first = options.entryPoints;- const entry = Array.isArray(first) ? first[0] : first && typeof first === 'object' ? Object.values(first)[0] : undefined;- const entryFile = typeof entry === 'string' ? entry : entry?.in;- const dir = entryFile ? path.dirname(path.resolve(options.absWorkingDir ?? '.', entryFile)) : options.stdin?.resolveDir ? path.join(options.stdin.resolveDir, 'src') : null;- const out = new Map<string, { from: string; to: string }>();- if (!dir) return out;- try {- const names = JSON.parse(readFileSync(path.join(dir, 'cocos-class-names.json'), 'utf8')) as Record<string, { from: string; to: string }>;- for (const [key, v] of Object.entries(names)) out.set(path.resolve(dir, key).toLowerCase(), v);- } catch { /* none renamed */ }- return out;-}--/** The decorator of a renamed class, written with its new name: `@ccclass('Old')` and a bare `@ccclass` both become `@ccclass('New')`. */-export function renameClass(source: string, from: string, to: string): string {- const escaped = from.replace(/[$]/g, (c) => `\\${c}`);- const named = new RegExp(String.raw`@ccclass\(\s*(['"])${escaped}\1\s*\)`);- if (named.test(source)) return source.replace(named, `@ccclass('${to}')`);- return source.replace(/@ccclass(?![\w(])/, `@ccclass('${to}')`);-}--export function cocosCompatPlugin(): Plugin {- return {- name: 'estella-cocos-compat',- setup(build) {- const renames = readClassNames(build);- build.onResolve({ filter: CC }, async (args) => {- if (args.pluginData === BUNDLER_RESOLVES) return undefined;- const layer = await build.resolve(COCOS_LAYER, {- kind: args.kind, importer: args.importer, resolveDir: args.resolveDir, pluginData: BUNDLER_RESOLVES,- });- if (layer.errors.length > 0) {- return { errors: [{ text: `"${args.path}" is the Cocos Creator module, which the engine provides as "${COCOS_LAYER}" — and that did not resolve here: ${layer.errors[0]!.text}` }] };- }- return { path: layer.path, external: layer.external, sideEffects: layer.sideEffects };- });-- // `preview-template/` is the page the Creator editor's preview serves, Node code included; a build never ships it, so what a script- // reaches for there is nothing.- build.onResolve({ filter: /(^|\/)preview-template\// }, (args) => ({ path: args.path, namespace: 'cocos-preview-only' }));- build.onLoad({ filter: /.*/, namespace: 'cocos-preview-only' }, () => ({ contents: 'export {};', loader: 'js' }));-- // Only a path the bundler could not resolve itself falls back to the plain file lookup.- build.onResolve({ filter: PACKAGE_FILE }, async (args) => {- if (args.pluginData === BUNDLER_RESOLVES || args.kind === 'entry-point') return undefined;- const tried = await build.resolve(args.path, { kind: args.kind, importer: args.importer, resolveDir: args.resolveDir, pluginData: BUNDLER_RESOLVES });- if (tried.errors.length === 0) return tried;- const file = packageFileFrom(args.resolveDir, args.path);- return file ? { path: file } : undefined;- });-- build.onLoad({ filter: TS }, async (args) => {- if (args.path.includes(`${path.sep}node_modules${path.sep}`)) return undefined;- let source: string;- try {- source = await readFile(args.path, 'utf8');- } catch {- return undefined;- }- const renamed = renames.get(args.path.replace(/\.(tsx?|jsx?)$/, '').toLowerCase());- if (renamed) source = renameClass(source, renamed.from, renamed.to);- if (!IMPORTS_CC.test(source)) {- const fixed = letTheReassignedConsts(source);- return fixed === source ? undefined : { contents: fixed, loader: args.path.endsWith('x') ? 'tsx' : 'ts', resolveDir: path.dirname(args.path) };- }- source = readNamedImportsThroughNamespace(letTheReassignedConsts(source));- const esbuild = await loadEsbuild();- const out = await esbuild.transform(source, {- loader: args.path.endsWith('x') ? 'tsx' : 'ts',- sourcefile: args.path,- sourcemap: 'inline',- target: 'es2020',- tsconfigRaw: { compilerOptions: { experimentalDecorators: true, useDefineForClassFields: false } },- });- return { contents: out.code, loader: 'js', resolveDir: path.dirname(args.path) };- });- },- };-}diff --git a/pipeline/src/bundle/engineSubpaths.ts b/pipeline/src/bundle/engineSubpaths.tsindex fa310e075..232fa5adb 100644--- a/pipeline/src/bundle/engineSubpaths.ts+++ b/pipeline/src/bundle/engineSubpaths.ts@@ -28,7 +28,6 @@ export const ESENGINE_SUBPATHS: Readonly<Record<string, string>> = {'esengine/replication': 'net/replication/index.js','esengine/session': 'net/session/index.js','esengine/gameplay': 'gameplay/index.js',- 'esengine/cocos': 'cocos/index.js','esengine/dragonbones': 'dragonbones/index.js','esengine/physics': 'physics/index.js','esengine/physics3d': 'physics3d/index.js',@@ -48,7 +47,7 @@ export const ESENGINE_SUBPATHS: Readonly<Record<string, string>> = {* the debug channel a development export adds, and the session layer, which a* game's own code imports and nothing in a scene asks for. Named here so the pickable set is derived rather than written twice.*/-export const NOT_A_MODULE: ReadonlySet<string> = new Set(['esengine/wasm', 'esengine/debug-channel', 'esengine/session', 'esengine/cocos', 'esengine/douyin', 'esengine/kuaishou', 'esengine/bilibili', 'esengine/quickgame', 'esengine/alipay', 'esengine/huawei', 'esengine/openpaas']);+export const NOT_A_MODULE: ReadonlySet<string> = new Set(['esengine/wasm', 'esengine/debug-channel', 'esengine/session', 'esengine/douyin', 'esengine/kuaishou', 'esengine/bilibili', 'esengine/quickgame', 'esengine/alipay', 'esengine/huawei', 'esengine/openpaas']);/** The modules a project can force in or refuse, as `features.modules` keys it. */export const ENGINE_MODULES: readonly string[] =diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.tsindex 618c65d98..3fe8ce0a9 100644--- a/pipeline/src/export/exportGame.ts+++ b/pipeline/src/export/exportGame.ts@@ -60,7 +60,6 @@ import { genericPlayableProfile, type PlayableAdProfile } from './playableAdProfimport type { OnExportProgress } from './exportProgress';import { ESENGINE_EXTERNAL, ESENGINE_SUBPATHS } from '../bundle/esengineResolve';import { officialPackagesPlugin } from '../bundle/officialPackages';-import { cocosCompatPlugin } from '../bundle/cocosCompat';import type { RpkSigningKey } from './rpk';import { buildCompiledSystems, type BuildMode } from '../bundle/buildCompiledSystems';import { resolveEmcc, runEmcc } from '../bundle/emccPath';@@ -952,7 +951,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>platform: 'browser',target: 'es2020',external: ESENGINE_EXTERNAL,- plugins: [officialPackagesPlugin(opts.packagesDir), cocosCompatPlugin()],+ plugins: [officialPackagesPlugin(opts.packagesDir)],minify: opts.minify ?? false,sourcemap: sourceMaps,write: true,@@ -1052,7 +1051,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>const proj = nativeContent? await build({...common, format: 'iife', external: [],- plugins: [esengineGlobalPlugin(), officialPackagesPlugin(opts.packagesDir), cocosCompatPlugin()],+ plugins: [esengineGlobalPlugin(), officialPackagesPlugin(opts.packagesDir)],entryPoints: [scriptsAbs], outfile: path.join(payloadDir, 'scripts.js'),}): await build({ ...common, entryPoints: [scriptsAbs], outfile: path.join(payloadDir, 'scripts.mjs') });diff --git a/pipeline/src/export/exportMiniGame.ts b/pipeline/src/export/exportMiniGame.tsindex d190cac2e..b8fc5ff76 100644--- a/pipeline/src/export/exportMiniGame.ts+++ b/pipeline/src/export/exportMiniGame.ts@@ -49,7 +49,6 @@ import { runtimeHostEntry } from '../bundle/runtimeHosts';import { breakdownOf, type ModuleBytes } from './bundleBreakdown';import { esengineAlias } from '../bundle/esengineResolve';import { officialPackagesPlugin } from '../bundle/officialPackages';-import { cocosCompatPlugin } from '../bundle/cocosCompat';import { explainBundleErrors, type BundleMessage } from '../bundle/bundleDiagnostics';import { scanSideModuleIds, sideModuleFiles, textureDecoderBytes } from '../bundle/sideModuleScan';import { exportedAssetFiles, pruneExportedAssets } from './assetCleanup';@@ -587,7 +586,7 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {// devtools accepts it; es2017 down-levels those while keeping async/await.target: profile.esTarget,alias: esengineAlias(opts.sdkDir, lean ? leanEntry! : profile.sdkEntryFile),- plugins: [officialPackagesPlugin(opts.packagesDir), cocosCompatPlugin()],+ plugins: [officialPackagesPlugin(opts.packagesDir)],minify: opts.minify ?? false,sourcemap: false,outfile: path.join(absOut, 'game-bundle.js'),diff --git a/pipeline/src/export/exportPlayable.ts b/pipeline/src/export/exportPlayable.tsindex 01efd7258..f86b48eb8 100644--- a/pipeline/src/export/exportPlayable.ts+++ b/pipeline/src/export/exportPlayable.ts@@ -33,7 +33,6 @@ import { optimizePlayableAssets, playableAssetsJsonBytes, type PlayableOptimizatimport type { OnExportProgress } from './exportProgress';import { esengineAlias } from '../bundle/esengineResolve';import { officialPackagesPlugin } from '../bundle/officialPackages';-import { cocosCompatPlugin } from '../bundle/cocosCompat';import { explainBundleErrors, type BundleMessage } from '../bundle/bundleDiagnostics';import type { ScreenOrientation } from './orientationHtml';import { genericPlayableProfile, playableAdInjection, isPlayableZipFileName, type PlayableAdProfile } from './playableAdProfile';@@ -320,7 +319,7 @@ export async function exportPlayable(opts: {// esengine is INLINED (single-file, no import map) → resolve it from the SDK// dist; the project root has no esengine installed.alias: esengineAlias(opts.sdkDir),- plugins: [officialPackagesPlugin(opts.packagesDir), cocosCompatPlugin()],+ plugins: [officialPackagesPlugin(opts.packagesDir)],minify: opts.minify ?? true,write: false,outfile: 'game-bundle.js',diff --git a/pipeline/src/import/cocos/animationClip.ts b/pipeline/src/import/cocos/animationClip.tsdeleted file mode 100644index 5742127aa..000000000--- a/pipeline/src/import/cocos/animationClip.ts+++ /dev/null@@ -1,214 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A Cocos `.anim` as an engine `.estimeline`.- *- * A clip is a list of tracks. Each names what it animates by a path (the nodes below the animated one, then a component, then a property) and- * carries curves of keyframes. The timeline says the same: a track addresses a node by `childPath`, a component and a property, with a channel of- * keys per number. A node's position, scale and a sprite's colour are numbers on both sides; a rotation is keyed as euler angles in Cocos and as a- * quaternion here, so it is sampled; an `active` track becomes the ranges the node is active in. A track on something the timeline cannot reach is- * counted, not dropped silently.- */-type Raw = Record<string, unknown>;-const isObj = (v: unknown): v is Raw => typeof v === 'object' && v !== null && !Array.isArray(v);-const num = (v: unknown, d: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : d);--export interface Key { time: number; value: number; inTangent: number; outTangent: number; interpolation: string }--export interface ConvertedClip {- document: {- version: string; type: 'timeline'; duration: number; wrapMode: 'once' | 'loop' | 'pingPong'; tracks: Raw[];- };- /** Tracks that could not be carried, by what they animated, with how many. */- skipped: Map<string, number>;- /** Whether the clip had events, which a timeline does not take from here. */- events: number;-}--/** Cocos's `AnimationClip.WrapMode`: Loop (2, 22) and PingPong (36) are themselves, the rest play once. */-function wrapModeOf(mode: unknown): 'once' | 'loop' | 'pingPong' {- return mode === 2 || mode === 22 ? 'loop' : mode === 36 ? 'pingPong' : 'once';-}--const INTERPOLATION = ['linear', 'step', 'hermite'];--/** One curve as keys. A value that is not an object (an older file) is a number on a straight line. */-function curveKeys(d: unknown[], curveRef: unknown, scale = 1): Key[] {- const curve = deref(d, curveRef);- if (!isObj(curve)) return [];- const times = Array.isArray(curve._times) ? (curve._times as unknown[]) : [];- const values = Array.isArray(curve._values) ? (curve._values as unknown[]) : [];- const keys: Key[] = [];- for (let i = 0; i < Math.min(times.length, values.length); i++) {- const v = deref(d, values[i]);- const time = num(times[i], 0);- if (isObj(v)) {- keys.push({- time, value: num(v.value, 0) * scale, inTangent: num(v.leftTangent, 0) * scale, outTangent: num(v.rightTangent, 0) * scale,- interpolation: INTERPOLATION[num(v.interpolationMode, 0)] ?? 'linear',- });- } else if (typeof v === 'number') {- keys.push({ time, value: v * scale, inTangent: 0, outTangent: 0, interpolation: 'linear' });- }- }- return keys;-}--function deref(d: unknown[], v: unknown): unknown {- return isObj(v) && typeof v.__id__ === 'number' ? d[v.__id__] : v;-}--/** A curve's value at @p t, straight between keys and held by a step key. */-function sample(keys: Key[], t: number): number {- if (keys.length === 0) return 0;- if (t <= keys[0]!.time) return keys[0]!.value;- const last = keys[keys.length - 1]!;- if (t >= last.time) return last.value;- for (let i = 1; i < keys.length; i++) {- const b = keys[i]!;- if (t <= b.time) {- const a = keys[i - 1]!;- if (a.interpolation === 'step') return a.value;- const f = b.time === a.time ? 0 : (t - a.time) / (b.time - a.time);- return a.value + (b.value - a.value) * f;- }- }- return last.value;-}--/** Euler degrees as a quaternion (x, y, z, w), by Cocos's own `Quat.fromEuler`. */-function quatFromEuler(xDeg: number, yDeg: number, zDeg: number): [number, number, number, number] {- const r = Math.PI / 360;- const x = xDeg * r, y = yDeg * r, z = zDeg * r;- const sx = Math.sin(x), cx = Math.cos(x), sy = Math.sin(y), cy = Math.cos(y), sz = Math.sin(z), cz = Math.cos(z);- return [sx * cy * cz + cx * sy * sz, cx * sy * cz + sx * cy * sz, cx * cy * sz - sx * sy * cz, cx * cy * cz - sx * sy * sz];-}--/** The times to sample a rotation at: every key of any axis, and a step between them so a turn is not cut across by a straight line. */-function sampleTimes(curves: Key[][], duration: number): number[] {- const times = new Set<number>();- for (const keys of curves) for (const k of keys) times.add(k.time);- const sorted = [...times].sort((a, b) => a - b);- const out = new Set<number>(sorted);- for (let i = 1; i < sorted.length; i++) {- const span = sorted[i]! - sorted[i - 1]!;- const steps = Math.min(30, Math.ceil(span * 30));- for (let s = 1; s < steps; s++) out.add(sorted[i - 1]! + (span * s) / steps);- }- if (sorted.length === 0 && duration > 0) out.add(0);- return [...out].sort((a, b) => a - b);-}--interface Target {- /** Names of the nodes below the animated one, joined by `/`. */- childPath: string;- /** The component the property is on (`cc.Sprite`), or null for the node itself. */- component: string | null;- property: string;-}--function targetOf(d: unknown[], binding: unknown): Target | null {- const b = deref(d, binding);- if (!isObj(b)) return null;- const path = deref(d, b.path);- if (!isObj(path) || !Array.isArray(path._paths)) return null;- const names: string[] = [];- let component: string | null = null;- let property = '';- for (const raw of path._paths as unknown[]) {- const p = deref(d, raw);- if (typeof p === 'string') {- property = p;- } else if (isObj(p) && typeof p.path === 'string') {- names.push(...p.path.split('/').filter(Boolean)); // a HierarchyPath- } else if (isObj(p) && typeof p.component === 'string') {- component = p.component;- }- }- return property ? { childPath: names.join('/'), component, property } : null;-}--const COMPONENT_OF: Record<string, { component: string; property: string; scale: number } | undefined> = {- 'cc.Sprite.color': { component: 'Sprite', property: 'color', scale: 1 / 255 },- 'cc.Label.color': { component: 'Text', property: 'color', scale: 1 / 255 },- 'cc.UIOpacity.opacity': { component: 'GroupOpacity', property: 'opacity', scale: 1 / 255 },-};--const channelNames = (property: string, n: number): string[] => ['x', 'y', 'z', 'w'].slice(0, n).map((c) => `${property}.${c}`);--/** Convert the objects of a `.anim` file. */-export function convertAnimationClip(objects: unknown): ConvertedClip {- const skipped = new Map<string, number>();- const skip = (what: string): void => { skipped.set(what, (skipped.get(what) ?? 0) + 1); };- const empty: ConvertedClip = { document: { version: '1.3', type: 'timeline', duration: 0, wrapMode: 'once', tracks: [] }, skipped, events: 0 };- const d = Array.isArray(objects) ? objects : [objects];- const clip = d[0];- if (!isObj(clip)) return empty;- const duration = num(clip._duration, 0);- const tracks: Raw[] = [];- for (const ref of Array.isArray(clip._tracks) ? (clip._tracks as unknown[]) : []) {- const track = deref(d, ref);- if (!isObj(track)) continue;- const target = targetOf(d, track._binding);- if (!target) { skip('unreadable'); continue; }- const channels = (Array.isArray(track._channels) ? (track._channels as unknown[]) : track._channel ? [track._channel] : [])- .map((c) => { const ch = deref(d, c); return isObj(ch) ? ch._curve : undefined; });- const name = target.childPath.split('/').pop() ?? '';- const kind = String(track.__type__ ?? '');-- if (target.component === null && (target.property === 'position' || target.property === 'scale') && kind.endsWith('VectorTrack')) {- const props = channelNames(target.property, 3);- const out = props.map((property, i) => ({ property, keyframes: curveKeys(d, channels[i]) })).filter((c) => c.keyframes.length > 0);- if (out.length > 0) tracks.push({ type: 'property', name, childPath: target.childPath, component: 'Transform', channels: out });- continue;- }- if (target.component === null && target.property === 'eulerAngles' && kind.endsWith('VectorTrack')) {- const curves = [0, 1, 2].map((i) => curveKeys(d, channels[i]));- const times = sampleTimes(curves, duration);- if (times.length === 0) continue;- const quats = times.map((t) => quatFromEuler(sample(curves[0]!, t), sample(curves[1]!, t), sample(curves[2]!, t)));- const out = channelNames('rotation', 4).map((property, i) => ({- property, keyframes: times.map((time, k) => ({ time, value: quats[k]![i]!, inTangent: 0, outTangent: 0, interpolation: 'linear' })),- }));- tracks.push({ type: 'property', name, childPath: target.childPath, component: 'Transform', channels: out });- continue;- }- if (target.component === null && target.property === 'rotation' && kind.endsWith('QuatTrack')) {- const out = channelNames('rotation', 4).map((property, i) => ({ property, keyframes: curveKeys(d, channels[i]) })).filter((c) => c.keyframes.length > 0);- if (out.length > 0) tracks.push({ type: 'property', name, childPath: target.childPath, component: 'Transform', channels: out });- continue;- }- const mapped = target.component ? COMPONENT_OF[`${target.component}.${target.property}`] : undefined;- if (mapped && kind.endsWith('ColorTrack')) {- const out = ['r', 'g', 'b', 'a'].map((c, i) => ({ property: `${mapped.property}.${c}`, keyframes: curveKeys(d, channels[i], mapped.scale) })).filter((c) => c.keyframes.length > 0);- if (out.length > 0) tracks.push({ type: 'property', name, childPath: target.childPath, component: mapped.component, channels: out });- continue;- }- if (mapped && kind.endsWith('RealTrack')) {- const keyframes = curveKeys(d, channels[0], mapped.scale);- if (keyframes.length > 0) tracks.push({ type: 'property', name, childPath: target.childPath, component: mapped.component, channels: [{ property: mapped.property, keyframes }] });- continue;- }- if (target.component === null && target.property === 'active' && kind.endsWith('ObjectTrack')) {- const curve = deref(d, channels[0]);- const times = isObj(curve) && Array.isArray(curve._times) ? (curve._times as number[]) : [];- const values = isObj(curve) && Array.isArray(curve._values) ? (curve._values as unknown[]) : [];- const ranges: Array<{ start: number; end: number }> = [];- let from: number | null = null;- for (let i = 0; i < Math.min(times.length, values.length); i++) {- const on = deref(d, values[i]) === true;- if (on && from === null) from = times[i]!;- if (!on && from !== null) { ranges.push({ start: from, end: times[i]! }); from = null; }- }- if (from !== null) ranges.push({ start: from, end: Math.max(duration, from) });- if (ranges.length > 0) tracks.push({ type: 'activation', name, childPath: target.childPath, ranges });- continue;- }- skip(`${target.component ?? 'node'}.${target.property}`);- }- return {- document: { version: '1.3', type: 'timeline', duration, wrapMode: wrapModeOf(clip.wrapMode), tracks },- skipped,- events: Array.isArray(clip._events) ? clip._events.length : 0,- };-}diff --git a/pipeline/src/import/cocos/animationGraph.ts b/pipeline/src/import/cocos/animationGraph.tsdeleted file mode 100644index 8ffabff76..000000000--- a/pipeline/src/import/cocos/animationGraph.ts+++ /dev/null@@ -1,194 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A Cocos `.animgraph` as an engine `.esanimator`.- *- * A graph is layers of state machines. A state plays a motion (one clip, or clips blended along a number), and transitions between states wait on- * conditions over named variables, optionally for the clip to end. The engine's Animator is the same model: parameters (numbers, flags,- * triggers), states with motions of any registered kind, transitions with conditions, an any-state, layers. So the conversion is a rename, and- * what the Animator cannot state is counted: a mask on a layer, `<=` and `>=` (the Animator has only- * `<` and `>`).- */-type Raw = Record<string, unknown>;-const isObj = (v: unknown): v is Raw => typeof v === 'object' && v !== null && !Array.isArray(v);-const num = (v: unknown, d: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : d);-const typeOf = (o: unknown): string => (isObj(o) && typeof o.__type__ === 'string' ? o.__type__.replace('cc.animation.', '') : '');--export interface GraphContext {- /** The timeline a clip uuid plays as on the node the controller is put on, or null when it cannot be found there. */- clip(clipUuid: string): string | null;- /** Called with a short code for something the Animator cannot state. */- note(code: string): void;-}--interface Condition { param: string; op: string; value?: number }-interface Transition { to: string; conditions: Condition[]; duration?: number; hasExitTime?: boolean }-interface State { name: string; motion?: Raw; speed?: number; speedParameter?: string; transitions: Transition[] }-interface Scope { states: State[]; initialState: string; anyStateTransitions: Transition[] }--export interface ConvertedGraph {- document: Raw;- /** Clip uuids the graph plays, found or not. */- clips: string[];-}--export function convertAnimationGraph(objects: unknown, ctx: GraphContext): ConvertedGraph {- const d = Array.isArray(objects) ? objects : [objects];- const at = (v: unknown): unknown => (isObj(v) && typeof v.__id__ === 'number' ? d[v.__id__] : v);- const root = d[0];- const clips: string[] = [];-- // ---- parameters --------------------------------------------------------------------------------------------------------------------- const parameters: Raw[] = [];- const variables = isObj(root) && isObj(root._variables) ? root._variables : {};- for (const [name, ref] of Object.entries(variables)) {- const v = at(ref);- const kind = typeOf(v);- if (kind === 'TriggerVariable') parameters.push({ name, type: 'trigger' });- else if (isObj(v) && num(v._type, 0) === 2) parameters.push({ name, type: 'bool', default: v._value === true });- else parameters.push({ name, type: 'float', default: isObj(v) ? num(v._value, 0) : 0 });- }- const boolean = new Set(parameters.filter((p) => p.type === 'bool').map((p) => p.name as string));-- // ---- motions ------------------------------------------------------------------------------------------------------------------------ const clipMotion = (ref: unknown): Raw | null => {- const motion = at(ref);- if (typeOf(motion) === 'ClipMotion' && isObj(motion)) {- const uuid = isObj(motion.clip) && typeof motion.clip.__uuid__ === 'string' ? motion.clip.__uuid__ : '';- if (!uuid) return null;- clips.push(uuid);- const timeline = ctx.clip(uuid);- if (!timeline) { ctx.note('graph-clip-not-found'); return null; }- return { kind: 'timeline', clip: timeline };- }- if (typeOf(motion) === 'AnimationBlend1D' && isObj(motion)) {- const param = at(motion.param);- const parameter = isObj(param) && typeof param.variable === 'string' ? param.variable : '';- const thresholds = (Array.isArray(motion._items) ? motion._items : []).flatMap((item) => {- const it = at(item);- const inner = isObj(it) ? clipMotion(it.motion) : null;- return inner && isObj(it) ? [{ value: num(it.threshold, 0), motion: inner }] : [];- });- if (!parameter || thresholds.length === 0) { ctx.note('graph-blend-empty'); return null; }- return { kind: 'blend1d', parameter, thresholds };- }- if (motion !== undefined && motion !== null) ctx.note(`graph-motion-${typeOf(motion) || 'unknown'}`);- return null;- };-- // ---- one state machine as a scope ----------------------------------------------------------------------------------------------- const scope = (machineRef: unknown): Scope => {- const machine = at(machineRef);- const m: Raw = isObj(machine) ? machine : {};- const names = new Map<unknown, string>();- const used = new Set<string>();- const unique = (name: string): string => {- let n = name || 'state';- for (let i = 2; used.has(n); i++) n = `${name || 'state'}_${i}`;- used.add(n);- return n;- };- const stateRefs = Array.isArray(m._states) ? (m._states as unknown[]) : [];- const entry = at(m._entryState), exit = at(m._exitState), any = at(m._anyState);- const states: State[] = [];- for (const ref of stateRefs) {- const s = at(ref);- if (s === entry || s === exit || s === any || !isObj(s)) continue;- const name = unique(typeof s.name === 'string' ? s.name : '');- names.set(s, name);- const state: State = { name, transitions: [] };- if (typeOf(s) === 'Motion') {- const motion = clipMotion(s.motion);- if (motion) state.motion = motion;- state.speed = num(s.speed, 1);- // the variable scales the state's clock; it has to be a number the graph declares- if (s.speedMultiplierEnabled === true && typeof s.speedMultiplier === 'string' && s.speedMultiplier !== '') {- if (parameters.some((p) => p.name === s.speedMultiplier && p.type === 'float')) state.speedParameter = s.speedMultiplier;- else ctx.note('graph-speed-variable-missing');- }- } else {- ctx.note(`graph-state-${typeOf(s) || 'unknown'}`);- }- states.push(state);- }- const conditionOf = (ref: unknown): Condition | null => {- const c = at(ref);- const kind = typeOf(c);- if (kind === 'TriggerCondition' && isObj(c)) return typeof c.trigger === 'string' ? { param: c.trigger, op: 'trigger' } : null;- if (kind === 'UnaryCondition' && isObj(c)) {- const operand = at(c.operand);- const param = isObj(operand) && typeof operand.variable === 'string' ? operand.variable : '';- if (!param) { ctx.note('graph-condition-constant'); return null; }- return { param, op: num(c.operator, 0) === 0 ? 'true' : 'false' };- }- if (kind === 'BinaryCondition' && isObj(c)) {- const lhs = at(c.lhs), rhs = at(c.rhs);- const param = isObj(lhs) && typeof lhs.variable === 'string' ? lhs.variable : '';- const value = isObj(rhs) ? num(rhs.value, 0) : 0;- if (!param) { ctx.note('graph-condition-constant'); return null; }- const operator = num(c.operator, 0);- if (operator === 3 || operator === 5) ctx.note('graph-condition-inclusive');- if (boolean.has(param)) return { param, op: value !== 0 && operator !== 1 ? 'true' : 'false' };- return { param, op: ['eq', 'neq', 'lt', 'lt', 'gt', 'gt'][operator] ?? 'eq', value };- }- ctx.note(`graph-condition-${kind || 'unknown'}`);- return null;- };- let initialState = '';- const transitions = Array.isArray(m._transitions) ? (m._transitions as unknown[]) : [];- const anyStateTransitions: Transition[] = [];- for (const ref of transitions) {- const t = at(ref);- if (!isObj(t)) continue;- const from = at(t.from), to = at(t.to);- if (from === entry) {- const target = names.get(to);- if (target && initialState === '') initialState = target;- continue;- }- const target = names.get(to);- if (to === exit || target === undefined) { ctx.note('graph-transition-to-exit'); continue; }- const kind = typeOf(t);- const conditions = (Array.isArray(t.conditions) ? t.conditions : []).map(conditionOf).filter((c): c is Condition => c !== null);- const out: Transition = { to: target, conditions };- if (kind === 'AnimationTransition') {- const duration = num(t.duration, 0);- if (duration > 0) out.duration = duration;- if (t.relativeDuration === true && duration > 0) ctx.note('graph-duration-relative');- if (t.exitConditionEnabled === true) out.hasExitTime = true;- }- if (from === any) anyStateTransitions.push(out);- else {- const owner = states.find((s) => names.get(from) === s.name);- if (owner) owner.transitions.push(out);- }- }- return { states, initialState: initialState || states[0]?.name || '', anyStateTransitions };- };-- const layers = isObj(root) && Array.isArray(root._layers) ? (root._layers as unknown[]) : [];- const built = layers.map((ref) => {- const layer = at(ref);- return { layer: isObj(layer) ? layer : ({} as Raw), scope: scope(isObj(layer) ? layer._stateMachine : undefined) };- });- const base = built[0]?.scope ?? { states: [], initialState: '', anyStateTransitions: [] };- const toState = (s: State): Raw => ({- name: s.name,- ...(s.motion ? { motion: s.motion } : {}),- ...(s.speed !== undefined && s.speed !== 1 ? { speed: s.speed } : {}),- ...(s.speedParameter ? { speedParameter: s.speedParameter } : {}),- transitions: s.transitions,- });- const scopeDoc = (s: Scope): Raw => ({- states: s.states.map(toState), initialState: s.initialState,- ...(s.anyStateTransitions.length > 0 ? { anyStateTransitions: s.anyStateTransitions } : {}),- });- const extra = built.slice(1).map(({ layer, scope: s }) => {- if (layer.mask) ctx.note('graph-layer-mask');- return { name: typeof layer.name === 'string' && layer.name ? layer.name : 'layer', weight: num(layer.weight, 1), blend: 'override', ...scopeDoc(s) };- });- return {- document: { version: 2, parameters, ...scopeDoc(base), ...(extra.length > 0 ? { layers: extra } : {}) },- clips,- };-}diff --git a/pipeline/src/import/cocos/assets.ts b/pipeline/src/import/cocos/assets.tsdeleted file mode 100644index 7d03a702f..000000000--- a/pipeline/src/import/cocos/assets.ts+++ /dev/null@@ -1,131 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file What a Cocos project's `.meta` files say about its assets.- *- * A scene names its assets by uuid; the `.meta` beside each file is the- * only place that says which file a uuid is, and a sprite frame is a- * sub-asset (`<image uuid>@f9941`) of its image. This reads every meta- * once into a lookup. Read-only.- */-import { existsSync, readdirSync, readFileSync } from 'node:fs';-import path from 'node:path';--export interface CocosAssetEntry {- uuid: string;- /** Absolute path of the asset file. */- file: string;- /** Path relative to the project's `assets` folder, forward slashes. */- rel: string;- importer: string;- userData: Record<string, unknown>;- /** Sub-assets by their full uuid (`<uuid>@<id>`). */- subs: Map<string, { importer: string; name: string; userData: Record<string, unknown> }>;-}--export interface CocosAssetIndex {- /** The project's `assets` folder. */- root: string;- /** Every asset and every sub-asset, by uuid. A sub-asset resolves to its parent file. */- byUuid: Map<string, CocosAssetEntry>;- /** Folders whose contents scripts load by path at run time: asset bundles, and the `resources` folders. */- bundles: CocosBundleRoot[];-}--export interface CocosBundleRoot {- /** The name a script loads it by: `resources`, or the bundle's own name. */- name: string;- /** The folder, relative to the project's `assets`. */- rel: string;-}--const SKIP = new Set(['node_modules', '.git']);--function* walk(dir: string): Generator<string> {- let entries;- try {- entries = readdirSync(dir, { withFileTypes: true });- } catch {- return;- }- for (const e of entries) {- if (e.isDirectory()) {- if (!SKIP.has(e.name)) yield* walk(path.join(dir, e.name));- } else if (e.name.endsWith('.meta')) {- yield path.join(dir, e.name);- }- }-}--const asObj = (v: unknown): Record<string, unknown> => (typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : {});--/** Where a project's own copy of the editor's built-in assets lands in the converted project, under the import's folder. */-export const INTERNAL_FOLDER = '__cocos_internal';--/**- * The editor's built-in assets (`default_ui`, the default particle, the default materials), which a project names by uuid and does not hold: they- * live in the Creator install. `COCOS_EDITOR_ASSETS` names the folder outright; otherwise the install the project's own version points at, in the- * place the installer puts it. Null when it is not on this machine, in which case what refers to one is left as a reference that does not resolve.- */-export function cocosEditorAssets(version: string | undefined): string | null {- const tail = ['resources', 'resources', '3d', 'engine', 'editor', 'assets'];- const candidates: string[] = [];- if (process.env.COCOS_EDITOR_ASSETS) candidates.push(process.env.COCOS_EDITOR_ASSETS);- if (version) {- candidates.push(path.join('C:/ProgramData/cocos/editors/Creator', version, ...tail));- candidates.push(path.join('/Applications/Cocos/Creator', version, 'CocosCreator.app/Contents', 'Resources', ...tail.slice(1)));- }- return candidates.find((c) => existsSync(c)) ?? null;-}--export function buildCocosAssetIndex(root: string, internalRoot?: string | null): CocosAssetIndex {- const byUuid = new Map<string, CocosAssetEntry>();- const bundles: CocosBundleRoot[] = [];- scan(root, root, '', byUuid, bundles, true);- // What the project does not hold itself: its own assets win, so a project that carries a copy of a built-in is read as it is.- if (internalRoot) {- const internal = new Map<string, CocosAssetEntry>();- scan(internalRoot, internalRoot, `${INTERNAL_FOLDER}/`, internal, [], false);- // Models are left out: the built-in shapes are mapped to the engine's own, by their uuid, and are not meant to be imported as files.- for (const [uuid, entry] of internal) if (!byUuid.has(uuid) && entry.importer !== 'fbx' && entry.importer !== 'gltf') byUuid.set(uuid, entry);- }- return { root, byUuid, bundles };-}--function scan(dir: string, root: string, relPrefix: string, byUuid: Map<string, CocosAssetEntry>, bundles: CocosBundleRoot[], withBundles: boolean): void {- for (const metaFile of walk(dir)) {- let meta: Record<string, unknown>;- try {- meta = asObj(JSON.parse(readFileSync(metaFile, 'utf8')));- } catch {- continue;- }- const uuid = meta.uuid;- if (meta.importer === 'directory') {- if (!withBundles) continue;- const folder = metaFile.slice(0, -'.meta'.length);- const rel = path.relative(root, folder).split(path.sep).join('/');- const userData = asObj(meta.userData);- if (userData.isBundle === true) bundles.push({ name: typeof userData.bundleName === 'string' && userData.bundleName ? userData.bundleName : path.basename(folder), rel });- else if (path.basename(folder) === 'resources') bundles.push({ name: 'resources', rel });- continue;- }- if (typeof uuid !== 'string') continue;- const file = metaFile.slice(0, -'.meta'.length);- const entry: CocosAssetEntry = {- uuid,- file,- rel: relPrefix + path.relative(root, file).split(path.sep).join('/'),- importer: typeof meta.importer === 'string' ? meta.importer : '',- userData: asObj(meta.userData),- subs: new Map(),- };- for (const sub of Object.values(asObj(meta.subMetas))) {- const s = asObj(sub);- if (typeof s.uuid !== 'string') continue;- entry.subs.set(s.uuid, { importer: typeof s.importer === 'string' ? s.importer : '', name: typeof s.name === 'string' ? s.name : '', userData: asObj(s.userData) });- byUuid.set(s.uuid, entry);- }- byUuid.set(uuid, entry);- }-}diff --git a/pipeline/src/import/cocos/components.ts b/pipeline/src/import/cocos/components.tsdeleted file mode 100644index 2500277f8..000000000--- a/pipeline/src/import/cocos/components.ts+++ /dev/null@@ -1,1071 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file Cocos components to Estella components, one node at a time.- *- * Only what has a faithful counterpart is mapped. Everything else is kept- * verbatim under the entity's `metadata.cocos`, so a later stage (a script- * shim, a Widget system) can read it and nothing is silently lost — and is- * counted in the report as unmapped.- *- * UI note: a Cocos UI node is "anchor + content size + local position".- * That is a world-space `Sprite`/`Text` with a pivot, not a flex box, so- * UI maps there and `UITransform` is folded into it.- */-import { readFileSync } from 'node:fs';-import { curveRange, particleSystem, particleSystem2D } from './particle';-import type { CocosAssetEntry, CocosAssetIndex } from './assets';-import { type CocosComponent, type CocosNode } from './document';-import type { ImportReport } from './report';-import { NODE_REF } from './document';--export interface ComponentData {- type: string;- data: Record<string, unknown>;-}--export interface SliceBorder { left: number; right: number; top: number; bottom: number }--/** What the engine needs to know about an asset beyond its bytes, learnt from how the project uses it. */-export interface AssetHints {- /** A bitmap font whose page carries the glyph in red and glyph-and-outline in alpha. */- bakedOutline?: boolean;-}--/** What a Cocos material says that a MeshRenderer, a Sprite or a particle can carry: the image and tint, and how it blends and culls. */-export interface MaterialInfo {- texture: CocosAssetEntry | null;- /** The tint (`mainColor` or `albedo`), 0..1, when the material sets one. */- color?: { r: number; g: number; b: number; a: number };- normal?: CocosAssetEntry | null;- additive: boolean;- /** Blends with what is behind it. */- transparent: boolean;- /** The effect does not light the surface. */- unlit: boolean;- /** Faces turned away are not drawn. */- cullBack: boolean;- /** The effect is one of the engine's built-ins rather than the project's own shader, which is approximated. */- builtinEffect: boolean;-}--export interface ComponentContext {- assets: CocosAssetIndex;- report: ImportReport;- /** The project-relative ref of a copied asset; records that it must be copied. */- assetRef(entry: CocosAssetEntry, slice?: SliceBorder, hints?: AssetHints): string;- /**- * Whether a Cocos material draws a bitmap font's page as two layers, a glyph in the red channel and its outline in alpha, with the- * outline's colour supplied at draw time. Such a font has to say so, in the channel flags BMFont gives that layout.- */- drawsBakedOutline?(materialUuid: string): boolean;- /** What a Cocos material draws and how; null when the project has no such material. */- material?(uuid: string): MaterialInfo | null;- /** The Estella material a Cocos material of the project's own effect became (its shader converted), by its project path; null when the effect could not be converted. */- /** The converted material for a project material, and whether it blends (its effect's pass says so, which the material file does not). */- convertedMaterial?(uuid: string): { ref: string; blends?: boolean; outline?: string } | null;- /**- * The engine MeshRenderer data of the part of a model a Cocos mesh sub-asset names, once that model was brought in. `exact` is false when- * the part was picked because the model draws only one.- */- modelMesh?(uuid: string): { components: Record<string, unknown>[]; exact: boolean } | null;- /** The engine prefab of a model a uuid names (the whole model, or its scene), or null when the uuid is not a model that was brought in. */- modelInstance?(uuid: string): { prefab: string; rootId: string; name: string; paths: Map<string, string>; parts: Map<string, string> } | null;- /**- * The `.esanimator` a Cocos animation graph is converted to for a node whose bones stand at @p paths, or null when the graph is not one of the- * project's. A graph that plays clips of a model is written once for each skeleton it is put on.- */- animatorController?(graphUuid: string, paths: Map<string, string>, where: string): { ref: string; complete: boolean } | null;- /** The skeleton and atlas files of a Spine data asset, copied into the project (project-relative), or null when the project does not have them. */- spineAssets?(uuid: string): { skeleton: string; atlas: string } | null;- /** The timeline a Cocos `.anim` clip is converted to (project-relative), or null when the clip is not one of the project's. */- animationClip?(clipUuid: string, where: string): string | null;- /** The joints, by name, a skinned part of a model is bound to, in the order its vertices index them. */- modelSkin?(meshUuid: string): string[] | null;- /**- * A clip of a model, ready to play on the hierarchy @p paths describes (node name to its path under the node the clip plays from): the- * project-relative timeline, or null when the clip or its nodes are not there.- */- clipOn?(clipUuid: string, paths: Map<string, string>, where: string): string | null;- /** The Cocos node an id names in the document being converted. */- nodeById?: Map<string, CocosNode>;- /** The script class a compressed class id names, when the project has that script. */- scriptClass?(classId: string): { name: string } | undefined;- /** The project-relative ref of a prefab, queuing it for conversion; null when the project does not have it. */- prefabAssetRef?(uuid: string): string | null;-}--type Raw = Record<string, unknown>;-const isObj = (v: unknown): v is Raw => typeof v === 'object' && v !== null && !Array.isArray(v);-const num = (v: unknown, d: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : d);--const color = (v: unknown, fallback = 1): Raw => {- const c = isObj(v) ? v : {};- return { r: num(c.r, 255) / 255, g: num(c.g, 255) / 255, b: num(c.b, 255) / 255, a: num(c.a, fallback * 255) / 255 };-};--const clamp012 = (v: unknown): number => Math.min(2, Math.max(0, Math.trunc(num(v, 0))));--const uuidOf = (v: unknown): string => (isObj(v) && typeof v.__uuid__ === 'string' ? v.__uuid__ : '');--/** The same value for `a` and `b`, structurally. Overrides are the fields where it is not. */-export function sameData(a: unknown, b: unknown): boolean {- if (a === b) return true;- if (typeof a !== typeof b || a === null || b === null || typeof a !== 'object') return false;- if (Array.isArray(a) !== Array.isArray(b)) return false;- const ka = Object.keys(a as Raw);- const kb = Object.keys(b as Raw);- if (ka.length !== kb.length) return false;- return ka.every((k) => sameData((a as Raw)[k], (b as Raw)[k]));-}--function transform(node: CocosNode): ComponentData {- return {- type: 'Transform',- data: { position: { ...node.pos }, rotation: { ...node.rot }, scale: { ...node.scale } },- };-}--interface UiBox { width: number; height: number; ax: number; ay: number }--function uiBox(node: CocosNode): UiBox | null {- const t = node.components.find((c) => c.type === 'cc.UITransform');- if (!t) return null;- const s = isObj(t.data._contentSize) ? t.data._contentSize : {};- const a = isObj(t.data._anchorPoint) ? t.data._anchorPoint : {};- return { width: num(s.width, 100), height: num(s.height, 100), ax: num(a.x, 0.5), ay: num(a.y, 0.5) };-}--function sprite(c: CocosComponent, box: UiBox | null, ctx: ComponentContext, where: string, as: 'cc.Sprite' | 'cc.SpriteRenderer' = 'cc.Sprite'): ComponentData | null {- const frameUuid = uuidOf(c.data._spriteFrame);- const data: Raw = { color: color(c.data._color), enabled: c.enabled };- if (box) {- data.size = { x: box.width, y: box.height };- data.pivot = { x: box.ax, y: box.ay };- }- if (!frameUuid) {- // No frame draws nothing in Cocos: the sprite is there, off, for a script that sets its frame; a white quad would be wrong.- ctx.report.component(as, 'mapped');- ctx.report.note('sprite-no-frame', where);- return { type: 'Sprite', data: { ...data, enabled: false } };- }- const entry = ctx.assets.byUuid.get(frameUuid);- const sub = entry?.subs.get(frameUuid);- if (!entry || !sub || entry.importer !== 'image' || sub.importer !== 'sprite-frame') {- // A frame the project does not have draws nothing in Cocos either. The sprite stays, switched off, so a script that sets its frame later- // finds the component, and a white quad does not stand where a picture was meant.- ctx.report.component(as, 'partial');- ctx.report.note(entry ? 'sprite-frame-not-from-image' : 'sprite-frame-missing', where);- if (!entry) ctx.report.missingAsset(frameUuid);- return { type: 'Sprite', data: { ...data, enabled: false } };- }-- const ud = sub.userData;- const kind = num(c.data._type, 0);- let status: 'mapped' | 'partial' = 'mapped';- // The material the sprite is drawn with, when the project's own effect for it was converted.- const customMaterial = uuidOf(c.data._customMaterial) || uuidOf(Array.isArray(c.data._materials) ? c.data._materials[0] : undefined);- if (customMaterial) {- const converted = ctx.convertedMaterial?.(customMaterial);- if (converted) data.material = converted.ref;- else if (ctx.material?.(customMaterial)?.builtinEffect === false) { status = 'partial'; ctx.report.note('sprite-custom-effect', where); }- }-- const border: SliceBorder = {- left: num(ud.borderLeft, 0),- right: num(ud.borderRight, 0),- top: num(ud.borderTop, 0),- bottom: num(ud.borderBottom, 0),- };- const hasBorder = border.left + border.right + border.top + border.bottom > 0;- if (kind === 1 && hasBorder) {- data.drawMode = 3; // NineSlice- data.texture = ctx.assetRef(entry, border);- } else {- data.texture = ctx.assetRef(entry);- if (kind === 2) {- data.drawMode = 2; // Tiled- } else if (kind === 3) {- status = 'partial';- ctx.report.note('sprite-filled-as-simple', where);- }- }-- const rawW = num(ud.rawWidth, 0);- const rawH = num(ud.rawHeight, 0);- const w = num(ud.width, rawW);- const h = num(ud.height, rawH);- const x = num(ud.trimX, 0);- const y = num(ud.trimY, 0);- if (rawW > 0 && rawH > 0 && (w !== rawW || h !== rawH || x !== 0 || y !== 0)) {- data.uvOffset = { x: x / rawW, y: 1 - (y + h) / rawH };- data.uvScale = { x: w / rawW, y: h / rawH };- // Cocos's `trim` (the default) fills the node's rectangle with the frame's trimmed region, which is what the UV window does. With trim- // off the region keeps the place it had in the full image, scaled with the node: its size is the node's times its share of the image,- // and its centre sits off the node's centre by how far it sat off the image's.- if (c.data._isTrimmedMode === false && box && kind !== 1) {- const sx = box.width / rawW, sy = box.height / rawH;- const size = { x: w * sx, y: h * sy };- const centre = {- x: (0.5 - box.ax) * box.width + (x + w / 2 - rawW / 2) * sx,- y: (0.5 - box.ay) * box.height - (y + h / 2 - rawH / 2) * sy,- };- data.size = size;- data.pivot = { x: size.x === 0 ? 0.5 : 0.5 - centre.x / size.x, y: size.y === 0 ? 0.5 : 0.5 - centre.y / size.y };- }- ctx.report.note('sprite-trimmed-frame', where);- }- if (ud.rotated === true) {- status = 'partial';- ctx.report.note('sprite-rotated-frame', where);- }- if (c.data._useGrayscale === true) {- status = 'partial';- ctx.report.note('sprite-grayscale', where);- }- ctx.report.component(as, status);- return { type: 'Sprite', data };-}--function label(c: CocosComponent, siblings: CocosComponent[], box: UiBox | null, ctx: ComponentContext, where: string): ComponentData {- const d = c.data;- const fontSize = num(d._fontSize, 40);- const lineHeight = num(d._lineHeight, fontSize);- const overflow = num(d._overflow, 0);- let status: 'mapped' | 'partial' = 'mapped';- const data: Raw = {- content: typeof d._string === 'string' ? d._string : '',- fontSize,- color: color(d._color),- // Left/Center/Right and Top/Middle/Bottom number the same in both engines (0, 1, 2).- align: clamp012(d._horizontalAlign),- verticalAlign: clamp012(d._verticalAlign),- // Cocos wraps only where the box limits the text: with no overflow rule (NONE) the node grows to the text and nothing wraps, and- // ResizeHeight wraps by width whatever the flag says.- wordWrap: overflow === 0 ? false : overflow === 3 ? true : d._enableWrapText !== false,- overflow: overflow === 1 ? 1 : overflow === 2 ? 3 : overflow === 3 ? 4 : 0, // Clip, Shrink, ResizeHeight, otherwise Visible- lineHeight: fontSize > 0 ? Math.round((lineHeight / fontSize) * 1000) / 1000 : 1.2,- bold: d._isBold === true,- italic: d._isItalic === true,- enabled: c.enabled,- };- // A Label wraps, aligns and clips inside its UITransform rect, and the node origin is that rect's anchor.- if (box) {- data.boxWidth = box.width;- data.boxHeight = box.height;- data.boxPivot = { x: box.ax, y: box.ay };- // A node that grows to its text keeps its anchor where it was, so the text is laid out from the anchor: a run on a node anchored at- // its middle spreads both ways from there, whatever alignment the label names (the alignment only matters inside a box that limits it).- if (overflow === 0) {- data.align = box.ax <= 0.25 ? 0 : box.ax >= 0.75 ? 2 : 1;- data.verticalAlign = box.ay >= 0.75 ? 0 : box.ay <= 0.25 ? 2 : 1;- }- }- const fontUuid = uuidOf(d._font);- if (d._isSystemFontUsed === false && fontUuid) {- const font = ctx.assets.byUuid.get(fontUuid);- if (font?.importer === 'ttf-font') {- data.font = ctx.assetRef(font);- } else if (font?.importer === 'bitmap-font') {- const material = uuidOf(d._customMaterial);- const baked = material !== '' && ctx.drawsBakedOutline?.(material) === true;- data.font = ctx.assetRef(font, undefined, baked ? { bakedOutline: true } : undefined);- } else {- status = 'partial';- ctx.report.note(font ? 'label-font-unsupported' : 'label-font-missing', where);- if (!font) ctx.report.missingAsset(fontUuid);- }- } else if (typeof d._fontFamily === 'string') {- data.fontFamily = d._fontFamily;- }- if (d._isUnderline === true) data.underline = true;-- const outline = siblings.find((s) => s.type === 'cc.LabelOutline' && s.enabled);- if (outline) {- data.strokeColor = color(outline.data._color);- data.strokeWidth = num(outline.data._width, 0);- }- const shadow = siblings.find((s) => s.type === 'cc.LabelShadow' && s.enabled);- if (shadow) {- const off = isObj(shadow.data._offset) ? shadow.data._offset : {};- data.shadowColor = color(shadow.data._color);- data.shadowBlur = num(shadow.data._blur, 0);- data.shadowOffsetX = num(off.x, 2);- data.shadowOffsetY = -num(off.y, -2);- }- ctx.report.component('cc.Label', status);- return { type: 'Text', data };-}--function richText(c: CocosComponent, box: UiBox | null, ctx: ComponentContext): ComponentData {- const d = c.data;- // The markup is the engine's rich-text parser's to read (it knows Cocos's tags), so the string goes across as written.- ctx.report.component('cc.RichText', 'mapped');- const maxWidth = num(d._maxWidth, 0);- return {- type: 'Text',- data: {- ...(box && maxWidth > 0 ? { boxWidth: maxWidth, boxHeight: box.height, boxPivot: { x: box.ax, y: box.ay } } : {}),- content: typeof d._string === 'string' ? d._string : '',- fontSize: num(d._fontSize, 40),- color: color(d._fontColor),- richText: true,- wordWrap: num(d._maxWidth, 0) > 0,- align: clamp012(d._horizontalAlign),- enabled: c.enabled,- },- };-}--/**- * What a Cocos camera clears, as the engine's: the engine's flags are colour (1) and depth (2). Cocos writes the graphics API's bits, so a solid- * colour is 7 (all three), depth only is 6 and a skybox is 14; the engine has no skybox, which a camera that would have drawn one clears as a colour.- */-export function engineClearFlags(cocos: number): number {- return cocos === 14 ? 3 : (cocos & 1 ? 1 : 0) | (cocos & 2 ? 2 : 0);-}--function camera(c: CocosComponent, ctx: ComponentContext): ComponentData {- const d = c.data;- ctx.report.component('cc.Camera', 'mapped');- return {- type: 'Camera',- data: {- projectionType: num(d._projection, 0) === 0 ? 1 : 0, // Orthographic : Perspective- fov: num(d._fov, 45),- orthoSize: num(d._orthoHeight, 10),- nearPlane: num(d._near, 1),- farPlane: num(d._far, 1000),- priority: num(d._priority, 0),- cullingMask: num(d._visibility, 0xffffffff) >>> 0,- // a camera drawn over another (the UI's, which clears only depth) must not wipe what the one under it drew- clearFlags: engineClearFlags(num(d._clearFlags, 7)),- ...(isObj(d._rect) ? { viewport: { x: num(d._rect.x, 0), y: num(d._rect.y, 0), z: num(d._rect.width, 1), w: num(d._rect.height, 1) } } : {}),- isActive: c.enabled,- },- };-}--// ----------------------------------------------------------------------------// The compatibility layer's components: UI geometry, alignment, layout, buttons, and the project's own scripts.-// -----------------------------------------------------------------------------/** Names of the components the layer declares for built-ins; a scene that holds one needs `esengine/cocos` loaded. */-const LAYER = 'Cocos.';--/** A node's rectangle as the engine's `ContentRect`: the size, and the pivot the node's position is the position of. */-function contentRectData(box: UiBox): ComponentData {- return { type: 'ContentRect', data: { size: { x: box.width, y: box.height }, pivot: { x: box.ax, y: box.ay } } };-}--/**- * `cc.Mask` as the engine's `UIMask`. A rectangle mask clips to the node's rectangle, exactly; a sprite-stencil mask clips to the shape the node's- * sprite draws, which is the engine's stencil mode. Ellipse and graphics masks clip to the rectangle instead of to their shape, so those are- * counted as partial.- */-function mask(c: CocosComponent, ctx: ComponentContext): ComponentData {- const type = num(c.data._type, 0);- // A sprite-stencil mask clips to the shape its node's sprite draws, above an alpha threshold: the engine's stencil mode.- if (type === 3) {- ctx.report.component('cc.Mask', 'mapped');- return { type: 'UIMask', data: { enabled: c.enabled, mode: 1, alphaCutoff: Math.max(num(c.data._alphaThreshold, 0.1), 0.001) } };- }- ctx.report.component('cc.Mask', type === 0 ? 'mapped' : 'partial');- return { type: 'UIMask', data: { enabled: c.enabled, mode: 0, alphaCutoff: 0 } };-}--/** Copy the serialised fields named in @p map to the layer's names, leaving out the ones the file does not carry. */-function renamed(c: CocosComponent, map: Record<string, string>): Raw {- const out: Raw = { enabled: c.enabled };- for (const [from, to] of Object.entries(map)) if (c.data[from] !== undefined) out[to] = c.data[from];- return out;-}--function widget(c: CocosComponent): ComponentData {- const data = renamed(c, {- _alignFlags: 'alignFlags', _left: 'left', _right: 'right', _top: 'top', _bottom: 'bottom',- _horizontalCenter: 'horizontalCenter', _verticalCenter: 'verticalCenter',- _isAbsLeft: 'isAbsLeft', _isAbsRight: 'isAbsRight', _isAbsTop: 'isAbsTop', _isAbsBottom: 'isAbsBottom',- _isAbsHorizontalCenter: 'isAbsHorizontalCenter', _isAbsVerticalCenter: 'isAbsVerticalCenter',- _alignMode: 'alignMode',- });- // The engine's own component: the same fields, aligned by the engine in the editor as well as in play. A widget that targets a node other- // than its parent has nothing to say that in; its fields come across and it aligns to the parent.- return { type: 'RectAnchors', data };-}--function layout(c: CocosComponent): ComponentData {- const data = renamed(c, {- _layoutType: 'type', _resizeMode: 'resizeMode', _paddingLeft: 'paddingLeft', _paddingRight: 'paddingRight',- _paddingTop: 'paddingTop', _paddingBottom: 'paddingBottom', _spacingX: 'spacingX', _spacingY: 'spacingY',- _verticalDirection: 'verticalDirection', _horizontalDirection: 'horizontalDirection', _affectedByScale: 'affectedByScale',- _startAxis: 'startAxis', _constraint: 'constraint', _constraintNum: 'constraintNum', _isAlign: 'isAlign',- });- if (isObj(c.data._cellSize)) {- data.cellWidth = num(c.data._cellSize.width, 40);- data.cellHeight = num(c.data._cellSize.height, 40);- }- return { type: `${LAYER}Layout`, data };-}--/**- * An editor-authored handler list as the data model keeps it: the target nodes in a list of their own (they are entity references the- * loader remaps) and the rest of each record beside it. @p prefix names the pair: `click` gives `clickTargets` / `clickHandlers`.- */-function handlerLists(events: unknown, prefix: string, ctx: ComponentContext): Raw {- const list = Array.isArray(events) ? events.filter(isObj) : [];- return {- [`${prefix}Targets`]: list.map((e) => e.target ?? null),- [`${prefix}Handlers`]: list.map((e) => {- const id = typeof e._componentId === 'string' ? e._componentId : '';- const known = id ? ctx.scriptClass?.(id)?.name : undefined;- return {- component: known ?? (typeof e.component === 'string' ? e.component : ''),- handler: typeof e.handler === 'string' ? e.handler : '',- customEventData: typeof e.customEventData === 'string' ? e.customEventData : '',- };- }),- };-}--const BUTTON_FIELDS: Record<string, string> = {- _interactable: 'interactable', _transition: 'transition', _zoomScale: 'zoomScale', _duration: 'duration',- _normalColor: 'normalColor', _hoverColor: 'hoverColor', _pressedColor: 'pressedColor', _disabledColor: 'disabledColor',- _target: 'target',-};--function button(c: CocosComponent, ctx: ComponentContext): ComponentData {- return { type: `${LAYER}Button`, data: { ...renamed(c, BUTTON_FIELDS), ...handlerLists(c.data.clickEvents, 'click', ctx) } };-}--function toggle(c: CocosComponent, ctx: ComponentContext): ComponentData {- return {- type: `${LAYER}Toggle`,- data: {- ...renamed(c, { ...BUTTON_FIELDS, _isChecked: 'isChecked', _checkMark: 'checkMark', _toggleGroup: 'toggleGroup' }),- ...handlerLists(c.data.clickEvents, 'click', ctx),- ...handlerLists(c.data.checkEvents, 'check', ctx),- },- };-}--function toggleContainer(c: CocosComponent, ctx: ComponentContext): ComponentData {- return { type: `${LAYER}ToggleContainer`, data: { ...renamed(c, { _allowSwitchOff: 'allowSwitchOff' }), ...handlerLists(c.data.checkEvents, 'check', ctx) } };-}--function progressBar(c: CocosComponent): ComponentData {- return { type: `${LAYER}ProgressBar`, data: renamed(c, { _barSprite: 'barSprite', _mode: 'mode', _totalLength: 'totalLength', _progress: 'progress_', _reverse: 'reverse' }) };-}--function slider(c: CocosComponent, ctx: ComponentContext): ComponentData {- return { type: `${LAYER}Slider`, data: { ...renamed(c, { _handle: 'handle', _direction: 'direction', _progress: 'progress_' }), ...handlerLists(c.data.slideEvents, 'slide', ctx) } };-}--function scrollView(c: CocosComponent, ctx: ComponentContext): ComponentData {- return {- type: `${LAYER}ScrollView`,- data: {- ...renamed(c, {- _content: 'content', horizontal: 'horizontal', vertical: 'vertical', inertia: 'inertia', brake: 'brake', elastic: 'elastic',- bounceDuration: 'bounceDuration', cancelInnerEvents: 'cancelInnerEvents',- }),- ...handlerLists(c.data.scrollEvents, 'scroll', ctx),- },- };-}--/** A script component's fields, with asset references turned into project paths. */-function scriptValue(v: unknown, ctx: ComponentContext): unknown {- if (Array.isArray(v)) return v.map((x) => scriptValue(x, ctx));- if (!isObj(v)) return v;- if (typeof v.__uuid__ === 'string') {- const uuid = v.__uuid__;- const prefab = ctx.prefabAssetRef?.(uuid);- if (prefab) return prefab;- const entry = ctx.assets.byUuid.get(uuid);- return entry ? ctx.assetRef(entry) : '';- }- const out: Raw = {};- for (const [k, x] of Object.entries(v)) out[k] = scriptValue(x, ctx);- return out;-}--/** A sunlight: colour and strength. Cocos states strength in lux; its LDR figure is the one a game without HDR is lit by. */-function directionalLight(c: CocosComponent, ctx: ComponentContext, where: string): ComponentData {- const d = c.data;- ctx.report.component('cc.DirectionalLight', 'partial');- ctx.report.note('light-intensity-units', where);- return {- type: 'Light',- data: {- type: 1, // Directional- color: color(d._color),- intensity: num(d._illuminanceLDR, 1),- enabled: c.enabled,- },- };-}--/** Where each node under @p node stands, by name, as a path from it: what a clip addresses a node by. The first node of a name wins. */-function namePaths(node: CocosNode, ctx: ComponentContext): Map<string, string> {- const paths = new Map<string, string>();- const walk = (n: CocosNode, prefix: string): void => {- for (const child of n.children) {- const here = prefix ? `${prefix}/${child.name}` : child.name;- if (!paths.has(child.name)) paths.set(child.name, here);- // a model put in under this node brings its own bones, which stand below the instance- const model = child.instance ? ctx.modelInstance?.(child.instance.asset) : null;- if (model) for (const [name, below] of model.paths) if (!paths.has(name)) paths.set(name, `${here}/${below}`);- walk(child, here);- }- };- walk(node, '');- return paths;-}--/** The first node of a name in the subtree under @p root, the root itself included. */-function findByName(root: CocosNode, name: string): CocosNode | null {- if (root.name === name) return root;- for (const child of root.children) {- const hit = findByName(child, name);- if (hit) return hit;- }- return null;-}--/**- * `cc.SkinnedMeshRenderer`: a part of a model bound to bones that are nodes of this document. The mesh is the model's own; the joints are the- * nodes under the skinning root that carry the names the model's skin binds, in the order the model's vertices index them.- */-function skinnedMeshRenderer(c: CocosComponent, ctx: ComponentContext, where: string): { component: ComponentData; extra: ComponentData[]; parts: ComponentData[][] } | null {- const mesh = meshRenderer(c, ctx, where);- if (!mesh) return null;- const meshUuid = uuidOf(c.data._mesh);- const names = ctx.modelSkin?.(meshUuid);- const rootRef = isObj(c.data._skinningRoot) ? c.data._skinningRoot[NODE_REF] : undefined;- const root = typeof rootRef === 'string' ? ctx.nodeById?.get(rootRef) : undefined;- if (!names || names.length === 0 || !root) {- ctx.report.component('cc.SkinnedMeshRenderer', 'partial');- ctx.report.note('skin-not-bound', where);- return { component: mesh.component, extra: [], parts: (mesh.more ?? []).map((m) => [m]) };- }- const joints = names.map((name) => {- const node = findByName(root, name);- return node ? { [NODE_REF]: node.id } : { [NODE_REF]: null };- });- const missing = names.filter((name) => !findByName(root, name)).length;- ctx.report.component('cc.SkinnedMeshRenderer', missing > 0 || mesh.partial ? 'partial' : 'mapped');- if (missing > 0) ctx.report.note('skin-joint-missing', `${where}: ${missing} of ${names.length}`);- return { component: mesh.component, extra: [{ type: 'MeshSkin', data: { joints } }], parts: (mesh.more ?? []).map((m) => [m, { type: 'MeshSkin', data: { joints: structuredClone(joints) } }]) };-}--/** `cc.Animation`: the clip it plays by default, as a timeline that plays on the node, from the start if the node asks. */-function animation(c: CocosComponent, node: CocosNode, ctx: ComponentContext, where: string): ComponentData | null {- const clips = (Array.isArray(c.data._clips) ? c.data._clips : []).map(uuidOf).filter(Boolean);- const wanted = uuidOf(c.data._defaultClip) || clips[0] || '';- // a clip of the project's own, or one that lives in a model file and animates the bones below this node- const ref = wanted ? ctx.animationClip?.(wanted, where) ?? ctx.clipOn?.(wanted, namePaths(node, ctx), where) : null;- if (!ref) {- ctx.report.note(wanted ? 'animation-clip-not-found' : 'animation-no-clip', `${where}: ${wanted}`);- // no clip yet (a script gives it one), or one the project does not have: the player stays, empty, so a script that sets a clip finds it- ctx.report.component('cc.Animation', wanted ? 'partial' : 'mapped');- return { type: 'TimelinePlayer', data: { timeline: '', playing: false, speed: 1, wrapMode: '' } };- }- if (clips.length > 1) ctx.report.note('animation-several-clips', where);- ctx.report.component('cc.Animation', clips.length > 1 ? 'partial' : 'mapped');- return { type: 'TimelinePlayer', data: { timeline: ref, playing: c.data.playOnLoad === true, speed: 1, wrapMode: '' } };-}--/** `cc.animation.AnimationController`: the graph as the engine's Animator, with its clips on this node's own bones. */-function animationController(c: CocosComponent, node: CocosNode, ctx: ComponentContext, where: string): ComponentData | null {- const graph = uuidOf(c.data._graph) || uuidOf(c.data.graph);- const made = graph ? ctx.animatorController?.(graph, namePaths(node, ctx), where) : null;- if (!made) {- // a graph the project does not have: the Animator stays with no controller, for a script that sets one- ctx.report.note('animator-graph-not-found', `${where}: ${graph}`);- ctx.report.component('cc.animation.AnimationController', 'partial');- return { type: 'Animator', data: { controller: '', enabled: c.enabled } };- }- ctx.report.component('cc.animation.AnimationController', made.complete ? 'mapped' : 'partial');- return { type: 'Animator', data: { controller: made.ref, enabled: c.enabled } };-}--/** `cc.SkeletalAnimation`: the clip it plays by default, copied onto this node's own bones, played from the start if the node asks. */-function skeletalAnimation(c: CocosComponent, node: CocosNode, ctx: ComponentContext, where: string): ComponentData | null {- const clips = (Array.isArray(c.data._clips) ? c.data._clips : []).map(uuidOf).filter(Boolean);- const wanted = uuidOf(c.data._defaultClip) || clips[0] || '';- const ref = wanted ? ctx.clipOn?.(wanted, namePaths(node, ctx), where) : null;- if (!ref) {- // no clip, or one this node has no bones for: the player stays, empty, for a script that gives it one- ctx.report.note(wanted ? 'skeletal-clip-not-found' : 'skeletal-no-clip', `${where}: ${wanted}`);- ctx.report.component('cc.SkeletalAnimation', wanted ? 'partial' : 'mapped');- return { type: 'TimelinePlayer', data: { timeline: '', playing: false, speed: 1, wrapMode: '' } };- }- if (clips.length > 1) ctx.report.note('animation-several-clips', where);- ctx.report.component('cc.SkeletalAnimation', clips.length > 1 ? 'partial' : 'mapped');- return { type: 'TimelinePlayer', data: { timeline: ref, playing: c.data.playOnLoad === true, speed: 1, wrapMode: '' } };-}--/**- * The shapes Cocos Creator builds in (`db://internal/primitives.fbx`), identified by the bounds of what the editor imported them to: the- * engine's own builtin meshes, and the size of the Cocos one in world units. The engine's are 100 across, the Cocos ones about 1 (a plane 10),- * so the node's scale carries the difference and the shape stays the size the scene meant.- */-const COCOS_PRIMITIVES = '1263d74c-8167-4928-91a6-4e2672411f47';-const PRIMITIVE_MESHES: Record<string, { ref: string; size: number; engineSize?: number }> = {- a804a: { ref: 'builtin:cube', size: 1 },- '17020': { ref: 'builtin:sphere', size: 1 },- '38fd2': { ref: 'builtin:cylinder', size: 1 },- '2e76e': { ref: 'builtin:cocos-plane', size: 10, engineSize: 10 },- fc873: { ref: 'builtin:quad', size: 1 },-};-const ENGINE_PRIMITIVE_SIZE = 100;--/**- * Put a Cocos material on a MeshRenderer's data: its image and tint, whether it blends, whether it lights, which faces it draws. The material the- * model brought is dropped then, since a material owns shading fully and would hide these. Only the first of several materials is carried.- *- * @returns `found`: the project had the material; `exact`: it was one of the built-in effects, so nothing of its look was approximated.- */-function applyMaterial(data: Raw, c: CocosComponent, ctx: ComponentContext, where: string, slot = 0): { found: boolean; exact: boolean; outline?: string } {- const uuids = (Array.isArray(c.data._materials) ? c.data._materials : []).map(uuidOf);- const uuid = uuids[slot] ?? '';- const info = uuid ? ctx.material?.(uuid) ?? null : null;- if (!info) {- if (uuid !== '') ctx.report.note('mesh-material-missing', where);- return { found: false, exact: false };- }- delete data.material;- const converted = ctx.convertedMaterial?.(uuid);- if (converted) data.material = converted.ref;- if (info.texture) data.texture = ctx.assetRef(info.texture);- if (info.normal) data.normalMap = ctx.assetRef(info.normal);- // A converted material holds its own colour (`mainColor`), and the renderer's colour reaches its shader as the vertex colour, which Cocos leaves- // white: the tint put there as well is applied twice, and read as sRGB besides, which is how a wall comes out a third as bright as it is.- if (converted) data.color = { r: 1, g: 1, b: 1, a: 1 };- else if (info.color) data.color = info.color;- data.lit = !info.unlit;- data.opaque = !info.transparent;- // what the effect's pass blends is what the draw does: a mesh the engine takes for opaque is drawn without blending, and a fog that fades out would draw black- if (converted?.blends !== undefined) data.opaque = !converted.blends;- data.cullBackfaces = info.cullBack;- const exact = info.builtinEffect || converted !== null && converted !== undefined;- if (!exact) ctx.report.note('mesh-custom-effect', where);- return { found: true, exact, ...(converted?.outline ? { outline: converted.outline } : {}) };-}--/**- * What a Cocos material makes of a MeshRenderer's data, as the fields it sets: the same as a renderer that holds the material, for an override that- * puts one on a part of a model. Null when the project does not have the material.- */-export function meshMaterialFields(uuid: string, ctx: ComponentContext, where: string): Raw | null {- const data: Raw = {};- const applied = applyMaterial(data, { type: 'cc.MeshRenderer', id: '', enabled: true, data: { _materials: [{ __uuid__: uuid }] } } as CocosComponent, ctx, where);- if (!applied.found) return null;- // the model's own material is dropped when this one has no converted counterpart: it would own the shading and hide the image- if (!('material' in data)) data.material = '';- return data;-}--/** `cc.MeshRenderer`: the mesh is the model's own part, drawn with the model's own material until the Cocos material is carried across. */-function meshRenderer(c: CocosComponent, ctx: ComponentContext, where: string): { component: ComponentData; scale?: number; partial: boolean; more?: ComponentData[] } | null {- const meshUuid = uuidOf(c.data._mesh);- const hasMaterial = Array.isArray(c.data._materials) && c.data._materials.some((m) => uuidOf(m) !== '');- if (meshUuid.startsWith(COCOS_PRIMITIVES)) {- const primitive = PRIMITIVE_MESHES[meshUuid.split('@')[1] ?? ''];- if (!primitive) {- ctx.report.note('mesh-builtin-shape-unknown', `${where}: ${meshUuid.split('@')[1] ?? ''}`);- return null;- }- const data: Raw = { mesh: primitive.ref, enabled: c.enabled };- const applied = applyMaterial(data, c, ctx, where);- return { component: { type: 'MeshRenderer', data }, scale: primitive.size / (primitive.engineSize ?? ENGINE_PRIMITIVE_SIZE), partial: hasMaterial && !applied.exact };- }- const found = meshUuid ? ctx.modelMesh?.(meshUuid) : null;- if (!found) {- // The renderer stays, with no mesh: a script that assigns one finds the component, and a mesh the project does not have draws nothing in- // Cocos either. A renderer that never had a mesh lost nothing; one whose mesh is missing did.- ctx.report.note(meshUuid ? 'mesh-model-part-not-found' : 'mesh-none', `${where}: ${meshUuid}`);- const data: Raw = { enabled: c.enabled };- const applied = applyMaterial(data, c, ctx, where);- return { component: { type: 'MeshRenderer', data }, partial: meshUuid !== '' || !applied.exact && hasMaterial };- }- const materials = (Array.isArray(c.data._materials) ? c.data._materials : []).map(uuidOf);- let partial = false;- if (!found.exact) {- partial = true;- ctx.report.note('mesh-guessed-from-model', where);- }- // A mesh of several primitives is drawn by one renderer in Cocos, each primitive with the material of its own slot; here each is a renderer, the- // first on this node and the others on parts that stand with it.- const outlines: ComponentData[] = [];- const renderers = found.components.map((part, slot) => {- const data: Raw = { ...part, enabled: c.enabled };- if (materials.some((m) => m !== '')) {- const applied = applyMaterial(data, c, ctx, where, slot);- if (!applied.exact) partial = true;- if (!applied.found) {- partial = true;- ctx.report.note('mesh-material-from-model', where);- }- // An outline is the same mesh drawn a second time, pushed out along its normals and shown from behind: a renderer of its own- if (applied.outline) {- outlines.push({ type: 'MeshRenderer', data: { mesh: part.mesh, enabled: c.enabled, material: applied.outline, lit: false, opaque: true, cullBackfaces: false } });- }- }- return { type: 'MeshRenderer', data } as ComponentData;- });- const more = [...renderers.slice(1), ...outlines];- return { component: renderers[0]!, partial, ...(more.length > 0 ? { more } : {}) };-}--/** `cc.Graphics`: the style a scene stores; what is drawn is what scripts draw with it. */-function graphics(c: CocosComponent): ComponentData {- return {- type: `${LAYER}Graphics`,- data: renamed(c, { _lineWidth: 'lineWidth', _lineJoin: 'lineJoin', _lineCap: 'lineCap', _miterLimit: 'miterLimit', _strokeColor: 'strokeColor', _fillColor: 'fillColor' }),- };-}--/** `cc.Line`: a polyline of a width and a colour. The width is a curve in Cocos and a number here, read at the start; the colour is the gradient's first. */-function line(c: CocosComponent, ctx: ComponentContext, where: string): ComponentData {- const d = c.data;- const width = curveRange(d._width, 0, 1);- const gradient = isObj(d._color) ? d._color : {};- const first = isObj(gradient.color) ? gradient.color : { r: 255, g: 255, b: 255, a: 255 };- if (isObj(d._width) && num(d._width.mode, 0) !== 0 && width.min !== width.max) ctx.report.note('line-width-curve', where);- if (num(gradient._mode, 0) !== 0) ctx.report.note('line-color-gradient', where);- return {- type: `${LAYER}Line`,- data: {- enabled: c.enabled,- worldSpace: d._worldSpace !== false,- width: (width.min + width.max) / 2,- color: { r: num(first.r, 255), g: num(first.g, 255), b: num(first.b, 255), a: num(first.a, 255) },- positions: (Array.isArray(d._positions) ? d._positions : []).filter(isObj).map((p) => ({ x: num(p.x, 0), y: num(p.y, 0), z: num(p.z, 0) })),- },- };-}--/** `sp.Skeleton`: a Spine skeleton, played from its default animation. The skeleton, its atlas and the atlas's images come with it. */-function spineSkeleton(c: CocosComponent, ctx: ComponentContext, where: string): ComponentData | null {- const d = c.data;- const files = ctx.spineAssets?.(uuidOf(d._skeletonData));- if (!files) {- ctx.report.note('spine-data-missing', where);- return null;- }- const animation = typeof d.defaultAnimation === 'string' ? d.defaultAnimation : '';- ctx.report.component('sp.Skeleton', 'mapped');- return {- type: 'SpineAnimation',- data: {- skeletonPath: files.skeleton,- atlasPath: files.atlas,- skin: typeof d.defaultSkin === 'string' ? d.defaultSkin : 'default',- animation,- timeScale: num(d._timeScale, 1),- loop: d.loop !== false,- playing: animation !== '',- color: color(d._color),- enabled: c.enabled,- },- };-}--/**- * `cc.BoxCollider`: the engine's box, half the node-scaled size on each side. A Cocos collider with no rigid body is a static one, which the engine- * spells as a static body beside the box. Where the box stood from the node's origin (`_center`, scaled by the node) is the collider's `center`.- */-function boxCollider(c: CocosComponent, node: CocosNode, ctx: ComponentContext, extra: ComponentData[]): ComponentData {- const size = isObj(c.data._size) ? c.data._size : {};- const center = isObj(c.data._center) ? c.data._center : {};- const half = (axis: 'x' | 'y' | 'z'): number => Math.abs(num(size[axis], 1) * (node.scale[axis] ?? 1)) / 2;- ctx.report.component('cc.BoxCollider', 'mapped');- if (!node.components.some((n) => n.type === 'cc.RigidBody') && !extra.some((e) => e.type === 'RigidBody3D')) extra.push({ type: 'RigidBody3D', data: { bodyType: 0 } });- const at = (axis: 'x' | 'y' | 'z'): number => num(center[axis], 0) * (node.scale[axis] ?? 1);- return { type: 'BoxCollider3D', data: { halfExtents: { x: half('x'), y: half('y'), z: half('z') }, center: { x: at('x'), y: at('y'), z: at('z') }, isSensor: c.data._isTrigger === true, enabled: c.enabled } };-}--/** `cc.PageView`: a scroll view whose content is pages, and the page it settles on. */-function pageView(c: CocosComponent, ctx: ComponentContext): ComponentData {- const scroll = scrollView(c, ctx).data;- const direction = num(c.data._direction, 0);- return {- type: `${LAYER}PageView`,- data: {- ...scroll,- ...renamed(c, { _sizeMode: 'sizeMode', _direction: 'direction', autoPageTurningThreshold: 'autoPageTurningThreshold', pageTurningSpeed: 'pageTurningSpeed', _indicator: 'indicator' }),- horizontal: direction === 0,- vertical: direction === 1,- ...handlerLists(c.data.pageEvents, 'page', ctx),- },- };-}--/** `cc.Terrain`: the ground's size, from the header of the terrain file. The heights and the painted layers inside it are not read. */-function terrain(c: CocosComponent, ctx: ComponentContext, where: string): ComponentData | null {- const asset = uuidOf(c.data.__asset);- const entry = asset ? ctx.assets.byUuid.get(asset) : undefined;- let size = 256;- if (entry) {- try {- const head = readFileSync(entry.file).subarray(0, 20);- const tile = head.readDoubleLE(4), blocksX = head.readInt32LE(12), blocksY = head.readInt32LE(16);- if (tile > 0 && blocksX > 0 && blocksY > 0 && blocksX < 256 && blocksY < 256) size = Math.max(blocksX, blocksY) * 64 * tile;- } catch {- // an unreadable file keeps the default size and is counted below- }- }- ctx.report.component('cc.Terrain', 'partial');- ctx.report.note('terrain-heights-not-carried', where);- return { type: 'Terrain', data: { extent: 0, sizeX: size, sizeZ: size, height: 0, collision: false } };-}--/** `cc.EditBox`: the box and its two labels are the scene's own nodes; what is typed goes through the platform's text editor. */-function editBox(c: CocosComponent, ctx: ComponentContext): ComponentData {- return {- type: `${LAYER}EditBox`,- data: {- ...renamed(c, {- _string: 'string_', _maxLength: 'maxLength', _inputMode: 'inputMode', _inputFlag: 'inputFlag', _returnType: 'returnType', _tabIndex: 'tabIndex',- _textLabel: 'textLabel', _placeholderLabel: 'placeholderLabel',- }),- ...handlerLists(c.data.editingDidBegan, 'editingDidBegan', ctx),- ...handlerLists(c.data.textChanged, 'textChanged', ctx),- ...handlerLists(c.data.editingDidEnded, 'editingDidEnded', ctx),- ...handlerLists(c.data.editingReturn, 'editingReturn', ctx),- },- };-}--/** `cc.UIOpacity`: the alpha of the node and everything under it, which the engine's GroupOpacity is. */-function uiOpacity(c: CocosComponent, ctx: ComponentContext): ComponentData {- ctx.report.component('cc.UIOpacity', 'mapped');- return { type: 'GroupOpacity', data: { opacity: Math.min(255, Math.max(0, num(c.data._opacity, 255))) / 255, enabled: c.enabled } };-}--/** `cc.Sorting`: the sorting layer and order of the renderer on the node, which the engine states for a node and its subtree. */-function sorting(c: CocosComponent, ctx: ComponentContext, where: string): ComponentData {- const d = c.data;- const order = num(d._sortingOrder, 0);- const clamped = Math.min(127, Math.max(-128, Math.trunc(order)));- if (clamped !== order) {- ctx.report.component('cc.Sorting', 'partial');- ctx.report.note('sorting-order-clamped', where);- } else {- ctx.report.component('cc.Sorting', 'mapped');- }- return { type: 'SortingGroup', data: { layer: Math.trunc(num(d._sortingLayer, 0)), order: clamped, enabled: c.enabled } };-}--function script(c: CocosComponent, ctx: ComponentContext): ComponentData | null {- const cls = ctx.scriptClass?.(c.type);- if (!cls) return null;- const data: Raw = { enabled: c.enabled };- for (const [k, v] of Object.entries(c.data)) data[k] = scriptValue(v, ctx);- return { type: `${LAYER}${cls.name}`, data };-}--/** The engine components that draw, and carry the layer a camera's culling mask selects. */-const LAYERED = new Set(['Sprite', 'Text', 'ShapeRenderer', 'SpineAnimation', 'ParticleEmitter', 'MeshRenderer']);--/** Components that are folded into another, or carry nothing of their own. */-const FOLDED = new Set(['cc.UITransform', 'cc.LabelOutline', 'cc.LabelShadow', 'cc.Canvas', 'cc.UIMeshRenderer', 'cc.RenderRoot2D']);--export interface ConvertedNode {- components: ComponentData[];- /** The primitives of a mesh beyond the first, each as the components of a part that stands with this node. */- parts?: ComponentData[][];- /** Everything not mapped, verbatim, for whatever consumes it next. */- metadata?: Raw;-}--export function convertNode(node: CocosNode, ctx: ComponentContext, where: string): ConvertedNode {- const components: ComponentData[] = [transform(node)];- // Cocos `active` is switched-off-with-its-subtree, which is what the engine's Disabled tag means; `visible: false`- // would instead not create the entity at all and leave its children standing on their own.- if (!node.active) components.push({ type: 'Disabled', data: {} });- const box = uiBox(node);- const unmapped: Raw[] = [];- // a mesh whose unit is not the engine's resizes the node it hangs on- let unitScale = 1;- // components a mapped one brings with it, added after the loop- const extra: ComponentData[] = [];- const parts: ComponentData[][] = [];-- for (const c of node.components) {- let out: ComponentData | null = null;- switch (c.type) {- case 'cc.Sprite':- out = sprite(c, box, ctx, where);- break;- case 'cc.SpriteRenderer': {- // a sprite standing in the 3D world: the same picture and tint, with no rectangle of its own, so the frame's size is the size- out = sprite({ ...c, data: { ...c.data, _type: 0 } }, null, ctx, where, 'cc.SpriteRenderer');- if (out && c.data._flipX === true) out.data.flipX = true;- if (out && c.data._flipY === true) out.data.flipY = true;- break;- }- case 'cc.Label':- out = label(c, node.components, box, ctx, where);- break;- case 'cc.RichText':- out = richText(c, box, ctx);- break;- case 'cc.Camera':- out = camera(c, ctx);- break;- case 'cc.UITransform':- // Also the size the renderers below were given; this keeps the rectangle for a node that draws nothing.- if (box) components.push(contentRectData(box));- break;- case 'cc.Mask':- out = mask(c, ctx);- break;- case 'cc.Widget':- out = widget(c);- ctx.report.component('cc.Widget', 'mapped');- break;- case 'cc.Layout':- out = layout(c);- break;- case 'cc.Button':- out = button(c, ctx);- break;- case 'cc.Toggle':- out = toggle(c, ctx);- break;- case 'cc.ToggleContainer':- out = toggleContainer(c, ctx);- break;- case 'cc.ProgressBar':- out = progressBar(c);- break;- case 'cc.Slider':- out = slider(c, ctx);- break;- case 'cc.ScrollView':- out = scrollView(c, ctx);- break;- case 'cc.ParticleSystem':- out = particleSystem(c, ctx, where);- break;- case 'cc.DirectionalLight':- out = directionalLight(c, ctx, where);- break;- case 'cc.MeshRenderer': {- const mesh = meshRenderer(c, ctx, where);- out = mesh?.component ?? null;- if (mesh) ctx.report.component('cc.MeshRenderer', mesh.partial ? 'partial' : 'mapped');- if (mesh?.scale !== undefined) unitScale = mesh.scale;- if (mesh?.more) parts.push(...mesh.more.map((m) => [m]));- break;- }- case 'cc.SkinnedMeshRenderer': {- const skinned = skinnedMeshRenderer(c, ctx, where);- out = skinned?.component ?? null;- if (skinned) {- extra.push(...skinned.extra);- parts.push(...skinned.parts);- }- break;- }- case 'cc.animation.AnimationController':- out = animationController(c, node, ctx, where);- break;- case 'cc.Animation':- out = animation(c, node, ctx, where);- break;- case 'cc.SkeletalAnimation':- out = skeletalAnimation(c, node, ctx, where);- break;- case 'sp.Skeleton':- out = spineSkeleton(c, ctx, where);- break;- case 'cc.Line':- out = line(c, ctx, where);- break;- case 'cc.BoxCollider':- out = boxCollider(c, node, ctx, extra);- break;- case 'cc.PageView':- out = pageView(c, ctx);- break;- case 'cc.PageViewIndicator':- out = { type: `${LAYER}PageViewIndicator`, data: { ...renamed(c, { spacing: 'spacing', _direction: 'direction' }), cellSize: isObj(c.data._cellSize) ? { width: num(c.data._cellSize.width, 20), height: num(c.data._cellSize.height, 20) } : { width: 20, height: 20 } } };- break;- case 'cc.ScrollBar':- out = { type: `${LAYER}ScrollBar`, data: renamed(c, { _scrollView: 'scrollView', _handle: 'handle', _direction: 'direction', _enableAutoHide: 'enableAutoHide', _autoHideTime: 'autoHideTime' }) };- break;- case 'cc.SafeArea':- out = { type: `${LAYER}SafeArea`, data: { enabled: c.enabled } };- break;- case 'cc.WebView':- out = { type: `${LAYER}WebView`, data: { enabled: c.enabled, url: typeof c.data._url === 'string' ? c.data._url : '', ...handlerLists(c.data.webviewEvents, 'webview', ctx) } };- break;- case 'cc.ParticleSystem2D':- out = particleSystem2D(c, { report: ctx.report, assetRef: ctx.assetRef, frame: (uuid) => { const e = ctx.assets.byUuid.get(uuid.split('@')[0]!); return e ? ctx.assetRef(e) : null; } }, where);- break;- case 'cc.Terrain':- out = terrain(c, ctx, where);- break;- case 'cc.EditBox':- out = editBox(c, ctx);- break;- case 'cc.Graphics':- out = graphics(c);- break;- case 'cc.UIOpacity':- out = uiOpacity(c, ctx);- break;- case 'cc.Sorting':- out = sorting(c, ctx, where);- break;- case 'cc.BlockInputEvents':- out = { type: `${LAYER}BlockInputEvents`, data: { enabled: c.enabled } };- break;- default:- out = c.type.startsWith('cc.') ? null : script(c, ctx);- break;- }- if (out) {- components.push(out);- if (out.type.startsWith(LAYER)) ctx.report.component(c.type.startsWith('cc.') ? c.type : `script:${out.type.slice(LAYER.length)}`, 'mapped');- continue;- }- if (FOLDED.has(c.type)) {- // A canvas carries nothing of its own here: the design resolution is the scene's, and its camera is a component of its own.- const host = c.type === 'cc.UITransform' || c.type === 'cc.Canvas' || c.type === 'cc.UIMeshRenderer' || c.type === 'cc.RenderRoot2D' ? true : node.components.some((s) => s.type === 'cc.Label');- if (host) {- ctx.report.component(c.type, 'mapped');- continue;- }- }- if (c.type === 'cc.Sprite') {- // the sprite counted itself unmapped; keep what it said- } else {- ctx.report.component(c.type, 'unmapped');- }- unmapped.push({ type: c.type, enabled: c.enabled, data: c.data });- }-- // A node's Cocos layer is the layer its renderers draw in: a camera's culling mask picks among those, and a renderer left in layer 0 is- // outside the mask of a UI camera (layer 25) and never drawn by it.- const layerBit = node.layer > 0 && (node.layer & (node.layer - 1)) === 0 ? Math.log2(node.layer) : -1;- if (layerBit >= 0 && layerBit < 32) {- for (const c of [...components, ...extra, ...parts.flat()]) if (LAYERED.has(c.type) && !(c.data.layer)) c.data.layer = layerBit;- }- components.push(...extra);- if (unitScale !== 1) {- const scale = components[0]!.data.scale as { x: number; y: number; z: number };- components[0]!.data.scale = { x: scale.x * unitScale, y: scale.y * unitScale, z: scale.z * unitScale };- }-- const cocos: Raw = {};- if (unmapped.length) cocos.components = unmapped;- if (box) cocos.ui = { width: box.width, height: box.height, anchorX: box.ax, anchorY: box.ay };- if (node.layer !== 33554432 && node.layer !== 0) cocos.layer = node.layer;- const metadata = Object.keys(cocos).length ? { cocos } : undefined;- return { components, ...(parts.length > 0 ? { parts } : {}), ...(metadata ? { metadata } : {}) };-}diff --git a/pipeline/src/import/cocos/convert.ts b/pipeline/src/import/cocos/convert.tsdeleted file mode 100644index 8ad8b3245..000000000--- a/pipeline/src/import/cocos/convert.ts+++ /dev/null@@ -1,619 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A Cocos prefab or scene as an Estella prefab or scene.- *- * A nested prefab stays a nested prefab: the instance becomes a slot that- * names the converted prefab, and what the Cocos instance changed becomes- * overrides. Those are not translated property by property — the instance's- * overrides are applied to the Cocos tree, both versions are converted, and- * the difference is the override list. So the override vocabulary is- * whatever the component mapping already knows, with no second table.- *- * Addresses follow the engine's own: an entity inside a nested prefab is- * `slot/localId`, a prefab's own entities are bare ids.- */-import { convertNode, meshMaterialFields, sameData, type ComponentContext, type ComponentData } from './components';-import { foldEditBoxes } from './editBoxFold';-import { NODE_REF, type CocosDocument, type CocosNode, type CocosOverride } from './document';-import { ImportReport } from './report';-import { anchoredRect, type RectAnchorsData } from '../../../../sdk/src/ui/layout/anchored-rect';--/** What a field a document does not carry means (the component's own defaults). */-const DEFAULT_ANCHORS: RectAnchorsData = {- alignFlags: 0, left: 0, right: 0, top: 0, bottom: 0, horizontalCenter: 0, verticalCenter: 0,- isAbsLeft: true, isAbsRight: true, isAbsTop: true, isAbsBottom: true, isAbsHorizontalCenter: true, isAbsVerticalCenter: true,- alignMode: 1, enabled: true,-};--const SEP = '/';--type Raw = Record<string, unknown>;--export interface PrefabOverride {- prefabEntityId: string;- type: 'property' | 'component_added' | 'component_removed' | 'name' | 'visibility';- componentType?: string;- propertyName?: string;- value?: unknown;- componentData?: ComponentData;-}--export interface PrefabEntity {- prefabEntityId: string;- name: string;- parent: string | null;- children: string[];- components: ComponentData[];- visible: boolean;- metadata?: Raw;- nestedPrefab?: { prefabPath: string; overrides: PrefabOverride[] };-}--export interface PrefabFile {- version: string;- name: string;- rootEntityId: string;- entities: PrefabEntity[];-}--export interface SceneEntity {- id: number;- name: string;- parent: number | null;- children: number[];- components: ComponentData[];- visible: boolean;- metadata?: Raw;-}--export interface SceneInstanceEntry {- id: number;- parent: number | null;- prefab: string;- overrides: PrefabOverride[];- added: never[];- removed: string[];-}--export interface SceneFile {- version: number;- name: string;- entities: (SceneEntity | SceneInstanceEntry)[];-}--export interface ConvertContext extends ComponentContext {- /** The parsed prefab a uuid names, or null when the project does not have it. */- loadPrefab(uuid: string): CocosDocument | null;- /** The project-relative path the converted prefab of a uuid is written to. */- prefabRef(uuid: string): string | null;- /** Where the document being converted lives, for notes. */- where: string;- /** The project's design resolution: the box a root pinned to the screen is placed in, so the document holds where it will be. */- design?: { width: number; height: number };-}--// ----------------------------------------------------------------------------// The expanded Cocos tree: instances inlined, overrides applied.-// -----------------------------------------------------------------------------interface XNode {- /** Engine address: bare id in a prefab's own space, `slot/id` across a nesting boundary. */- addr: string;- /** Prefix the engine address adds to this node's components' ids. */- prefix: string;- node: CocosNode;- children: XNode[];-}--const MAX_DEPTH = 24;--function build(node: CocosNode, ctx: ConvertContext, stack: string[]): XNode {- if (node.instance) {- const sub = expandAsset(node.instance.asset, ctx, stack);- if (!sub) {- ctx.report.note('prefab-missing', `${ctx.where}: ${node.name}`);- ctx.report.missingAsset(node.instance.asset);- return { addr: node.id, prefix: '', node: { ...node, children: [] }, children: [] };- }- applyOverrides(sub, node.instance.overrides, ctx);- applyMounted(sub, node.instance.mounted, ctx);- if (node.instance.mountedChildren) ctx.report.note('instance-mounted-children', `${ctx.where}: ${node.name}`);- if (node.instance.removedComponents) ctx.report.note('instance-removed-components', `${ctx.where}: ${node.name}`);- return lift(sub, node.id);- }- return { addr: node.id, prefix: '', node: { ...node, children: [] }, children: node.children.map((c) => build(c, ctx, stack)) };-}--/** Put a tree under a slot: every address gains the slot's prefix. */-function lift(tree: XNode, slot: string): XNode {- const walk = (x: XNode): XNode => ({- addr: `${slot}${SEP}${x.addr}`,- prefix: x.prefix ? `${slot}${SEP}${x.prefix}` : slot,- node: x.node,- children: x.children.map(walk),- });- return walk(tree);-}--const expanded = new WeakMap<ConvertContext, Map<string, XNode | null>>();--/** A prefab with its own instances expanded, in its own address space. Cached; callers get a copy. */-function expandAsset(uuid: string, ctx: ConvertContext, stack: string[]): XNode | null {- let cache = expanded.get(ctx);- if (!cache) expanded.set(ctx, (cache = new Map()));- const hit = cache.get(uuid);- if (hit !== undefined) return hit ? structuredClone(hit) : null;- if (stack.includes(uuid) || stack.length > MAX_DEPTH) {- ctx.report.note('prefab-cycle', `${ctx.where}: ${uuid}`);- return null;- }- const doc = ctx.loadPrefab(uuid);- const root = doc?.roots[0];- if (!doc || !root) {- cache.set(uuid, null);- return null;- }- const tree = build(root, ctx, [...stack, uuid]);- cache.set(uuid, tree);- return structuredClone(tree);-}--// ----------------------------------------------------------------------------// Overrides, in the Cocos domain.-// -----------------------------------------------------------------------------/** A Cocos value without its `__type__` tags, which name the class and mean nothing to the data. */-function clean(v: unknown): unknown {- if (Array.isArray(v)) return v.map(clean);- if (typeof v !== 'object' || v === null) return v;- return Object.fromEntries(Object.entries(v).filter(([k]) => k !== '__type__').map(([k, x]) => [k, clean(x)]));-}--function applyOverrides(tree: XNode, overrides: CocosOverride[], ctx: ConvertContext): void {- const nodes = new Map<string, XNode>();- const comps = new Map<string, { c: CocosNode["components"][number] }>();- const index = (x: XNode): void => {- nodes.set(x.addr, x);- for (const c of x.node.components) comps.set(x.prefix ? `${x.prefix}${SEP}${c.id}` : c.id, { c });- x.children.forEach(index);- };- index(tree);-- for (const raw of overrides) {- const o = { ...raw, value: clean(raw.value) };- const key = o.target.join(SEP);- const prop = o.path[0];- const nodeHit = nodes.get(key);- const compHit = comps.get(key);- if (compHit && prop !== undefined) {- // The tree came from a clone, so its nodes are this call's to change.- const { c } = compHit;- if (prop === '_enabled') {- c.enabled = o.value !== false;- continue;- }- setPath(c.data, o.path, o.value);- continue;- }- if (nodeHit && prop !== undefined) {- const n = nodeHit.node;- const v = o.value as Raw;- if (typeof v === 'object' && v !== null && '__id__' in v) {- ctx.report.note('override-object-reference', `${ctx.where}: ${key}.${prop}`);- continue;- }- switch (prop) {- case '_name': n.name = String(o.value); break;- case '_active': n.active = o.value !== false; break;- case '_lpos': n.pos = { ...n.pos, ...(v as object) }; break;- case '_lrot': n.rot = { ...n.rot, ...(v as object) }; break;- case '_lscale': n.scale = { ...n.scale, ...(v as object) }; break;- case '_layer': n.layer = Number(o.value); break;- case '_euler': break; // derived from the rotation- default: ctx.report.note('override-node-property', `${ctx.where}: ${prop}`);- }- continue;- }- ctx.report.note(o.target.length > 1 ? 'override-target-missing-nested' : 'override-target-missing', `${ctx.where}: ${key}`);- }-}--/**- * The components the instance's file mounts on nodes of the prefab it names. The target is addressed as an override's is; a mounted component- * with no node to land on is counted, not lost silently.- */-function applyMounted(tree: XNode, mounted: NonNullable<CocosNode['instance']>['mounted'], ctx: ConvertContext): void {- if (mounted.length === 0) return;- const nodes = new Map<string, XNode>();- const index = (x: XNode): void => {- nodes.set(x.addr, x);- x.children.forEach(index);- };- index(tree);- for (const m of mounted) {- const target = nodes.get(m.target.join(SEP));- if (!target) {- ctx.report.note('mounted-target-missing', `${ctx.where}: ${m.target.join(SEP)}`);- continue;- }- for (const c of m.components) {- target.node.components.push(structuredClone(c));- }- }-}--function setPath(target: Raw, path: string[], value: unknown): void {- let cur = target;- for (let i = 0; i < path.length - 1; i++) {- const k = path[i]!;- const next = cur[k];- cur[k] = typeof next === 'object' && next !== null ? { ...(next as Raw) } : {};- cur = cur[k] as Raw;- }- cur[path[path.length - 1]!] = value;-}--// ----------------------------------------------------------------------------// Converting an expanded tree, and the difference between two.-// -----------------------------------------------------------------------------interface Flat {- name: string;- visible: boolean;- components: ComponentData[];-}--function flatten(tree: XNode, ctx: ConvertContext): Map<string, Flat> {- const out = new Map<string, Flat>();- const walk = (x: XNode): void => {- const conv = convertNode(x.node, ctx, `${ctx.where}: ${x.node.name}`);- out.set(x.addr, { name: x.node.name, visible: true, components: conv.components });- x.children.forEach(walk);- };- walk(tree);- return out;-}--/** What turns `pristine` into `patched`, as the engine's override list. */-function diff(pristine: Map<string, Flat>, patched: Map<string, Flat>, ctx: ConvertContext): PrefabOverride[] {- const out: PrefabOverride[] = [];- for (const [addr, now] of patched) {- const was = pristine.get(addr);- if (!was) {- ctx.report.note('instance-added-entity', `${ctx.where}: ${addr}`);- continue;- }- if (was.name !== now.name) out.push({ prefabEntityId: addr, type: 'name', value: now.name });- if (was.visible !== now.visible) out.push({ prefabEntityId: addr, type: 'visibility', value: now.visible });- const before = new Map(was.components.map((c) => [c.type, c]));- const after = new Map(now.components.map((c) => [c.type, c]));- for (const [type, c] of after) {- const b = before.get(type);- if (!b) {- out.push({ prefabEntityId: addr, type: 'component_added', componentType: type, componentData: c });- continue;- }- for (const [field, value] of Object.entries(c.data)) {- if (!sameData(b.data[field], value)) {- if (holdsRef(value)) {- ctx.report.note('override-node-reference', `${ctx.where}: ${addr} ${type}.${field}`);- continue;- }- out.push({ prefabEntityId: addr, type: 'property', componentType: type, propertyName: field, value });- }- }- }- for (const type of before.keys()) {- if (!after.has(type)) out.push({ prefabEntityId: addr, type: 'component_removed', componentType: type });- }- }- return out;-}--/**- * What an instance of a model changes about it. The model's own nodes were named by Cocos with ids this import does not know, so only the- * instance's root can be addressed: its name, whether it is active and where it stands. The rest (a material put on a mesh, a clip set on its- * animation) is counted, not lost silently.- */-function modelInstanceOverrides(node: CocosNode, model: { rootId: string; name: string; paths: Map<string, string>; parts: Map<string, string> }, ctx: ConvertContext): PrefabOverride[] {- const inst = node.instance!;- // A property of the instance's root: its name, whether it is on, where it stands. The overrides on a component of the model are told apart- // by what they set: a skeletal animation's clip is carried, anything else is counted.- const animation = animationOverrides(inst.overrides);- const shape = (o: CocosOverride): boolean => ['_name', '_active', '_lpos', '_lrot', '_lscale', '_euler'].includes(o.path[0] ?? '');- const roots = inst.overrides.filter((o) => o.target.length === 1 && shape(o));- // The material a part of the model is given: the part is told by the id of its renderer, and the material is put on it as it would be on a- // renderer that holds it.- const out: PrefabOverride[] = [];- let materials = 0;- for (const o of inst.overrides) {- if (o.path[0] !== '_materials' || o.path[1] !== '0' || o.target.length !== 1) continue;- const part = model.parts.get(o.target[0]!);- const uuid = (o.value as { __uuid__?: unknown } | null)?.__uuid__;- if (part === undefined || typeof uuid !== 'string') continue;- const fields = meshMaterialFields(uuid, ctx, `${ctx.where}: ${node.name}`);- if (!fields) continue;- materials++;- for (const [propertyName, value] of Object.entries(fields)) {- out.push({ prefabEntityId: part, type: 'property', componentType: 'MeshRenderer', propertyName, value });- }- }- // where a skinned part finds its skeleton is the model's own: the engine's import binds the part to its joints- const skeleton = inst.overrides.filter((o) => o.path[0] === '_skinningRoot').length;- const inner = inst.overrides.length - roots.length - animation.used - materials - skeleton;- if (inner > 0) {- // what is left, by the property it sets, so the note says what was not carried- const carried = new Set(['_defaultClip', '_clips', 'playOnLoad', '_skinningRoot']);- const left = new Set(inst.overrides.filter((o) => !carried.has(o.path[0] ?? '') && !(o.target.length === 1 && shape(o)) && !(o.path[0] === '_materials' && model.parts.has(o.target[0] ?? ''))).map((o) => o.path.join('.')));- ctx.report.note('model-instance-overrides', `${ctx.where}: ${node.name} (${inner} on the model's own parts: ${[...left].slice(0, 4).join(', ')})`);- }- if (animation.clip) {- const timeline = ctx.clipOn?.(animation.clip, model.paths, `${ctx.where}: ${node.name}`);- if (timeline) {- out.push({- prefabEntityId: model.rootId, type: 'component_added', componentType: 'TimelinePlayer',- componentData: { type: 'TimelinePlayer', data: { timeline, playing: animation.playOnLoad, speed: 1, wrapMode: '' } },- });- } else {- ctx.report.note('model-instance-clip-not-found', `${ctx.where}: ${node.name}`);- }- }- const addr = roots[0]?.target[0];- if (addr === undefined) return out;- const base: CocosNode = {- id: addr, name: model.name, active: true, pos: { x: 0, y: 0, z: 0 }, rot: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 1, y: 1, z: 1 },- layer: 33554432, components: [], children: [],- };- const pristine: XNode = { addr, prefix: '', node: base, children: [] };- const patched = structuredClone(pristine);- applyOverrides(patched, roots, ctx);- const quiet: ConvertContext = { ...ctx, report: new ImportReport() };- return [...out, ...diff(flatten(pristine, quiet), flatten(patched, quiet), ctx).map((o) => ({ ...o, prefabEntityId: model.rootId }))];-}--/** The clip an instance sets on its model's skeletal animation, if it sets one, and whether it plays on load. `used` counts the overrides read. */-function animationOverrides(overrides: CocosOverride[]): { clip: string | null; playOnLoad: boolean; used: number } {- let defaultClip = '';- let firstClip = '';- let playOnLoad = false;- let used = 0;- for (const o of overrides) {- const prop = o.path[0];- const value = o.value as { __uuid__?: unknown } | boolean | null;- if (prop === '_defaultClip' && typeof value === 'object' && value && typeof value.__uuid__ === 'string') { defaultClip = value.__uuid__; used++; }- else if (prop === '_clips' && o.path[1] === '0' && typeof value === 'object' && value && typeof value.__uuid__ === 'string') { firstClip = value.__uuid__; used++; }- else if (prop === '_clips' && o.path[1] === 'length') used++;- else if (prop === 'playOnLoad') { playOnLoad = value === true; used++; }- }- return { clip: defaultClip || firstClip || null, playOnLoad, used };-}--/** The overrides an instance node applies over the prefab it names, or null when that prefab is missing. */-function instanceOverrides(node: CocosNode, ctx: ConvertContext): PrefabOverride[] | null {- const inst = node.instance;- if (!inst) return null;- const model = ctx.modelInstance?.(inst.asset);- if (model) return modelInstanceOverrides(node, model, ctx);- const pristine = expandAsset(inst.asset, ctx, []);- if (!pristine) return null;- const patched = structuredClone(pristine);- applyOverrides(patched, inst.overrides, ctx);- applyMounted(patched, inst.mounted, ctx);- if (inst.mountedChildren) ctx.report.note('instance-mounted-children', `${ctx.where}: ${node.name}`);- if (inst.removedComponents) ctx.report.note('instance-removed-components', `${ctx.where}: ${node.name}`);- // Converting both sides is for the difference only; the report counts a component where its own prefab is converted.- const quiet: ConvertContext = { ...ctx, report: new ImportReport() };- return diff(flatten(pristine, quiet), flatten(patched, quiet), ctx);-}--// ----------------------------------------------------------------------------// References to nodes, inside component data.-// -----------------------------------------------------------------------------const isRef = (v: unknown): v is Raw => typeof v === 'object' && v !== null && !Array.isArray(v) && NODE_REF in v;--/** Whether a value holds a node reference anywhere inside it. */-function holdsRef(v: unknown): boolean {- if (Array.isArray(v)) return v.some(holdsRef);- if (typeof v !== 'object' || v === null) return false;- return NODE_REF in v || Object.values(v).some(holdsRef);-}--/** Replace every node reference in @p v by what @p to makes of the node's id; a node the file does not hold gets @p missing. */-function mapRefs(v: unknown, to: (id: string) => unknown, missing: unknown): unknown {- if (Array.isArray(v)) return v.map((x) => mapRefs(x, to, missing));- if (typeof v !== 'object' || v === null) return v;- if (isRef(v)) return typeof v[NODE_REF] === 'string' ? to(v[NODE_REF] as string) : missing;- return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, mapRefs(x, to, missing)]));-}--function resolveRefs(components: ComponentData[], to: (id: string) => unknown, missing: unknown): void {- for (const c of components) for (const [k, v] of Object.entries(c.data)) if (holdsRef(v)) c.data[k] = mapRefs(v, to, missing);-}--// ----------------------------------------------------------------------------// Documents.-// -----------------------------------------------------------------------------/** Every node of a document by id, the nodes under an instance left out (they are the prefab's own, in its own space). */-function indexNodes(roots: CocosNode[]): Map<string, CocosNode> {- const nodes = new Map<string, CocosNode>();- const walk = (n: CocosNode): void => {- nodes.set(n.id, n);- if (!n.instance) n.children.forEach(walk);- };- roots.forEach(walk);- return nodes;-}--/** A part that stands with its node, where the node stands. */-function partTransform(): ComponentData {- return { type: 'Transform', data: { position: { x: 0, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 1, y: 1, z: 1 } } };-}--export function convertPrefab(doc: CocosDocument, ctx: ConvertContext): PrefabFile {- ctx.nodeById = indexNodes(doc.roots);- const root = doc.roots[0];- if (!root) throw new Error('prefab has no root node');- const entities: PrefabEntity[] = [];- ctx.report.documents.converted++;- if (doc.duplicateIds) ctx.report.note('duplicate-fileid', `${ctx.where}: ${doc.duplicateIds}`);-- const walk = (n: CocosNode, parent: string | null): void => {- ctx.report.nodes++;- const here = `${ctx.where}: ${n.name}`;- const entity: PrefabEntity = { prefabEntityId: n.id, name: n.name, parent, children: [], components: [], visible: true };- entities.push(entity);- const ref = n.instance ? ctx.prefabRef(n.instance.asset) : null;- const overrides = n.instance && ref ? instanceOverrides(n, ctx) : null;- if (n.instance) {- ctx.report.prefabInstances++;- if (ref && overrides) entity.nestedPrefab = { prefabPath: ref, overrides };- else {- ctx.report.note('prefab-missing', here);- ctx.report.missingAsset(n.instance.asset);- }- return;- }- const conv = convertNode(n, ctx, here);- entity.components = conv.components;- if (conv.metadata) entity.metadata = conv.metadata;- // the primitives of a mesh beyond the first stand with it, each a part of its own- for (const [i, part] of (conv.parts ?? []).entries()) {- const id = `${n.id}|part${i + 1}`;- entities.push({ prefabEntityId: id, name: `${n.name}_${i + 1}`, parent: n.id, children: [], components: [partTransform(), ...part], visible: true });- entity.children.push(id);- }- for (const c of n.children) {- entity.children.push(c.id);- walk(c, n.id);- }- };- walk(root, null);- // A reference to a node of this prefab is that node's prefab-local id; a prefab's refs are strings the loader maps.- const own = new Set(entities.map((e) => e.prefabEntityId));- for (const e of entities) resolveRefs(e.components, (id) => (own.has(id) ? id : ''), '');- // an edit box is the engine's text field, with the style its two labels had; the labels are not written- return { version: '2', name: doc.name, rootEntityId: root.id, entities: foldEditBoxes(entities, (e) => e.prefabEntityId) };-}--/**- * A root pinned to the screen is stored where the engine will put it: Cocos keeps such a root at its own corner-based position, and the- * engine's screen is centred on the origin, so the document would otherwise say one place and show another until the first frame. The- * same function the engine aligns with places it, in the project's design box.- */-function placeInDesign(components: ComponentData[], design: { width: number; height: number }): void {- const anchors = components.find((c) => c.type === 'RectAnchors');- const transform = components.find((c) => c.type === 'Transform');- if (!anchors || !transform) return;- const a = { ...DEFAULT_ANCHORS, ...(anchors.data as Partial<RectAnchorsData>) };- if (!a.alignFlags || a.enabled === false) return;- const rect = components.find((c) => c.type === 'ContentRect')?.data as { size?: { x: number; y: number }; pivot?: { x: number; y: number } } | undefined;- const t = transform.data as { position: { x: number; y: number; z: number }; scale?: { x: number; y: number } };- const out = anchoredRect(- a, { left: -design.width / 2, right: design.width / 2, bottom: -design.height / 2, top: design.height / 2 },- { width: rect?.size?.x ?? 0, height: rect?.size?.y ?? 0, pivotX: rect?.pivot?.x ?? 0.5, pivotY: rect?.pivot?.y ?? 0.5 },- { x: t.scale?.x ?? 1, y: t.scale?.y ?? 1 }, { x: t.position.x, y: t.position.y },- );- t.position = { ...t.position, x: out.x, y: out.y };- if (rect?.size) rect.size = { x: out.width, y: out.height };-}--export function convertScene(doc: CocosDocument, ctx: ConvertContext): SceneFile {- ctx.nodeById = indexNodes(doc.roots);- const entities: (SceneEntity | SceneInstanceEntry)[] = [];- ctx.report.documents.converted++;- // From 1: 0 is the engine's "no entity", and a reference to an entity numbered 0 would read as none.- let next = 1;- // Ids are given before any node is converted, so a reference to a node that comes later in the file has something to point at.- const ids = new Map<string, number>();- const assign = (n: CocosNode): void => {- ids.set(n.id, next++);- if (!n.instance) n.children.forEach(assign);- };- doc.roots.forEach(assign);- // what is left of the scene's settings that are on is not carried: the ambient light and a linear fog are- const dropped = doc.globals.filter((g) => !(g === 'ambient' && doc.ambient) && !(g === 'fog' && doc.fog));- if (dropped.length) ctx.report.note('scene-globals-dropped', `${ctx.where}: ${dropped.join(',')}`);-- const walk = (n: CocosNode, parent: SceneEntity | null): void => {- ctx.report.nodes++;- const id = ids.get(n.id)!;- const here = `${ctx.where}: ${n.name}`;- if (n.instance) {- ctx.report.prefabInstances++;- const ref = ctx.prefabRef(n.instance.asset);- const overrides = ref ? instanceOverrides(n, ctx) : null;- if (ref && overrides) {- // Same shape the engine writes: the entry carries its parent, the parent lists the entry.- entities.push({ id, parent: parent ? parent.id : null, prefab: ref, overrides, added: [], removed: [] });- parent?.children.push(id);- return;- }- ctx.report.note('prefab-missing', here);- ctx.report.missingAsset(n.instance.asset);- }- const conv = n.instance ? { components: [] as ComponentData[] } : convertNode(n, ctx, here);- const entity: SceneEntity = {- id,- name: n.name,- parent: parent ? parent.id : null,- children: [],- components: conv.components,- visible: true,- };- if ('metadata' in conv && conv.metadata) entity.metadata = conv.metadata;- entities.push(entity);- parent?.children.push(id);- for (const [i, part] of ('parts' in conv ? conv.parts ?? [] : []).entries()) {- const partId = next++;- entities.push({ id: partId, name: `${n.name}_${i + 1}`, parent: id, children: [], components: [partTransform(), ...part], visible: true });- entity.children.push(partId);- }- if (!n.instance) for (const c of n.children) walk(c, entity);- };- for (const r of doc.roots) walk(r, null);- // 0 is the engine's "no entity"; the loader maps the rest.- for (const e of entities) if ('components' in e) resolveRefs(e.components, (id) => ids.get(id) ?? 0, 0);- // an edit box is the engine's text field, with the style its two labels had; the labels are not written- const withComponents = entities.filter((e): e is SceneEntity => 'components' in e);- const surviving = new Set<SceneEntity | SceneInstanceEntry>(foldEditBoxes(withComponents, (e) => e.id));- const folded = entities.filter((e) => !('components' in e) || surviving.has(e));- entities.length = 0;- entities.push(...folded);- if (ctx.design) for (const e of entities) if ('components' in e && e.parent === null) placeInDesign(e.components, ctx.design);- // The scene's ambient light is a setting of the scene in Cocos and an entity in the engine: a mesh that is lit gets all it is lit by from it.- if (doc.ambient) {- const { color, intensity } = doc.ambient;- entities.push({- id: next++, name: 'Ambient', parent: null, children: [], visible: true,- components: [- { type: 'Transform', data: { position: { x: 0, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 1, y: 1, z: 1 } } },- { type: 'Light', data: { type: 2, color: { r: color.r, g: color.g, b: color.b, a: 1 }, intensity, enabled: true } },- ],- });- }- // The scene's fog is a setting of the scene in Cocos and a global volume in the engine: the distance fog the post-process stack already has.- if (doc.fog) {- const { start, end, color } = doc.fog;- entities.push({- id: next++, name: 'Fog', parent: null, children: [], visible: true,- components: [- { type: 'Transform', data: { position: { x: 0, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 1, y: 1, z: 1 } } },- {- type: 'PostProcessVolume',- data: {- effects: [{- type: 'distanceFog', enabled: true,- uniforms: { u_fogNear: start, u_fogFar: end },- colors: { u_fogColor: { r: color.r, g: color.g, b: color.b, a: 1 } },- }],- isGlobal: true, shape: 'box', size: { x: 1, y: 1, z: 0 }, priority: 0, weight: 1, blendDistance: 0,- },- },- ],- });- }- return { version: 4, name: doc.name, entities };-}diff --git a/pipeline/src/import/cocos/document.ts b/pipeline/src/import/cocos/document.tsdeleted file mode 100644index e93b9a367..000000000--- a/pipeline/src/import/cocos/document.ts+++ /dev/null@@ -1,282 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A Cocos Creator 3.x `.scene` / `.prefab` file read as a tree.- *- * The file is a flat array whose objects point at each other by index- * (`{__id__: n}`) and at assets by uuid (`{__uuid__}`). Nothing downstream- * wants that shape, so it is resolved once here into nodes with their- * components, and a prefab instance — a node whose children live in- * another file — is kept as a reference plus the overrides it applies.- *- * Read-only: nothing here touches the project it reads.- */--export interface CocosVec3 { x: number; y: number; z: number }-export interface CocosQuat { x: number; y: number; z: number; w: number }--/** One `propertyOverrides` entry of a prefab instance. */-export interface CocosOverride {- /** `localID` of the target: the instance nodes crossed, then the node or component. */- target: string[];- /** Property path on the target (`['_lpos']`, `['_color']`). */- path: string[];- value: unknown;-}--export interface CocosComponent {- /** `cc.Sprite`, or a script's compressed class id. */- type: string;- /** Stable id inside its file (the `CompPrefabInfo` fileId). */- id: string;- enabled: boolean;- /** The serialised fields, without the bookkeeping that points back at the node. */- data: Record<string, unknown>;-}--export interface CocosInstanceRef {- /** uuid of the prefab this node stands for. */- asset: string;- overrides: CocosOverride[];- /** Things an instance can carry that this reader does not carry across yet. */- mountedChildren: number;- mountedComponents: number;- removedComponents: number;- /**- * The components the instance's file adds to nodes of the prefab it names (`mountedComponents`): the target is the `localID` path of a- * node, crossing the instances inside the prefab as an override's does.- */- mounted: Array<{ target: string[]; components: CocosComponent[] }>;-}--export interface CocosNode {- /** Stable id inside its file: the `PrefabInstance` fileId for an instance, else the `PrefabInfo` fileId, else the node's `_id`. */- id: string;- name: string;- active: boolean;- pos: CocosVec3;- rot: CocosQuat;- scale: CocosVec3;- layer: number;- components: CocosComponent[];- children: CocosNode[];- instance?: CocosInstanceRef;-}--export interface CocosDocument {- kind: 'prefab' | 'scene';- name: string;- roots: CocosNode[];- /** Scene-level settings (skybox, fog, shadows...) that are switched on. The ambient light and a linear fog are carried; the rest are not. */- globals: string[];- /** The scene's ambient light, as the low-dynamic-range sky colour and the illumination it is lit by; absent when the scene sets none. */- ambient?: { color: { r: number; g: number; b: number }; intensity: number };- /** The scene's fog when it is switched on and falls off linearly between two distances (the other falloffs are not carried); colour is 0..1. */- fog?: { start: number; end: number; color: { r: number; g: number; b: number } };- /** Node ids that had to be made unique because the file repeats them. */- duplicateIds: number;-}--type Raw = Record<string, unknown>;--/** Key of a reference to a node inside a component's data: the value is that node's `CocosNode.id`. */-export const NODE_REF = '__node__';--const BOOKKEEPING = new Set(['__type__', '_name', '_objFlags', 'node', '__prefab', '_id', '__editorExtras__']);--const isObj = (v: unknown): v is Raw => typeof v === 'object' && v !== null && !Array.isArray(v);-const num = (v: unknown, d: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : d);--function vec3(v: unknown, d: CocosVec3): CocosVec3 {- return isObj(v) ? { x: num(v.x, d.x), y: num(v.y, d.y), z: num(v.z, d.z) } : { ...d };-}--function quat(v: unknown): CocosQuat {- return isObj(v) ? { x: num(v.x, 0), y: num(v.y, 0), z: num(v.z, 0), w: num(v.w, 1) } : { x: 0, y: 0, z: 0, w: 1 };-}--/** A fileId is base64, so it can hold `/`; the engine reads `/` as the step into a nested prefab, so it cannot stay. */-const safeId = (id: string): string => id.replaceAll('/', '|');--export function parseCocosDocument(file: unknown, fallbackName = ''): CocosDocument {- if (!Array.isArray(file) || file.length === 0) throw new Error('not a Cocos scene/prefab: expected a non-empty array');- const objs = file as unknown[];- const at = (ref: unknown): Raw | null => {- if (!isObj(ref) || typeof ref.__id__ !== 'number') return null;- const o = objs[ref.__id__];- return isObj(o) ? o : null;- };- const indexOf = (ref: unknown): number => (isObj(ref) && typeof ref.__id__ === 'number' ? ref.__id__ : -1);-- const head = isObj(objs[0]) ? objs[0] : null;- const globals: string[] = [];- let ambient: CocosDocument['ambient'];- let fog: CocosDocument['fog'];- let rootRefs: unknown[];- let kind: CocosDocument['kind'];- let name = fallbackName;- if (head?.__type__ === 'cc.Prefab') {- kind = 'prefab';- name = typeof head._name === 'string' && head._name ? head._name : name;- rootRefs = [head.data];- } else if (head?.__type__ === 'cc.SceneAsset') {- kind = 'scene';- const scene = at(head.scene);- if (!scene) throw new Error('scene asset has no scene');- name = typeof scene._name === 'string' && scene._name ? scene._name : name;- rootRefs = Array.isArray(scene._children) ? scene._children : [];- const g = at(scene._globals);- // A setting the scene leaves switched off changes nothing drawn, so only a setting that is on counts as one the scene has.- // The skybox is `_skybox` in the file, the rest are named as they are here.- const settings: Array<[string, unknown]> = g- ? [['ambient', g.ambient], ['shadows', g.shadows], ['skybox', g._skybox ?? g.skybox], ['fog', g.fog], ['octree', g.octree], ['lightProbeInfo', g.lightProbeInfo]]- : [];- for (const [k, ref] of settings) {- const s = at(ref);- if (s && (k === 'ambient' || s._enabled === true)) globals.push(k);- }- const fogInfo = g ? at(g.fog) : null;- if (fogInfo && fogInfo._enabled === true && num(fogInfo._type, 0) === 0) {- const c = isObj(fogInfo._fogColor) ? fogInfo._fogColor : {};- fog = {- start: num(fogInfo._fogStart, 0), end: num(fogInfo._fogEnd, 300),- color: { r: num(c.r, 200) / 255, g: num(c.g, 200) / 255, b: num(c.b, 200) / 255 },- };- }- const amb = g ? at(g.ambient) : null;- const sky = amb && isObj(amb._skyColorLDR) ? amb._skyColorLDR : null;- if (amb && sky && typeof sky.x === 'number' && typeof sky.y === 'number' && typeof sky.z === 'number') {- ambient = { color: { r: sky.x, g: sky.y, b: sky.z }, intensity: typeof amb._skyIllumLDR === 'number' ? amb._skyIllumLDR : 1 };- }- } else {- throw new Error(`not a Cocos scene/prefab: first object is ${String(head?.__type__)}`);- }-- const seen = new Set<number>();- /** Which node an object in the file is, or belongs to: a `cc.Node` itself, or a component on one. */- const nodeAt = new Map<number, CocosNode>();- const usedIds = new Map<string, number>();- let duplicateIds = 0;- // Copy-pasted instances can carry the same fileId; the engine needs every entity in a prefab to have its own.- const unique = (id: string): string => {- const n = usedIds.get(id) ?? 0;- usedIds.set(id, n + 1);- if (n === 0) return id;- duplicateIds++;- return `${id}~${n + 1}`;- };- const readComponent = (cref: unknown): CocosComponent | null => {- const c = at(cref);- if (!c || typeof c.__type__ !== 'string') return null;- const cinfo = at(c.__prefab);- const cid = safeId((cinfo && typeof cinfo.fileId === 'string' && cinfo.fileId) || (typeof c._id === 'string' && c._id) || `#${indexOf(cref)}`);- const data: Record<string, unknown> = {};- for (const [k, v] of Object.entries(c)) if (!BOOKKEEPING.has(k)) data[k] = v;- return { type: c.__type__, id: cid, enabled: c._enabled !== false, data };- };- const readNode = (ref: unknown): CocosNode | null => {- const idx = indexOf(ref);- const n = at(ref);- if (!n || n.__type__ !== 'cc.Node' || seen.has(idx)) return null;- seen.add(idx);- const rawComponents = Array.isArray(n._components) ? n._components : [];- const info = at(n._prefab);- const instRaw = info ? at(info.instance) : null;- // An instance node's PrefabInfo.fileId is the nested prefab's own root id, so two instances of one prefab share it;- // the instance's identity inside this file — and the first step of any override path crossing it — is the PrefabInstance's.- const id = unique(safeId((instRaw && typeof instRaw.fileId === 'string' && instRaw.fileId)- || (info && typeof info.fileId === 'string' && info.fileId)- || (typeof n._id === 'string' && n._id)- || `#${idx}`));-- const node: CocosNode = {- id,- name: typeof n._name === 'string' ? n._name : '',- active: n._active !== false,- pos: vec3(n._lpos, { x: 0, y: 0, z: 0 }),- rot: quat(n._lrot),- scale: vec3(n._lscale, { x: 1, y: 1, z: 1 }),- layer: num(n._layer, 0),- components: [],- children: [],- };- nodeAt.set(idx, node);- for (const cref of rawComponents) nodeAt.set(indexOf(cref), node);-- for (const cref of Array.isArray(n._components) ? n._components : []) {- const comp = readComponent(cref);- if (comp) node.components.push(comp);- }-- if (instRaw && info) {- const asset = isObj(info.asset) && typeof info.asset.__uuid__ === 'string' ? info.asset.__uuid__ : '';- const overrides: CocosOverride[] = [];- for (const oref of Array.isArray(instRaw.propertyOverrides) ? instRaw.propertyOverrides : []) {- const o = at(oref);- const t = o ? at(o.targetInfo) : null;- if (!o || !t || !Array.isArray(t.localID) || !Array.isArray(o.propertyPath)) continue;- overrides.push({ target: t.localID.map((x) => safeId(String(x))), path: o.propertyPath.map(String), value: o.value });- }- const count = (v: unknown): number => (Array.isArray(v) ? v.length : 0);- const mounted: CocosInstanceRef['mounted'] = [];- for (const mref of Array.isArray(instRaw.mountedComponents) ? instRaw.mountedComponents : []) {- const m = at(mref);- const t = m ? at(m.targetInfo) : null;- if (!m || !t || !Array.isArray(t.localID)) continue;- const components = (Array.isArray(m.components) ? m.components : []).map(readComponent).filter((c): c is CocosComponent => c !== null);- if (components.length > 0) mounted.push({ target: t.localID.map((x) => safeId(String(x))), components });- }- node.instance = {- mounted,- asset,- overrides,- mountedChildren: count(instRaw.mountedChildren),- mountedComponents: count(instRaw.mountedComponents),- removedComponents: count(instRaw.removedComponents),- };- }-- for (const cr of Array.isArray(n._children) ? n._children : []) {- const child = readNode(cr);- if (child) node.children.push(child);- }- return node;- };-- const roots: CocosNode[] = [];- for (const r of rootRefs) {- const n = readNode(r);- if (n) roots.push(n);- }- // A component's fields point at other objects in the file by index. Nodes and components become the id of their node, which is what- // a later stage can map to an entity; any other object (a click event, a nested serialised class) is read in place.- const resolveRefs = (value: unknown, stack: Set<number>): unknown => {- if (Array.isArray(value)) return value.map((v) => resolveRefs(v, stack));- if (!isObj(value)) return value;- if (typeof value.__id__ === 'number') {- const owner = nodeAt.get(value.__id__);- if (owner) return { [NODE_REF]: owner.id };- const target = objs[value.__id__];- if (!isObj(target) || stack.has(value.__id__) || target.__type__ === 'cc.Node') return null;- stack.add(value.__id__);- const out = resolveObject(target, stack);- stack.delete(value.__id__);- return out;- }- return resolveObject(value, stack);- };- const resolveObject = (o: Raw, stack: Set<number>): Raw => {- const out: Raw = {};- for (const [k, v] of Object.entries(o)) if (k !== '__type__' && !BOOKKEEPING.has(k)) out[k] = resolveRefs(v, stack);- return out;- };- const resolveNode = (node: CocosNode): void => {- for (const c of node.components) for (const [k, v] of Object.entries(c.data)) c.data[k] = resolveRefs(v, new Set());- for (const m of node.instance?.mounted ?? []) {- for (const c of m.components) for (const [k, v] of Object.entries(c.data)) c.data[k] = resolveRefs(v, new Set());- }- node.children.forEach(resolveNode);- };- roots.forEach(resolveNode);- return { kind, name, roots, globals, ambient, fog, duplicateIds };-}diff --git a/pipeline/src/import/cocos/editBoxFold.ts b/pipeline/src/import/cocos/editBoxFold.tsdeleted file mode 100644index 77100967b..000000000--- a/pipeline/src/import/cocos/editBoxFold.ts+++ /dev/null@@ -1,106 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file editBoxFold.ts- * @brief A Cocos edit box becomes the engine's `TextInput`, and the two labels it was built from are folded into it.- *- * In Cocos an edit box is a node with a component and two children, a label for the typed text and one for the hint, which the- * component keeps in step. The engine's field draws its own text and hint, caret and selection, so what those two labels said — the- * font, the size, the colours, the alignment, where the text starts inside the box — is the field's own style, and the two nodes are not- * written: there is nothing for them to be.- *- * Done after the references between nodes are resolved, because the labels are named by the component as nodes of the document.- */-import type { ComponentData } from './components';--type Raw = Record<string, unknown>;--/** The part of a converted entity this needs: what it carries and who it holds. */-export interface FoldEntity {- components: ComponentData[];- children: Array<string | number>;-}--const COCOS_EDIT_BOX = 'Cocos.EditBox';--/** Cocos's `InputMode`: ANY, EMAIL, NUMERIC, PHONE_NUMBER, URL, DECIMAL, SINGLE_LINE. */-const NUMERIC = 2, PHONE_NUMBER = 3, DECIMAL = 5, ANY = 0;-/** The engine's `TextInputFilter`. */-const FILTER = { none: 0, digits: 1, decimal: 2, phone: 3 };-const PASSWORD = 0;--const isObj = (v: unknown): v is Raw => typeof v === 'object' && v !== null && !Array.isArray(v);-const num = (v: unknown, fallback: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : fallback);-const part = (e: FoldEntity, type: string): Raw | null => (e.components.find((c) => c.type === type)?.data as Raw | undefined) ?? null;--/** Where the label's text starts inside the box, measured from the box's left edge: the field's padding. */-function paddingOf(box: FoldEntity, label: FoldEntity | null): number {- if (!label) return 0;- const boxRect = part(box, 'ContentRect');- const labelRect = part(label, 'ContentRect');- const labelAt = part(label, 'Transform');- if (!boxRect || !labelRect || !labelAt) return 0;- const size = (r: Raw): { x: number; y: number } => (isObj(r.size) ? { x: num(r.size.x, 0), y: num(r.size.y, 0) } : { x: 0, y: 0 });- const pivot = (r: Raw): { x: number; y: number } => (isObj(r.pivot) ? { x: num(r.pivot.x, 0.5), y: num(r.pivot.y, 0.5) } : { x: 0.5, y: 0.5 });- const position = isObj(labelAt.position) ? num(labelAt.position.x, 0) : 0;- const boxLeft = -pivot(boxRect).x * size(boxRect).x;- const labelLeft = position - pivot(labelRect).x * size(labelRect).x;- return Math.max(0, Math.round((labelLeft - boxLeft) * 100) / 100);-}--/**- * Replace each edit box component by a `TextInput` carrying the style of its labels, and drop the labels' entities (with whatever is- * under them) from @p entities. @p idOf names an entity the way the component's references do. Entities that are not edit boxes, and- * those a reference could not be resolved for, are left as they are.- */-export function foldEditBoxes<E extends FoldEntity>(entities: E[], idOf: (e: E) => string | number): E[] {- const byId = new Map<string | number, E>(entities.map((e) => [idOf(e), e]));- const dropped = new Set<string | number>();- const dropWithDescendants = (id: string | number): void => {- if (dropped.has(id)) return;- dropped.add(id);- for (const child of byId.get(id)?.children ?? []) dropWithDescendants(child);- };-- for (const entity of entities) {- const index = entity.components.findIndex((c) => c.type === COCOS_EDIT_BOX);- if (index < 0) continue;- const box = entity.components[index]!.data as Raw;- const textId = box.textLabel as string | number | undefined;- const hintId = box.placeholderLabel as string | number | undefined;- const textEntity = textId !== undefined && textId !== '' && textId !== 0 ? byId.get(textId) ?? null : null;- const hintEntity = hintId !== undefined && hintId !== '' && hintId !== 0 ? byId.get(hintId) ?? null : null;- const text = textEntity ? part(textEntity, 'Text') : null;- const hint = hintEntity ? part(hintEntity, 'Text') : null;- // the typed text's style leads; a box that has only the hint takes the size and the font from it- const style = text ?? hint ?? {};-- const mode = num(box.inputMode, ANY);- const inputFilter = mode === NUMERIC ? FILTER.digits : mode === DECIMAL ? FILTER.decimal : mode === PHONE_NUMBER ? FILTER.phone : FILTER.none;- const data: Raw = {- value: typeof box.string_ === 'string' ? box.string_ : '',- placeholder: hint && typeof hint.content === 'string' ? hint.content : '',- maxLength: num(box.maxLength, 0) > 0 ? num(box.maxLength, 0) : 0,- inputFilter,- multiline: mode === ANY,- password: num(box.inputFlag, 5) === PASSWORD,- readOnly: box.enabled === false,- fontSize: num(style.fontSize, 16),- padding: paddingOf(entity, textEntity ?? hintEntity),- textAlign: num(style.align, 0),- renderMode: num(style.renderMode, 0),- };- if (isObj(text?.color)) data.color = text!.color;- if (isObj(hint?.color)) data.placeholderColor = hint!.color;- if (typeof style.fontFamily === 'string' && style.fontFamily !== '') data.fontFamily = style.fontFamily;- if (typeof style.font === 'string' || (typeof style.font === 'number' && style.font !== 0)) data.font = style.font;- entity.components[index] = { type: 'TextInput', data };-- for (const labelId of [textId, hintId]) {- if (labelId === undefined || !byId.has(labelId)) continue;- dropWithDescendants(labelId);- entity.children = entity.children.filter((c) => c !== labelId);- }- }- return dropped.size === 0 ? entities : entities.filter((e) => !dropped.has(idOf(e)));-}diff --git a/pipeline/src/import/cocos/effectConvert.ts b/pipeline/src/import/cocos/effectConvert.tsdeleted file mode 100644index 6c5373169..000000000--- a/pipeline/src/import/cocos/effectConvert.ts+++ /dev/null@@ -1,733 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file effectConvert.ts- * @brief A Cocos `.effect` pass as an Estella `.esshader` and the render state of its `.esmaterial`.- *- * What carries across is what a pass says about its own fragment: the `frag()` function, the properties it reads (a `Constant` block's- * members and its samplers, which become `#pragma param`), the macros it branches on (`#pragma switch`, or `#define` when a material's own are given)- * and the pass's blend, depth and cull- * state. The vertex stage is the engine's own: a pass whose vertex program only applies the standard transform needs nothing of its own, which- * is the usual case (a sprite, a UI quad, an unlit mesh). A pass whose vertex program does more (a wave, a sway, an outline expansion) cannot be- * given the engine's stage and is reported, not approximated: the converted material would draw something other than what it was made to.- *- * The Cocos built-ins a fragment calls (`CCFragOutput`, `CC_APPLY_FOG`, `cc_time`…) are given by a short prelude written here, not by- * expanding the chunks of the Creator install, which are written against Cocos's own uniform buffers and pipeline.- */-import { macrosIn, type CocosEffect, type EffectPass, type EffectProperty } from './effects';--export interface ConvertedShader {- /** The `.esshader` source. */- source: string;- /** The macros the shader branches on, which a material turns on by name (`switches`). */- switches: string[];- /** The parameters it declares, by name, with the value a material starts from. */- params: Array<{ name: string; type: 'float' | 'vec2' | 'vec3' | 'vec4' | 'color' | 'int' | 'texture'; value: number[] | string }>;- /** What the engine does not do the way the effect asked: the shader still converts, and says so. */- approximations: string[];-}--export interface PassConversion {- shader: ConvertedShader | null;- /** Why there is no shader: what the pass needs that the engine's stage does not give. */- unsupported: string | null;- /** `.esmaterial` render state. */- state: { blendMode: number; depthTest: boolean; depthWrite: boolean; cull: number };-}--// ----------------------------------------------------------------------------// Render state-// -----------------------------------------------------------------------------const FACTOR = (v: unknown): string => String(v ?? '').toLowerCase();--/** The engine's blend mode for a Cocos blend target, or null where the pair is none of the engine's. */-function blendModeOf(blend: unknown): number {- const targets = (blend as { targets?: Array<Record<string, unknown>> } | null)?.targets;- const t = targets?.[0];- if (!t || t.blend === false || t.blend === undefined) return 9; // BlendMode.None: the source replaces- const src = FACTOR(t.blendSrc ?? 'one');- const dst = FACTOR(t.blendDst ?? 'zero');- if (src === 'src_alpha' && dst === 'one_minus_src_alpha') return 0;- if (src === 'src_alpha' && dst === 'one') return 1;- if ((src === 'dst_color' || src === 'zero') && (dst === 'one_minus_src_alpha' || dst === 'src_color')) return 2;- if (src === 'one' && dst === 'one_minus_src_color') return 3;- if (src === 'one' && dst === 'one_minus_src_alpha') return 4;- if (src === 'one' && dst === 'one') return 5;- return 0;-}--function cullOf(rasterizer: unknown): number {- const c = FACTOR((rasterizer as { cullMode?: unknown } | null)?.cullMode ?? 'back');- return c === 'none' ? 0 : c === 'front' ? 2 : 1;-}--function stateOf(pass: EffectPass): PassConversion['state'] {- const ds = (pass.depthStencil ?? {}) as { depthTest?: boolean; depthWrite?: boolean };- return {- blendMode: blendModeOf(pass.blend),- depthTest: ds.depthTest ?? true,- depthWrite: ds.depthWrite ?? true,- cull: cullOf(pass.rasterizer),- };-}--// ----------------------------------------------------------------------------// Programs-// -----------------------------------------------------------------------------/** Cocos names for what the engine's vertex stage hands the fragment. */-const VARYINGS: Record<string, { name: string; glsl: string; mesh?: boolean }> = {- v_uv: { name: 'v_texCoord', glsl: 'in vec2 v_texCoord;' },- uv0: { name: 'v_texCoord', glsl: 'in vec2 v_texCoord;' },- uv: { name: 'v_texCoord', glsl: 'in vec2 v_texCoord;' },- v_color: { name: 'v_color', glsl: 'in vec4 v_color;' },- color: { name: 'v_color', glsl: 'in vec4 v_color;' },-};--/** The world position a Cocos fragment reads as `v_position`. The engine's vertex stage gives the full position to a mesh that has normals and the position in the plane otherwise. */-const POSITION_VARYING = `#ifdef MESH_NORMALS-in highp vec3 v_worldXYZ;-#define cocos_position v_worldXYZ-#else-in highp vec2 v_worldPos;-#define cocos_position vec3(v_worldPos, 0.0)-#endif`;-const NORMAL_VARYING = `#ifdef MESH_NORMALS-in highp vec3 v_worldNormal;-#define cocos_normal v_worldNormal-#else-#define cocos_normal vec3(0.0, 0.0, 1.0)-#endif`;--// A Cocos fragment works in linear light, decoding its textures and colours, and ends in \`CCFragOutput\`, which encodes for the display. The engine's-// linear colour space encodes in the pass that ends the frame, so there the output stays as it is; in the gamma one the shader's own result is what-// reaches the screen, and it is encoded here, or everything the shader lit comes out dark.-const PRELUDE = `// Cocos built-ins the converted fragment calls.-#define cc_time u_time-vec3 LinearToSRGB(vec3 c) { return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(vec3(0.0031308), c)); }-vec3 SRGBToLinear(vec3 c) { return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), c)); }-#ifdef ES_LINEAR-#define CCFragOutput(c) (c)-#else-#define CCFragOutput(c) vec4(LinearToSRGB((c).rgb), (c).a)-#endif-`;--/**- * A preprocessor expression with each bare macro name asked as `defined(NAME)`: a name that is not defined is 0 in Cocos, and in GLSL ES it is an- * error. A name compared with a number (`LEVEL == 2`) is left as it is, which is the one thing a bare switch cannot say.- */-export function pruneUnreachable(source: string, roots: readonly string[]): string {- // The top-level functions: a header at brace depth 0, the span up to the brace that closes it.- interface Fn { name: string; start: number; end: number }- const functions: Fn[] = [];- let depth = 0;- let open: { name: string; start: number } | null = null;- const header = /(?:^|\n)[ \t]*(?:(?:highp|mediump|lowp|const|inout|in|out)\s+)*\w+(?:\[\d*\])?\s+(\w+)\s*\([^;{}]*\)\s*\{/y;- // What a macro defines (a directive whose lines end in a backslash) is not a function of the shader: its text is the macro's to expand, and cutting- // a function out of it leaves the macro running on into the lines after it. It is blanked for the reading of the structure, same length.- const structure = ((): string => {- const lines = source.split('\n');- let inDirective = false;- return lines.map((line) => {- const starts = inDirective || /^[ \t]*#/.test(line);- inDirective = starts && /\\[ \t]*$/.test(line);- return starts ? line.replace(/[^\n]/g, ' ') : line;- }).join('\n');- })();- for (let i = 0; i < structure.length; i++) {- const c = structure[i]!;- if (depth === 0 && !open && (c === '\n' || i === 0)) {- header.lastIndex = i;- const m = header.exec(structure);- if (m && !/^(?:if|for|while|switch|return)$/.test(m[1]!)) {- const braceAt = i + m[0].length - 1;- open = { name: m[1]!, start: i === 0 && source[0] !== '\n' ? 0 : i + 1 };- depth = 1;- i = braceAt;- continue;- }- }- if (c === '{') depth++;- else if (c === '}') {- depth--;- if (depth === 0 && open) { functions.push({ ...open, end: i + 1 }); open = null; }- }- }- if (functions.length === 0) return source;- // What the roots reach by name, through the bodies of the functions of that name (overloads share one).- const reached = new Set<string>(roots);- const byName = new Map<string, Fn[]>();- for (const f of functions) byName.set(f.name, [...(byName.get(f.name) ?? []), f]);- const queue = [...roots];- // A function is a root too where something outside every function names it (a macro, an initialiser).- const outside = functions.reduceRight((text, f) => text.slice(0, f.start) + ' ' + text.slice(f.end), source);- for (const name of byName.keys()) if (new RegExp(`\\b${name}\\b`).test(outside) && !reached.has(name)) { reached.add(name); queue.push(name); }- while (queue.length > 0) {- const name = queue.pop()!;- for (const f of byName.get(name) ?? []) {- for (const m of source.slice(f.start, f.end).matchAll(/\b([A-Za-z_]\w*)\s*\(/g)) {- const callee = m[1]!;- if (byName.has(callee) && !reached.has(callee)) { reached.add(callee); queue.push(callee); }- }- }- }- let out = source;- for (const f of [...functions].reverse()) if (!reached.has(f.name)) out = out.slice(0, f.start) + out.slice(f.end);- return out;-}--function definedForm(expr: string): string {- const kept: string[] = [];- const guarded = expr.replace(/\bdefined\s*(?:\(\s*\w+\s*\)|\s+\w+)/g, (m) => { kept.push(m); return `\u0001${kept.length - 1}\u0001`; });- const wrapped = guarded.replace(/\b([A-Z][A-Z0-9_]+)\b(?!\s*(?:==|!=|<=|>=|<|>))(?<!(?:==|!=|<=|>=|<|>)\s*[A-Z][A-Z0-9_]*)/g, 'defined($1)');- return wrapped.replace(/\u0001(\d+)\u0001/g, (_m, i: string) => kept[Number(i)]!);-}--type ParamType = ConvertedShader['params'][number]['type'];--function paramTypeOf(glsl: string, prop: EffectProperty | undefined): ParamType {- if (glsl === 'float') return 'float';- if (glsl === 'int' || glsl === 'bool') return 'int';- if (glsl === 'vec2') return 'vec2';- if (glsl === 'vec3') return prop?.editorType === 'color' ? 'color' : 'vec3';- return prop?.editorType === 'color' ? 'color' : 'vec4';-}--const TEXTURE_DEFAULTS: Record<string, string> = { white: 'white', grey: 'grey', gray: 'grey', black: 'black', normal: 'normal', default: 'white' };--const csv = (v: number[]): string => v.map((x) => String(+x.toFixed(6))).join(',');--function numbersOf(value: unknown, n: number): number[] {- const arr = Array.isArray(value) ? value.map(Number) : typeof value === 'number' ? [value] : [];- while (arr.length < n) arr.push(0);- return arr.slice(0, n).map((x) => (Number.isFinite(x) ? x : 0));-}--const ARITY: Record<string, number> = { float: 1, int: 1, vec2: 2, vec3: 3, vec4: 4, color: 4 };--// ----------------------------------------------------------------------------// Includes-// -----------------------------------------------------------------------------export interface EffectOptions {- /** The text of a chunk by its include name (`common/data/unpack`, a project's `tower_defense_death_dissolve`), or null when there is none. */- chunk?(name: string): string | null;- /** The values a scene gives a fragment (`cc_ambientSky`…), where the project has them: the parameters of the material start there. */- scene?: Record<string, number[]>;-}--/** Chunks of Cocos that the prelude gives (a fragment's built-ins, the scene's uniform blocks): they are left out rather than read. */-const PROVIDED = /(?:^|\/)(?:fog-fs|output|output-standard|embedded-alpha|cc-global|cc-local|cc-environment|cc-forward-light|cc-shadow|gamma|aces)$/;--/** Chunks that make up Cocos's vertex input and its world matrix. The vertex stage is emulated (see below) with the prelude's version of them. */-const VERTEX_STRUCTURE = /(?:^|\/)(?:input|input-standard|decode-base|decode-standard|local-batch|fog-vs|shadow-map-vs|morph|skinning)$/;--const PROVIDED_AND_STRUCTURE = new RegExp(`${PROVIDED.source}|${VERTEX_STRUCTURE.source}`);--/**- * A program's text with each `#include <name>` that is not the prelude's replaced by the chunk it names: a program of the same effect first, then- * the project's chunks and the Creator install's, through {@link EffectOptions.chunk}. A chunk is read once for the whole shader, since a second- * copy would declare its functions twice. What cannot be found is returned, so the pass can say what it lacked.- */-function expandIncludes(- source: string, effect: CocosEffect, options: EffectOptions, seen: Set<string>, missing: string[], depth = 0,- skip: RegExp = PROVIDED,-): string {- return source.replace(/^[ \t]*#[ \t]*include[ \t]*<([^>]+)>[ \t]*$/gm, (line, name: string) => {- if (skip.test(name)) return '';- if (seen.has(name)) return '';- seen.add(name);- const text = (effect.programs.get(name)?.source ?? options.chunk?.(name) ?? null)?.replace(/\r\n/g, '\n') ?? null;- if (text === null) { missing.push(name); return line; }- if (depth > 12) { missing.push(`${name} (too deep)`); return line; }- return expandIncludes(text, effect, options, seen, missing, depth + 1, skip);- });-}--// ----------------------------------------------------------------------------// The vertex stage, carried into the fragment-// -----------------------------------------------------------------------------/**- * What a vertex program of an effect hands to its fragment is almost always the surface made ready for shading: the world position and normal, the- * uv scaled and offset by the material's tiling, a second uv, the vertex colour. The engine's vertex stage supplies the first of those and the uv,- * and the rest are arithmetic on them. So the vertex program is not given a stage of its own: it is run in the fragment, ahead of the fragment's own- * function, with the attributes it reads standing for what the engine's stage passes down. The result is the same for everything that is a function- * of the vertex's own values and the material's (a tiling, a world position, a tangent frame), and costs a little more per pixel than per vertex.- * Where the vertex is drawn is the engine's, so a program that displaces the position (a sway, a wave) is also given to the engine as the material's- * vertex hook, run with the same attributes, which moves the vertex where the effect moved it. The hook reads no texture: one that does is not given.- */-const VERTEX_PRELUDE = `// The vertex stage of the effect, run per fragment on what the engine's vertex stage hands down.-struct StandardVertInput { highp vec4 position; vec3 normal; vec4 tangent; };-#define CCGetWorldMatrix(m) m = mat4(1.0)-#define CCGetWorldMatrixFull(m, mit) m = mat4(1.0); mit = mat4(1.0)-#define CCVertInput(In) CCDecode(In)-void CCDecode(out StandardVertInput In) { In.position = vec4(a_position, 1.0); In.normal = a_normal; In.tangent = a_tangent; }-void CCDecode(out vec4 position) { position = vec4(a_position, 1.0); }-`;--const ATTRIBUTE_SOURCES: Record<string, string> = {- a_position: 'cocos_position', a_normal: 'cocos_normal', a_tangent: 'cocos_tangent', a_texCoord: 'v_texCoord', a_color: 'v_color',- a_texCoord1: 'cocos_texCoord1', a_uv0: 'v_texCoord',-};--/** The attributes the vertex stage always has: declared whether or not the program says so, since the prelude's decode reads them. */-const STANDARD_ATTRIBUTES: Record<string, string> = { a_position: 'vec3', a_normal: 'vec3', a_texCoord: 'vec2', a_tangent: 'vec4' };--/** The varyings the engine's vertex stage owns. */-const ENGINE_VARYING_NAMES = new Set(['v_color', 'v_texCoord', 'v_worldPos', 'v_worldXYZ', 'v_worldNormal', 'v_worldTangent', 'v_localPos']);--/** The second uv set: the engine hands it down wherever the vertices carry one (MESH_LIGHTMAP), and a draw with none reads the first. */-const UV1_VARYING = `#ifdef MESH_LIGHTMAP-in highp vec2 v_texCoord1;-#define cocos_texCoord1 v_texCoord1-#else-#define cocos_texCoord1 v_texCoord-#endif`;--const TANGENT_VARYING = `#ifdef MESH_TANGENTS-#define cocos_tangent v_worldTangent-#else-#define cocos_tangent vec4(1.0, 0.0, 0.0, 1.0)-#endif`;--/**- * The mesh's position before it is placed, which the engine's vertex stage hands down to a shader that declares MESH_LOCAL_POSITION. Where a draw has none- * (a sprite, whose vertices are already in the world) it is the world position, which is what it would be.- */-const LOCAL_POSITION_VARYING = `#ifdef MESH_LOCAL_POSITION-in highp vec3 v_localPos;-#define cocos_localPosition v_localPos-#else-#define cocos_localPosition cocos_position-#endif`;--interface Emulated {- /** The program reads the position as the mesh has it, in its own space (a swizzle of it, not a point it puts through the world matrix). */- readsModelPosition: boolean;- /** The program, as GLSL that declares what it wrote as globals and has the entry `cocos_vert`. */- source: string;- /** The attributes it reads, as globals. */- attributes: string;- /** The names the vertex program writes for the fragment. */- outputs: Set<string>;- /** The assignments that give the attributes it declares their values. */- attributeSetup: string[];- approximations: string[];- /** The program moves the vertex before it is placed (a displacement by time or by a function of the position). */- displaces: boolean;-}--/**- * A vertex program with the branches it takes only for a light probe taken out. A material is not given probe data, so `CC_USE_LIGHT_PROBE` is off for it, and a- * program that mentions probes only under that macro does not read them.- */-function withoutLightProbeBranches(program: string): string {- interface Frame { probe: boolean; dropping: boolean; reopened: boolean }- const stack: Frame[] = [];- const out: string[] = [];- const emitting = (): boolean => stack.every((f) => !f.dropping);- for (const line of program.split('\n')) {- const directive = /^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b(.*)$/.exec(line);- if (!directive) {- if (emitting()) out.push(line);- continue;- }- const [, kind, rest] = directive as unknown as [string, string, string];- if (kind === 'if' || kind === 'ifdef' || kind === 'ifndef') {- const probe = kind !== 'ifndef' && /^\s*(?:defined\s*\(\s*)?CC_USE_LIGHT_PROBE\b/.test(rest);- const emit = emitting();- stack.push({ probe, dropping: probe, reopened: false });- if (emit && !probe) out.push(line);- } else if (kind === 'endif') {- const frame = stack.pop();- if (emitting() && !(frame?.probe && !frame.reopened)) out.push(line);- } else {- // #else / #elif: the side of a probe branch that comes after it is the one a material takes- const frame = stack[stack.length - 1];- if (frame?.probe && frame.dropping) {- frame.dropping = false;- if (kind === 'elif') { frame.reopened = true; if (emitting()) out.push('#if' + rest); }- } else if (emitting()) {- out.push(line);- }- }- }- return out.join('\n');-}--function emulateVertex(program: string, entry: string): Emulated | { error: string } {- const outputs = new Set<string>();- const attributes = new Map<string, string>(Object.entries(STANDARD_ATTRIBUTES));- const approximations: string[] = [];- let text = withoutLightProbeBranches(program);- // Declarations: an attribute is a global the setup fills; an output is a global the fragment then reads.- text = text.replace(/^[ \t]*(?:layout\s*\([^)]*\)\s*)?in\s+(?:(?:highp|mediump|lowp|flat)\s+)*(\w+)\s+(a_\w+)\s*;[ \t]*$/gm, (_m, type: string, name: string) => {- attributes.set(name, type);- return '';- });- text = text.replace(/^[ \t]*(?:layout\s*\([^)]*\)\s*)?(?:flat\s+)?out\s+(?:(?:highp|mediump|lowp|flat)\s+)*(\w+)\s+(\w+)\s*;[ \t]*$/gm, (_m, type: string, name: string) => {- outputs.add(name);- return `${type} ${name};`;- });- const unknown = [...attributes.keys()].filter((a) => !(a in ATTRIBUTE_SOURCES) && !/^a_(?:matWorld|instanced|jointAnim|sh_|lightingMap|localShadow|vertexId|joints|weights|texCoord[2-9]|color1|dir|age)/.test(a));- if (unknown.length > 0) return { error: `its vertex program reads the attributes ${unknown.join(', ')}, which the engine's vertex stage does not carry` };- if (/\ba_sh_|\bCCGetSH|\bCC_USE_LIGHT_PROBE/.test(text)) return { error: 'its vertex program reads light-probe data, which a material does not get' };- if ([...attributes.keys()].some((a) => /^a_(?:joints|weights)$/.test(a))) return { error: 'its vertex program skins the mesh, which the converted material does not' };- if ([...attributes.keys()].some((a) => /^a_(?:matWorld|instanced|dir|age)/.test(a))) return { error: 'its vertex program reads per-instance data, which the engine\'s own instancing does not give a material' };- const entryRe = new RegExp(`\\bvec4\\s+${entry}\\s*\\(\\s*\\)`);- // A vertex program written as GLSL's own `void main()` writes `gl_Position` instead of returning it: the position is kept in a global, and the- // entry returns it, which is what the emulation calls.- const mainRe = /\bvoid\s+main\s*\(\s*\)/;- if (!entryRe.test(text) && mainRe.test(text)) {- text = `vec4 cocos_glPosition;\n#define gl_Position cocos_glPosition\n${text.replace(mainRe, 'void cocos_vert_main()')}\nvec4 cocos_vert() { cocos_vert_main(); return cocos_glPosition; }\n`;- } else {- if (!entryRe.test(text)) return { error: `the vertex entry ${entry}() is not there` };- text = text.replace(entryRe, 'vec4 cocos_vert()');- }- // A statement that assigns the position before the matrices are applied, from time or a periodic function: a displacement.- const displaces = /(?:\bIn\.position|\bposition|\ba_position)\b[^;]*\b(?:cc_time|sin|cos)\b|\b(?:cc_time|sin|cos)\b[^;]*(?:\bIn\.position|\bposition|\ba_position)\b/.test(text);- // A statement that takes components of the position and does not put it through the world matrix reads it in the mesh's own space (a terrain tiles its- // detail by `position.xz`); the engine's value for it, the world position, is the same only for a mesh that stands at the origin, unscaled and unturned.- const readsModelPosition = text.split(';').some((statement) => /(?:\bIn\.position|\bposition|\ba_position)\.[xyzw]{1,4}\b/.test(statement) && !/matWorld|cc_matWorld|matWorldIT/.test(statement));- const setup: string[] = [];- const declared: string[] = [];- for (const [name, type] of attributes) {- declared.push(`${type} ${name};`);- const source = name === 'a_position' && readsModelPosition ? 'cocos_localPosition' : ATTRIBUTE_SOURCES[name];- if (source) setup.push(` ${name} = ${source}${coerce(type, name)};`);- if (name === 'a_texCoord1') approximations.push('the second uv is the mesh\'s own where it has one and the first uv where it has none');- }- if (readsModelPosition) approximations.push('the vertex position is the mesh\'s own where the draw is a mesh, and the world position where it is a sprite');- return { source: text, attributes: declared.join('\n'), outputs, attributeSetup: setup, approximations, displaces, readsModelPosition };-}--/** The conversion that makes an engine value of one width fit the type an attribute is declared with. */-function coerce(type: string, name: string): string {- const width = { float: 1, vec2: 2, vec3: 3, vec4: 4 }[type] ?? 4;- const from = name === 'a_color' ? 4 : name === 'a_tangent' ? 4 : name === 'a_position' || name === 'a_normal' ? 3 : 2;- if (width === from) return '';- if (width < from) return `.${'xyzw'.slice(0, width)}`;- return '';-}--// ----------------------------------------------------------------------------// One pass-// -----------------------------------------------------------------------------/** Convert one pass. The effect's name is the shader's. */-export function convertPass(- effect: CocosEffect, pass: EffectPass, shaderName: string, options: EffectOptions = {}, defines?: Readonly<Record<string, number | boolean | string>>,-): PassConversion {- const state = stateOf(pass);- const fail = (unsupported: string): PassConversion => ({ shader: null, unsupported, state });- const [fragProgram, fragEntry = 'frag'] = pass.frag.split(':');- const [vertProgram, vertEntry = 'vert'] = pass.vert.split(':');- const programText = (name: string | undefined): string | null => (name ? effect.programs.get(name)?.source ?? options.chunk?.(name) ?? null : null)?.replace(/\r\n/g, '\n') ?? null;- const fragSource = programText(fragProgram);- if (fragSource === null) return fail(`fragment program ${fragProgram} is not in the effect`);- // A vertex stage the Creator install supplies (`general-vs`, `legacy/main-functions/general-vs`) is the standard one: the engine's.- const vertSource = programText(vertProgram);- const standardVertex = vertSource === null- && /^(?:(?:general|unlit|sprite|standard)-vs|legacy\/main-functions\/(?:general|unlit|standard)-vs|builtin\/.*)$/.test(vertProgram ?? '');- if (vertSource === null && !standardVertex) return fail(`vertex program ${vertProgram} is not in the effect`);- // A particle's vertex program builds the billboard from the emitter's own data, which is what the engine's particle stage does: that stage is the- // one this pass is drawn with, and only its fragment is converted. The fragment's `uv` and `color` are what the particle stage hands down.- const particleVertex = /particle|trail/i.test(vertProgram ?? '');-- const approximations: string[] = [];- const props = new Map(pass.properties.map((p) => [p.name, p]));- // A property that says `target: colorScaleAndCutoff.xyz` is part of a vec4 uniform, and what the uniform starts as is those parts put together:- // the uniform has no property of its own to say it.- const packedDefaults = new Map<string, number[]>();- for (const p of pass.properties) {- const m = p.target ? /^(\w+)\.([xyzwrgba]+)$/.exec(p.target) : null;- if (!m || p.value === null || p.value === undefined) continue;- const lanes = [...m[2]!].map((c) => 'xyzw'.indexOf(c) >= 0 ? 'xyzw'.indexOf(c) : 'rgba'.indexOf(c));- const whole = packedDefaults.get(m[1]!) ?? [0, 0, 0, 0];- const given = numbersOf(p.value, lanes.length);- lanes.forEach((lane, i) => { whole[lane] = given[i] ?? 0; });- packedDefaults.set(m[1]!, whole);- }- const params: ConvertedShader['params'] = [];- const declared = new Set<string>();- const missing: string[] = [];- const seen = new Set<string>();-- // The vertex program, carried into the fragment.- let vertex: Emulated | null = null;- let vertexText = '';- if (vertSource !== null && !particleVertex) {- const expanded = expandIncludes(vertSource, effect, options, seen, missing, 0, PROVIDED_AND_STRUCTURE);- const emulated = emulateVertex(expanded, vertEntry);- if ('error' in emulated) return fail(emulated.error);- vertex = emulated;- vertexText = emulated.source;- approximations.push(...emulated.approximations);- }- let body = expandIncludes(fragSource, effect, options, seen, missing);- if (missing.length > 0) return fail(`it includes ${[...new Set(missing)].join(', ')}, which the engine has no counterpart for`);- if (/fog-fs|fog-vs/.test(fragSource + (vertSource ?? ''))) approximations.push('fog is not applied');-- // Macros that only Cocos's own effect compiler reads: one that carries a preprocessor directive in its body or pastes tokens (`##`) is no GLSL ES, and- // is left out; a pass that calls one fails to compile, and says so.- const portable = (text: string): string => text- .replace(/^[ \t]*#[ \t]*define(?:\\\n|[^\n])*/gm, (block) => (/##|\\\n[ \t]*#[ \t]*(?:if|endif|else)/.test(block) ? '' : block))- .replace(/^[ \t]*#[ \t]*pragma[ \t]*\/\/[^\n]*$/gm, '');- const strip = (text: string): string => text.replace(/^[ \t]*#[ \t]*pragma[ \t]+define[ \t]+(?!-meta)/gm, '#define ').replace(/^\s*#include\s*<[^>]+>\s*$/gm, '').replace(/^\s*precision\s+\w+\s+float\s*;\s*$/gm, '').replace(/^\s*#pragma\s+(?:builtin|define-meta|format)\([^)]*\)\s*$/gm, '').replace(/^\s*#pragma\s+define-meta[^\n]*$/gm, '');- // What a chunk declares as a macro's default (`#pragma define-meta NAME default(1)`, `options([a, r])`): the value a material that sets none has.- const metaDefaults = new Map<string, string>();- for (const m of `${body}\n${vertexText}`.matchAll(/^[ \t]*#[ \t]*pragma[ \t]+define-meta[ \t]+(\w+)[ \t]+(.*)$/gm)) {- const value = /\bdefault\(([^)]*)\)/.exec(m[2]!)?.[1] ?? /\boptions\(\[\s*([^,\]\s]+)/.exec(m[2]!)?.[1];- if (value !== undefined && !metaDefaults.has(m[1]!)) metaDefaults.set(m[1]!, value.trim());- }- body = portable(strip(body));- vertexText = portable(strip(vertexText));-- // The Constant blocks' members become parameters, the vertex program's as well as the fragment's; the blocks go.- const blocks = (text: string): string => text.replace(/(?:layout\s*\([^)]*\)\s*)?uniform\s+(\w+)\s*\{([\s\S]*?)\}\s*;?/g, (_m, _block: string, members: string) => {- for (const decl of members.split(';')) {- const m = /^\s*(?:highp\s+|mediump\s+|lowp\s+)?(float|int|bool|vec2|vec3|vec4)\s+(\w+)\s*$/.exec(decl.replace(/\/\/[^\n]*/g, '').trim());- if (!m) continue;- const [, glsl, name] = m as unknown as [string, string, string];- if (declared.has(name)) continue;- declared.add(name);- const prop = props.get(name);- const type = paramTypeOf(glsl, prop);- params.push({ name, type, value: numbersOf(prop?.value ?? packedDefaults.get(name) ?? (name === 'alphaThreshold' ? 0.5 : 0), ARITY[type]!) });- }- return '';- });- body = blocks(body);- vertexText = blocks(vertexText);-- // Samplers: `uniform sampler2D name;` is a texture parameter, bound by the engine.- const samplers = (text: string): string => text.replace(/(?:layout\s*\([^)]*\)\s*)?uniform\s+(?:highp\s+|mediump\s+|lowp\s+)?sampler(\w+)\s+(\w+)\s*;/g, (_m, dim: string, name: string) => {- if (dim !== '2D') { approximations.push(`${name} is a sampler${dim}, which has no counterpart; it reads as a 2D texture`); }- // The sprite's own texture is the engine's batch texture, not a parameter of the material.- if (name === 'cc_spriteTexture') return '';- if (!declared.has(name)) {- declared.add(name);- const def = props.get(name)?.value;- params.push({ name, type: 'texture', value: TEXTURE_DEFAULTS[String(def)] ?? 'white' });- }- return '';- });- body = samplers(body);- vertexText = samplers(vertexText);-- // Varyings: what the vertex program wrote is a global of the emulation; the rest are the engine's, under Cocos's names. A name that is neither is- // the pass's reason not to convert.- const needed = new Set<string>();- const renames = new Map<string, string>();- const mapped = new Set<string>();- const produced = vertex?.outputs ?? new Set<string>();- body = body.replace(/^\s*in\s+(?:highp\s+|mediump\s+|lowp\s+)?(\w+)\s+(\w+)\s*;\s*$/gm, (_m, _type: string, name: string) => {- if (produced.has(name)) return '';- const v = VARYINGS[name];- if (v) { needed.add(v.glsl); renames.set(name, v.name); return ''; }- if (name === 'v_position' || name === 'v_worldPos') { needed.add(POSITION_VARYING); renames.set(name, 'cocos_position'); return ''; }- if (name === 'v_normal') { needed.add(NORMAL_VARYING); renames.set(name, 'cocos_normal'); return ''; }- // What a particle's own vertex program computes for its fragment, stood for by what the engine's particle stage gives: the mask's uv is the uv.- if (name === 'uvmask') { needed.add(VARYINGS.v_uv!.glsl); renames.set(name, 'v_texCoord'); mapped.add('uvmask is the uv'); return ''; }- if (name === 'mPosition') { needed.add(POSITION_VARYING); renames.set(name, 'cocos_position'); return ''; }- if (name === 'mNormal') { needed.add(NORMAL_VARYING); renames.set(name, 'cocos_normal'); return ''; }- if (name === 'v_tangent') { needed.add(TANGENT_VARYING); renames.set(name, 'cocos_tangent.xyz'); return ''; }- needed.add(`/* the vertex stage does not supply ${name} */`);- return '';- });- for (const m of mapped) approximations.push(m);- const unsupplied = [...needed].filter((n) => n.startsWith('/*'));- if (unsupplied.length > 0) return fail(`its fragment reads ${unsupplied.map((m) => /supply (\w+)/.exec(m)![1]).join(', ')}, which the engine's vertex stage does not supply`);- for (const [from, to] of renames) if (from !== to) body = body.replace(new RegExp(`\\b${from}\\b`, 'g'), to);- // A vertex output named like one of the engine's varyings (`v_color`) is the emulation's own value, not the engine's: it goes by another name.- for (const name of produced) {- if (!ENGINE_VARYING_NAMES.has(name)) continue;- const own = `cocos_${name}`;- const re = new RegExp(`\\b${name}\\b`, 'g');- body = body.replace(re, own);- vertexText = vertexText.replace(re, own);- }- if (vertex) {- // The emulation reads the engine's values through these, so it needs them declared even where the fragment itself does not.- needed.add(VARYINGS.v_uv!.glsl);- needed.add(VARYINGS.v_color!.glsl);- needed.add(POSITION_VARYING);- needed.add(NORMAL_VARYING);- needed.add(TANGENT_VARYING);- if (/\ba_texCoord1\b/.test(vertex.attributes)) needed.add(UV1_VARYING);- if (vertex.readsModelPosition) needed.add(LOCAL_POSITION_VARYING);- }- const usesPosition = needed.has(POSITION_VARYING);- if (usesPosition) approximations.push('v_position is the world position of the draw: the engine gives the full position to meshes with normals, and the plane position to sprites');-- // GLSL 1.00 spellings of the 3.00 functions, which Cocos's own compiler accepts.- const modern = (text: string): string => text.replace(/\btexture2D\s*\(/g, 'texture(').replace(/\btextureCube\s*\(/g, 'texture(').replace(/\btexture2DLodEXT\s*\(/g, 'textureLod(');- body = modern(body);- vertexText = modern(vertexText);-- // Fog and shadow transfers are statements with the arguments of whichever overload the effect uses, and GLSL ES has no variadic macros, so they are- // taken out as statements.- const noStatements = (text: string): string => text.replace(/\b(?:CC_APPLY_FOG|CC_TRANSFER_FOG|CC_TRANSFER_SHADOW|CC_TRANSFER_SH)\s*\([^;]*\)\s*;/g, '');- body = noStatements(body);- vertexText = noStatements(vertexText);-- // An atlas whose alpha is kept apart (ETC1) is sampled by a helper; here a texture holds its own alpha, so it is a plain sample. Spelt out, not- // a macro: the engine's twin tool finds a batch texture by the form `texture(u_textures[N], …)`.- body = body.replace(/\bCCSampleWithAlphaSeparated\s*\(/g, 'texture(');-- // The sprite's own texture: the engine binds it as the first of the batch's textures.- let usesSpriteTexture = false;- if (/\bcc_spriteTexture\b/.test(body)) {- usesSpriteTexture = true;- body = body.replace(/\bcc_spriteTexture\b/g, 'u_textures[0]');- }-- // Cocos's scene values (`cc_ambientSky`, `cc_cameraPos`): the engine has no counterpart at the fragment, so each is a parameter of the material- // that starts at a value that changes nothing, which the project can set where it had a scene setting.- const sceneValues: Record<string, number[]> = {- cc_ambientSky: [1, 1, 1, 1], cc_ambientGround: [1, 1, 1, 1], cc_cameraPos: [0, 0, 0, 1], cc_nearFar: [0.1, 1000, 0, 0],- cc_screenSize: [1, 1, 1, 1], cc_exposure: [1, 1, 0, 0], cc_mainLitColor: [1, 1, 1, 1], cc_mainLitDir: [0, 0, -1, 0],- ...options.scene,- };- const everything = `${vertexText}\n${body}`;- for (const [name, value] of Object.entries(sceneValues)) {- if (!new RegExp(`\\b${name}\\b`).test(everything) || declared.has(name)) continue;- declared.add(name);- params.push({ name, type: 'vec4', value });- approximations.push(`${name} is a parameter of the material, not the scene's`);- }- // The camera's matrices have no value at the fragment that means the same: the emulation's matrices are the identity.- const matrices = ['cc_matView', 'cc_matProj', 'cc_matViewProj', 'cc_matWorld', 'cc_matWorldIT', 'cc_matViewInv'].filter((m) => new RegExp(`\\b${m}\\b`).test(everything));- const everyText = `${body}\n${vertexText}`;- // Cocos's helper macros: the install's own where its common-define is included, these where it is not.- const flipFallback = Object.entries({ CC_HANDLE_RT_SAMPLE_FLIP: '(uv)', CC_HANDLE_GET_CLIP_FLIP: '(p) p' })- .filter(([name]) => new RegExp(`\\b${name}\\s*\\(`).test(everyText) && !new RegExp(`#define\\s+${name}\\b`).test(everyText))- .map(([name, tail]) => `#define ${name}${tail}\n`).join('');- const matrixDefs = matrices.map((m) => `#define ${m} mat4(1.0)`).join('\n');-- // The entry: `vec4 frag()` is the fragment's colour.- const entry = new RegExp(`\\bvec4\\s+${fragEntry}\\s*\\(\\s*\\)`);- // A fragment program written as GLSL's own `void main()` writes the colour to an `out vec4` instead of returning it: the output is a global, and the- // entry returns it.- const outDeclaration = /^[ \t]*(?:layout\s*\([^)]*\)\s*)?out\s+(?:(?:highp|mediump|lowp)\s+)?vec4\s+(\w+)\s*;[ \t]*$/m.exec(body);- const mainFragment = /\bvoid\s+main\s*\(\s*\)/;- if (!entry.test(body) && outDeclaration && mainFragment.test(body)) {- const written = outDeclaration[1]!;- body = `${body.replace(outDeclaration[0], `vec4 ${written};`).replace(mainFragment, 'void cocos_frag_main()')}\nvec4 cocos_frag() { cocos_frag_main(); return ${written}; }\n`;- } else {- if (!entry.test(body)) return fail(`the fragment entry ${fragEntry}() is not there`);- body = body.replace(entry, 'vec4 cocos_frag()');- }- // A function nothing reaches (a variant of the entry this pass does not name) may read what the pass never declares, which a compiler refuses.- body = pruneUnreachable(body, ['cocos_frag']);- if (vertex) vertexText = pruneUnreachable(vertexText, ['cocos_vert']);-- // Cocos reads a macro that is not defined as 0 in `#if`; GLSL ES refuses an undefined name there. A switch is defined when it is on.- const definedFormed = (text: string): string => text.replace(/^([ \t]*#[ \t]*(?:el)?if)([ \t]+.*)$/gm, (_m, directive: string, expr: string) => `${directive}${definedForm(expr)}`);- body = definedFormed(body);- vertexText = definedFormed(vertexText);-- // Macros: what the code branches on. A material fixes them (its `defines`), so given those they are baked into the shader as `#define`s and it- // has no switches: one shader per combination a project uses, which is the same set of programs and a shader that can be given a WGSL twin- // (a twin carries a body for every combination of what is left to toggle). Without them they are switches a material turns on.- const found = macrosIn(`${vertexText}\n${body}`);- const ENGINE_FEATURE = /^(?:MESH_NORMALS|MESH_TANGENTS|MESH_LIGHTMAP|MESH_LOCAL_POSITION|GL_ES|CC_[A-Z_]+_ENABLED)$/;- const named = found.switches.filter((m) => !ENGINE_FEATURE.test(m) && !found.compared.includes(m));- const compared = found.compared.filter((m) => !ENGINE_FEATURE.test(m));- let switches: string[] = [];- const baked: string[] = [];- if (defines) {- const value = { ...Object.fromEntries(metaDefaults), ...pass.macros, ...defines } as Record<string, unknown>;- // What the code branches on, and what it merely reads (a channel name a material gives).- const text = `${vertexText}-${body}`;- const used = Object.keys(value).filter((k) => new RegExp(`\\b${k}\\b`).test(text));- for (const m of new Set([...named, ...compared, ...used])) {- const v = value[m];- // Zero is the undefined of Cocos's `#if`, so a name that is not compared is left undefined for it.- if (typeof v === 'string') { if (v !== '0' || compared.includes(m)) baked.push(`#define ${m} ${v}`); continue; }- const n = typeof v === 'number' ? v : v === true ? 1 : 0;- // A name asked as a number has to be defined; a name asked as a switch is defined when it is on.- if (compared.includes(m) || n !== 0) baked.push(`#define ${m} ${n}`);- }- } else {- switches = named;- if (compared.length > 0) approximations.push(`${compared.join(', ')} is compared to a number; the engine's switches are on or off`);- }- // What the engine's vertex stage offers a fragment, which the shader asks for by name so that a twin carries a body for each.- const offered = ['MESH_NORMALS', 'MESH_TANGENTS', 'MESH_LIGHTMAP', 'MESH_LOCAL_POSITION']- .filter((f) => new RegExp(`\\b${f}\\b`).test(`${[...needed].join('\n')}\n${vertexText}\n${body}`));-- const lines: string[] = [- `#pragma shader "${shaderName}"`,- '#pragma version 300 es',- usesPosition ? '#pragma domain Lit' : '#pragma domain Unlit',- ];- for (const f of offered) lines.push(`#pragma feature ${f}`);- for (const s of switches) lines.push(`#pragma switch ${s} default(${pass.macros[s] ? 'on' : 'off'})`);- for (const p of params) {- lines.push(p.type === 'texture'- ? `#pragma param ${p.name} texture default(${p.value})`- : `#pragma param ${p.name} ${p.type} default(${csv(p.value as number[])})`);- }- const main = ['void main() {'];- if (vertex) main.push(...vertex.attributeSetup, ' cocos_vert();');- main.push(' fragColor = cocos_frag();', '}');- lines.push('', '#pragma fragment', 'precision mediump float;', ...baked, '', ...[...needed].filter((n) => !n.startsWith('/*')), '',- ...(usesSpriteTexture ? ['uniform sampler2D u_textures[8];'] : []), 'out vec4 fragColor;', '', PRELUDE,- ...(matrixDefs ? [matrixDefs, ''] : []), ...(flipFallback ? [flipFallback] : []),- ...(vertex ? [vertex.attributes, VERTEX_PRELUDE, vertexText.trim(), ''] : []), body.trim(), '', ...main, '#pragma end', '');- // The displacement, given to the engine as the material's vertex hook: the same program, run on the vertex's own position and normal. The engine's- // vertex stage owns the attribute names, so the program's are its own here.- if (vertex?.displaces) {- const vertexReadsTexture = params.some((p) => p.type === 'texture' && new RegExp(`\\b${p.name}\\b`).test(vertexText));- if (vertexReadsTexture) {- approximations.push('a displacement of the vertex position that reads a texture is not applied');- } else {- const own = (text: string): string => text.replace(/\ba_(\w+)\b/g, 'hook_a_$1');- const extra = [...vertex.attributes.matchAll(/\ba_(texCoord1|uv0)\b/g)].map((m) => ` hook_a_${m[1]} = uv;`);- const hook = [- '#pragma vertexoffset',- ...baked,- '#define cc_time u_time',- ...(matrixDefs ? [matrixDefs] : []),- own(vertex.attributes), own(VERTEX_PRELUDE), own(vertexText.trim()), '',- 'void esMaterialVertex(inout vec3 local, inout vec3 localNormal, in vec2 uv) {',- ' hook_a_position = local; hook_a_normal = localNormal; hook_a_tangent = vec4(1.0, 0.0, 0.0, 1.0); hook_a_texCoord = uv; hook_a_color = es_vertexColor;',- ...extra,- ' local = cocos_vert().xyz;',- '}', '#pragma end', '',- ];- lines.splice(lines.indexOf('#pragma fragment'), 0, ...hook);- }- } else if (vertex && /\bcc_time\b/.test(vertexText) && /\bsin\b|\bcos\b/.test(vertexText)) {- approximations.push('the vertex program computes something of time that the fragment does not reproduce');- }- return { shader: { source: lines.join('\n'), switches, params, approximations }, unsupported: null, state };-}--/**- * Whether a pass draws an outline: a second draw of the mesh pushed out along its normals and shown from behind. It is a way of drawing the mesh, not- * the mesh's own surface, so the pass that is the surface is the one a material is converted from.- */-export function isOutlinePass(pass: EffectPass): boolean {- return /outline/i.test(pass.vert) || /outline/i.test(pass.frag);-}--export interface EffectConversion {- /** Each technique's passes, in order. */- techniques: Array<{ name: string; passes: PassConversion[] }>;-}--/** Convert every pass of an effect. @p stem names the shaders. */-export function convertEffect(effect: CocosEffect, stem: string, options: EffectOptions = {}): EffectConversion {- return {- techniques: effect.techniques.map((t) => ({- name: t.name,- passes: t.passes.map((p, i) => convertPass(effect, p, `${stem}.${t.name}.${i}`, options)),- })),- };-}diff --git a/pipeline/src/import/cocos/effects.ts b/pipeline/src/import/cocos/effects.tsdeleted file mode 100644index 605e51f86..000000000--- a/pipeline/src/import/cocos/effects.ts+++ /dev/null@@ -1,180 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file effects.ts- * @brief Reading a Cocos `.effect` file: its technique/pass/property description and its GLSL programs.- *- * An effect is one text file of two kinds of block: `CCEffect %{ … }%`, YAML describing the techniques, their passes (which program is the- * vertex stage and which the fragment, the blend, depth and cull state) and each pass's properties; and `CCProgram name %{ … }%`, GLSL 3.00- * that the passes name as `program:entry`. The programs `#include <builtin/…>` chunks of the Creator install and declare the uniform blocks- * they read. This reads both into data; turning that into an Estella material is the converter's job (effectConvert.ts), and what an- * effect needs of the renderer, which decides whether it can be converted at all, is {@link describeEffect}.- */-import yaml from 'js-yaml';--export interface EffectProperty {- name: string;- /** The declared default, as written: a number, a vector, or a texture default name (`white`, `grey`, `normal`, …). */- value: unknown;- /** The editor's type for it (`color`, `vector`, …), which tells a colour from a vector. */- editorType: string | null;- /** The uniform (or sampler) the property is stored in, when it says: `target: baseColor.rgb`. */- target: string | null;-}--export interface EffectPass {- /** `program:entry` of each stage as written. */- vert: string;- frag: string;- /** Macro defines the pass fixes (`embeddedMacros`). */- macros: Record<string, unknown>;- blend: unknown;- depthStencil: unknown;- rasterizer: unknown;- /** The pass's phase (`forward-add`, a custom pipeline's name…), which says which part of the frame draws it. */- phase: string | null;- properties: EffectProperty[];- /** The pass is a reference to another effect's pass (`switch`, `pass: builtin-xxx`) rather than its own. */- inherits: string | null;-}--export interface EffectProgram {- name: string;- source: string;-}--export interface CocosEffect {- techniques: Array<{ name: string; passes: EffectPass[] }>;- programs: Map<string, EffectProgram>;-}--const BLOCK = /(CCEffect|CCProgram)\s*([A-Za-z0-9_\-.]*)\s*%\{([\s\S]*?)\}%/g;--/** Read an effect file's blocks. A file with no CCEffect has no techniques. Throws on YAML it cannot read. */-export function parseEffect(text: string): CocosEffect {- const effect: CocosEffect = { techniques: [], programs: new Map() };- for (const m of text.matchAll(BLOCK)) {- const [, kind, name, body] = m;- if (kind === 'CCProgram') { effect.programs.set(name!, { name: name!, source: body! }); continue; }- const doc = yaml.load(body!) as { techniques?: unknown[] } | null;- for (const [i, t] of (doc?.techniques ?? []).entries()) {- const tech = t as { name?: string; passes?: unknown[] };- effect.techniques.push({- name: tech.name ?? `technique${i}`,- passes: (tech.passes ?? []).map((p) => passOf(p as Record<string, unknown>)),- });- }- }- return effect;-}--function passOf(p: Record<string, unknown>): EffectPass {- const props = (p.properties ?? {}) as Record<string, unknown>;- return {- vert: String(p.vert ?? ''),- frag: String(p.frag ?? ''),- macros: (p.embeddedMacros ?? {}) as Record<string, unknown>,- blend: p.blendState ?? null,- depthStencil: p.depthStencilState ?? null,- rasterizer: p.rasterizerState ?? null,- phase: typeof p.phase === 'string' ? p.phase : null,- inherits: typeof p.switch === 'string' ? p.switch : typeof p.pass === 'string' ? p.pass : null,- properties: Object.entries(props).map(([name, def]) => {- const d = (def ?? {}) as { value?: unknown; editor?: { type?: string }; target?: string };- return { name, value: d.value ?? null, editorType: d.editor?.type ?? null, target: d.target ?? null };- }),- };-}--// ----------------------------------------------------------------------------// What an effect asks of the renderer-// -----------------------------------------------------------------------------export interface EffectFacts {- passes: number;- techniques: number;- phases: string[];- /** `builtin/…` and `common/…` chunks the programs include. */- includes: string[];- /** The Cocos uniform blocks and built-in uniforms the shader code reads (`cc_time`, `cc_matWorld`, …). */- builtinUniforms: string[];- /** The vertex attributes the vertex program reads. */- attributes: string[];- samplers: number;- properties: number;- /** Macros the programs branch on (`#if USE_TEXTURE`). */- macros: string[];- /** Reads the frame behind it, or the depth: not a function of the object alone. */- readsFrame: boolean;- readsDepth: boolean;- /** Uses the scene's lights or shadows: needs what the renderer's lighting provides. */- usesLighting: boolean;- usesShadow: boolean;- skinned: boolean;- instanced: boolean;- /** What kind of thing it draws, by its stages: a sprite/UI quad, a mesh, a particle, a screen pass. */- kind: 'sprite' | 'mesh' | 'particle' | 'screen' | 'other';-}--const unique = (xs: Iterable<string>): string[] => [...new Set(xs)].sort();--/**- * The macros a program branches on: every name in an `#if`, `#elif`, `#ifdef` or `#ifndef`, wherever it stands in the expression. A name a number- * is compared with (`LEVEL == 2`) is in the second list, since a switch cannot say it.- */-export function macrosIn(source: string): { switches: string[]; compared: string[] } {- const switches = new Set<string>(), compared = new Set<string>();- const code = source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '');- for (const m of code.matchAll(/^[ \t]*#[ \t]*(if|elif|ifdef|ifndef)\b(.*)$/gm)) {- const expr = m[2]!.replace(/\bdefined\b/g, ' ');- for (const t of expr.matchAll(/\b([A-Z][A-Z0-9_]+)\b(\s*(?:==|!=|<=|>=|<|>))?/g)) {- (t[2] ? compared : switches).add(t[1]!);- }- }- return { switches: [...switches].sort(), compared: [...compared].sort() };-}--/** The facts about one effect that decide how it can be taken across. Reads the passes' programs, not their names. */-export function describeEffect(effect: CocosEffect, file = ''): EffectFacts {- const passes = effect.techniques.flatMap((t) => t.passes);- const stageNames = new Set<string>();- const vertNames = new Set<string>();- for (const p of passes) {- for (const ref of [p.vert, p.frag]) if (ref) stageNames.add(ref.split(':')[0]!);- if (p.vert) vertNames.add(p.vert.split(':')[0]!);- }- const source = [...stageNames].map((n) => effect.programs.get(n)?.source ?? '').join('\n');- const vertSource = [...vertNames].map((n) => effect.programs.get(n)?.source ?? '').join('\n');- const includes = [...source.matchAll(/#include\s*<([^>]+)>/g)].map((m) => m[1]!);- const builtinUniforms = [...source.matchAll(/\b(cc_[A-Za-z0-9_]+)\b/g)].map((m) => m[1]!);- const attributes = [...vertSource.matchAll(/^\s*in\s+(?:highp\s+|mediump\s+|lowp\s+)?\w+\s+(a_\w+)/gm)].map((m) => m[1]!);- const macros = macrosIn(source).switches;- const samplers = [...source.matchAll(/uniform\s+(?:highp\s+|mediump\s+|lowp\s+)?sampler\w+\s+\w+/g)].length;- const has = (re: RegExp): boolean => re.test(source);- const lower = file.toLowerCase();- const attrs = new Set(attributes);- let kind: EffectFacts['kind'] = 'other';- if (/particle|trail/.test(lower) || attrs.has('a_dir') || attrs.has('a_texCoord1')) kind = 'particle';- else if (attrs.has('a_normal') || attrs.has('a_tangent') || attrs.has('a_joints')) kind = 'mesh';- else if (/bloom|post|blur|screen/.test(lower) || has(/cc_screenSize|cc_spriteTexture.*RT/)) kind = 'screen';- else if (attrs.has('a_position') && attrs.has('a_texCoord') && attrs.has('a_color')) kind = 'sprite';- else if (attrs.has('a_position')) kind = 'mesh';- return {- passes: passes.length,- techniques: effect.techniques.length,- phases: unique(passes.map((p) => p.phase).filter((x): x is string => !!x)),- includes: unique(includes),- builtinUniforms: unique(builtinUniforms),- attributes: unique(attributes),- samplers,- properties: passes.reduce((n, p) => n + p.properties.length, 0),- macros: unique(macros),- readsFrame: has(/cc_gbuffer|cc_(?:grab|screen)Tex|SAMPLE_FROM_RT|frameBuffer|sceneColor/i),- readsDepth: has(/cc_depth|depthTex|cc_gbufferDepth/i),- usesLighting: includes.some((i) => /lighting|cc-forward-light|shading|pbr|standard-surface/i.test(i)) || has(/cc_mainLitDir|CCStandardShading|CCToon/),- usesShadow: includes.some((i) => /shadow/i.test(i)) || has(/cc_shadow|CC_RECEIVE_SHADOW/),- skinned: attrs.has('a_joints') || has(/CCSkin|USE_SKINNING/),- instanced: has(/USE_INSTANCING|a_matWorld0/),- kind,- };-}diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.tsdeleted file mode 100644index c07da729e..000000000--- a/pipeline/src/import/cocos/importProject.ts+++ /dev/null@@ -1,1192 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file Take a Cocos Creator 3.x project into an Estella project, without- * touching it.- *- * The source is only ever read. Output goes under `<out>/assets/cocos/`,- * keeping the source's folder layout so a path in one is findable in the- * other. Only what the converted documents reference is copied.- */-import { createHash } from 'node:crypto';-import { decodePngImage } from '../../assets/atlasPacker';-import { copyFileSync, existsSync, linkSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs';-import path from 'node:path';-import { pathToFileURL } from 'node:url';-import { isInsideRoot } from '../../fs/pathSandbox';-import { buildScriptIndex } from './scripts';-import { buildCocosAssetIndex, cocosEditorAssets, INTERNAL_FOLDER, type CocosAssetEntry, type CocosAssetIndex } from './assets';-import type { AssetHints, SliceBorder } from './components';-import { convertPrefab, convertScene, type ConvertContext } from './convert';-import { parseCocosDocument, type CocosDocument } from './document';-import { ImportReport, type ImportReportData } from './report';-import { CocosModels, clipOf, clipPlayOf, mintSidecar, retargetClip } from './models';-import { convertAnimationClip } from './animationClip';-import { convertAnimationGraph } from './animationGraph';-import type { MaterialInfo } from './components';-import { parseEffect, type CocosEffect, type EffectPass } from './effects';-import { convertPass, isOutlinePass, type PassConversion } from './effectConvert';-import { dominantAmbient } from './sceneAmbient';-import { OUTLINE_SHADER } from './outlineShader';--/**- * The revision of what an import writes. It is recorded in the state file; a converted project whose record is older was written by an- * importer that made less (or differently), and is brought up to date when it is opened. Raise it when the converted output changes in a- * way an existing project needs to pick up: a new generated file, a field a document or a manifest now carries.- */-export const COCOS_IMPORT_REVISION = 28;--/** Whether the project at @p projectRoot was written by an importer of this revision. A project that was not converted has nothing to bring up. */-export function cocosImportIsCurrent(projectRoot: string): boolean {- try {- const state = JSON.parse(readFileSync(path.join(projectRoot, 'assets', 'cocos', '.import-state.json'), 'utf8')) as { revision?: unknown };- return state.revision === COCOS_IMPORT_REVISION;- } catch {- return true;- }-}--export interface CocosImportOptions {- /** The Cocos project folder (the one holding `assets/` and `settings/`). */- source: string;- /** The Estella project folder to write into. */- out: string;- /** Convert only documents whose path under `assets/` starts with one of these; prefabs they use follow. */- only?: string[];- /** Parse and convert but write nothing. */- dryRun?: boolean;- /** Folder under the project's `assets/` that receives everything. */- into?: string;- /** Told how far along the import is, so a long one can show it. */- onProgress?: (p: CocosImportProgress) => void;-}--/** Where an import is: the step it is in and how many of that step's items are done. */-export interface CocosImportProgress {- stage: 'index' | 'shaders' | 'prefabs' | 'scenes' | 'textures' | 'finish';- done: number;- total: number;- /** The document or asset being worked on, when there is one. */- item?: string;-}--const norm = (p: string): string => p.split(path.sep).join('/');--function* walk(dir: string): Generator<string> {- let entries;- try {- entries = readdirSync(dir, { withFileTypes: true });- } catch {- return;- }- for (const e of entries) {- if (e.isDirectory()) yield* walk(path.join(dir, e.name));- else yield path.join(dir, e.name);- }-}--/** A shader's source without the WGSL twin derived into it: the part the importer wrote. */-function withoutDerivedTwin(source: string): string {- return source- .replace(/\n?#pragma (?:vertex|fragment) wgsl full\n[\s\S]*?#pragma end\n?/g, '\n')- .replace(/\n?#pragma vertexoffset wgsl\n\/\/ GENERATED[\s\S]*?#pragma end\n?/g, '\n');-}--/**- * Whether a PNG keeps its colour under a clear alpha: most of its texels are clear and carry colour all the same. That is a texture that holds numbers in- * its channels (a weight map the ground is mixed by), not a picture, and compressing it, or reading its colour as sRGB, wrecks it: a cook that encodes a- * texture is free to forget what is under alpha 0.- */-export function hidesColorUnderClearAlpha(file: string): boolean {- try {- const bytes = readFileSync(file);- // IHDR: colour type 4 (grey + alpha) and 6 (RGBA) are the ones with an alpha channel- if (bytes.length < 26 || bytes.toString('latin1', 1, 4) !== 'PNG' || (bytes[25] !== 4 && bytes[25] !== 6)) return false;- const image = decodePngImage(file, new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength));- // only one that spans a map: a weight map covers a ground, while the effects' masks and sheets that are clear and coloured are a particle's, and keep what they were- if (Math.max(image.width, image.height) < 2048) return false;- let clear = 0, coloured = 0, solid = 0;- const hues = new Set<number>();- const step = Math.max(1, Math.floor(image.rgba.length / 4 / 65536));- let sampled = 0;- for (let i = 0; i < image.rgba.length; i += 4 * step) {- sampled++;- if (image.rgba[i + 3]! === 255) solid++;- if (image.rgba[i + 3]! !== 0) continue;- clear++;- if (image.rgba[i]! + image.rgba[i + 1]! + image.rgba[i + 2]! > 0) {- coloured++;- hues.add(((image.rgba[i]! >> 4) << 8) | ((image.rgba[i + 1]! >> 4) << 4) | (image.rgba[i + 2]! >> 4));- }- }- // a painter leaves one colour under a background (white, black); numbers are laid out in several- // and nothing is drawn: a sprite has a body that shows, a picture of numbers has next to none- return sampled > 0 && clear / sampled > 0.5 && solid / sampled < 0.02 && coloured / sampled > 0.1 && hues.size >= 4;- } catch {- return false;- }-}--function writeOut(file: string, text: string): void {- mkdirSync(path.dirname(file), { recursive: true });- writeFileSync(file, text);-}--/**- * A bitmap font is a .fnt that names its glyph pages; they sit beside it and must travel with it. Each page gets a- * `.meta` that keeps it at full size: the default cap (2048) would halve a 4096 page, and glyphs drawn from half the- * pixels they were drawn with are soft and fringed. Glyph UVs are fractions of the page, so only the sharpness suffers,- * never the placement — which is why nothing else notices.- */-function copyFontPages(fnt: string, dest: string, uuidFor: (pageFile: string) => string | undefined): void {- const text = readFileSync(fnt, 'utf8');- const common = /\bcommon\b[^\n]*/.exec(text)?.[0] ?? '';- const side = Math.max(Number(/\bscaleW=(\d+)/.exec(common)?.[1]) || 0, Number(/\bscaleH=(\d+)/.exec(common)?.[1]) || 0);- let maxSize = 256;- while (maxSize < side && maxSize < 8192) maxSize *= 2;- for (const m of text.matchAll(/file="([^"]+)"/g)) {- const page = path.join(path.dirname(fnt), m[1]!);- if (!existsSync(page)) continue;- const to = path.join(path.dirname(dest), m[1]!);- placeFile(page, to);- const uuid = uuidFor(page);- if (uuid) {- const meta = {- uuid, version: '2.0', type: 'texture',- importer: { maxSize: Math.max(2048, maxSize), filterMode: 'linear', wrapMode: 'clamp', premultiplyAlpha: false },- };- writeOut(`${to}.meta`, `${JSON.stringify(meta, null, 2)}\n`);- }- }-}--/**- * The `.fnt`, with its `common` line saying what the page holds, in the channel flags BMFont defines for it: glyph in red (`redChnl=0`), glyph and- * outline in alpha (`alphaChnl=2`). That is how the engine knows to draw it in two passes, and it is what a real BMFont export of such a page says.- */-function declareBakedOutline(fnt: string): string {- return fnt.replace(/^(\s*common\b[^\r\n]*?)(\r?\n|$)/m, (line, head: string, eol: string) => (- /\balphaChnl=/.test(head) ? line : `${head} alphaChnl=2 redChnl=0 greenChnl=0 blueChnl=0${eol}`- ));-}--/**- * A source file, in the project. Left alone when it is already there as it was, otherwise a hard link to it (instant, and a multi-gigabyte art- * folder is not stored twice), and where the two folders are on different drives a copy that keeps the source's modification time, so the next- * import can tell it is unchanged. Nothing here ever writes into the file: the project reads it, and writes its settings beside it.- */-function placeFile(from: string, to: string): void {- const source = statSync(from);- const there = (() => { try { return statSync(to); } catch { return null; } })();- if (there && there.ino !== 0 && there.ino === source.ino && there.dev === source.dev) return;- // linked beside the destination and moved over it, so a file system that cannot link leaves what was there untouched- const staged = `${to}.linking`;- try {- rmSync(staged, { force: true });- linkSync(from, staged);- renameSync(staged, to);- return;- } catch {- rmSync(staged, { force: true }); // another drive, or a file system without links- }- if (there && there.size === source.size && Math.abs(there.mtimeMs - source.mtimeMs) < 2) return;- copyFileSync(from, to);- utimesSync(to, source.atime, source.mtime);-}--/**- * The scripts whose class was given another name than it wrote (two scripts wrote the same `@ccclass` name) — all of them, not only the ones a scene- * uses, since a script is loaded by whatever imports it — by the path the entry requires them- * at. The bundler reads this beside the entry and writes the new name into the decorator, so the component a scene names is the class it means.- */-function writeClassNames(out: string, entry: string, assetsDir: string, scripts: Map<string, { name: string; rel: string; wrote?: string }>): void {- const names: Record<string, { from: string; to: string }> = {};- for (const cls of scripts.values()) {- if (!cls.wrote) continue;- const target = path.join(assetsDir, cls.rel.replace(/\.(ts|js)$/, ''));- names[path.relative(path.dirname(entry), target).split(path.sep).join('/')] = { from: cls.wrote, to: cls.name };- }- const file = path.join(out, 'src', 'cocos-class-names.json');- if (Object.keys(names).length > 0) writeOut(file, JSON.stringify(names, null, 2) + '\n');- else rmSync(file, { force: true });-}--/** The scene a Cocos game starts in: its launch scene when there is one, else a scene named main at the top. */-function startSceneOf(scenes: readonly string[]): string | undefined {- const find = (re: RegExp): string | undefined => scenes.find((r) => re.test(r));- return find(/(^|\/)launch\/main\.scene$/) ?? find(/(^|\/)launch\/[^/]+\.scene$/) ?? find(/^main\.scene$/);-}--/**- * The engine's shader tools as a check on one converted shader: it compiles every combination of what the shader leaves to toggle, in GLSL (glslang)- * and as the WGSL twin the WebGPU backend runs. Null where the tools are not here (anywhere but a checkout of the engine with a built wasm), and the- * conversion then goes unchecked. The module is named by a path held in a variable so that the bundlers leave it and its wasm alone.- */-let shaderChecking: Promise<((source: string) => Promise<string | null>) | null> | undefined;-function shaderChecker(): Promise<((source: string) => Promise<string | null>) | null> {- shaderChecking ??= (async () => {- try {- // Beside the package when it runs from source, or from the bin that started a bundled run of it (the command line bundles the importer into a- // temporary folder), or where ESTELLA_TOOLS says.- const candidates = [- '../../../../tools/gen-shader-twins.mjs',- ...(process.argv[1] ? [pathToFileURL(path.resolve(path.dirname(process.argv[1]), '..', '..', 'tools', 'gen-shader-twins.mjs')).href] : []),- ...(process.env.ESTELLA_TOOLS ? [pathToFileURL(path.join(process.env.ESTELLA_TOOLS, 'gen-shader-twins.mjs')).href] : []),- ];- let loaded: unknown = null;- for (const specifier of candidates) {- try { loaded = await import(/* @vite-ignore */ specifier); break; } catch { /* the next */ }- }- if (!loaded) return null;- const tool = loaded as {- loadTwinModule(): Promise<unknown>;- deriveTwin(module: unknown, source: string, opts: object): Promise<{ status: string }>;- };- const module = await tool.loadTwinModule();- return async (source: string) => {- try {- const derived = await tool.deriveTwin(module, source, {});- // More toggles than a twin may carry is no error of the shader's: it runs on WebGL.- return derived.status === 'generated' || derived.status === 'has-twin' || derived.status.startsWith('skipped') ? null : derived.status;- } catch (err) {- return String((err as Error).message ?? err).split('\n').filter((l) => /ERROR|error|failed/.test(l)).slice(0, 2).join(' ').trim().slice(0, 240) || 'it could not be translated';- }- };- } catch {- return null;- }- })();- return shaderChecking;-}--/** The design resolution a Cocos project declares, which is the box its screen-pinned roots are placed in. */-function designSizeOf(source: string): { width: number; height: number } | undefined {- try {- const settings = JSON.parse(readFileSync(path.join(source, 'settings', 'v2', 'packages', 'project.json'), 'utf8')) as { general?: { designResolution?: { width?: number; height?: number } } };- const size = settings.general?.designResolution;- return size?.width && size.height ? { width: size.width, height: size.height } : undefined;- } catch { return undefined; }-}--/**- * Make the converted project start where the Cocos game does: the starter project opens its own empty scene and an 800x600 design size, so- * playing it shows nothing of the game. Only a manifest still carrying the starter's values is changed; one the creator edited is theirs.- */-function wireManifest(out: string, source: string, into: string, scenes: readonly string[]): void {- const file = path.join(out, 'project.esproject');- let manifest: { defaultScene?: string; designResolution?: { width?: number; height?: number }; features?: { rendering?: { cameraScaleMode?: string } } };- try {- manifest = JSON.parse(readFileSync(file, 'utf8'));- } catch {- return;- }- let changed = false;- const start = startSceneOf(scenes);- if (start && manifest.defaultScene === 'assets/scenes/main.esscene') {- manifest.defaultScene = `assets/${into}/${start.replace(/\.scene$/, '.esscene')}`;- changed = true;- }- try {- const settings = JSON.parse(readFileSync(path.join(source, 'settings', 'v2', 'packages', 'project.json'), 'utf8')) as { general?: { designResolution?: { width?: number; height?: number; fitWidth?: boolean; fitHeight?: boolean } } };- const size = settings.general?.designResolution;- // Fit width (and not height) keeps the design width across the screen and lets the height follow the window: Cocos's FIXED_WIDTH, which is what- // a UI laid out in design units needs to come out the same size on every screen.- const fit = size?.fitWidth && !size.fitHeight ? 'fixed-width' : size?.fitHeight && !size.fitWidth ? 'fixed-height' : undefined;- if (fit && !manifest.features?.rendering?.cameraScaleMode) {- manifest.features = { ...manifest.features, rendering: { ...manifest.features?.rendering, cameraScaleMode: fit } };- changed = true;- }- const dr = manifest.designResolution;- if (size?.width && size.height && (!dr || (dr.width === 800 && dr.height === 600))) {- manifest.designResolution = { width: size.width, height: size.height };- changed = true;- }- } catch { /* a project with no settings keeps the starter's size */ }- if (changed) writeOut(file, JSON.stringify(manifest, null, 2) + '\n');-}--/** A top-level assignment to a global: `globalThis.x = …`, `window.x = …` or `window['x'] = …`. */-const GLOBAL_DEFINITION = /^(?:globalThis|window)(?:\.\w+|\[['"]\w+['"]\])\s*=/m;--/** The scripts that define globals at their top level, in path order. */-function globalDefiningScripts(assets: CocosAssetIndex): string[] {- const found: string[] = [];- for (const entry of assets.byUuid.values()) {- if (!/\.(ts|js)$/.test(entry.rel) || entry.rel.endsWith('.d.ts')) continue;- if (entry.importer !== 'typescript' && entry.importer !== 'javascript') continue;- try {- if (GLOBAL_DEFINITION.test(readFileSync(entry.file, 'utf8'))) found.push(entry.rel);- } catch { /* unreadable: not one */ }- }- return found.sort();-}--/**- * A document the creator edited is left as it is, but it was written when a Cocos widget was a component of the compatibility layer- * (`Cocos.Widget`), and is now the engine's `RectAnchors`: the same fields, under the engine's name. Only that name changes, in place;- * everything the creator did to the document stays. Answers whether the document held one.- */-function migrateWidgets(file: string): boolean {- let text: string;- try { text = readFileSync(file, 'utf8'); } catch { return false; }- if (!text.includes('"Cocos.Widget"')) return false;- let changed = false;- const walk = (v: unknown): void => {- if (Array.isArray(v)) { v.forEach(walk); return; }- if (typeof v !== 'object' || v === null) return;- const o = v as Record<string, unknown>;- if (o.type === 'Cocos.Widget') {- o.type = 'RectAnchors';- if (typeof o.data === 'object' && o.data !== null) delete (o.data as Record<string, unknown>).target;- changed = true;- }- Object.values(o).forEach(walk);- };- let doc: unknown;- try { doc = JSON.parse(text); } catch { return false; }- walk(doc);- if (changed) writeOut(file, JSON.stringify(doc, null, 2) + '\n');- return changed;-}--const GENERATED = 'Generated by import-cocos';--/** A default for a field, of the kind its sample is: what the editor shows before anything is typed. */-function defaultLike(sample: unknown): unknown {- if (typeof sample === 'number') return 0;- if (typeof sample === 'string') return '';- if (typeof sample === 'boolean') return false;- if (Array.isArray(sample)) return [];- return null;-}--/**- * Make the converted project run and open in the editor as converted. `src/components.ts` is the entry the editor reads component schemas- * from without running the project: it gets the compatibility layer's own components, and one declaration for each script class the- * scenes use, with the fields they carry. `src/main.ts` starts the project, so it loads the scripts themselves (which declare the real- * classes) and not those declarations. Both files are rewritten only while they are still what the starter project or this import wrote:- * once the creator has edited one, it is theirs.- */-function wireProjectEntries(out: string, scriptFields: Map<string, Map<string, unknown>>): void {- const read = (file: string): string | null => { try { return readFileSync(file, 'utf8'); } catch { return null; } };- const components = path.join(out, 'src', 'components.ts');- const current = read(components);- if (current === null || current.includes(GENERATED) || /^(\s*\/\/[^\n]*\n)*\s*export \{\};?\s*$/.test(current)) {- const lines = [- `// ${GENERATED}. The editor reads component schemas from this file without running the project.`,- "// The Cocos compatibility layer's own components, and the script classes the converted scenes use, with the fields they carry.",- "// Running the project loads the scripts themselves (src/cocos-scripts.ts); these declarations are for the editor only.",- "import { defineComponent } from 'esengine';",- "import 'esengine/cocos';", '',- ];- for (const [name, fields] of [...scriptFields].sort((a, b) => a[0].localeCompare(b[0]))) {- const body = ['enabled: true', ...[...fields].filter(([k]) => k !== 'enabled').sort((a, b) => a[0].localeCompare(b[0]))- .map(([k, v]) => `${JSON.stringify(k)}: ${JSON.stringify(defaultLike(v))}`)];- lines.push(`defineComponent(${JSON.stringify(name)}, { ${body.join(', ')} });`);- }- writeOut(components, `${lines.join('\n')}\n`);- }- const main = path.join(out, 'src', 'main.ts');- const text = read(main);- if (text !== null && !text.includes('cocos-scripts') && /^import '\.\/components';\s*$/m.test(text)) {- writeOut(main, text.replace(/^import '\.\/components';\s*$/m, "// The converted Cocos scripts (the editor reads src/components.ts instead).\nimport './cocos-scripts';"));- }-}--export async function importCocosProject(opts: CocosImportOptions): Promise<ImportReportData> {- const source = path.resolve(opts.source);- const out = path.resolve(opts.out);- if (out === source || isInsideRoot(source, out)) {- throw new Error('the output project must not be inside the Cocos project: the source is never written to');- }- const assetsDir = path.join(source, 'assets');- if (!existsSync(assetsDir)) throw new Error(`no assets folder in ${source}: is this a Cocos Creator project?`);- const into = opts.into ?? 'cocos';-- const report = new ImportReport();- const progress = (stage: CocosImportProgress['stage'], done: number, total: number, item?: string): void => opts.onProgress?.({ stage, done, total, ...(item ? { item } : {}) });- progress('index', 0, 1);- const version = (() => { try { return (JSON.parse(readFileSync(path.join(source, 'package.json'), 'utf8')) as { creator?: { version?: string } }).creator?.version; } catch { return undefined; } })();- const editorAssets = cocosEditorAssets(version);- const index = buildCocosAssetIndex(assetsDir, editorAssets);-- const outRef = (assetRel: string): string => `assets/${into}/${assetRel}`;- const esRel = (assetRel: string, ext: string): string => assetRel.replace(/\.[^./]+$/, ext);-- const textures = new Map<string, { entry: CocosAssetEntry; slice?: SliceBorder; hints?: AssetHints }>();- /** The textures a converted material samples: a sprite's picture is never read as numbers, so only these can be data. */- const materialTextures = new Set<string>();- const docs = new Map<string, CocosDocument | null>();- const pending: string[] = [];- const queued = new Set<string>();-- const prefabEntry = (uuid: string): CocosAssetEntry | null => {- const e = index.byUuid.get(uuid);- return e && e.rel.endsWith('.prefab') ? e : null;- };- const loadDoc = (e: CocosAssetEntry): CocosDocument | null => {- if (docs.has(e.file)) return docs.get(e.file) ?? null;- let doc: CocosDocument | null = null;- try {- doc = parseCocosDocument(JSON.parse(readFileSync(e.file, 'utf8')), path.basename(e.rel).replace(/\.[^.]+$/, ''));- } catch (err) {- report.documents.failed.push({ file: e.rel, error: (err as Error).message });- }- docs.set(e.file, doc);- return doc;- };-- const models = new CocosModels(index, out, into, opts.dryRun === true);- const clips = new Map<string, string | null>();- const spines = new Map<string, { skeleton: string; atlas: string } | null>();- const scripts = buildScriptIndex(index);- /** The scripts a converted document refers to, which the project has to bundle for those components to exist. */- const usedScripts = new Set<string>();- /** The component each script class became, and the fields its instances carry: what the editor needs to show them without running the script. */- const scriptFields = new Map<string, Map<string, unknown>>();- const collectScriptFields = (doc: unknown): void => {- const walk = (v: unknown): void => {- if (Array.isArray(v)) { v.forEach(walk); return; }- if (typeof v !== 'object' || v === null) return;- const o = v as Record<string, unknown>;- if (typeof o.type === 'string' && o.type.startsWith('Cocos.') && typeof o.data === 'object' && o.data !== null && scriptNames.has(o.type)) {- const fields = scriptFields.get(o.type) ?? new Map<string, unknown>();- for (const [k, x] of Object.entries(o.data as Record<string, unknown>)) if (!fields.has(k) || fields.get(k) == null) fields.set(k, x);- scriptFields.set(o.type, fields);- }- Object.values(o).forEach(walk);- };- walk(doc);- };- const scriptNames = new Set<string>();- const ctx: ConvertContext = {- assets: index,- design: designSizeOf(source),- scriptClass: (classId) => {- const found = scripts.get(classId);- if (found) { usedScripts.add(found.rel); scriptNames.add(`Cocos.${found.name}`); }- return found;- },- prefabAssetRef: (uuid) => ctx.prefabRef(uuid),- report,- where: '',- assetRef(entry, slice, hints) {- const prev = textures.get(entry.file);- const merged = slice ?? prev?.slice;- // A font any label draws as two layers is declared so; the declaration is about the page, not the label.- const bakedOutline = hints?.bakedOutline === true || prev?.hints?.bakedOutline === true;- textures.set(entry.file, {- entry,- ...(merged ? { slice: merged } : {}),- ...(bakedOutline ? { hints: { bakedOutline: true } } : {}),- });- return outRef(entry.rel);- },- drawsBakedOutline(materialUuid) {- return materialBakesOutline(materialUuid);- },- material(materialUuid) {- return materialInfo(materialUuid);- },- convertedMaterial(materialUuid) {- return convertedMaterial(materialUuid);- },- modelInstance(uuid) {- const m = models.use(uuid);- if (!m || !m.use.prefab) return null;- const parts = new Map<string, string>();- for (const [fileId, name] of models.partsOf(m.entry)) {- const id = m.use.renderers.get(name);- if (id !== undefined) parts.set(fileId, id);- }- return { prefab: m.use.prefab, rootId: m.use.rootId, name: path.basename(m.entry.rel).replace(/\.[^.]+$/, ''), paths: m.use.paths, parts };- },- modelSkin(meshUuid) {- const m = models.use(meshUuid);- if (!m) return null;- const name = models.meshName(m.entry, meshUuid);- const own = name ? m.use.skin.get(name) : undefined;- if (own) return own;- return m.use.skin.size === 1 ? [...m.use.skin.values()][0]! : null;- },- spineAssets(uuid) {- const entry = index.byUuid.get(uuid);- if (!entry || !/\.(skel|json)$/i.test(entry.rel)) return null;- const key = entry.file;- if (spines.has(key)) return spines.get(key) ?? null;- let found: { skeleton: string; atlas: string } | null = null;- try {- const dir = path.dirname(entry.file);- const stem = path.basename(entry.file).replace(/\.[^.]+$/, '');- const atlasFile = readdirSync(dir).find((f) => f.toLowerCase() === `${stem.toLowerCase()}.atlas`) ?? readdirSync(dir).find((f) => f.toLowerCase().endsWith('.atlas'));- if (atlasFile) {- const toRef = (name: string): string => outRef(norm(path.relative(assetsDir, path.join(dir, name))));- // the images the atlas names (a page is a line that ends in an image extension) travel with it- const pages = readFileSync(path.join(dir, atlasFile), 'utf8').split(/\r?\n/).map((l) => l.trim()).filter((l) => /\.(png|jpg|jpeg|webp)$/i.test(l));- if (!opts.dryRun) {- for (const name of [path.basename(entry.file), atlasFile, ...pages]) {- const from = path.join(dir, name);- if (!existsSync(from)) continue;- const to = path.join(out, toRef(name));- mkdirSync(path.dirname(to), { recursive: true });- placeFile(from, to);- mintSidecar(to);- }- }- found = { skeleton: toRef(path.basename(entry.file)), atlas: toRef(atlasFile) };- }- } catch {- found = null;- }- spines.set(key, found);- return found;- },- animationClip(clipUuid, where) {- const entry = index.byUuid.get(clipUuid.split('@')[0]!);- if (!entry || !entry.rel.endsWith('.anim')) return null;- const rel = outRef(esRel(entry.rel, '.estimeline'));- if (clips.has(entry.file)) return clips.get(entry.file) ?? null;- let ref: string | null = null;- try {- const converted = convertAnimationClip(JSON.parse(readFileSync(entry.file, 'utf8')));- for (const [what, count] of converted.skipped) report.note('animation-track-unsupported', `${entry.rel}: ${what} ×${count}`);- if (converted.events > 0) report.note('animation-events-dropped', `${entry.rel}: ${converted.events}`);- write(rel, converted.document);- if (!opts.dryRun) mintSidecar(path.join(out, rel));- ref = rel;- } catch (err) {- report.note('animation-clip-unreadable', `${where}: ${entry.rel}: ${(err as Error).message}`);- }- clips.set(entry.file, ref);- return ref;- },- animatorController(graphUuid, paths, where) {- const entry = index.byUuid.get(graphUuid.split('@')[0]!);- if (!entry || !entry.rel.endsWith('.animgraph')) return null;- let ref: string | null = null;- let complete = true;- try {- let onModel = false;- const converted = convertAnimationGraph(JSON.parse(readFileSync(entry.file, 'utf8')), {- clip: (uuid) => {- const own = ctx.animationClip?.(uuid, where);- if (own) return own;- onModel = true;- return ctx.clipOn?.(uuid, paths, where) ?? null;- },- note: (code) => {- report.note(code, `${where}: ${entry.rel}`);- if (code !== 'graph-transition-to-exit') complete = false;- },- });- // a graph that plays a model's clips is written for the skeleton it is put on- const key = createHash('sha1').update(JSON.stringify([...paths].sort())).digest('hex').slice(0, 8);- const rel = outRef(esRel(entry.rel, onModel ? `__${key}.esanimator` : '.esanimator'));- write(rel, converted.document);- if (!opts.dryRun) mintSidecar(path.join(out, rel));- ref = rel;- } catch (err) {- report.note('animation-graph-unreadable', `${where}: ${entry.rel}: ${(err as Error).message}`);- }- return ref ? { ref, complete } : null;- },- clipOn(clipUuid, paths, where) {- const clip = models.use(clipUuid);- if (!clip) return null;- const sub = clip.entry.subs.get(clipUuid);- const ref = clipOf(clip.use, sub?.name);- if (!ref) return null;- if (opts.dryRun) return ref;- const key = createHash('sha1').update(JSON.stringify([...paths].sort())).digest('hex').slice(0, 8);- // a node with no bones of its own (a prefab that only holds a clip) gets the clip as it was written- const copy = retargetClip(out, ref, paths, key, clipPlayOf(sub?.userData)) ?? (paths.size === 0 ? retargetClip(out, ref, null, 'free', clipPlayOf(sub?.userData)) : null);- if (!copy) {- report.note('animation-no-matching-bones', where);- return null;- }- if (copy.dropped > 0) report.note('animation-tracks-dropped', `${where}: ${copy.dropped}`);- return copy.ref;- },- modelMesh(uuid) {- const m = models.use(uuid);- if (!m) return null;- const name = models.meshName(m.entry, uuid);- const hit = name ? m.use.byEntity.get(name) : undefined;- const renderers = (hit ?? []).filter((c) => c.type === 'MeshRenderer');- if (renderers.length > 0) return { components: renderers.map((c) => structuredClone(c.data) as Record<string, unknown>), exact: true };- // a mesh's name can be in any language and any state of repair, but its place in the file is a number: the engine names the parts of a- // model with several meshes `<stem>_<mesh>_<primitive>`- const gltfIndex = m.entry.subs.get(uuid)?.userData.gltfIndex;- if (typeof gltfIndex === 'number') {- const wanted = new RegExp(`_${gltfIndex}_\\d+\\.esmesh$`);- const byIndex = [...m.use.byEntity.values()].flat().filter((c) => c.type === 'MeshRenderer' && typeof (c.data as { mesh?: unknown }).mesh === 'string' && wanted.test((c.data as { mesh: string }).mesh));- if (byIndex.length > 0) return { components: byIndex.map((c) => structuredClone(c.data) as Record<string, unknown>), exact: true };- }- // a model with one drawn part has no other mesh a node could mean- const all = [...m.use.byEntity.values()].flat().filter((c) => c.type === 'MeshRenderer');- return all.length === 1 ? { components: [structuredClone(all[0]!.data) as Record<string, unknown>], exact: true } : null;- },- loadPrefab(uuid) {- const e = prefabEntry(uuid);- return e ? loadDoc(e) : null;- },- prefabRef(uuid) {- const model = models.use(uuid);- if (model?.use.prefab) return model.use.prefab;- const e = prefabEntry(uuid);- if (!e) return null;- if (!queued.has(e.rel)) {- queued.add(e.rel);- pending.push(e.rel);- }- return outRef(esRel(e.rel, '.esprefab'));- },- };-- // What a material draws and how: its main texture (a sub-asset of an image), its tint, and the state it sets.- const BUILTIN_EFFECTS = new Set(['a3cd009f-0ab0-420d-9278-b9fdab939bbc', '1baf0fc9-befa-459c-8bdd-af1a450a0319']); // builtin-standard, builtin-unlit- const BUILTIN_UNLIT = '1baf0fc9-befa-459c-8bdd-af1a450a0319';- const materials = new Map<string, MaterialInfo | null>();- const colorOf = (v: unknown): { r: number; g: number; b: number; a: number } | undefined => {- if (typeof v !== 'object' || v === null) return undefined;- const o = v as Record<string, unknown>;- const n = (x: unknown, d: number): number => (typeof x === 'number' && Number.isFinite(x) ? x : d);- // a Color is 0..255 by r g b a; a Vec4 is 0..1 by x y z w- if ('r' in o) return { r: n(o.r, 255) / 255, g: n(o.g, 255) / 255, b: n(o.b, 255) / 255, a: n(o.a, 255) / 255 };- if ('x' in o) return { r: n(o.x, 1), g: n(o.y, 1), b: n(o.z, 1), a: n(o.w, 1) };- return undefined;- };- // What a project's own effect is, read from its source: whether its main pass lights the surface (it names the unlit or the standard fragment- // stage), which is how the project's effects are built even when they add outlines, a toon light or a dissolve behind switches.- const effectKinds = new Map<string, { unlit: boolean; known: boolean }>();- const effectKind = (effect: CocosAssetEntry | undefined): { unlit: boolean; known: boolean } => {- if (!effect) return { unlit: false, known: false };- const hit = effectKinds.get(effect.file);- if (hit) return hit;- let kind = { unlit: /unlit/i.test(effect.rel), known: false };- try {- const text = readFileSync(effect.file, 'utf8');- const frags = [...text.matchAll(/frag:\s*([A-Za-z0-9_-]+)-fs/g)].map((m) => m[1]!.toLowerCase());- const main = frags.filter((f) => f !== 'outline');- if (main.length > 0) kind = { unlit: main.every((f) => f.includes('unlit')), known: main.every((f) => f.includes('unlit') || f.includes('standard')) };- } catch {- // an effect that cannot be read is judged by its name- }- effectKinds.set(effect.file, kind);- return kind;- };- const materialInfo = (materialUuid: string): MaterialInfo | null => {- if (materials.has(materialUuid)) return materials.get(materialUuid) ?? null;- let info: MaterialInfo | null = null;- try {- const mat = index.byUuid.get(materialUuid);- if (mat) {- const json = JSON.parse(readFileSync(mat.file, 'utf8')) as {- _effectAsset?: { __uuid__?: string };- _defines?: Array<Record<string, unknown>>;- _props?: Array<Record<string, unknown>>;- _states?: Array<{ blendState?: { targets?: Array<{ blend?: boolean; blendSrc?: number; blendDst?: number }> }; rasterizerState?: { cullMode?: number } }>;- };- const props = Object.assign({}, ...(json._props ?? [])) as Record<string, unknown>;- const uuidIn = (v: unknown): string | undefined => (typeof v === 'object' && v !== null ? ((v as { __uuid__?: string }).__uuid__ ?? undefined) : undefined);- const entryOf = (v: unknown): CocosAssetEntry | null => {- const u = uuidIn(v);- return u ? index.byUuid.get(u.split('@')[0]!) ?? null : null;- };- const target = json._states?.[0]?.blendState?.targets?.[0];- const effectUuid = json._effectAsset?.__uuid__ ?? '';- const effectEntry = index.byUuid.get(effectUuid);- const effectName = (effectEntry ? path.basename(effectEntry.rel) : '').toLowerCase();- const color = colorOf(props.mainColor) ?? colorOf(props.albedo);- const kind = effectKind(effectEntry);- // the optional features a material switches on (a toon light, an outline, a dissolve) are what a plain texture and tint do not say- const switched = [...new Set((json._defines ?? []).flatMap((pass) => Object.entries(pass).filter(([, on]) => on === true).map(([name]) => name)))]- .filter((name) => !['USE_ALBEDO_MAP', 'USE_TEXTURE', 'USE_VERTEX_COLOR', 'USE_ALPHA_TEST', 'USE_INSTANCING', 'USE_BATCHING', 'CC_SUPPORT_CASCADED_SHADOW_MAP'].includes(name));- info = {- texture: entryOf(props.mainTexture) ?? entryOf(props.albedoMap),- ...(color ? { color } : {}),- normal: entryOf(props.normalMap),- additive: target?.blend === true && target.blendDst === 1,- transparent: target?.blend === true,- unlit: effectUuid === BUILTIN_UNLIT || effectName.includes('unlit') || kind.unlit,- cullBack: (json._states?.[0]?.rasterizerState?.cullMode ?? 2) === 2,- builtinEffect: BUILTIN_EFFECTS.has(effectUuid) || (kind.known && switched.length === 0),- };- }- } catch {- info = null;- }- materials.set(materialUuid, info);- return info;- };-- // A material of the project's own effect, taken across: the effect's pass becomes a shader of the project, the material's settings become a- // material of it, and the renderers that wore the Cocos material wear that one. Null when the pass cannot be given the engine's vertex stage.- // The chunks an effect includes: the project's own (by their path under the assets folder, or just their name), then the Creator install's.- const projectChunks = [...index.byUuid.values()].filter((e) => e.rel.endsWith('.chunk') && !e.rel.startsWith(`${INTERNAL_FOLDER}/`));- // What the project's scenes set for the ambient, which the converted effects read as parameters of their material.- const ambient = dominantAmbient(index);- const sceneValues = ambient ? { cc_ambientSky: ambient.sky, cc_ambientGround: ambient.ground } : null;- const chunkText = (name: string): string | null => {- const own = projectChunks.find((e) => { const rel = e.rel.replace(/\.chunk$/, ''); return rel === name || rel.endsWith(`/${name}`); });- if (own) return readFileSync(own.file, 'utf8');- // A bare name is one of the install's own, which Cocos finds by where it keeps them.- const places = name.includes('/') ? [''] : ['', 'builtin/internal/', 'builtin/', 'common/', 'legacy/'];- for (const place of places) {- const installed = editorAssets ? path.join(editorAssets, 'chunks', `${place}${name}.chunk`) : null;- if (installed && existsSync(installed)) return readFileSync(installed, 'utf8');- }- return null;- };- type EffectTechnique = { name: string; passes: EffectPass[]; outline: boolean[] };- type ParsedEffect = { effect: CocosEffect; techniques: EffectTechnique[] };- const effects = new Map<string, ParsedEffect | null>();- const convertedMaterials = new Map<string, { ref: string; blends?: boolean; outline?: string } | null>();- const effectOf = (entry: CocosAssetEntry): ParsedEffect | null => {- if (effects.has(entry.file)) return effects.get(entry.file) ?? null;- let result: ParsedEffect | null = null;- try {- const effect = parseEffect(readFileSync(entry.file, 'utf8'));- result = { effect, techniques: effect.techniques.map((t) => ({ name: t.name, passes: t.passes, outline: t.passes.map(isOutlinePass) })) };- } catch (err) {- report.note('effect-unreadable', `${entry.rel}: ${(err as Error).message.split('\n')[0]}`);- }- effects.set(entry.file, result);- return result;- };- // One shader for each combination of macros a project's materials use of a pass: the macros are baked in, so a shader has nothing left to switch.- const shaders = new Map<string, PassConversion & { rel: string }>();- const shaderFor = (entry: CocosAssetEntry, parsed: ParsedEffect, techIndex: number, passIndex: number, defines: Record<string, number | boolean | string>): PassConversion & { rel: string } => {- const key = `${entry.file}|${techIndex}|${passIndex}|${JSON.stringify(Object.entries(defines).sort())}`;- const hit = shaders.get(key);- if (hit) return hit;- const technique = parsed.techniques[techIndex]!;- const stem = entry.rel.replace(/^assets\//, '').replace(/\.effect$/, '');- const variant = Object.keys(defines).length === 0 ? '' : `.${createHash('sha1').update(JSON.stringify(Object.entries(defines).sort())).digest('hex').slice(0, 8)}`;- const rel = outRef(`effects/${stem}.${technique.name}.${passIndex}${variant}.esshader`);- const converted = convertPass(parsed.effect, technique.passes[passIndex]!, `${stem}.${technique.name}.${passIndex}${variant}`, { chunk: chunkText, ...(sceneValues ? { scene: sceneValues } : {}) }, defines);- const error = refused.get(rel);- const result = error ? { shader: null, unsupported: `the converted shader does not compile: ${error}`, state: converted.state, rel } : { ...converted, rel };- shaders.set(key, result);- return result;- };- const FACTORS: Record<number, string> = { 0: 'zero', 1: 'one', 2: 'src_alpha', 3: 'dst_alpha', 4: 'one_minus_src_alpha', 5: 'one_minus_dst_alpha', 6: 'src_color', 7: 'dst_color', 8: 'one_minus_src_color', 9: 'one_minus_dst_color' };- const numberOf = (x: unknown, d: number): number => (typeof x === 'number' && Number.isFinite(x) ? x : d);- type MaterialJson = {- _effectAsset?: { __uuid__?: string }; _techIdx?: number;- _defines?: Array<Record<string, unknown>>; _props?: Array<Record<string, unknown>>;- _states?: Array<{ blendState?: { targets?: Array<{ blend?: boolean; blendSrc?: number; blendDst?: number }> }; rasterizerState?: { cullMode?: number }; depthStencilState?: { depthTest?: boolean; depthWrite?: boolean } }>;- };- /** Which pass of which effect a material is drawn with, and the macros it fixes for it; null for a material of a built-in effect or of none. */- const planOf = (mat: CocosAssetEntry) => {- const json = JSON.parse(readFileSync(mat.file, 'utf8')) as MaterialJson;- // the engine's own look-alikes of Cocos's built-in effects are what a built-in effect becomes, as before- const effectEntry = BUILTIN_EFFECTS.has(json._effectAsset?.__uuid__ ?? '') ? undefined : index.byUuid.get(json._effectAsset?.__uuid__ ?? '');- const parsed = effectEntry && effectEntry.rel.endsWith('.effect') ? effectOf(effectEntry) : null;- const techIndex = json._techIdx ?? 0;- const technique = parsed?.techniques[techIndex];- // The pass that is the surface: the first that is not an outline, which is where a material's own settings are (its arrays run by pass).- const passIndex = technique ? Math.max(0, technique.outline.findIndex((o) => !o)) : 0;- const defines: Record<string, number | boolean | string> = {};- for (const [name, v] of Object.entries(json._defines?.[passIndex] ?? json._defines?.[0] ?? {})) {- if (typeof v === 'number' || typeof v === 'boolean' || typeof v === 'string') defines[name] = v;- }- return { json, effectEntry, parsed, techIndex, technique, passIndex, defines };- };- /**- * Whether each converted shader compiles, found out ahead of the conversion where the engine's shader tools are here (a checkout of the engine, which- * the cook uses as well): glslang reads every combination the shader can take. A pass whose converted fragment does not is reported as not converted, so- * that no material is written that names a shader the engine would refuse.- */- const refused = new Map<string, string>();- const checkShaders = async (): Promise<void> => {- const check = await shaderChecker();- if (!check) return;- const seen = new Set<string>();- for (const mat of index.byUuid.values()) {- if (!mat.rel.endsWith('.mtl') || !wanted(mat.rel)) continue;- try {- const plan = planOf(mat);- if (!plan.effectEntry || !plan.parsed || !plan.technique?.passes[plan.passIndex]) continue;- const shader = shaderFor(plan.effectEntry, plan.parsed, plan.techIndex, plan.passIndex, plan.defines);- if (!shader.shader || seen.has(shader.rel)) continue;- seen.add(shader.rel);- const error = await check(shader.shader.source);- if (error) {- refused.set(shader.rel, error);- if (process.env.COCOS_IMPORT_TRACE_DIR) writeOut(path.join(process.env.COCOS_IMPORT_TRACE_DIR, path.basename(shader.rel)), shader.shader.source);- }- } catch { /* a material that cannot be read is dealt with when it is converted */ }- }- // what was converted before the check is converted again with its answer- shaders.clear();- };- /**- * The outline a material asks for, as a material of its own: the shared outline shader with the width and colour the Cocos material gave its outline- * pass. Null when the effect has none, or the material does not turn it on.- */- const outlineMaterial = (mat: CocosAssetEntry, json: MaterialJson, technique: EffectTechnique): string | null => {- const at = technique.outline.findIndex(Boolean);- const pass = at >= 0 ? technique.passes[at] : undefined;- if (!pass) return null;- const on = pass.inherits ? (json._defines?.[at] ?? {})[pass.inherits] : true;- if (on !== true && on !== 1 && on !== 'true') return null;- const props = (json._props?.[at] ?? {}) as Record<string, unknown>;- const declared = (name: string): unknown => pass.properties.find((p) => p.name === name)?.value;- const width = numberOf(props.lineWidth ?? declared('lineWidth'), 10);- const bias = numberOf(props.depthBias ?? declared('depthBias'), 0);- const given = (props.baseColor ?? declared('baseColor')) as Record<string, unknown> | number[] | undefined;- const colour = Array.isArray(given)- ? { r: numberOf(given[0], 0), g: numberOf(given[1], 0), b: numberOf(given[2], 0), a: 1 }- : given && typeof given === 'object' && 'r' in given- ? { r: numberOf(given.r, 0) / 255, g: numberOf(given.g, 0) / 255, b: numberOf(given.b, 0) / 255, a: 1 }- : { r: 0, g: 0, b: 0, a: 1 };- const shaderRel = outRef('effects/cocos-outline.esshader');- writeText(shaderRel, OUTLINE_SHADER);- const materialRel = outRef(`materials/${mat.rel.replace(/^assets\//, '').replace(/\.mtl$/, '')}.outline.esmaterial`);- write(materialRel, {- version: '1.0', type: 'material', shader: path.posix.relative(path.posix.dirname(materialRel), shaderRel),- blendMode: 9, depthTest: true, depthWrite: true, cull: 2,- properties: { lineWidth: width, depthBias: bias, baseColor: colour },- });- return materialRel;- };- const convertedMaterial = (materialUuid: string): { ref: string; blends?: boolean; outline?: string } | null => {- if (convertedMaterials.has(materialUuid)) return convertedMaterials.get(materialUuid) ?? null;- let result: { ref: string; blends?: boolean; outline?: string } | null = null;- try {- const mat = index.byUuid.get(materialUuid);- if (mat && mat.rel.endsWith('.mtl')) {- const { json, effectEntry, parsed, techIndex, technique, passIndex, defines } = planOf(mat);- const pass = parsed && technique?.passes[passIndex] ? shaderFor(effectEntry!, parsed, techIndex, passIndex, defines) : null;- if (effectEntry && technique && pass) {- if (!pass.shader) {- report.note('effect-not-converted', `${effectEntry.rel}: ${pass.unsupported}`);- if (process.env.COCOS_IMPORT_TRACE) console.log(`[effect] ${effectEntry.rel} (${technique.name}): ${pass.unsupported}`);- } else {- if (technique.passes.length > 1) report.note('effect-extra-passes', `${effectEntry.rel} (${technique.name}): only pass ${passIndex} is drawn${technique.outline.some(Boolean) ? ' (its outline is not)' : ''}`);- for (const a of pass.shader.approximations) report.note('effect-approximated', `${effectEntry.rel}: ${a}`);- const shaderRel = pass.rel;- writeText(shaderRel, pass.shader.source);- const materialRel = outRef(`materials/${mat.rel.replace(/^assets\//, '').replace(/\.mtl$/, '')}.esmaterial`);- const props = (json._props?.[passIndex] ?? json._props?.[0] ?? {}) as Record<string, unknown>;- const properties: Record<string, unknown> = {};- for (const param of pass.shader.params) {- const v = props[param.name];- if (v === undefined || v === null) continue;- if (param.type === 'texture') {- const u = typeof v === 'object' ? (v as { __uuid__?: string }).__uuid__ : undefined;- const entry = u ? index.byUuid.get(u.split('@')[0]!) : undefined;- if (entry) {- properties[param.name] = ctx.assetRef(entry);- materialTextures.add(entry.file);- }- } else if (typeof v === 'number') {- properties[param.name] = v;- } else if (typeof v === 'object') {- const o = v as Record<string, unknown>;- if ('r' in o) {- const c = { r: numberOf(o.r, 255) / 255, g: numberOf(o.g, 255) / 255, b: numberOf(o.b, 255) / 255, a: numberOf(o.a, 255) / 255 };- properties[param.name] = param.type === 'color' ? c : { x: c.r, y: c.g, z: c.b, w: c.a };- } else if ('x' in o) {- properties[param.name] = param.type === 'color'- ? { r: numberOf(o.x, 1), g: numberOf(o.y, 1), b: numberOf(o.z, 1), a: numberOf(o.w, 1) }- : { x: numberOf(o.x, 0), y: numberOf(o.y, 0), z: numberOf(o.z, 0), w: numberOf(o.w, 0) };- }- }- }- // A property that is lanes of a vec4 uniform (`fogLayerBlend`, which is `fogParams.x`) is written under the uniform's name: the material says the lane,- // the shader has the whole of it.- const packed = new Map<string, number[]>();- for (const p of technique.passes[passIndex]?.properties ?? []) {- const m = p.target ? /^(\w+)\.([xyzwrgba]+)$/.exec(p.target) : null;- const v = m ? props[p.name] : undefined;- const uniform = m ? pass.shader.params.find((q) => q.name === m[1] && q.type !== 'texture') : undefined;- if (!m || !uniform || v === undefined || v === null) continue;- const given = typeof v === 'number' ? [v] : typeof v === 'object' && 'x' in (v as object)- ? [numberOf((v as Record<string, unknown>).x, 0), numberOf((v as Record<string, unknown>).y, 0), numberOf((v as Record<string, unknown>).z, 0), numberOf((v as Record<string, unknown>).w, 0)]- : null;- if (!given) continue;- const whole = packed.get(uniform.name) ?? ((): number[] => {- const own = properties[uniform.name] as Record<string, number> | undefined;- if (own && typeof own === 'object') return 'x' in own ? [own.x!, own.y!, own.z!, own.w!] : [own.r!, own.g!, own.b!, own.a!];- return Array.isArray(uniform.value) ? [...(uniform.value as number[]), 0, 0, 0, 0].slice(0, 4) : [0, 0, 0, 0];- })();- [...m[2]!].forEach((lane, i) => {- const at = 'xyzw'.indexOf(lane) >= 0 ? 'xyzw'.indexOf(lane) : 'rgba'.indexOf(lane);- if (given[i] !== undefined) whole[at] = given[i]!;- });- packed.set(uniform.name, whole);- }- for (const [name, whole] of packed) {- const isColor = pass.shader.params.find((q) => q.name === name)?.type === 'color';- properties[name] = isColor ? { r: whole[0]!, g: whole[1]!, b: whole[2]!, a: whole[3]! } : { x: whole[0]!, y: whole[1]!, z: whole[2]!, w: whole[3]! };- }- const state = json._states?.[passIndex] ?? json._states?.[0];- const target = state?.blendState?.targets?.[0];- let blendMode = pass.state.blendMode;- if (target && target.blend !== undefined) {- const src = FACTORS[target.blendSrc ?? 1], dst = FACTORS[target.blendDst ?? 0];- blendMode = target.blend !== true ? 9 : src === 'src_alpha' && dst === 'one' ? 1 : src === 'one' && dst === 'one_minus_src_alpha' ? 4 : src === 'one' && dst === 'one' ? 5 : 0;- }- const cull = state?.rasterizerState?.cullMode;- write(materialRel, {- version: '1.0',- type: 'material',- shader: path.posix.relative(path.posix.dirname(materialRel), shaderRel),- blendMode,- depthTest: state?.depthStencilState?.depthTest ?? pass.state.depthTest,- depthWrite: state?.depthStencilState?.depthWrite ?? pass.state.depthWrite,- cull: cull === undefined ? pass.state.cull : cull === 0 ? 0 : cull === 1 ? 2 : 1,- properties,- });- report.note('effect-converted', `${effectEntry.rel} (${technique.name})`);- result = { ref: materialRel, blends: blendMode !== 9 };- const outline = outlineMaterial(mat, json, technique);- if (outline) result.outline = outline;- }- }- }- } catch {- result = null;- }- convertedMaterials.set(materialUuid, result);- return result;- };-- // A material says how its font page is read through the effect it uses; the outline effect mixes an outline colour in by the red channel.- const bakes = new Map<string, boolean>();- const materialBakesOutline = (materialUuid: string): boolean => {- const known = bakes.get(materialUuid);- if (known !== undefined) return known;- let result = false;- try {- const mat = index.byUuid.get(materialUuid);- const effectUuid = mat && JSON.parse(readFileSync(mat.file, 'utf8'))?._effectAsset?.__uuid__;- const effect = typeof effectUuid === 'string' ? index.byUuid.get(effectUuid) : undefined;- result = !!effect && /alphaLerp\s*=\s*o\.r/.test(readFileSync(effect.file, 'utf8'));- } catch {- result = false;- }- bakes.set(materialUuid, result);- return result;- };-- const wanted = (relPath: string): boolean => !opts.only?.length || opts.only.some((p) => relPath.startsWith(p));- const scenes: string[] = [];- for (const f of walk(assetsDir)) {- const r = norm(path.relative(assetsDir, f));- if (!wanted(r)) continue;- if (r.endsWith('.scene')) scenes.push(r);- else if (r.endsWith('.prefab') && !queued.has(r)) {- queued.add(r);- pending.push(r);- }- }-- // A converted document is the project's own once it is written: the creator edits it here. A re-import brings the Cocos side's- // changes into the documents nobody touched, and leaves an edited one alone — the state file holds what was written last.- const stateFile = path.join(out, 'assets', into, '.import-state.json');- const written: Record<string, string> = (() => {- try {- return (JSON.parse(readFileSync(stateFile, 'utf8')) as { documents?: Record<string, string> }).documents ?? {};- } catch {- return {};- }- })();- const digest = (text: string): string => createHash('sha1').update(text).digest('hex');- const write = (relPath: string, json: unknown): void => writeText(relPath, `${JSON.stringify(json, null, 2)}\n`);- const touched = new Set<string>();- function writeText(relPath: string, text: string): void {- touched.add(relPath);- const file = path.join(out, relPath);- const next = digest(text);- const onDisk = existsSync(file) ? readFileSync(file, 'utf8') : null;- // A shader gets its WGSL twin written into it after the import (the editor and the cook derive it), which is not an edit of the creator's: what- // the importer wrote is the GLSL, so that is what the file is compared by.- const isShader = relPath.endsWith('.esshader');- const compared = onDisk !== null && isShader ? withoutDerivedTwin(onDisk) : onDisk;- const now = compared !== null ? digest(compared) : null;- // stripping a twin leaves the blank lines it stood between, so a shader is the same when only its trailing whitespace differs- const same = compared !== null && (now === next || (isShader && compared.trimEnd() === text.trimEnd()));- const ownedBefore = compared !== null && (isShader ? [compared, compared.trimEnd(), `${compared.trimEnd()}\n`] : [compared]).some((t) => written[relPath] === digest(t));- if (now === null) report.sync.added++;- else if (same) report.sync.unchanged++;- else if (ownedBefore) report.sync.updated++;- else {- report.sync.kept.push(relPath);- if (!opts.dryRun && migrateWidgets(file)) report.note('widget-migrated', relPath);- return;- }- written[relPath] = next;- if (!opts.dryRun && !same) writeOut(file, text);- }-- const byRel = new Map<string, CocosAssetEntry>();- for (const e of index.byUuid.values()) byRel.set(e.rel, e);-- // Assets scripts load by path at run time (`resources.load('ui/icon')`) are named by no scene, so nothing above would bring them- // across. They are copied, and listed by bundle in a manifest the runtime layer resolves those paths through.- const manifest: Record<string, Record<string, { path: string; kind: string; uuid: string }>> = {};- if (index.bundles.length > 0) {- const files = new Set(index.byUuid.values());- for (const bundle of index.bundles) {- const entries = (manifest[bundle.name] ??= {});- for (const entry of files) {- if (!entry.rel.startsWith(`${bundle.rel}/`) || !wanted(entry.rel)) continue;- const key = entry.rel.slice(bundle.rel.length + 1).replace(/\.[^./]+$/, '');- const ext = /\.([^./]+)$/.exec(entry.rel)?.[1]?.toLowerCase() ?? '';- if (ext === 'prefab') {- const ref = ctx.prefabRef(entry.uuid);- if (ref) entries[key] = { path: ref, kind: 'prefab', uuid: entry.uuid };- } else if (ext === 'json') {- entries[key] = { path: ctx.assetRef(entry), kind: 'json', uuid: entry.uuid };- } else if (['txt', 'text', 'xml', 'csv', 'atlas'].includes(ext)) {- entries[key] = { path: ctx.assetRef(entry), kind: 'text', uuid: entry.uuid };- } else if (['png', 'jpg', 'jpeg', 'webp'].includes(ext)) {- entries[key] = { path: ctx.assetRef(entry), kind: 'texture', uuid: entry.uuid };- } else if (['mp3', 'wav', 'ogg', 'm4a'].includes(ext)) {- entries[key] = { path: ctx.assetRef(entry), kind: 'audio', uuid: entry.uuid };- } else if (ext === 'scene') {- // a scene is run by its name (`director.loadScene('scene_level_003')`), which is the file's, wherever its bundle puts it- entries[key] = { path: outRef(esRel(entry.rel, '.esscene')), kind: 'scene', uuid: entry.uuid };- } else if (ext !== 'meta' && ext !== 'ts' && ext !== 'js') {- entries[key] = { path: '', kind: ext || 'other', uuid: entry.uuid };- }- }- }- write(outRef('resources.json'), manifest);- }-- progress('shaders', 0, 1);- await checkShaders();- for (let i = 0; i < pending.length; i++) {- const r = pending[i]!;- const e = byRel.get(r);- const doc = e ? loadDoc(e) : null;- if (!e || !doc) continue;- ctx.where = r;- progress('prefabs', i, pending.length, r);- await models.ensureFor(e.file);- try {- const converted = convertPrefab(doc, ctx);- collectScriptFields(converted);- write(outRef(esRel(r, '.esprefab')), converted);- } catch (err) {- report.documents.failed.push({ file: r, error: (err as Error).message });- }- }- for (const [si, r] of scenes.entries()) {- const e = byRel.get(r);- const doc = e ? loadDoc(e) : null;- if (!e || !doc) continue;- ctx.where = r;- progress('scenes', si, scenes.length, r);- await models.ensureFor(e.file);- try {- const converted = convertScene(doc, ctx);- collectScriptFields(converted);- write(outRef(esRel(r, '.esscene')), converted);- } catch (err) {- report.documents.failed.push({ file: r, error: (err as Error).message });- }- }-- for (const f of models.failures) report.documents.failed.push(f);- for (const w of models.warnings) report.note('model-import-warning', `${w.file}: ${w.warning}`);-- if (usedScripts.size > 0) {- // The scripts stay where they are, unchanged; this file is how the new project's bundle reaches them.- const entry = path.join(out, 'src', 'cocos-scripts.ts');- // Cocos runs every script of the project when the game starts, and a game leans on that: a script that only defines globals (the game's- // configuration, its helpers on `window`) is named by no scene, and what loads next reads them. Those run first.- // And every script that declares a component class: a game finds its classes by name too (a view is opened by its class's name), and a- // class no scene names is still there in Cocos.- // The editor's own scripts (its debug tools) are not the project's and are not on disk beside it.- const ours = (rel: string): boolean => !rel.startsWith(`${INTERNAL_FOLDER}/`);- const everyClass = new Set([...usedScripts, ...[...scripts.values()].map((c) => c.rel)].filter(ours));- const starters = globalDefiningScripts(index).filter((rel) => ours(rel) && !everyClass.has(rel));- const loads = [...starters, ...[...everyClass].sort()].map((rel) => {- const target = path.join(assetsDir, rel.replace(/\.(ts|js)$/, ''));- // On another drive there is no relative path, only the absolute one, which a require takes just as well.- const rel2 = path.relative(path.dirname(entry), target).split(path.sep).join('/');- return "load(() => require('" + (path.isAbsolute(rel2) || /^[A-Za-z]:/.test(rel2) || rel2.startsWith('.') ? rel2 : "./" + rel2) + "'), '" + rel.replace(/'/g, "\\'") + "');";- });- // Each script is its own load: a project's scripts are evaluated together, and one whose module throws (a Cocos API this engine does not- // have, a script that reaches for the page) must not take the others with it. Loaded in order, synchronously, so the components exist before the scene does.- const text = [- "// Generated by import-cocos. Brings the Cocos project's scripts into this project's bundle, read from where they are.",- "// src/main.ts loads this file. Scripts resolve `cc` to the engine's compatibility layer.",- "import 'esengine/cocos';",- "declare const require: (id: string) => unknown;",- "function load(script: () => unknown, name: string): void {",- " try {",- " script();",- " } catch (err) {",- " console.error('[cocos] the script ' + name + ' failed to load:', err);",- " }",- "}",- ...loads, '',- ].join('\n');- if (!opts.dryRun) writeOut(entry, text);- if (!opts.dryRun) writeClassNames(out, entry, assetsDir, scripts);- report.note('cocos-scripts-entry', `${path.relative(out, entry).split(path.sep).join('/')}: ${everyClass.size} script(s)`);- if (!opts.dryRun) wireProjectEntries(out, scriptFields);- }- if (!opts.dryRun) wireManifest(out, source, into, scenes);-- report.textures = textures.size;- if (!opts.dryRun) {- let copied = 0;- for (const { entry, slice, hints } of textures.values()) {- if (copied % 25 === 0) progress('textures', copied, textures.size, entry.rel);- copied++;- const dest = path.join(out, outRef(entry.rel));- if (!existsSync(entry.file)) {- report.missingAsset(entry.uuid);- continue;- }- mkdirSync(path.dirname(dest), { recursive: true });- if (entry.file.endsWith('.fnt') && hints?.bakedOutline) writeOut(dest, declareBakedOutline(readFileSync(entry.file, 'utf8')));- else placeFile(entry.file, dest);- if (entry.file.endsWith('.fnt')) {- copyFontPages(entry.file, dest, (page) => byRel.get(norm(path.relative(assetsDir, page)))?.uuid);- // The asset database ships a font's page image only for a `bitmapfont`, since nothing else names it.- writeOut(`${dest}.meta`, `${JSON.stringify({ uuid: entry.uuid, version: '2.0', type: 'bitmapfont', importer: {} }, null, 2)}-`);- }- const data = dest.endsWith('.png') && materialTextures.has(entry.file) && hidesColorUnderClearAlpha(entry.file);- if (slice || data) {- // A slice border is a texture import setting here; the Cocos image keeps its uuid. A texture that holds numbers is shipped as the numbers it has.- const importer = { ...(slice ? { sliceBorder: slice } : {}), ...(data ? { compress: 'off', sRGB: false } : {}) };- writeOut(`${dest}.meta`, `${JSON.stringify({ uuid: entry.uuid, version: '2.0', type: 'texture', importer }, null, 2)}\n`);- if (data) report.note('texture-kept-as-data', entry.rel);- } else if (existsSync(`${dest}.meta`)) {- // what an earlier import wrote for a texture it no longer takes for data, and only that, is taken away- try {- const earlier = JSON.parse(readFileSync(`${dest}.meta`, 'utf8')) as { importer?: Record<string, unknown> };- const keys = Object.keys(earlier.importer ?? {}).sort().join(',');- if (keys === 'compress,sRGB' && earlier.importer!.compress === 'off' && earlier.importer!.sRGB === false) rmSync(`${dest}.meta`, { force: true });- } catch { /* a meta that is not readable is not ours to remove */ }- }- }- // The shaders and materials of an earlier import that this one did not write are the effects' own leftovers (a combination of macros no material- // uses now, a material that was deleted): taken away while they are still what the importer wrote, kept once the creator has edited them.- for (const rel of Object.keys(written)) {- if (touched.has(rel) || !new RegExp(`^assets/${into}/(?:effects|materials)/`).test(rel)) continue;- const file = path.join(out, rel);- if (existsSync(file) && digest(readFileSync(file, 'utf8')) === written[rel]) {- rmSync(file, { force: true });- rmSync(`${file}.meta`, { force: true });- report.note('effect-stale-removed', rel);- delete written[rel];- } else if (!existsSync(file)) {- delete written[rel];- }- }- progress('finish', 0, 1);- writeOut(stateFile, `${JSON.stringify({ revision: COCOS_IMPORT_REVISION, source, documents: written }, null, 2)}\n`);- writeOut(path.join(out, 'assets', into, 'import-report.json'), `${JSON.stringify(report.toJSON(), null, 2)}\n`);- }- return report.toJSON();-}diff --git a/pipeline/src/import/cocos/index.ts b/pipeline/src/import/cocos/index.tsdeleted file mode 100644index 98f9d6706..000000000--- a/pipeline/src/import/cocos/index.ts+++ /dev/null@@ -1,7 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-export { importCocosProject, cocosImportIsCurrent, COCOS_IMPORT_REVISION, type CocosImportOptions, type CocosImportProgress } from './importProject';-export { parseCocosDocument, type CocosDocument, type CocosNode } from './document';-export { buildCocosAssetIndex, type CocosAssetIndex } from './assets';-export { convertPrefab, convertScene, type ConvertContext, type PrefabFile, type SceneFile } from './convert';-export { ImportReport, type ImportReportData } from './report';diff --git a/pipeline/src/import/cocos/models.ts b/pipeline/src/import/cocos/models.tsdeleted file mode 100644index ade76106e..000000000--- a/pipeline/src/import/cocos/models.ts+++ /dev/null@@ -1,279 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file The models a Cocos project draws, taken in with the engine's own model import.- *- * A Cocos mesh, material and skeleton live inside an `.fbx` or `.gltf` as sub-assets, and a scene points at them as `<uuid>@<id>`. The engine reads- * a model by importing it: a prefab that places the pieces, a mesh per primitive, the materials, the images, a clip per animation. This does that- * import for each model a converted document uses, and answers the two questions the converter has: which prefab is this model, and which mesh- * component does this Cocos mesh correspond to.- */-import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';-import path from 'node:path';-import { importModelFile } from '../../assets/importModelFile';-import { modelStem } from '../../assets/readModelSource';-import { metaTypeFor, mintMeta } from '../../assets/assetMeta';-import type { CocosAssetEntry, CocosAssetIndex } from './assets';--type Raw = Record<string, unknown>;-const isObj = (v: unknown): v is Raw => typeof v === 'object' && v !== null && !Array.isArray(v);--export interface ModelUse {- /** Project-relative path of the model's prefab; empty for a file that only holds animation. */- prefab: string;- /** The prefab's root entity id, which an override addresses. */- rootId: string;- /** Components by the name of the entity that carries them. */- byEntity: Map<string, Raw[]>;- /** Project-relative path of each animation clip, by the animation's own name. */- clips: Map<string, string>;- /** Where each node of the model stands under the prefab's root, as the path a clip addresses it by, keyed by the node's name. */- paths: Map<string, string>;- /** The names of the joints a skinned part is bound to, in the order its vertices index them, keyed by the part's name. */- skin: Map<string, string[]>;- /** The prefab entity id of the mesh renderer of each part of the model, by the part's name: a part is a node, and its renderer is on the node or on the child the import made for its geometry. */- renderers: Map<string, string>;-}--const MODEL_EXT = /\.(fbx|gltf|glb)$/i;-export const isModelEntry = (entry: CocosAssetEntry | undefined): entry is CocosAssetEntry => !!entry && MODEL_EXT.test(entry.rel);--export class CocosModels {- private readonly uses = new Map<string, ModelUse | null>();- private readonly scanned = new Map<string, string[]>();- private readonly scanning = new Set<string>();- readonly failures: Array<{ file: string; error: string }> = [];- readonly warnings: Array<{ file: string; warning: string }> = [];-- constructor(- private readonly index: CocosAssetIndex,- private readonly out: string,- private readonly into: string,- private readonly dryRun: boolean,- ) {}-- /** The model files a document refers to, by looking for their uuids in its text. */- modelsIn(file: string): CocosAssetEntry[] {- let uuids = this.scanned.get(file);- if (!uuids) {- uuids = [];- try {- const text = readFileSync(file, 'utf8');- for (const m of text.matchAll(/"__uuid__"\s*:\s*"([0-9a-f-]{36})(?:@[0-9a-f]+)?"/g)) uuids.push(m[1]!);- } catch {- // an unreadable document is reported where it is parsed- }- this.scanned.set(file, [...new Set(uuids)]);- uuids = this.scanned.get(file)!;- }- const found: CocosAssetEntry[] = [];- for (const u of uuids) {- const entry = this.index.byUuid.get(u);- if (isModelEntry(entry) && !found.includes(entry)) found.push(entry);- // an animation graph names the clips it plays, which live in model files the document itself never mentions- else if (entry && entry.rel.endsWith('.animgraph') && !this.scanning.has(entry.file)) {- this.scanning.add(entry.file);- for (const nested of this.modelsIn(entry.file)) if (!found.includes(nested)) found.push(nested);- }- }- return found;- }-- /** Bring in every model a document uses that has not been brought in. */- async ensureFor(file: string): Promise<void> {- for (const entry of this.modelsIn(file)) await this.ensure(entry);- }-- async ensure(entry: CocosAssetEntry): Promise<void> {- if (this.uses.has(entry.file)) return;- this.uses.set(entry.file, null);- if (this.dryRun) return;- const destDir = `assets/${this.into}/${path.posix.dirname(entry.rel)}`.replace(/\/\.$/, '');- const stem = modelStem(entry.file);- const prefabAbs = path.join(this.out, destDir, `${stem}.esprefab`);- try {- // A model already imported is the project's now (its prefab may have been edited): it is read, not written over.- if (!existsSync(prefabAbs)) {- const result = await importModelFile({ root: this.out, destDir, absSource: entry.file });- for (const warning of result.warnings) this.warnings.push({ file: entry.rel, warning });- }- this.uses.set(entry.file, readUse(prefabAbs, `${destDir}/${stem}.esprefab`, path.join(this.out, destDir), stem, destDir));- } catch (err) {- this.failures.push({ file: entry.rel, error: (err as Error).message });- }- }-- /**- * The mesh renderers of a model by the id Cocos gave each component: what a property override on a model's part addresses. Read from the- * editor's library of imported assets, which is there when the project has been opened; without it the parts cannot be told apart.- */- partsOf(entry: CocosAssetEntry): Map<string, string> {- const found = new Map<string, string>();- const scene = [...entry.subs.entries()].find(([, sub]) => sub.importer === 'gltf-scene')?.[0];- if (!scene) return found;- const file = path.join(this.index.root, '..', 'library', scene.slice(0, 2), `${scene}.json`);- try {- const objs = JSON.parse(readFileSync(file, 'utf8')) as Raw[];- for (const o of objs) {- if (!isObj(o) || (o.__type__ !== 'cc.MeshRenderer' && o.__type__ !== 'cc.SkinnedMeshRenderer')) continue;- const info = isObj(o.__prefab) && typeof o.__prefab.__id__ === 'number' ? objs[o.__prefab.__id__] : null;- const node = isObj(o.node) && typeof o.node.__id__ === 'number' ? objs[o.node.__id__] : null;- if (isObj(info) && typeof info.fileId === 'string' && isObj(node) && typeof node._name === 'string') found.set(info.fileId, node._name);- }- } catch {- // no library: the parts stay unaddressed, and the overrides on them are counted- }- return found;- }-- /** The model a `<uuid>` or `<uuid>@<id>` names, once it has been brought in. */- use(uuid: string): { entry: CocosAssetEntry; use: ModelUse } | null {- const entry = this.index.byUuid.get(uuid.split('@')[0]!);- if (!isModelEntry(entry)) return null;- const use = this.uses.get(entry.file);- return use ? { entry, use } : null;- }-- /** The name a mesh sub-asset carries, without its `.mesh`. */- meshName(entry: CocosAssetEntry, uuid: string): string | null {- const name = entry.subs.get(uuid)?.name;- return name ? name.replace(/\.mesh$/i, '') : null;- }-}--/** A clip's name as a file name carries it: what the model import made of it, so a Cocos name and a product name compare. */-const clipKey = (name: string): string => name.replace(/\.(animation|anim)$/i, '').replace(/[^A-Za-z0-9]+/g, '_').replace(/^_+|_+$/g, '').toLowerCase();--/**- * A clip of this model by the name Cocos gave it, or its only clip when the names do not meet (a model with one animation has nothing- * else a node could mean).- */-export function clipOf(use: ModelUse, cocosName: string | undefined): string | null {- if (cocosName) {- const wanted = clipKey(cocosName);- for (const [name, ref] of use.clips) if (clipKey(name) === wanted) return ref;- }- return use.clips.size === 1 ? [...use.clips.values()][0]! : null;-}--function readUse(prefabAbs: string, prefab: string, absDir: string, stem: string, destDir: string): ModelUse {- // A file with animation and no mesh produces no prefab, only clips.- const hasPrefab = existsSync(prefabAbs);- const doc = hasPrefab ? JSON.parse(readFileSync(prefabAbs, 'utf8')) as { rootEntityId?: string; entities?: Raw[] } : {};- const byEntity = new Map<string, Raw[]>();- for (const e of (doc as { entities?: Raw[] }).entities ?? []) {- if (typeof e.name !== 'string' || !Array.isArray(e.components)) continue;- byEntity.set(e.name, [...(byEntity.get(e.name) ?? []), ...(e.components as Raw[]).filter(isObj)]);- }- const clips = new Map<string, string>();- try {- for (const file of readdirSync(absDir)) {- if (file.startsWith(`${stem}_`) && file.endsWith('.estimeline')) clips.set(file.slice(stem.length + 1, -'.estimeline'.length), `${destDir}/${file}`);- }- } catch {- // no clips beside the model- }- // where each node stands, by name: a clip addresses a node by its path under the root, the root itself left out- const entities = (doc as { entities?: Raw[] }).entities ?? [];- const byId = new Map(entities.map((e) => [String(e.prefabEntityId), e]));- const paths = new Map<string, string>();- const pathOf = (e: Raw): string => {- const parent = typeof e.parent === 'string' ? byId.get(e.parent) : undefined;- return parent && parent.parent !== null && parent.parent !== undefined ? `${pathOf(parent)}/${String(e.name)}` : String(e.name);- };- for (const e of entities) if (e.parent !== null && e.parent !== undefined && !paths.has(String(e.name))) paths.set(String(e.name), pathOf(e));- const skin = new Map<string, string[]>();- for (const e of entities) {- for (const c of Array.isArray(e.components) ? (e.components as Raw[]) : []) {- if (c.type !== 'MeshSkin' || !isObj(c.data) || !Array.isArray(c.data.joints)) continue;- skin.set(String(e.name), c.data.joints.map((id) => String(byId.get(String(id))?.name ?? '')));- }- }- const renderers = new Map<string, string>();- for (const e of entities) {- const holds = (Array.isArray(e.components) ? (e.components as Raw[]) : []).some((c) => c.type === 'MeshRenderer');- if (!holds || typeof e.name !== 'string') continue;- const parent = typeof e.parent === 'string' ? byId.get(e.parent) : undefined;- const part = e.name === 'GeometryTransform' && typeof parent?.name === 'string' ? parent.name : e.name;- if (!renderers.has(part)) renderers.set(part, String(e.prefabEntityId));- }- return { prefab: hasPrefab ? prefab : '', rootId: (doc as { rootEntityId?: string }).rootEntityId ?? 'n1', byEntity, clips, paths, skin, renderers };-}--/** Give a generated asset the `.meta` an export needs to ship it, unless it has one. */-export function mintSidecar(file: string): void {- const type = metaTypeFor(file);- if (type && !existsSync(`${file}.meta`)) writeFileSync(`${file}.meta`, `${JSON.stringify(mintMeta(type), null, 2)}\n`);-}--/** How a Cocos clip plays, from the sub-asset the scene names: the part of the animation it is, and what it does at its end. */-export interface ClipPlay {- span?: { from: number; to: number };- wrapMode?: 'once' | 'loop' | 'pingPong';-}--/** Cocos's `AnimationClip.WrapMode` in the timeline's names: Loop (2) and PingPong (36) are themselves; the rest play once. */-export function wrapModeOf(cocos: unknown): ClipPlay['wrapMode'] {- return cocos === 2 || cocos === 22 ? 'loop' : cocos === 36 ? 'pingPong' : 'once';-}--/** What a clip sub-asset says about how it plays: the span of the take it covers and its wrap mode. */-export function clipPlayOf(userData: Record<string, unknown> | undefined): ClipPlay {- const span = userData?.span;- const play: ClipPlay = { wrapMode: wrapModeOf(userData?.wrapMode) };- if (isObj(span) && typeof span.from === 'number' && typeof span.to === 'number' && span.to > span.from) play.span = { from: span.from, to: span.to };- return play;-}--interface Key { time: number; [k: string]: unknown }--/**- * A clip written for one hierarchy, addressed to another: each track follows the node of its last name to where that node stands in @p paths.- * Cocos plays an animation file's clip on any skeleton whose bones carry the names it animates, and the engine addresses by path, so the clip is- * copied once for each skeleton it is played on. A track whose node the target does not have is dropped, and counted. Cocos also cuts one take- * into named clips by time range; the copy keeps the keys inside @p play.span, moved to start at zero.- *- * @returns the project-relative path of the copy, or null when no track found its node.- */-export function retargetClip(out: string, clipRef: string, paths: Map<string, string> | null, key: string, play: ClipPlay = {}): { ref: string; dropped: number } | null {- const abs = path.join(out, clipRef);- const doc = JSON.parse(readFileSync(abs, 'utf8')) as { tracks?: Raw[]; duration?: number; wrapMode?: string };- const span = play.span;- const tracks: Raw[] = [];- let dropped = 0;- // A clip of a single object animates the object itself, which the file calls by its own name and a scene calls whatever it likes: when exactly- // every track is on one top-level name and it finds no node, it is the node the clip plays on.- const loose = new Set<string>();- for (const track of doc.tracks ?? []) {- const cp = typeof track.childPath === 'string' ? track.childPath : '';- if (paths !== null && cp !== '' && !cp.includes('/') && !paths.has(cp)) loose.add(cp);- }- const host = loose.size === 1 && (doc.tracks ?? []).every((t) => t.childPath === [...loose][0]) ? [...loose][0]! : null;- for (const track of doc.tracks ?? []) {- const childPath = typeof track.childPath === 'string' ? track.childPath : '';- const name = childPath.split('/').pop() ?? '';- // with no skeleton to follow, the clip keeps the paths it was written with: it is the holder of a clip, to be played on a skeleton later- const target = paths === null ? childPath : childPath === '' || (host !== null && childPath === host) ? '' : paths.get(name);- if (target === undefined) {- dropped++;- continue;- }- const channels = (Array.isArray(track.channels) ? (track.channels as Raw[]) : []).map((channel) => {- const keys = (Array.isArray(channel.keyframes) ? (channel.keyframes as Key[]) : []);- if (!span) return channel;- const inside = keys.filter((k) => k.time >= span.from - 1e-6 && k.time <= span.to + 1e-6).map((k) => ({ ...k, time: Math.max(0, k.time - span.from) }));- return { ...channel, keyframes: inside };- }).filter((channel) => (channel.keyframes as unknown[]).length > 0);- if (channels.length === 0) continue;- tracks.push({ ...track, childPath: target, name: (target.split('/').pop() ?? '') || track.name, channels });- }- if (tracks.length === 0) return null;- const tag = [key, span ? `${span.from}-${span.to}` : '', play.wrapMode ?? ''].filter(Boolean).join('_').replace(/[^A-Za-z0-9]+/g, '_');- const ref = clipRef.replace(/\.estimeline$/, `__${tag}.estimeline`);- const file = path.join(out, ref);- mkdirSync(path.dirname(file), { recursive: true });- const copy = { ...doc, tracks, duration: span ? span.to - span.from : doc.duration, ...(play.wrapMode ? { wrapMode: play.wrapMode } : {}) };- writeFileSync(file, `${JSON.stringify(copy, null, 2)}\n`);- mintSidecar(file);- return { ref, dropped };-}diff --git a/pipeline/src/import/cocos/outlineShader.ts b/pipeline/src/import/cocos/outlineShader.tsdeleted file mode 100644index 7c04c3d26..000000000--- a/pipeline/src/import/cocos/outlineShader.ts+++ /dev/null@@ -1,38 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file The outline a Cocos effect draws as a pass of its own.- *- * Cocos draws such a mesh twice: first pushed out along its normals and shown from behind (a front-face cull), in one colour; then as the surface. The- * engine has one material to a renderer, so the pass is a material of its own on a second renderer that stands with the first, drawn with this shader.- * The push is in the mesh's own space, by the width the Cocos effect gives in view space, which is about the same for a model drawn near its own size.- */-export const OUTLINE_SHADER = `#pragma shader "cocos-outline"-#pragma version 300 es-#pragma domain Lit-#pragma feature MESH_NORMALS-#pragma param lineWidth float default(10)-#pragma param depthBias float default(0)-#pragma param baseColor color default(0,0,0,1)--#pragma vertexoffset-void esMaterialVertex(inout vec3 local, inout vec3 localNormal, in vec2 uv) {- float len = length(localNormal);- vec3 dir = len > 0.0001 ? localNormal / len : vec3(0.0);- local += dir * (lineWidth * 0.001);-}-#pragma end--#pragma fragment-precision mediump float;-out vec4 fragColor;--void main() {-#ifdef ES_LINEAR- fragColor = vec4(baseColor.rgb, 1.0);-#else- fragColor = vec4(linearToSrgb(baseColor.rgb), 1.0);-#endif-}-#pragma end-`;diff --git a/pipeline/src/import/cocos/particle.ts b/pipeline/src/import/cocos/particle.tsdeleted file mode 100644index 633492c6b..000000000--- a/pipeline/src/import/cocos/particle.ts+++ /dev/null@@ -1,403 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file `cc.ParticleSystem` as the engine's `ParticleEmitter`.- *- * Cocos describes a system as a main block plus optional modules (shape, size/colour/rotation over lifetime, texture animation, ...), each- * value a range that is a constant, two constants, or a curve. The emitter carries a start and an end value per quantity, and for a- * colour or size that changes in more than a straight line, an authored gradient (`colorGradient`) or curve (`sizeCurve`) that the sim- * samples by age. What the emitter has no field for is counted, so the gap is a list.- */-import type { CocosAssetEntry } from './assets';-import type { ImportReport } from './report';--type Raw = Record<string, unknown>;-const isObj = (v: unknown): v is Raw => typeof v === 'object' && v !== null && !Array.isArray(v);-const num = (v: unknown, d: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : d);--export interface ParticleContext {- report: ImportReport;- /** A material's main texture and whether it blends additively; null when the project has no such material. */- material?(uuid: string): { texture: CocosAssetEntry | null; additive: boolean } | null;- convertedMaterial?(uuid: string): { ref: string } | null;- assetRef(entry: CocosAssetEntry): string;-}--export interface Range { min: number; max: number }--/** One keyframe track's value at time @p t (0..1), linear between the keys. */-function sampleKeys(keys: Array<{ time: number; value: number }>, t: number): number {- if (keys.length === 0) return 0;- const sorted = [...keys].sort((a, b) => a.time - b.time);- if (t <= sorted[0]!.time) return sorted[0]!.value;- const last = sorted[sorted.length - 1]!;- if (t >= last.time) return last.value;- for (let i = 1; i < sorted.length; i++) {- const b = sorted[i]!;- if (t <= b.time) {- const a = sorted[i - 1]!;- const f = b.time === a.time ? 0 : (t - a.time) / (b.time - a.time);- return a.value + (b.value - a.value) * f;- }- }- return last.value;-}--function splineAt(spline: unknown, t: number): number | null {- if (!isObj(spline)) return null;- const values = spline._values;- if (!Array.isArray(values)) return null;- const keys = values.filter(isObj).map((k) => ({ time: num(k.time, 0), value: num(k.value, 0) }));- return keys.length ? sampleKeys(keys, t) : null;-}--/** A `cc.CurveRange` evaluated at time @p t of its domain (emission time for a start value, lifetime for an over-lifetime one). */-export function curveRange(v: unknown, t: number, fallback = 0): Range {- if (!isObj(v)) return { min: fallback, max: fallback };- const mult = num(v.multiplier, 1);- switch (num(v.mode, 0)) {- case 1: {- const s = splineAt(v.spline, t);- return s === null ? { min: fallback, max: fallback } : { min: s * mult, max: s * mult };- }- case 2: {- const a = splineAt(v.splineMin, t);- const b = splineAt(v.splineMax, t);- return a === null || b === null ? { min: fallback, max: fallback } : { min: a * mult, max: b * mult };- }- case 3: {- const lo = num(v.constantMin, fallback);- const hi = num(v.constantMax, fallback);- return { min: Math.min(lo, hi), max: Math.max(lo, hi) };- }- default: {- const c = num(v.constant, fallback);- return { min: c, max: c };- }- }-}--type Rgba = [number, number, number, number];--function colorOf(v: unknown): Rgba {- const c = isObj(v) ? v : {};- return [num(c.r, 255) / 255, num(c.g, 255) / 255, num(c.b, 255) / 255, num(c.a, 255) / 255];-}--/** A `cc.Gradient` at time @p t. Colour and alpha have their own keys. */-function gradientAt(g: unknown, t: number): Rgba {- if (!isObj(g)) return [1, 1, 1, 1];- const ck = (Array.isArray(g.colorKeys) ? g.colorKeys : []).filter(isObj).map((k) => ({ time: num(k.time, 0), c: colorOf(k.color) }));- const ak = (Array.isArray(g.alphaKeys) ? g.alphaKeys : []).filter(isObj).map((k) => ({ time: num(k.time, 0), value: num(k.alpha, 255) / 255 }));- const rgb: [number, number, number] = [1, 1, 1];- for (let i = 0; i < 3; i++) rgb[i] = ck.length ? sampleKeys(ck.map((k) => ({ time: k.time, value: k.c[i]! })), t) : 1;- return [rgb[0], rgb[1], rgb[2], ak.length ? sampleKeys(ak, t) : 1];-}--/** A `cc.GradientRange` at time @p t: a colour, or the gradient (or the first of a pair of them). */-function gradientRange(v: unknown, t: number): Rgba {- if (!isObj(v)) return [1, 1, 1, 1];- switch (num(v._mode, 0)) {- case 1: return gradientAt(v.gradient, t);- case 2: return colorOf(v.colorMin);- case 3: return gradientAt(v.gradientMin, t);- case 4: return gradientAt(v.gradient, t);- default: return colorOf(v.color);- }-}--const mid = (r: Range): number => (r.min + r.max) / 2;--/** The times at which a gradient range changes, ends included, in order. */-function gradientTimes(v: unknown): number[] {- const times = new Set<number>([0, 1]);- if (isObj(v)) {- for (const g of [v.gradient, v.gradientMin]) {- if (!isObj(g)) continue;- for (const list of [g.colorKeys, g.alphaKeys]) {- for (const k of Array.isArray(list) ? list : []) {- if (isObj(k)) times.add(Math.min(1, Math.max(0, num(k.time, 0))));- }- }- }- }- return [...times].sort((a, b) => a - b);-}--/** The colour over a particle's life: the start colour times the over-lifetime gradient, as stops the sim samples by age. */-function colorStops(start: Rgba, over: unknown): Array<{ t: number; color: Raw }> {- return gradientTimes(over).map((t) => {- const g = gradientRange(over, t);- return { t, color: { r: start[0] * g[0], g: start[1] * g[1], b: start[2] * g[2], a: start[3] * g[3] } };- });-}--/** A size-over-lifetime curve as the engine's keyframes (value times the start size). Two curves are averaged at every key time. */-function sizeKeys(v: unknown): Array<{ time: number; value: number; inTangent: number; outTangent: number }> | null {- if (!isObj(v)) return null;- const mode = num(v.mode, 0);- const mult = num(v.multiplier, 1);- const read = (spline: unknown): Array<{ time: number; value: number; inTangent: number; outTangent: number }> | null => {- if (!isObj(spline) || !Array.isArray(spline._values)) return null;- const keys = spline._values.filter(isObj).map((k) => ({- time: num(k.time, 0), value: num(k.value, 0) * mult, inTangent: num(k.inTangent, 0) * mult, outTangent: num(k.outTangent, 0) * mult,- }));- return keys.length ? keys : null;- };- if (mode === 1) return read(v.spline);- if (mode === 2) {- const lo = read(v.splineMin);- const hi = read(v.splineMax);- if (!lo || !hi) return lo ?? hi;- const times = [...new Set([...lo, ...hi].map((k) => k.time))].sort((a, b) => a - b);- return times.map((time) => ({ time, value: (sampleKeys(lo, time) + sampleKeys(hi, time)) / 2, inTangent: 0, outTangent: 0 }));- }- const k = mid(curveRange(v, 0, 1));- return [{ time: 0, value: k, inTangent: 0, outTangent: 0 }, { time: 1, value: k, inTangent: 0, outTangent: 0 }];-}--/** Cocos's emitter shapes in the engine's numbering. */-const SHAPE: Record<number, number> = { 0: 2 /* Box */, 1: 1 /* Circle */, 2: 3 /* Cone */, 3: 4 /* Sphere */, 4: 5 /* Hemisphere */ };--function enabledModule(v: unknown): Raw | null {- return isObj(v) && v._enable === true ? v : null;-}--export function particleSystem(c: { enabled: boolean; data: Raw }, ctx: ParticleContext, where: string): { type: string; data: Raw } {- const d = c.data;- const note = (code: string): void => ctx.report.note(code, where);- let partial = false;- const lose = (code: string): void => { partial = true; note(code); };-- const lifetime = curveRange(d.startLifetime, 0, 1);- const speed = curveRange(d.startSpeed, 0, 0);- const size = curveRange(d.startSize, 0, 1);- const rotation = curveRange(d.startRotationZ ?? d.startRotation, 0, 0);- const rate = curveRange(d.rateOverTime, 0, 0);- const gravity = curveRange(d.gravityModifier, 0, 0);-- const out: Raw = {- enabled: c.enabled,- looping: d.loop === true,- playOnStart: d.playOnAwake !== false,- duration: num(d.duration, 5),- maxParticles: Math.max(1, Math.trunc(num(d._capacity, 100))),- rate: mid(rate),- lifetimeMin: lifetime.min,- lifetimeMax: lifetime.max,- speedMin: speed.min,- speedMax: speed.max,- startSizeMin: size.min,- startSizeMax: size.max,- rotationMin: rotation.min,- rotationMax: rotation.max,- gravity: { x: 0, y: -9.8 * mid(gravity), z: 0 },- simulationSpace: num(d._simulationSpace, 1) === 0 ? 1 /* Local */ : 0 /* World */,- };- out.simulationSpeed = Math.max(0, num(d.simulationSpeed, 1));- out.startDelay = Math.max(0, mid(curveRange(d.startDelay, 0, 0)));- if (mid(curveRange(d.rateOverDistance, 0, 0)) > 0) lose('particle-rate-over-distance');-- // colour: the start colour times the over-lifetime gradient, sampled by age- const start = gradientRange(d.startColor, 0);- const colorModule = isObj(d._colorOverLifetimeModule) && d._colorOverLifetimeModule._enable === true ? d._colorOverLifetimeModule : null;- const stops = colorStops(start, colorModule?.color);- out.startColor = stops[0]!.color;- out.endColor = stops[stops.length - 1]!.color;- if (colorModule && stops.length > 2) out.colorGradient = { stops };-- // size over lifetime multiplies the start size by the curve's value at the particle's age- const sizeModule = isObj(d._sizeOvertimeModule) && d._sizeOvertimeModule._enable === true ? d._sizeOvertimeModule : null;- out.endSizeMin = size.min;- out.endSizeMax = size.max;- const keys = sizeModule ? sizeKeys(sizeModule.size) : null;- if (keys) {- out.sizeCurve = { keys };- const end = sampleKeys(keys, 1);- out.endSizeMin = size.min * end;- out.endSizeMax = size.max * end;- }-- const rotationModule = isObj(d._rotationOvertimeModule) && d._rotationOvertimeModule._enable === true ? d._rotationOvertimeModule : null;- if (rotationModule) {- const spin = curveRange(rotationModule.z, 0, 0);- out.angularVelocityMin = spin.min;- out.angularVelocityMax = spin.max;- }-- // where particles start- const shape = isObj(d._shapeModule) && d._shapeModule._enable === true ? d._shapeModule : null;- if (shape) {- out.shape = SHAPE[num(shape._shapeType, 2)] ?? 3;- out.shapeRadius = num(shape.radius, 1);- out.shapeAngle = num(shape.angle, 25);- const scale = isObj(shape._scale) ? shape._scale : isObj(shape.scale) ? shape.scale : null;- if (scale) out.shapeSize = { x: num(scale.x, 1), y: num(scale.y, 1), z: num(scale.z, 1) };- } else {- out.shape = 0; // Point- }-- // bursts: each one fires at its time, `repeatCount` times `repeatInterval` apart, and the schedule repeats with the system's loop- const bursts = (Array.isArray(d.bursts) ? d.bursts : []).filter(isObj);- if (bursts.length > 0) {- const schedule: { time: number; count: number }[] = [];- for (const b of bursts) {- const count = Math.round(mid(curveRange(b.count, 0, 0)));- const repeats = Math.max(1, Math.min(Math.trunc(isObj(b.repeatCount) ? mid(curveRange(b.repeatCount, 1, 1)) : num(b._repeatCount ?? b.repeatCount, 1)), 64));- const every = Math.max(num(b.repeatInterval, 1), 0.01);- if (count <= 0) continue;- for (let i = 0; i < repeats && schedule.length < 64; i++) schedule.push({ time: Math.max(num(b._time, 0), 0) + i * every, count });- }- schedule.sort((a, c) => a.time - c.time);- if (schedule.length > 0) out.bursts = schedule;- }-- // a sheet of frames played over a life- const sheet = isObj(d._textureAnimationModule) && d._textureAnimationModule._enable === true ? d._textureAnimationModule : null;- if (sheet) {- const cols = Math.max(1, Math.trunc(num(sheet.numTilesX, 1)));- const rows = Math.max(1, Math.trunc(num(sheet.numTilesY, 1)));- out.spriteColumns = cols;- out.spriteRows = rows;- out.spriteFPS = (cols * rows * Math.max(1, num(sheet.cycleCount, 1))) / Math.max(mid(lifetime), 0.001);- }-- // the material says what is drawn and how it blends- const matUuid = ((Array.isArray(d._materials) ? d._materials[0] : undefined) as Raw | undefined)?.__uuid__;- const material = typeof matUuid === 'string' ? ctx.material?.(matUuid) ?? null : null;- if (material) {- if (material.texture) out.texture = ctx.assetRef(material.texture);- out.blendMode = material.additive ? 1 : 0;- // The project's own effect for it, when it was converted: its fragment draws the particle.- const converted = typeof matUuid === 'string' ? ctx.convertedMaterial?.(matUuid) ?? null : null;- if (converted) out.material = converted.ref;- } else {- lose('particle-no-material');- }-- // a velocity carried on top of the particle's own, chosen per axis when it is born- const velocity = enabledModule(d._velocityOvertimeModule);- if (velocity) {- const axes = (['x', 'y', 'z'] as const).map((a) => curveRange(velocity[a], 0, 0));- out.addedVelocityMin = { x: axes[0]!.min, y: axes[1]!.min, z: axes[2]!.min };- out.addedVelocityMax = { x: axes[0]!.max, y: axes[1]!.max, z: axes[2]!.max };- if (['x', 'y', 'z'].some((a) => [1, 2].includes(num((velocity[a] as Raw | undefined)?.mode, 0)))) lose('particle-velocity-curve');- if (mid(curveRange(velocity.speedModifier, 0, 1)) !== 1) lose('particle-velocity-speed-modifier');- }-- // a force is an acceleration: it joins gravity- const force = enabledModule(d._forceOvertimeModule);- if (force) {- const accel = (['x', 'y', 'z'] as const).map((a) => mid(curveRange(force[a], 0, 0)));- const g = out.gravity as { x: number; y: number; z: number };- out.gravity = { x: g.x + accel[0]!, y: g.y + accel[1]!, z: g.z + accel[2]! };- if (['x', 'y', 'z'].some((a) => [1, 2].includes(num((force[a] as Raw | undefined)?.mode, 0)))) lose('particle-force-curve');- }-- // the fastest a particle may go, pulled back by the dampen fraction- const limit = enabledModule(d._limitVelocityOvertimeModule);- if (limit) {- if (limit.separateAxes === true || limit._separateAxes === true) {- lose('particle-limit-per-axis');- } else {- out.speedLimit = Math.max(mid(curveRange(limit.limit, 0, 0)), 1e-4); // 0 means "stop" there, and "off" here- out.limitDampen = Math.min(1, Math.max(0, num(limit.dampen, 1)));- }- }-- // turbulence: a flow the particles are pushed along, as strong and as fine as the module says- const noise = enabledModule(d._noiseModule);- if (noise) {- const strength = (num(noise._strengthX, 0) + num(noise._strengthY, 0)) / 2;- out.noiseStrength = strength;- out.noiseFrequency = Math.max(num(noise._noiseFrequency, 1), 0.0001);- out.noiseScrollSpeed = (num(noise._noiseSpeedX, 0) + num(noise._noiseSpeedY, 0)) / 2;- out.noiseOctaves = Math.min(8, Math.max(1, Math.trunc(num(noise._octaves, 1))));- }-- // a ribbon behind each particle: how long it lives sets how many points it keeps, and the width is the ratio read at the head- const trail = enabledModule(d._trailModule);- if (trail) {- const life = mid(curveRange(trail.lifeTime, 0, 0.3));- const ratio = mid(curveRange(trail.widthRatio, 0, 1));- out.trailEnabled = true;- out.trailPoints = Math.min(12, Math.max(2, Math.round(life / 0.05)));- out.trailMinDistance = Math.max(0, num(trail._minParticleDistance, 0.1));- out.trailWidth = trail.widthFromParticle === true ? mid(size) * ratio : ratio;- if (isObj(trail.colorOverTrail) && num(trail.colorOverTrail._mode, 0) !== 0) lose('particle-trail-colour');- if (num(trail._space, 0) !== 0) lose('particle-trail-space');- }- const renderer = isObj(d.renderer) ? d.renderer : null;- const renderMode = renderer ? num(renderer._renderMode, 0) : 0;- if (renderMode === 1) {- out.renderMode = 1; // Stretched- out.velocityScale = num(renderer?._velocityScale, 0);- out.lengthScale = num(renderer?._lengthScale, 1);- } else if (renderMode !== 0) {- lose('particle-render-mode'); // horizontal, vertical and mesh particles have no counterpart- }-- ctx.report.component('cc.ParticleSystem', partial ? 'partial' : 'mapped');- return { type: 'ParticleEmitter', data: out };-}--export interface Particle2DContext extends ParticleContext {- /** The image of a sprite frame, as a project path. */- frame?(uuid: string): string | null;-}--/**- * `cc.ParticleSystem2D`: the 2D particle model of the older engine, a start and an end for size, spin and colour, each with a variance, and either- * gravity or a ring that the particles circle. The emitter's start and end ranges are the same idea; the gravity model maps, a radial one is counted.- */-export function particleSystem2D(c: { enabled: boolean; data: Raw }, ctx: Particle2DContext, where: string): { type: string; data: Raw } {- const d = c.data;- let partial = false;- const lose = (code: string): void => { partial = true; ctx.report.note(code, where); };- const life = num(d.life, 1), lifeVar = num(d.lifeVar, 0);- const speed = num(d.speed, 0), speedVar = num(d.speedVar, 0);- const angle = num(d.angle, 90), angleVar = num(d.angleVar, 0);- const startSize = num(d.startSize, 50), startSizeVar = num(d.startSizeVar, 0);- const endSize = num(d.endSize, 0), endSizeVar = num(d.endSizeVar, 0);- // a colour and its variance: the middle of the range it can start at (the variance is a spread around the colour)- const colour = (value: unknown): Rgba => colorOf(value);- const start = colour(d._startColor), end = colour(d._endColor);- const out: Raw = {- enabled: c.enabled,- looping: num(d.duration, -1) < 0,- playOnStart: d.playOnLoad !== false,- duration: num(d.duration, -1) < 0 ? 5 : num(d.duration, 5),- maxParticles: Math.max(1, Math.trunc(num(d._totalParticles, 150))),- rate: num(d.emissionRate, 100),- lifetimeMin: Math.max(0, life - lifeVar), lifetimeMax: life + lifeVar,- shape: 0, // Point: the position variance is a small box in the old model- angleSpreadMin: angle - angleVar, angleSpreadMax: angle + angleVar,- speedMin: Math.max(0, speed - speedVar), speedMax: speed + speedVar,- startSizeMin: Math.max(0, startSize - startSizeVar), startSizeMax: startSize + startSizeVar,- endSizeMin: Math.max(0, endSize - endSizeVar), endSizeMax: endSize + endSizeVar,- rotationMin: num(d.startSpin, 0) - num(d.startSpinVar, 0), rotationMax: num(d.startSpin, 0) + num(d.startSpinVar, 0),- startColor: { r: start[0], g: start[1], b: start[2], a: start[3] },- endColor: { r: end[0], g: end[1], b: end[2], a: end[3] },- simulationSpace: num(d._positionType, 0) === 0 ? 0 : 1, // free is the world's, relative and grouped follow the emitter- blendMode: num(d._dstBlendFactor, 1) === 1 ? 1 : 0,- };- // the spin that changes over a life is a steady turn from the start spin to the end spin- const spinChange = (num(d.endSpin, 0) - num(d.startSpin, 0)) / Math.max(life, 0.0001);- out.angularVelocityMin = spinChange - num(d.endSpinVar, 0) / Math.max(life, 0.0001);- out.angularVelocityMax = spinChange + num(d.endSpinVar, 0) / Math.max(life, 0.0001);- if (num(d.emitterMode, 0) === 0) {- const g = isObj(d.gravity) ? d.gravity : {};- out.gravity = { x: num(g.x, 0), y: num(g.y, 0), z: 0 };- if (num(d.tangentialAccel, 0) !== 0 || num(d.radialAccel, 0) !== 0) lose('particle2d-accel');- } else {- lose('particle2d-radius-mode');- }- const pos = isObj(d.posVar) ? d.posVar : {};- if (num(pos.x, 0) !== 0 || num(pos.y, 0) !== 0) lose('particle2d-position-variance');- const frameUuid = isObj(d._spriteFrame) && typeof d._spriteFrame.__uuid__ === 'string' ? d._spriteFrame.__uuid__ : '';- const texture = frameUuid ? ctx.frame?.(frameUuid) : null;- if (texture) out.texture = texture;- else lose('particle2d-no-texture');- ctx.report.component('cc.ParticleSystem2D', partial ? 'partial' : 'mapped');- return { type: 'ParticleEmitter', data: out };-}diff --git a/pipeline/src/import/cocos/report.ts b/pipeline/src/import/cocos/report.tsdeleted file mode 100644index fd71de07f..000000000--- a/pipeline/src/import/cocos/report.ts+++ /dev/null@@ -1,70 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file What an import did and did not carry across.- *- * A converter that only reports success is worse than none: a game that- * loads with half its UI missing looks like a runtime bug. Every- * component is counted as mapped, partial or unmapped, and every- * approximation names itself, so the gap is a list rather than a hunt.- */--export type MapStatus = 'mapped' | 'partial' | 'unmapped';--export interface ComponentTally { mapped: number; partial: number; unmapped: number }-export interface NoteTally { count: number; examples: string[] }--export interface ImportReportData {- documents: { converted: number; failed: { file: string; error: string }[] };- nodes: number;- prefabInstances: number;- components: Record<string, ComponentTally>;- notes: Record<string, NoteTally>;- assets: { textures: number; missing: string[] };- /** What a run did to documents already in the project: a document edited since the last run is kept, never overwritten. */- sync: { added: number; updated: number; unchanged: number; kept: string[] };-}--const EXAMPLES = 3;--export class ImportReport {- documents = { converted: 0, failed: [] as { file: string; error: string }[] };- nodes = 0;- prefabInstances = 0;- private readonly components = new Map<string, ComponentTally>();- private readonly notes = new Map<string, NoteTally>();- private readonly missing = new Set<string>();- textures = 0;- readonly sync = { added: 0, updated: 0, unchanged: 0, kept: [] as string[] };-- component(type: string, status: MapStatus): void {- let t = this.components.get(type);- if (!t) this.components.set(type, (t = { mapped: 0, partial: 0, unmapped: 0 }));- t[status]++;- }-- /** A thing approximated, dropped or not understood, keyed by a stable code. */- note(code: string, where: string): void {- let n = this.notes.get(code);- if (!n) this.notes.set(code, (n = { count: 0, examples: [] }));- n.count++;- if (n.examples.length < EXAMPLES && !n.examples.includes(where)) n.examples.push(where);- }-- missingAsset(uuid: string): void {- this.missing.add(uuid);- }-- toJSON(): ImportReportData {- const byCount = <T>(m: Map<string, T>, size: (v: T) => number): [string, T][] => [...m].sort((a, b) => size(b[1]) - size(a[1]));- return {- documents: this.documents,- nodes: this.nodes,- prefabInstances: this.prefabInstances,- components: Object.fromEntries(byCount(this.components, (v) => v.mapped + v.partial + v.unmapped)),- notes: Object.fromEntries(byCount(this.notes, (v) => v.count)),- assets: { textures: this.textures, missing: [...this.missing].slice(0, 50) },- sync: this.sync,- };- }-}diff --git a/pipeline/src/import/cocos/sceneAmbient.ts b/pipeline/src/import/cocos/sceneAmbient.tsdeleted file mode 100644index 7d7ee8e51..000000000--- a/pipeline/src/import/cocos/sceneAmbient.ts+++ /dev/null@@ -1,65 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file The ambient light most of a project's scenes share, as the values Cocos hands a fragment (`cc_ambientSky`, `cc_ambientGround`).- *- * A converted effect reads these as parameters of its material, which start at a value that changes nothing. A scene that lights its models by the- * ambient (a fake light that adds the ground colour times the sky's illumination) comes out as bright as that value is wrong, so the parameters- * start at what the project's scenes set: one value for every material, the one most of them agree on.- */-import { readFileSync } from 'node:fs';-import type { CocosAssetIndex } from './assets';--type Raw = Record<string, unknown>;-const isObj = (v: unknown): v is Raw => typeof v === 'object' && v !== null && !Array.isArray(v);--/** Scenes that are tools and tests of the editor: what they set is not what the game draws with. */-const NOT_THE_GAME = /(?:^|\/)(?:editor|test|tools?)(?:\/|$)|(?:^|\/)(?:MapEditor|scene-test)/i;--export interface SceneAmbient {- /** `cc_ambientSky`: the sky colour and, in w, the illumination it is lit by. */- sky: [number, number, number, number];- /** `cc_ambientGround`: the ground albedo, and 1. */- ground: [number, number, number, number];-}--const three = (v: unknown): [number, number, number] | null =>- isObj(v) && typeof v.x === 'number' && typeof v.y === 'number' && typeof v.z === 'number' ? [v.x, v.y, v.z] : null;--/** The ambient of one scene file, or null when it sets none. */-export function ambientOfScene(file: string): SceneAmbient | null {- try {- const objs = JSON.parse(readFileSync(file, 'utf8')) as unknown[];- const head = objs[0];- const scene = isObj(head) && isObj(head.scene) && typeof head.scene.__id__ === 'number' ? objs[head.scene.__id__] : null;- const globals = isObj(scene) && isObj(scene._globals) && typeof scene._globals.__id__ === 'number' ? objs[scene._globals.__id__] : null;- const info = isObj(globals) && isObj(globals.ambient) && typeof globals.ambient.__id__ === 'number' ? objs[globals.ambient.__id__] : null;- if (!isObj(info)) return null;- const sky = three(info._skyColorLDR);- const ground = three(info._groundAlbedoLDR);- if (!sky || !ground) return null;- const illum = typeof info._skyIllumLDR === 'number' ? info._skyIllumLDR : 1;- return { sky: [sky[0], sky[1], sky[2], illum], ground: [ground[0], ground[1], ground[2], 1] };- } catch {- return null;- }-}--/** The ambient most of the project's game scenes set, or null when none does. */-export function dominantAmbient(index: CocosAssetIndex): SceneAmbient | null {- const tally = new Map<string, { count: number; ambient: SceneAmbient }>();- const seen = new Set<string>();- for (const entry of index.byUuid.values()) {- if (seen.has(entry.file) || !entry.rel.endsWith('.scene') || NOT_THE_GAME.test(entry.rel)) continue;- seen.add(entry.file);- const ambient = ambientOfScene(entry.file);- if (!ambient) continue;- const key = [...ambient.sky, ...ambient.ground].map((x) => x.toFixed(4)).join(',');- const held = tally.get(key);- if (held) held.count++;- else tally.set(key, { count: 1, ambient });- }- let best: { count: number; ambient: SceneAmbient } | null = null;- for (const t of tally.values()) if (!best || t.count > best.count) best = t;- return best?.ambient ?? null;-}diff --git a/pipeline/src/import/cocos/scripts.ts b/pipeline/src/import/cocos/scripts.tsdeleted file mode 100644index a6353be82..000000000--- a/pipeline/src/import/cocos/scripts.ts+++ /dev/null@@ -1,68 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file Which script class a component of a Cocos scene is.- *- * A scene does not name a script component's class; it carries the script's uuid in a compressed form- * (five hex digits kept, the other twenty-seven as eighteen base64 characters). The uuid is the `.meta`- * of the script file, and the class name is what its `@ccclass('...')` says — which is also the name the- * compatibility layer registers the component under (`Cocos.<name>`).- *- * Read-only: scripts are read to find the name, never changed or copied.- */-import { readFileSync } from 'node:fs';-import type { CocosAssetIndex } from './assets';--const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';--/** Cocos's compressed uuid: what a script component's `__type__` is. */-export function compressUuid(uuid: string): string {- const hex = uuid.replaceAll('-', '').toLowerCase();- if (hex.length !== 32) return uuid;- let out = hex.slice(0, 5);- for (let i = 5; i < 32; i += 3) {- const v = parseInt(hex.slice(i, i + 3), 16);- out += B64[v >> 6]! + B64[v & 63]!;- }- return out;-}--export interface ScriptClass {- /** The `@ccclass` name, which the layer registers as `Cocos.<name>`. */- name: string;- /** Path of the script, relative to the project's `assets`. */- rel: string;- /** The `@ccclass` name the script wrote, when another script had it first and this class was given a name of its own. */- wrote?: string;-}--const NAMED = /@ccclass\(\s*['"]([^'"]+)['"]\s*\)/;-/** What may sit between the decorator and the class: other decorators, and comments. */-const BETWEEN = String.raw`(?:\s*(?:@[^\r\n]*|//[^\r\n]*))*\s*`;-/** `@ccclass` or `@ccclass()` takes the class's own name. */-const UNNAMED = new RegExp(String.raw`@ccclass(?:\(\s*\))?(?![\w(])${BETWEEN}(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+(\w+)`);--/** The compressed uuid of every script that declares a component class, mapped to that class. */-export function buildScriptIndex(assets: CocosAssetIndex): Map<string, ScriptClass> {- const out = new Map<string, ScriptClass>();- // Cocos tells classes apart by their script, so two may share a name; here a name is a component, so the second of a name (in path order,- // which is the same on every import) is numbered.- const taken = new Set<string>();- for (const entry of [...assets.byUuid.values()].sort((x, y) => (x.rel < y.rel ? -1 : x.rel > y.rel ? 1 : 0))) {- if (!/\.(ts|js)$/.test(entry.rel) || entry.rel.endsWith('.d.ts')) continue;- if (entry.importer !== 'typescript' && entry.importer !== 'javascript') continue;- let text: string;- try {- text = readFileSync(entry.file, 'utf8');- } catch {- continue;- }- const name = NAMED.exec(text)?.[1] ?? UNNAMED.exec(text)?.[1];- if (!name) continue;- let unique = name;- for (let n = 2; taken.has(unique); n++) unique = `${name}_${n}`;- taken.add(unique);- out.set(compressUuid(entry.uuid), { name: unique, rel: entry.rel, ...(unique !== name ? { wrote: name } : {}) });- }- return out;-}diff --git a/pipeline/tests/cocos-animation-clip.test.ts b/pipeline/tests/cocos-animation-clip.test.tsdeleted file mode 100644index 54546e70f..000000000--- a/pipeline/tests/cocos-animation-clip.test.ts+++ /dev/null@@ -1,118 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A Cocos `.anim` as an engine timeline: what each kind of track becomes, and what is counted instead of lost.- */-import { describe, expect, it } from 'vitest';-import { convertAnimationClip } from '../src/import/cocos/animationClip';--/** Build a `.anim`'s object list from tracks written as [binding path parts, track kind, curves]; ids are assigned as the list grows. */-function anim(tracks: Array<{ kind: string; path: unknown[]; curves: Array<{ times: number[]; values: unknown[] }> }>, over: Record<string, unknown> = {}): unknown[] {- const objects: unknown[] = [];- const add = (o: unknown): { __id__: number } => { objects.push(o); return { __id__: objects.length - 1 }; };- const clip: Record<string, unknown> = { __type__: 'cc.AnimationClip', _name: 'clip', wrapMode: 1, _duration: 1, _tracks: [], _events: [], ...over };- add(clip);- const refs = tracks.map((t) => {- const path = add({ __type__: 'cc.animation.TrackPath', _paths: t.path.map((p) => (typeof p === 'string' ? p : add(p))) });- const channels = t.curves.map((c) => add({ __type__: 'cc.animation.Channel', _curve: add({ __type__: 'cc.RealCurve', _times: c.times, _values: c.values }) }));- return add({ __type__: t.kind, _binding: { __type__: 'cc.animation.TrackBinding', path }, _channels: channels });- });- clip._tracks = refs;- return objects;-}-const real = (value: number, extra: object = {}) => ({ __type__: 'cc.RealKeyframeValue', interpolationMode: 0, value, leftTangent: 0, rightTangent: 0, ...extra });-const hierarchy = (path: string) => ({ __type__: 'cc.animation.HierarchyPath', path });-const component = (name: string) => ({ __type__: 'cc.animation.ComponentPath', component: name });--describe('a Cocos animation clip', () => {- it('moves a child node: position becomes the transform\'s three channels, under the child\'s path', () => {- const { document } = convertAnimationClip(anim([{- kind: 'cc.animation.VectorTrack', path: [hierarchy('body/arm'), 'position'],- curves: [- { times: [0, 1], values: [real(0), real(10)] }, { times: [0, 1], values: [real(5), real(5)] }, { times: [0, 1], values: [real(0), real(0)] },- ],- }]));- expect(document.tracks).toHaveLength(1);- const t = document.tracks[0] as any;- expect([t.type, t.childPath, t.component]).toEqual(['property', 'body/arm', 'Transform']);- expect(t.channels.map((c: any) => c.property)).toEqual(['position.x', 'position.y', 'position.z']);- expect(t.channels[0].keyframes.map((k: any) => k.value)).toEqual([0, 10]);- });-- it('fades a sprite: its colour keyed 0..255 becomes 0..1 on the Sprite', () => {- const key = (v: number) => real(v);- const curve = (a: number, b: number) => ({ times: [0, 1], values: [key(a), key(b)] });- const { document } = convertAnimationClip(anim([{- kind: 'cc.animation.ColorTrack', path: [component('cc.Sprite'), 'color'], curves: [curve(255, 255), curve(255, 255), curve(255, 255), curve(255, 0)],- }]));- const t = document.tracks[0] as any;- expect([t.component, t.childPath]).toEqual(['Sprite', '']);- expect(t.channels.map((c: any) => c.property)).toEqual(['color.r', 'color.g', 'color.b', 'color.a']);- expect(t.channels[3].keyframes.map((k: any) => k.value)).toEqual([1, 0]);- });-- it('turns a node about its Z: euler angles become the quaternion channels, sampled finely enough to follow the turn', () => {- const { document } = convertAnimationClip(anim([{- kind: 'cc.animation.VectorTrack', path: [hierarchy('wheel'), 'eulerAngles'],- curves: [{ times: [0, 1], values: [real(0), real(0)] }, { times: [0, 1], values: [real(0), real(0)] }, { times: [0, 1], values: [real(0), real(180)] }],- }]));- const t = document.tracks[0] as any;- expect(t.channels.map((c: any) => c.property)).toEqual(['rotation.x', 'rotation.y', 'rotation.z', 'rotation.w']);- const z = t.channels[2].keyframes;- const w = t.channels[3].keyframes;- expect(z.length).toBeGreaterThan(10);- expect(z[0].value).toBeCloseTo(0, 5);- expect(z[z.length - 1].value).toBeCloseTo(1, 5); // 180 degrees about Z: (0, 0, 1, 0)- expect(w[w.length - 1].value).toBeCloseTo(0, 5);- const mid = Math.floor(z.length / 2);- expect(Math.hypot(z[mid].value, w[mid].value)).toBeCloseTo(1, 2); // still a rotation half-way- });-- it('turns an active track into the ranges the node is on in', () => {- const { document } = convertAnimationClip(anim([{- kind: 'cc.animation.ObjectTrack', path: [hierarchy('flash'), 'active'], curves: [{ times: [0, 0.25, 0.5], values: [false, true, false] }],- }]));- expect(document.tracks[0]).toMatchObject({ type: 'activation', childPath: 'flash', ranges: [{ start: 0.25, end: 0.5 }] });- });-- it('keeps the key\'s curve: held, straight, or with its tangents', () => {- const { document } = convertAnimationClip(anim([{- kind: 'cc.animation.VectorTrack', path: ['scale'],- curves: [{ times: [0, 1, 2], values: [real(1, { interpolationMode: 1 }), real(2, { interpolationMode: 2, leftTangent: 3, rightTangent: 4 }), real(3)] },- { times: [0], values: [real(1)] }, { times: [0], values: [real(1)] }],- }], { _duration: 2 }));- const keys = (document.tracks[0] as any).channels[0].keyframes;- expect(keys.map((k: any) => k.interpolation)).toEqual(['step', 'hermite', 'linear']);- expect([keys[1].inTangent, keys[1].outTangent]).toEqual([3, 4]);- });-- it('plays once, loops or ping-pongs as the clip says, and counts what it cannot carry', () => {- expect(convertAnimationClip(anim([], { wrapMode: 2 })).document.wrapMode).toBe('loop');- expect(convertAnimationClip(anim([], { wrapMode: 36 })).document.wrapMode).toBe('pingPong');- expect(convertAnimationClip(anim([], { wrapMode: 1 })).document.wrapMode).toBe('once');- const clip = convertAnimationClip(anim([{- kind: 'cc.animation.RealTrack', path: [component('cc.ParticleSystem'), 'material'], curves: [{ times: [0], values: [real(1)] }],- }], { _events: [{}, {}] }));- expect(clip.document.tracks).toEqual([]);- expect(clip.skipped.get('cc.ParticleSystem.material')).toBe(1);- expect(clip.events).toBe(2);- });-});--describe('what the engine reads of it', () => {- it('parses every kind of track written here with the timeline loader the runtime uses', async () => {- const path = await import('node:path');- const { parseTimelineAsset } = await import(/* @vite-ignore */ path.resolve(__dirname, '../../sdk/src/timeline/TimelineLoader.ts'));- const curve = (v: number[]) => ({ times: v.map((_, i) => i), values: v.map((x) => real(x)) });- const clip = convertAnimationClip(anim([- { kind: 'cc.animation.VectorTrack', path: [hierarchy('a'), 'position'], curves: [curve([0, 1]), curve([0, 1]), curve([0, 0])] },- { kind: 'cc.animation.VectorTrack', path: [hierarchy('a'), 'eulerAngles'], curves: [curve([0, 0]), curve([0, 0]), curve([0, 90])] },- { kind: 'cc.animation.ColorTrack', path: [component('cc.Sprite'), 'color'], curves: [curve([255, 0]), curve([255, 0]), curve([255, 0]), curve([255, 0])] },- { kind: 'cc.animation.RealTrack', path: [component('cc.UIOpacity'), 'opacity'], curves: [curve([255, 0])] },- { kind: 'cc.animation.ObjectTrack', path: [hierarchy('b'), 'active'], curves: [{ times: [0, 1], values: [true, false] }] },- ], { wrapMode: 2 }));- const asset = parseTimelineAsset(clip.document);- expect(asset.tracks.map((t: any) => t.type)).toEqual(['property', 'property', 'property', 'property', 'activation']);- expect(asset.wrapMode).toBeDefined();- });-});diff --git a/pipeline/tests/cocos-animation-graph.test.ts b/pipeline/tests/cocos-animation-graph.test.tsdeleted file mode 100644index 1c8facc8c..000000000--- a/pipeline/tests/cocos-animation-graph.test.ts+++ /dev/null@@ -1,121 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A Cocos animation graph as the engine's animator controller: states, transitions, conditions and blends map one to one, and what the- * Animator cannot state is counted.- */-import { describe, expect, it } from 'vitest';-import path from 'node:path';-import { convertAnimationGraph } from '../src/import/cocos/animationGraph';--/** A graph: attack/move/idle on one layer, driven by a trigger, a number and a flag. Ids are positions in the list. */-function graph(over: { motionSpeedFollows?: boolean; inclusive?: boolean } = {}): unknown[] {- const o: unknown[] = [];- const add = (x: unknown): { __id__: number } => { o.push(x); return { __id__: o.length - 1 }; };- const root: Record<string, unknown> = { __type__: 'cc.animation.AnimationGraph', _layers: [], _variables: {} };- add(root);- const layer: Record<string, unknown> = { __type__: 'cc.animation.Layer', name: '', weight: 1, mask: null };- root._layers = [add(layer)];- const machine: Record<string, unknown> = { __type__: 'cc.animation.StateMachine', _states: [], _transitions: [] };- layer._stateMachine = add(machine);- const entry = add({ __type__: 'cc.animation.State', name: 'Entry' });- const exit = add({ __type__: 'cc.animation.State', name: 'Exit' });- const any = add({ __type__: 'cc.animation.State', name: 'Any State' });- const clip = (uuid: string) => add({ __type__: 'cc.animation.ClipMotion', clip: { __uuid__: uuid } });- const idle = add({ __type__: 'cc.animation.Motion', name: 'idle', motion: clip('idle-clip'), speed: 1 });- const blend = add({- __type__: 'cc.animation.AnimationBlend1D', name: 'move', param: add({ __type__: 'cc.animation.BindableNumber', variable: 'MoveSpeed', value: 0 }),- _items: [- add({ __type__: 'cc.animation.AnimationBlend1DItem', motion: clip('walk-clip'), threshold: 0 }),- add({ __type__: 'cc.animation.AnimationBlend1DItem', motion: clip('run-clip'), threshold: 1 }),- ],- });- const move = add({ __type__: 'cc.animation.Motion', name: 'move', motion: blend, speed: 2, speedMultiplierEnabled: over.motionSpeedFollows === true, speedMultiplier: 'MoveSpeed' });- const attack = add({ __type__: 'cc.animation.Motion', name: 'attack', motion: clip('attack-clip'), speed: 1 });- machine._states = [entry, exit, any, idle, move, attack];- machine._entryState = entry; machine._exitState = exit; machine._anyState = any;- root._variables = {- MoveSpeed: add({ __type__: 'cc.animation.PlainVariable', _type: 0, _value: 0 }),- Grounded: add({ __type__: 'cc.animation.PlainVariable', _type: 2, _value: true }),- hit: add({ __type__: 'cc.animation.TriggerVariable', _flags: 0 }),- };- const trig = (name: string) => add({ __type__: 'cc.animation.TriggerCondition', trigger: name });- const flag = (name: string, operator: number) => add({ __type__: 'cc.animation.UnaryCondition', operator, operand: add({ __type__: 'cc.animation.BindableBoolean', variable: name, value: false }) });- const faster = add({- __type__: 'cc.animation.BinaryCondition', operator: over.inclusive ? 5 : 4,- lhs: add({ __type__: 'cc.animation.BindableNumber', variable: 'MoveSpeed', value: 0 }), rhs: add({ __type__: 'cc.animation.BindableNumber', variable: '', value: 0.5 }),- });- machine._transitions = [- add({ __type__: 'cc.animation.Transition', from: entry, to: idle, conditions: [] }),- add({ __type__: 'cc.animation.AnimationTransition', from: idle, to: move, conditions: [faster, flag('Grounded', 0)], duration: 0.2, exitConditionEnabled: false }),- add({ __type__: 'cc.animation.AnimationTransition', from: any, to: attack, conditions: [trig('hit')], duration: 0 }),- add({ __type__: 'cc.animation.AnimationTransition', from: attack, to: idle, conditions: [], duration: 0.1, exitConditionEnabled: true }),- add({ __type__: 'cc.animation.AnimationTransition', from: move, to: exit, conditions: [] }),- ];- return o;-}--const convert = (objects: unknown[]) => {- const notes: string[] = [];- const result = convertAnimationGraph(objects, { clip: (uuid) => (uuid === 'run-clip' ? null : `clips/${uuid}.estimeline`), note: (c) => notes.push(c) });- return { ...result, notes, doc: result.document as any };-};--describe('a Cocos animation graph', () => {- it('keeps its parameters: numbers, flags and triggers', () => {- const { doc } = convert(graph());- expect(doc.parameters).toEqual([- { name: 'MoveSpeed', type: 'float', default: 0 }, { name: 'Grounded', type: 'bool', default: true }, { name: 'hit', type: 'trigger' },- ]);- });-- it('starts where the entry state leads and names the states it plays', () => {- const { doc } = convert(graph());- expect(doc.initialState).toBe('idle');- expect(doc.states.map((s: any) => s.name)).toEqual(['idle', 'move', 'attack']);- expect(doc.states[0].motion).toEqual({ kind: 'timeline', clip: 'clips/idle-clip.estimeline' });- expect(doc.states[1].speed).toBe(2);- });-- it('turns a 1D blend into a blend over its clips, and drops a clip the node has no bones for', () => {- const { doc, notes } = convert(graph());- const blend = doc.states[1].motion;- expect(blend.kind).toBe('blend1d');- expect(blend.parameter).toBe('MoveSpeed');- expect(blend.thresholds).toEqual([{ value: 0, motion: { kind: 'timeline', clip: 'clips/walk-clip.estimeline' } }]);- expect(notes).toContain('graph-clip-not-found');- });-- it('carries transitions with their conditions, blend time and wait for the clip to end', () => {- const { doc } = convert(graph());- expect(doc.states[0].transitions).toEqual([{- to: 'move', duration: 0.2,- conditions: [{ param: 'MoveSpeed', op: 'gt', value: 0.5 }, { param: 'Grounded', op: 'true' }],- }]);- expect(doc.states[2].transitions).toEqual([{ to: 'idle', duration: 0.1, hasExitTime: true, conditions: [] }]);- });-- it('puts what leaves the any-state in the any-state transitions, and says what leaves for the exit state', () => {- const { doc, notes } = convert(graph());- expect(doc.anyStateTransitions).toEqual([{ to: 'attack', conditions: [{ param: 'hit', op: 'trigger' }] }]);- expect(notes).toContain('graph-transition-to-exit');- });-- it('makes a state\'s speed follow the variable Cocos names, and counts one it cannot find', () => {- const { doc, notes } = convert(graph({ motionSpeedFollows: true }));- expect(doc.states[1].speedParameter).toBe('MoveSpeed');- expect(notes).not.toContain('graph-speed-variable-missing');- expect(convert(graph()).doc.states[1].speedParameter).toBeUndefined();- });-- it('counts a comparison the Animator has only in strict form', () => {- expect(convert(graph({ inclusive: true })).notes).toContain('graph-condition-inclusive');- });-- it('is a controller the engine accepts', async () => {- const { migrateAnimatorController } = await import(/* @vite-ignore */ path.resolve(__dirname, '../../sdk/src/animation/animatorMigrate.ts'));- const migrated = migrateAnimatorController(convert(graph()).document);- expect(migrated.def.states.map((s: any) => s.name)).toEqual(['idle', 'move', 'attack']);- expect(migrated.def.initialState).toBe('idle');- });-});diff --git a/pipeline/tests/cocos-camera-clear.test.ts b/pipeline/tests/cocos-camera-clear.test.tsdeleted file mode 100644index 95b7c94b7..000000000--- a/pipeline/tests/cocos-camera-clear.test.ts+++ /dev/null@@ -1,16 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A Cocos camera's `_clearFlags` become the engine's: the UI camera clears depth only, so what the world camera drew under it stays.- */-import { describe, expect, it } from 'vitest';-import { engineClearFlags } from '../src/import/cocos/components';--describe('engineClearFlags', () => {- it('maps the graphics API bits to colour and depth', () => {- expect(engineClearFlags(7)).toBe(3); // solid colour: colour, depth, stencil- expect(engineClearFlags(6)).toBe(2); // depth only: the UI camera's- expect(engineClearFlags(0)).toBe(0); // does not clear- expect(engineClearFlags(14)).toBe(3); // a skybox the engine does not have: cleared to colour- });-});diff --git a/pipeline/tests/cocos-class-names.test.ts b/pipeline/tests/cocos-class-names.test.tsdeleted file mode 100644index f959778f0..000000000--- a/pipeline/tests/cocos-class-names.test.ts+++ /dev/null@@ -1,90 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file Two Cocos scripts may write the same `@ccclass` name (Cocos tells classes apart by their script). Here a name is a component, so- * the second is given a name of its own, and the decorator in the bundle says so.- */-import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';-import path from 'node:path';-import { afterAll, beforeAll, describe, expect, it } from 'vitest';-import { build } from 'esbuild';-import { importCocosProject } from '../src/import/cocos';-import { buildCocosAssetIndex } from '../src/import/cocos/assets';-import { buildScriptIndex, compressUuid } from '../src/import/cocos/scripts';-import { cocosCompatPlugin, renameClass } from '../src/bundle/cocosCompat';--const A = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';-const B = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';-const meta = (uuid: string, importer: string): object => ({ ver: '1', importer, uuid, subMetas: {}, userData: {} });--describe('two scripts that write the same class name', () => {- let root: string;- beforeAll(async () => {- root = mkdtempSync(path.join(tmpdir(), 'cocos-names-'));- const put = (rel: string, v: string | object): void => {- const f = path.join(root, 'creator', 'assets', rel);- mkdirSync(path.dirname(f), { recursive: true });- writeFileSync(f, typeof v === 'string' ? v : JSON.stringify(v));- };- put('a/Skin.ts', "import { _decorator, Component } from 'cc';\nconst { ccclass } = _decorator;\n@ccclass('Skin')\nexport class Skin extends Component {}\n");- put('a/Skin.ts.meta', meta(A, 'typescript'));- put('b/Skin.ts', "import { _decorator, Component } from 'cc';\nconst { ccclass } = _decorator;\n@ccclass('Skin')\nexport class Skin extends Component {}\n");- put('b/Skin.ts.meta', meta(B, 'typescript'));- const unit = { __type__: 'cc.Vec3', x: 1, y: 1, z: 1 };- const zero = { __type__: 'cc.Vec3', x: 0, y: 0, z: 0 };- const node = (name: string, comp: number): object => ({ __type__: 'cc.Node', _name: name, _parent: { __id__: 1 }, _children: [], _active: true, _components: [{ __id__: comp }], _prefab: null, _lpos: zero, _lrot: { __type__: 'cc.Quat', x: 0, y: 0, z: 0, w: 1 }, _lscale: unit, _layer: 1 });- put('main.scene', [- { __type__: 'cc.SceneAsset', _name: 'main', scene: { __id__: 1 } },- { __type__: 'cc.Scene', _name: 'main', _children: [{ __id__: 2 }, { __id__: 3 }] },- node('one', 4), node('two', 5),- { __type__: compressUuid(A), node: { __id__: 2 }, _enabled: true, hp: 1 },- { __type__: compressUuid(B), node: { __id__: 3 }, _enabled: true, mp: 2 },- ]);- put('main.scene.meta', meta('dddddddd-dddd-4ddd-8ddd-dddddddddddd', 'scene'));- mkdirSync(path.join(root, 'out', 'src'), { recursive: true });- writeFileSync(path.join(root, 'out', 'src', 'main.ts'), "// entry\nimport './components';\n");- await importCocosProject({ source: path.join(root, 'creator'), out: path.join(root, 'out') });- });- afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));-- it('numbers the second, in path order', () => {- const index = buildScriptIndex(buildCocosAssetIndex(path.join(root, 'creator', 'assets')));- expect(index.get(compressUuid(A))).toEqual({ name: 'Skin', rel: 'a/Skin.ts' });- expect(index.get(compressUuid(B))).toEqual({ name: 'Skin_2', rel: 'b/Skin.ts', wrote: 'Skin' });- });-- it('names each instance by its own class in the scene', () => {- const scene = JSON.parse(readFileSync(path.join(root, 'out', 'assets', 'cocos', 'main.esscene'), 'utf8')) as { entities: Array<{ name: string; components: Array<{ type: string }> }> };- const types = (name: string) => scene.entities.find((e) => e.name === name)!.components.map((c) => c.type);- expect(types('one')).toContain('Cocos.Skin');- expect(types('two')).toContain('Cocos.Skin_2');- });-- it('writes which script was renamed, beside the entry, and the editor declarations carry both', () => {- const names = JSON.parse(readFileSync(path.join(root, 'out', 'src', 'cocos-class-names.json'), 'utf8')) as Record<string, { from: string; to: string }>;- expect(Object.values(names)).toEqual([{ from: 'Skin', to: 'Skin_2' }]);- const components = readFileSync(path.join(root, 'out', 'src', 'components.ts'), 'utf8');- expect(components).toContain('"Cocos.Skin"');- expect(components).toContain('"Cocos.Skin_2"');- });-- it('bundles the renamed class under its new name', async () => {- const result = await build({- entryPoints: [path.join(root, 'out', 'src', 'cocos-scripts.ts')],- bundle: true, write: false, format: 'esm', platform: 'browser', logLevel: 'silent',- external: ['esengine/cocos'], plugins: [cocosCompatPlugin()],- }).catch((e) => e);- const text = result.outputFiles?.[0]?.text ?? '';- expect((text.match(/ccclass\d*\("Skin_2"\)/g) ?? []).length).toBe(1);- expect((text.match(/ccclass\d*\("Skin"\)/g) ?? []).length).toBe(1);- });-});--describe('renaming a decorator', () => {- it('rewrites the named form and the bare one', () => {- expect(renameClass("@ccclass('Skin')\nclass Skin {}", 'Skin', 'Skin_2')).toContain("@ccclass('Skin_2')");- expect(renameClass('@ccclass("Skin")\nclass Skin {}', 'Skin', 'Skin_2')).toContain("@ccclass('Skin_2')");- expect(renameClass('@ccclass\nclass Skin {}', 'Skin', 'Skin_2')).toContain("@ccclass('Skin_2')");- });-});diff --git a/pipeline/tests/cocos-compat-bundle.test.ts b/pipeline/tests/cocos-compat-bundle.test.tsdeleted file mode 100644index 7037753b0..000000000--- a/pipeline/tests/cocos-compat-bundle.test.ts+++ /dev/null@@ -1,118 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A Cocos script bundles against the engine: `cc` and `cc/env` become `esengine/cocos`, however the build resolves that, and- * the script's decorators come out in the legacy form the layer's `@ccclass` / `@property` take.- */-import { existsSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';-import path from 'node:path';-import { afterAll, beforeAll, describe, expect, it } from 'vitest';-import { build } from 'esbuild';-import { cocosCompatPlugin } from '../src/bundle/cocosCompat';--const SCRIPT = `-import { _decorator, Component } from 'cc';-import { EDITOR } from 'cc/env';-const { ccclass, property } = _decorator;--@ccclass('Counter')-export class Counter extends Component {- @property speed = 3;- start() { if (EDITOR) return; this.speed++; }-}-`;--describe('bundling a Cocos script', () => {- let root: string;- beforeAll(() => {- root = mkdtempSync(path.join(tmpdir(), 'cocos-compat-'));- mkdirSync(path.join(root, 'scripts'));- writeFileSync(path.join(root, 'scripts', 'Counter.ts'), SCRIPT);- // A file that is not a Cocos script keeps its own rules: no `cc` import, so it is not touched.- writeFileSync(path.join(root, 'scripts', 'Plain.ts'), 'export const answer: number = 42;\n');- writeFileSync(path.join(root, 'layer.js'), 'export const _decorator = { ccclass: (n) => (c) => c, property: () => () => {} };\nexport class Component {}\nexport const EDITOR = false;\n');- });- afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));-- const run = (extra: object) => build({- entryPoints: [path.join(root, 'scripts', 'Counter.ts')],- bundle: true, write: false, format: 'esm', platform: 'browser', logLevel: 'silent',- plugins: [cocosCompatPlugin()], ...extra,- });-- it('leaves cc and cc/env as esengine/cocos when the build keeps esengine external', async () => {- const out = (await run({ external: ['esengine', 'esengine/*'] })).outputFiles[0]!.text;- expect(out).toMatch(/from "esengine\/cocos"/);- expect(out).not.toMatch(/from "cc/);- });-- it('inlines the layer when the build aliases it, for the builds that have no import map', async () => {- const out = (await run({ alias: { 'esengine/cocos': path.join(root, 'layer.js') }, format: 'iife' })).outputFiles[0]!.text;- expect(out).not.toMatch(/esengine\/cocos|from "cc/);- expect(out).toMatch(/Component = class|class Component/); // the layer's own text is in the bundle- });-- it('lowers decorators in the legacy form with fields assigned, not defined', async () => {- const out = (await run({ external: ['esengine/*'] })).outputFiles[0]!.text;- expect(out).toMatch(/__decorateClass|__decorate\(/);- expect(out).not.toMatch(/__esDecorate|__publicField/);- expect(out).toMatch(/this\.speed = 3/);- });-- it('says what it could not do, in the layer\'s terms, when the layer does not resolve', async () => {- await expect(run({})).rejects.toMatchObject({ errors: expect.arrayContaining([expect.objectContaining({ text: expect.stringContaining('esengine/cocos') })]) });- });-- it('does not touch a file that is not a Cocos script', async () => {- const plain = await build({- entryPoints: [path.join(root, 'scripts', 'Plain.ts')], bundle: true, write: false, format: 'esm', logLevel: 'silent', plugins: [cocosCompatPlugin()],- });- expect(plain.outputFiles[0]!.text).toContain('answer = 42');- });-- // Against the SDK as built, when it has been: every name a script imports from `cc` must be a name the layer exports, or the- // bundle fails with esbuild's "no matching export" at the script, not at a user's first run.- const BUILT = path.resolve(__dirname, '../../sdk/dist/cocos/index.js');- it.skipIf(!existsSync(BUILT))('bundles against the layer as built, for the names a script commonly imports', async () => {- const names = ['_decorator', 'Component', 'Node', 'Vec2', 'Vec3', 'Quat', 'Color', 'Size', 'Rect', 'director', 'UITransform', 'Label',- 'Sprite', 'Button', 'Widget', 'Layout', 'EventTouch', 'NodeEventType', 'EventHandler', 'Prefab', 'SpriteFrame', 'v2', 'v3', 'find', 'isValid'];- writeFileSync(path.join(root, 'scripts', 'Names.ts'), `import { ${names.join(', ')} } from 'cc';-import { EDITOR, DEBUG } from 'cc/env';-export default [${names.join(', ')}, EDITOR, DEBUG];-`);- const result = await build({- entryPoints: [path.join(root, 'scripts', 'Names.ts')], bundle: true, write: false, format: 'esm', platform: 'browser', logLevel: 'silent',- alias: { 'esengine/cocos': BUILT }, plugins: [cocosCompatPlugin()],- });- expect(result.errors).toEqual([]);- });-});--describe('a const the script assigns to again', () => {- it('is read as let, and only that one', async () => {- const { letTheReassignedConsts } = await import('../src/bundle/cocosCompat');- const fixed = letTheReassignedConsts('const a = null;\nconst b = 1;\nif (x) {\n a = 2;\n}\nconst c: number = 3;\n c += 1;\nuse(b == 1, a);');- expect(fixed).toContain('let a = null');- expect(fixed).toContain('const b = 1');- expect(fixed).toContain('let c: number = 3');- });- it('leaves a source with no reassignment as it is', async () => {- const { letTheReassignedConsts } = await import('../src/bundle/cocosCompat');- const src = 'const a = 1;\nconst f = () => a === 2 ? a : 3;\nconst o = { a: 1 };\no.a = 2;\n';- expect(letTheReassignedConsts(src)).toBe(src);- });-});--describe('named imports from cc', () => {- it('are read from the layer namespace, so a name the layer lacks is undefined instead of a build error', async () => {- const { readNamedImportsThroughNamespace } = await import('../src/bundle/cocosCompat');- const out = readNamedImportsThroughNamespace("const { ccclass } = _decorator;\nimport { _decorator, Node as N, type Vec3, gfx } from 'cc';\nimport { EDITOR } from 'cc/env';\nconst x = 1;");- // the bindings come first, on line one: a script may use a name above the import line that declares it- expect(out.startsWith("import * as __cc0 from 'cc'; const _decorator = __cc0._decorator ?? __cc0.unsupported(\"_decorator\"), N = __cc0.Node ?? __cc0.unsupported(\"Node\"), gfx = __cc0.gfx ?? __cc0.unsupported(\"gfx\");")).toBe(true);- expect(out).toContain("import * as __cc1 from 'cc/env'; const EDITOR = __cc1.EDITOR ?? __cc1.unsupported(\"EDITOR\");");- expect(out.split('\n')).toHaveLength(4);- expect(out).toContain('const { ccclass } = _decorator;');- expect(out).toContain('const x = 1;');- });-});diff --git a/pipeline/tests/cocos-editbox-fold.test.ts b/pipeline/tests/cocos-editbox-fold.test.tsdeleted file mode 100644index c9f52240e..000000000--- a/pipeline/tests/cocos-editbox-fold.test.ts+++ /dev/null@@ -1,64 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A Cocos edit box becomes the engine's text field with the style its two labels had, and the labels are not written.- */-import { describe, expect, it } from 'vitest';-import { foldEditBoxes, type FoldEntity } from '../src/import/cocos/editBoxFold';--interface E extends FoldEntity { id: string }--const rect = (w: number, h: number, px = 0.5, py = 0.5) => ({ type: 'ContentRect', data: { size: { x: w, y: h }, pivot: { x: px, y: py } } });-const at = (x: number, y = 0) => ({ type: 'Transform', data: { position: { x, y, z: 0 } } });-const color = (r: number, g: number, b: number) => ({ r, g, b, a: 1 });--function field(over: Record<string, unknown> = {}): E[] {- return [- {- id: 'box', children: ['text', 'hint', 'other'],- components: [- at(0), rect(400, 80),- { type: 'Cocos.EditBox', data: { string_: '7930', maxLength: 20, inputMode: 6, inputFlag: 5, returnType: 0, tabIndex: 0, textLabel: 'text', placeholderLabel: 'hint', ...over } },- ],- },- { id: 'text', children: ['caretInside'], components: [at(-180), rect(380, 80, 0, 0.5), { type: 'Text', data: { content: '', fontSize: 36, color: color(1, 1, 1), align: 0, fontFamily: 'Arial', renderMode: 0 } }] },- { id: 'caretInside', children: [], components: [at(0), rect(2, 30)] },- { id: 'hint', children: [], components: [at(-180), rect(380, 80, 0, 0.5), { type: 'Text', data: { content: '输入账号', fontSize: 36, color: color(0.5, 0.5, 0.5), align: 0 } }] },- { id: 'other', children: [], components: [at(100), rect(40, 40)] },- ];-}--describe('folding an edit box into the engine field', () => {- it('becomes a TextInput with the style of its labels, and the labels are not kept', () => {- const out = foldEditBoxes(field(), (e) => e.id);- expect(out.map((e) => e.id)).toEqual(['box', 'other']);- const box = out[0]!;- expect(box.children).toEqual(['other']);- const input = box.components.find((c) => c.type === 'TextInput')!;- expect(box.components.some((c) => c.type === 'Cocos.EditBox')).toBe(false);- expect(input.data).toMatchObject({- value: '7930', placeholder: '输入账号', maxLength: 20, multiline: false, password: false, inputFilter: 0,- fontSize: 36, fontFamily: 'Arial', textAlign: 0,- color: color(1, 1, 1), placeholderColor: color(0.5, 0.5, 0.5),- });- // the text starts 20 units inside the box's left edge: that is the field's padding- expect(input.data.padding).toBe(20);- });-- it('turns the input mode into the field\'s filter and line mode, and the flag into a password', () => {- const numeric = foldEditBoxes(field({ inputMode: 2 }), (e) => e.id)[0]!.components.find((c) => c.type === 'TextInput')!;- expect(numeric.data).toMatchObject({ inputFilter: 1, multiline: false });- const any = foldEditBoxes(field({ inputMode: 0 }), (e) => e.id)[0]!.components.find((c) => c.type === 'TextInput')!;- expect(any.data).toMatchObject({ inputFilter: 0, multiline: true });- const secret = foldEditBoxes(field({ inputFlag: 0 }), (e) => e.id)[0]!.components.find((c) => c.type === 'TextInput')!;- expect(secret.data.password).toBe(true);- // no limit in Cocos is a negative one; the field's is zero- const unlimited = foldEditBoxes(field({ maxLength: -1 }), (e) => e.id)[0]!.components.find((c) => c.type === 'TextInput')!;- expect(unlimited.data.maxLength).toBe(0);- });-- it('leaves a scene with no edit box exactly as it is', () => {- const plain: E[] = [{ id: 'a', children: ['b'], components: [at(0)] }, { id: 'b', children: [], components: [at(1)] }];- expect(foldEditBoxes(plain, (e) => e.id)).toBe(plain);- });-});diff --git a/pipeline/tests/cocos-effect-convert.test.ts b/pipeline/tests/cocos-effect-convert.test.tsdeleted file mode 100644index 1165f9b16..000000000--- a/pipeline/tests/cocos-effect-convert.test.ts+++ /dev/null@@ -1,290 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A Cocos `.effect` pass as an Estella `.esshader`: what is read from the effect, what the converted fragment declares, and which passes are- * not converted because the engine's vertex stage cannot stand in for theirs.- */-import { describe, expect, it } from 'vitest';-import { parseEffect, describeEffect } from '../src/import/cocos/effects';-import { convertEffect, convertPass, pruneUnreachable } from '../src/import/cocos/effectConvert';--const SPRITE_ADD = `-CCEffect %{- techniques:- - passes:- - vert: sprite-vs:vert- frag: sprite-fs:frag- depthStencilState: { depthTest: false, depthWrite: false }- blendState:- targets:- - blend: true- blendSrc: src_alpha- blendDst: one- rasterizerState: { cullMode: none }- properties:- addColor: { value: [0.0, 0.5, 0.25, 1], editor: { type: color } }- addWeight: { value: 1.0 }- mainTexture: { value: grey }-}%-CCProgram sprite-vs %{- precision highp float;- #include <builtin/uniforms/cc-global>- in vec3 a_position;- in vec2 a_texCoord;- in vec4 a_color;- out vec4 color;- out vec2 uv0;- vec4 vert () {- vec4 pos = cc_matViewProj * vec4(a_position, 1);- uv0 = a_texCoord;- color = a_color;- return pos;- }-}%-CCProgram sprite-fs %{- precision highp float;- #include <builtin/internal/alpha-test>- in vec4 color;- in vec2 uv0;- uniform sampler2D mainTexture;- uniform Constant {- vec4 addColor;- float addWeight;- };- vec4 frag () {- vec4 o = texture(mainTexture, uv0) * color;- #if USE_GLOW- o.rgb += addColor.rgb * addWeight;- #endif- #if !USE_GLOW && USE_TINT- o.rgb *= 0.5;- #endif- ALPHA_TEST(o);- return CCFragOutput(o);- }-}%-`;--// The Creator install's own chunk, which a project has no copy of: the alpha test applies only where the effect switches USE_ALPHA_TEST on.-const ALPHA_TEST_CHUNK = `-#if USE_ALPHA_TEST- uniform ALPHA_TEST_DATA {- float alphaThreshold;- };-#endif-void ALPHA_TEST (in vec4 color) {- #if USE_ALPHA_TEST- if (color.a < alphaThreshold) discard;- #endif-}-`;-const chunk = (name: string): string | null => (name === 'builtin/internal/alpha-test' ? ALPHA_TEST_CHUNK : null);-const convertWithChunks = (effect: ReturnType<typeof parseEffect>, stem: string) => convertEffect(effect, stem, { chunk });--describe('reading an effect', () => {- it('reads its techniques, passes and properties, and its programs', () => {- const effect = parseEffect(SPRITE_ADD);- expect(effect.techniques).toHaveLength(1);- const pass = effect.techniques[0]!.passes[0]!;- expect(pass.frag).toBe('sprite-fs:frag');- expect(pass.properties.map((p) => [p.name, p.editorType])).toEqual([['addColor', 'color'], ['addWeight', null], ['mainTexture', null]]);- expect([...effect.programs.keys()]).toEqual(['sprite-vs', 'sprite-fs']);- });-- it('says what the programs ask of the renderer', () => {- const facts = describeEffect(parseEffect(SPRITE_ADD), 'sprite-add.effect');- expect(facts.kind).toBe('sprite');- expect(facts.macros).toEqual(['USE_GLOW', 'USE_TINT']);- expect(facts.usesLighting).toBe(false);- expect(facts.samplers).toBe(1);- });-});--describe('converting a pass', () => {- const pass = convertWithChunks(parseEffect(SPRITE_ADD), 'sprite-add').techniques[0]!.passes[0]!;-- it('turns the Constant block and the samplers into parameters, with the effect\'s defaults', () => {- expect(pass.unsupported).toBeNull();- const source = pass.shader!.source;- expect(source).toContain('#pragma param addColor color default(0,0.5,0.25,1)');- expect(source).toContain('#pragma param addWeight float default(1)');- expect(source).toContain('#pragma param mainTexture texture default(grey)');- expect(source).not.toMatch(/uniform\s+Constant/);- expect(source).not.toMatch(/uniform sampler2D mainTexture/);- });-- it('runs the effect vertex program ahead of the fragment, on what the engine vertex stage hands down', () => {- const source = pass.shader!.source;- expect(source).not.toContain('#pragma vertex');- expect(source).toContain('in vec2 v_texCoord;');- expect(source).toContain('vec4 cocos_vert()');- expect(source).toContain('a_texCoord = v_texCoord;');- expect(source).toContain(' cocos_vert();\n fragColor = cocos_frag();');- });-- it('makes the macros it branches on switches, asked as defined() because an undefined name is an error in GLSL ES', () => {- expect(pass.shader!.switches).toEqual(['USE_ALPHA_TEST', 'USE_GLOW', 'USE_TINT']);- const source = pass.shader!.source;- expect(source).toContain('#pragma switch USE_GLOW default(off)');- expect(source).toContain('#if defined(USE_GLOW)');- expect(source).toContain('#if !defined(USE_GLOW) && defined(USE_TINT)');- });-- it('reads the alpha test from the install chunk, so it applies only where the effect switches it on', () => {- const source = pass.shader!.source;- expect(source).toContain('#pragma param alphaThreshold float default(0.5)');- expect(source).toContain('#if defined(USE_ALPHA_TEST)');- expect(source).toContain('void ALPHA_TEST (in vec4 color)');- expect(source).not.toContain('#define ALPHA_TEST(c)');- });-- it('has no switches when a material fixes its macros: they are baked in, and what is off is not defined', () => {- const effect = parseEffect(SPRITE_ADD);- const baked = convertPass(effect, effect.techniques[0]!.passes[0]!, 'baked', { chunk }, { USE_GLOW: true, USE_TINT: false });- expect(baked.unsupported).toBeNull();- const source = baked.shader!.source;- expect(baked.shader!.switches).toEqual([]);- expect(source).not.toContain('#pragma switch');- expect(source).toContain('#define USE_GLOW 1');- expect(source).not.toContain('#define USE_TINT');- expect(source).not.toContain('#define USE_ALPHA_TEST');- });-- it('bakes a macro the code only reads, such as the channel a material names for its alpha test', () => {- const channel = SPRITE_ADD.replace('vec4 o = texture(mainTexture, uv0) * color;', 'vec4 o = texture(mainTexture, uv0) * color;\n float edge = o.TEST_CHANNEL;');- const effect = parseEffect(channel);- const baked = convertPass(effect, effect.techniques[0]!.passes[0]!, 'channel', { chunk }, { TEST_CHANNEL: 'r' });- expect(baked.unsupported).toBeNull();- expect(baked.shader!.source).toContain('#define TEST_CHANNEL r');- });-- it('converts a pass written as GLSL main() programs, which write gl_Position and an out colour instead of returning them', () => {- const raw = `-CCEffect %{- techniques:- - passes:- - vert: raw-vs- frag: raw-fs- properties:- tint: { value: [1, 0.5, 0.25, 1], editor: { type: color } }-}%-CCProgram raw-vs %{- precision highp float;- #include <builtin/uniforms/cc-global>- in vec3 a_position;- in vec2 a_texCoord;- out vec2 v_uv;- void main () {- v_uv = a_texCoord;- gl_Position = cc_matViewProj * vec4(a_position, 1.0);- }-}%-CCProgram raw-fs %{- precision highp float;- in vec2 v_uv;- uniform Constant { vec4 tint; };- layout(location = 0) out vec4 outColor;- void main () {- outColor = tint * vec4(v_uv, 0.0, 1.0);- }-}%-`;- const effect = parseEffect(raw);- const converted = convertPass(effect, effect.techniques[0]!.passes[0]!, 'raw', { chunk }, {});- expect(converted.unsupported).toBeNull();- const source = converted.shader!.source;- expect(source).toContain('vec4 cocos_frag()');- expect(source).toContain('return outColor;');- expect(source).toContain('#define gl_Position cocos_glPosition');- });-- it('maps the pass\'s blend, depth and cull state', () => {- expect(pass.state).toEqual({ blendMode: 1, depthTest: false, depthWrite: false, cull: 0 });- });-});--describe('a pass whose vertex program does more than place the vertex', () => {- const SWAY = SPRITE_ADD.replace('vec4 pos = cc_matViewProj * vec4(a_position, 1);', 'vec4 pos = cc_matViewProj * vec4(a_position + vec3(sin(cc_time.x), 0, 0), 1);');-- it('is converted with its displacement as the material vertex hook, and that hook translates for WebGPU as well', async () => {- const effect = parseEffect(SWAY);- const swayed = convertPass(effect, effect.techniques[0]!.passes[0]!, 'sway', { chunk }, {});- expect(swayed.unsupported).toBeNull();- const source = swayed.shader!.source;- expect(source).toContain('#pragma vertexoffset');- expect(source).toContain('void esMaterialVertex(inout vec3 local, inout vec3 localNormal, in vec2 uv)');- expect(source).toContain('local = cocos_vert().xyz;');- // the hook has attribute names of its own: the engine vertex stage declares a_position and the others- const hook = /#pragma vertexoffset\n([\s\S]*?)#pragma end/.exec(source)![1]!;- expect(hook).not.toMatch(/(?<!hook_)\ba_position\b/);- expect(swayed.shader!.approximations.join('\n')).not.toContain('displacement');- // and the twin tool derives its WGSL, which is what a GLSL error in it would show as- // @ts-expect-error a repo tool, shipped as .mjs with no declarations- const tool = await import('../../tools/gen-shader-twins.mjs');- let module: unknown = null;- try { module = await tool.loadTwinModule(); } catch { /* no built engine here */ }- if (module) {- const derived = await tool.deriveTwin(module, source, {});- expect(derived.status).toBe('generated');- expect(derived.text).toContain('#pragma vertexoffset wgsl');- expect(derived.text).toContain('tc.u_time');- }- }, 120000);-- it('is not converted when its vertex program skins the mesh', () => {- const skinned = SPRITE_ADD.replace('in vec4 a_color;', 'in vec4 a_color;\n in vec4 a_joints;');- const converted = convertWithChunks(parseEffect(skinned), 'skin').techniques[0]!.passes[0]!;- expect(converted.shader).toBeNull();- expect(converted.unsupported).toMatch(/a_joints|skins/);- });-- it('is not converted when its fragment reads something the vertex stage does not supply', () => {- const odd = SPRITE_ADD.replace('in vec2 uv0;\n uniform sampler2D', 'in vec2 uv0;\n in vec3 v_barycentric;\n uniform sampler2D');- const converted = convertWithChunks(parseEffect(odd), 'odd').techniques[0]!.passes[0]!;- expect(converted.shader).toBeNull();- expect(converted.unsupported).toContain('v_barycentric');- });-});--describe('what an entry does not reach', () => {- it('is dropped, so a function of another entry that reads what this pass never declares cannot stop the shader', () => {- const source = [- 'uniform float k;',- 'float helper(float x) { return x * k; }',- 'vec4 other() { return vec4(undeclaredName); }',- 'vec4 cocos_frag() {',- ' if (k > 0.0) { return vec4(helper(1.0)); }',- ' return vec4(0.0);',- '}',- ].join('\n');- const pruned = pruneUnreachable(source, ['cocos_frag']);- expect(pruned).toContain('float helper(float x)');- expect(pruned).toContain('vec4 cocos_frag()');- expect(pruned).not.toContain('undeclaredName');- expect(pruned).toContain('uniform float k;');- });-- it('keeps what a macro or a declaration outside the functions names', () => {- const source = ['float a() { return 1.0; }', '#define USE_A a()', 'vec4 cocos_frag() { return vec4(USE_A); }'].join('\n');- expect(pruneUnreachable(source, ['cocos_frag'])).toContain('float a()');- });-- it('leaves a macro that defines functions as it is, for the preprocessor to expand', () => {- const source = [- '#define DEFINE_PACK(type) \\',- 'highp type unpackData (type a, type b) {\\',- ' return a + b;\\',- '}\\',- 'void packData (out type a, highp type d) {\\',- ' a = fract(d);\\',- '}',- '',- 'DEFINE_PACK(float)',- 'vec4 cocos_frag() { return vec4(1.0); }',- ].join('\n');- const pruned = pruneUnreachable(source, ['cocos_frag']);- expect(pruned).toContain('return a + b;\\');- expect(pruned).toContain('a = fract(d);\\');- expect(pruned).toContain('DEFINE_PACK(float)');- });-});diff --git a/pipeline/tests/cocos-effect-local-position.test.ts b/pipeline/tests/cocos-effect-local-position.test.tsdeleted file mode 100644index 0d3f86785..000000000--- a/pipeline/tests/cocos-effect-local-position.test.ts+++ /dev/null@@ -1,72 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A vertex program that reads the position in the mesh's own space (a terrain tiles its detail by `position.xz`) is given the engine's local position,- * and one that puts it through the world matrix keeps the world position it was given.- */-import { describe, expect, it } from 'vitest';-import { convertPass } from '../src/import/cocos/effectConvert';-import { parseEffect } from '../src/import/cocos/effects';--const effectWith = (vertexBody: string): string => `-CCEffect %{- techniques:- - name: opaque- passes:- - vert: pos-vs:vert- frag: pos-fs:frag- properties:- mainColor: { value: [1, 1, 1, 1], editor: { type: color } }-}%--CCProgram pos-vs %{- precision highp float;- in vec3 a_position;- out vec2 v_uv;-${vertexBody}-}%--CCProgram pos-fs %{- precision highp float;- in vec2 v_uv;- uniform Constant {- vec4 mainColor;- };- vec4 frag () { return mainColor * vec4(v_uv, 0.0, 1.0); }-}%-`;--const convert = (vertexBody: string) => {- const effect = parseEffect(effectWith(vertexBody));- return convertPass(effect, effect.techniques[0]!.passes[0]!, 'pos.opaque.0');-};--describe('the position a vertex program reads', () => {- it('is the mesh\'s own when the program takes components of it', () => {- const converted = convert(`- vec4 vert () {- vec4 position = vec4(a_position, 1.0);- v_uv = position.xz * 0.5;- return position;- }`);- expect(converted.unsupported).toBeNull();- const source = converted.shader!.source;- expect(source).toContain('#pragma feature MESH_LOCAL_POSITION');- expect(source).toContain('a_position = cocos_localPosition');- expect(source).toContain('in highp vec3 v_localPos;');- });-- it('stays the world position when the program puts it through the world matrix', () => {- const converted = convert(`- uniform Local { mat4 cc_matWorld; };- vec4 vert () {- vec4 world = cc_matWorld * vec4(a_position, 1.0);- v_uv = world.xz * 0.5;- return world;- }`);- expect(converted.unsupported).toBeNull();- const source = converted.shader!.source;- expect(source).not.toContain('MESH_LOCAL_POSITION');- expect(source).toContain('a_position = cocos_position');- });-});diff --git a/pipeline/tests/cocos-effect-packed.test.ts b/pipeline/tests/cocos-effect-packed.test.tsdeleted file mode 100644index e00870c9d..000000000--- a/pipeline/tests/cocos-effect-packed.test.ts+++ /dev/null@@ -1,48 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A uniform that properties are parts of (`colorScale: { value: [1,1,1], target: colorScaleAndCutoff.xyz }`) starts as those parts put together, not as- * zero: a fragment that multiplies by it would otherwise draw black.- */-import { describe, expect, it } from 'vitest';-import { convertPass } from '../src/import/cocos/effectConvert';-import { parseEffect } from '../src/import/cocos/effects';--const EFFECT = `-CCEffect %{- techniques:- - name: opaque- passes:- - vert: unlit-vs:vert- frag: unlit-fs:frag- properties:- mainColor: { value: [1, 1, 1, 1], linear: true, editor: { type: color } }- colorScale: { value: [1, 0.5, 0.25], target: colorScaleAndCutoff.xyz }- alphaThreshold: { value: 0.4, target: colorScaleAndCutoff.w }-}%--CCProgram unlit-vs %{- precision highp float;- in vec3 a_position;- vec4 vert () { return vec4(a_position, 1.0); }-}%--CCProgram unlit-fs %{- precision highp float;- uniform Constant {- vec4 mainColor;- vec4 colorScaleAndCutoff;- };- vec4 frag () { vec4 o = mainColor; o.rgb *= colorScaleAndCutoff.xyz; return o; }-}%-`;--describe('a uniform made of properties', () => {- it('starts as the properties it is made of', () => {- const effect = parseEffect(EFFECT);- const technique = effect.techniques[0]!;- const converted = convertPass(effect, technique.passes[0]!, 'packed.opaque.0');- const param = converted.shader?.params.find((p) => p.name === 'colorScaleAndCutoff');- expect(param?.value).toEqual([1, 0.5, 0.25, 0.4]);- });-});diff --git a/pipeline/tests/cocos-effect-probe.test.ts b/pipeline/tests/cocos-effect-probe.test.tsdeleted file mode 100644index 2150590f3..000000000--- a/pipeline/tests/cocos-effect-probe.test.ts+++ /dev/null@@ -1,68 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A vertex program that reads light-probe data only under `CC_USE_LIGHT_PROBE` does not read it for a material, which is given none: such a pass converts,- * and one that reads probes without that guard still does not.- */-import { describe, expect, it } from 'vitest';-import { convertPass } from '../src/import/cocos/effectConvert';-import { parseEffect } from '../src/import/cocos/effects';--const effectWith = (vertexBody: string): string => `-CCEffect %{- techniques:- - name: opaque- passes:- - vert: probe-vs:vert- frag: probe-fs:frag- properties:- mainColor: { value: [1, 1, 1, 1], editor: { type: color } }-}%--CCProgram probe-vs %{- precision highp float;- in vec3 a_position;-${vertexBody}-}%--CCProgram probe-fs %{- precision highp float;- uniform Constant {- vec4 mainColor;- };- vec4 frag () { return mainColor; }-}%-`;--const convert = (vertexBody: string) => {- const effect = parseEffect(effectWith(vertexBody));- return convertPass(effect, effect.techniques[0]!.passes[0]!, 'probe.opaque.0');-};--describe('a vertex program that mentions light probes', () => {- it('converts when it reads them only under the probe macro', () => {- const converted = convert(`- #if CC_USE_LIGHT_PROBE- in vec4 a_sh_linear_const_r;- out vec3 v_sh;- vec3 probe () { return CCGetSH(a_sh_linear_const_r); }- #endif- vec4 vert () {- #if CC_USE_LIGHT_PROBE- vec3 sh = probe();- #else- vec3 sh = vec3(0.0);- #endif- return vec4(a_position + sh, 1.0);- }`);- expect(converted.unsupported).toBeNull();- expect(converted.shader?.source).toContain('cocos_vert');- });-- it('is still refused when it reads them outside that guard', () => {- const converted = convert(`- in vec4 a_sh_linear_const_r;- vec4 vert () { return vec4(a_position + CCGetSH(a_sh_linear_const_r), 1.0); }`);- expect(converted.unsupported).toContain('light-probe');- });-});diff --git a/pipeline/tests/cocos-import-ambient.test.ts b/pipeline/tests/cocos-import-ambient.test.tsdeleted file mode 100644index 1100bd75a..000000000--- a/pipeline/tests/cocos-import-ambient.test.ts+++ /dev/null@@ -1,61 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A Cocos scene's ambient light becomes an Ambient light entity, so a lit mesh has what it is lit by.- */-import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';-import path from 'node:path';-import { afterAll, beforeAll, describe, expect, it } from 'vitest';-import { importCocosProject } from '../src/import/cocos';--const scene = [- { __type__: 'cc.SceneAsset', _name: 'main', scene: { __id__: 1 } },- { __type__: 'cc.Scene', _name: 'main', _children: [], _globals: { __id__: 2 } },- { __type__: 'cc.SceneGlobals', ambient: { __id__: 3 }, shadows: { __id__: 4 }, _skybox: { __id__: 5 }, fog: { __id__: 6 } },- { __type__: 'cc.AmbientInfo', _skyColorLDR: { __type__: 'cc.Vec4', x: 0.5, y: 0.75, z: 1, w: 0.8 }, _skyIllumLDR: 0.8 },- { __type__: 'cc.ShadowsInfo', _enabled: true },- { __type__: 'cc.SkyboxInfo', _enabled: false },- { __type__: 'cc.FogInfo', _enabled: true, _type: 0, _fogStart: 20, _fogEnd: 200, _fogColor: { __type__: 'cc.Color', r: 51, g: 102, b: 255, a: 255 } },-];--describe('a Cocos scene with an ambient light', () => {- let root: string;- let doc: { entities: Array<{ name: string; components: Array<{ type: string; data: Record<string, any> }> }> };- let report: Awaited<ReturnType<typeof importCocosProject>>;-- beforeAll(async () => {- root = mkdtempSync(path.join(tmpdir(), 'cocos-ambient-'));- const dir = path.join(root, 'creator', 'assets');- mkdirSync(dir, { recursive: true });- writeFileSync(path.join(dir, 'main.scene'), JSON.stringify(scene));- writeFileSync(path.join(dir, 'main.scene.meta'), JSON.stringify({ ver: '1', importer: 'scene', uuid: 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', subMetas: {}, userData: {} }));- report = await importCocosProject({ source: path.join(root, 'creator'), out: path.join(root, 'out') });- doc = JSON.parse(readFileSync(path.join(root, 'out', 'assets', 'cocos', 'main.esscene'), 'utf8'));- });- afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));-- it('is an ambient Light with the sky colour and the illumination', () => {- const ambient = doc.entities.find((e) => e.name === 'Ambient');- const light = ambient?.components.find((c) => c.type === 'Light');- expect(light?.data).toMatchObject({ type: 2, intensity: 0.8, color: { r: 0.5, g: 0.75, b: 1 } });- });-- it('is a global distance fog volume when the scene turns a linear fog on', () => {- const volume = doc.entities.find((e) => e.name === 'Fog')?.components.find((c) => c.type === 'PostProcessVolume');- expect(volume?.data).toMatchObject({ isGlobal: true });- expect(volume?.data.effects[0]).toMatchObject({- type: 'distanceFog', enabled: true,- uniforms: { u_fogNear: 20, u_fogFar: 200 },- colors: { u_fogColor: { r: 0.2, g: 0.4, b: 1, a: 1 } },- });- });-- it('says only what of the scene settings that are on it did not carry', () => {- const said = report.notes['scene-globals-dropped']?.examples.join(' ') ?? '';- expect(said).toContain('shadows');- expect(said).not.toContain('ambient');- expect(said).not.toContain('fog');- expect(said).not.toContain('skybox');- });-});diff --git a/pipeline/tests/cocos-import-collider.test.ts b/pipeline/tests/cocos-import-collider.test.tsdeleted file mode 100644index 395d06a03..000000000--- a/pipeline/tests/cocos-import-collider.test.ts+++ /dev/null@@ -1,50 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A Cocos BoxCollider keeps where it stood: `_center`, scaled by the node, becomes the engine collider's `center`.- */-import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';-import path from 'node:path';-import { afterAll, beforeAll, describe, expect, it } from 'vitest';-import { importCocosProject } from '../src/import/cocos';--const vec = (x: number, y: number, z: number) => ({ __type__: 'cc.Vec3', x, y, z });-const scene = [- { __type__: 'cc.SceneAsset', _name: 'main', scene: { __id__: 1 } },- { __type__: 'cc.Scene', _name: 'main', _children: [{ __id__: 2 }] },- {- __type__: 'cc.Node', _name: 'Crate', _parent: { __id__: 1 }, _children: [], _active: true, _components: [{ __id__: 3 }], _prefab: null,- _lpos: vec(0, 0, 0), _lrot: { __type__: 'cc.Quat', x: 0, y: 0, z: 0, w: 1 }, _lscale: vec(2, 3, 1), _layer: 1,- },- { __type__: 'cc.BoxCollider', node: { __id__: 2 }, _enabled: true, _isTrigger: false, _size: vec(1, 1, 1), _center: vec(0.5, 1, -2) },-];--describe('a Cocos box collider off its node\'s origin', () => {- let root: string;- let crate: { components: Array<{ type: string; data: Record<string, any> }> };- let report: Awaited<ReturnType<typeof importCocosProject>>;-- beforeAll(async () => {- root = mkdtempSync(path.join(tmpdir(), 'cocos-collider-'));- const dir = path.join(root, 'creator', 'assets');- mkdirSync(dir, { recursive: true });- writeFileSync(path.join(dir, 'main.scene'), JSON.stringify(scene));- writeFileSync(path.join(dir, 'main.scene.meta'), JSON.stringify({ ver: '1', importer: 'scene', uuid: 'dddddddd-dddd-4ddd-8ddd-dddddddddddd', subMetas: {}, userData: {} }));- report = await importCocosProject({ source: path.join(root, 'creator'), out: path.join(root, 'out') });- const doc = JSON.parse(readFileSync(path.join(root, 'out', 'assets', 'cocos', 'main.esscene'), 'utf8'));- crate = doc.entities.find((e: { name: string }) => e.name === 'Crate');- });- afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));-- it('carries the centre, scaled by the node, and the scaled half size', () => {- const box = crate.components.find((c) => c.type === 'BoxCollider3D')!;- expect(box.data.halfExtents).toEqual({ x: 1, y: 1.5, z: 0.5 });- expect(box.data.center).toEqual({ x: 1, y: 3, z: -2 });- });-- it('counts the collider as fully mapped', () => {- expect(report.components['cc.BoxCollider']).toEqual(expect.objectContaining({ mapped: 1 }));- expect(report.components['cc.BoxCollider']?.partial ?? 0).toBe(0);- });-});diff --git a/pipeline/tests/cocos-import-data-texture.test.ts b/pipeline/tests/cocos-import-data-texture.test.tsdeleted file mode 100644index 1eed03c87..000000000--- a/pipeline/tests/cocos-import-data-texture.test.ts+++ /dev/null@@ -1,54 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A PNG that keeps its colour under a clear alpha holds numbers (a weight map), and is told apart from a picture so it ships as it is.- */-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';-import path from 'node:path';-import { afterAll, beforeAll, describe, expect, it } from 'vitest';-import { encodeRgbaPng } from '../src/assets/atlasPacker';-import { hidesColorUnderClearAlpha } from '../src/import/cocos/importProject';--describe('a PNG that hides colour under a clear alpha', () => {- let dir: string;- const png = (name: string, texel: (i: number) => [number, number, number, number], width = 16, height = 16): string => {- const rgba = new Uint8Array(width * height * 4);- for (let i = 0; i < width * height; i++) rgba.set(texel(i), i * 4);- const file = path.join(dir, name);- writeFileSync(file, encodeRgbaPng(width, height, rgba));- return file;- };- beforeAll(() => { dir = mkdtempSync(path.join(tmpdir(), 'cocos-data-texture-')); });- afterAll(() => rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));-- it('is a weight map: clear everywhere, with the weights laid out in the colour, and as big as a map', () => {- const weights: Array<[number, number, number, number]> = [[255, 0, 0, 0], [0, 255, 0, 0], [0, 0, 255, 0], [128, 128, 0, 0], [0, 128, 128, 0]];- expect(hidesColorUnderClearAlpha(png('weights.png', (i) => weights[i % weights.length]!, 2048, 8))).toBe(true);- });-- it('is not the mask of an effect: the same laid out, but small', () => {- const weights: Array<[number, number, number, number]> = [[255, 0, 0, 0], [0, 255, 0, 0], [0, 0, 255, 0], [128, 128, 0, 0]];- expect(hidesColorUnderClearAlpha(png('mask.png', (i) => weights[i % weights.length]!))).toBe(false);- });-- it('is not one when what lies under the clear is a single colour, as a painter leaves under a background', () => {- expect(hidesColorUnderClearAlpha(png('white-bleed.png', () => [255, 255, 255, 0]))).toBe(false);- });-- it('is not a picture: opaque, or clear with nothing under it', () => {- expect(hidesColorUnderClearAlpha(png('opaque.png', () => [200, 120, 40, 255]))).toBe(false);- expect(hidesColorUnderClearAlpha(png('empty.png', () => [0, 0, 0, 0]))).toBe(false);- });-- it('is not a cutout: a few clear texels around a solid shape', () => {- expect(hidesColorUnderClearAlpha(png('sprite.png', (i) => (i < 40 ? [0, 0, 0, 0] : [200, 120, 40, 255])))).toBe(false);- });-- it('is not one when the file is not a PNG, or is missing', () => {- const jpg = path.join(dir, 'x.png');- writeFileSync(jpg, Buffer.from('not a png at all, not even close to one'));- expect(hidesColorUnderClearAlpha(jpg)).toBe(false);- expect(hidesColorUnderClearAlpha(path.join(dir, 'nowhere.png'))).toBe(false);- });-});diff --git a/pipeline/tests/cocos-import-layer.test.ts b/pipeline/tests/cocos-import-layer.test.tsdeleted file mode 100644index fca7bd92e..000000000--- a/pipeline/tests/cocos-import-layer.test.ts+++ /dev/null@@ -1,229 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file What the importer hands the runtime compatibility layer: UI geometry, alignment, layout, buttons, and the project's own- * scripts as components, with their references to other nodes pointing at the entities those nodes became.- *- * The scene is built by hand in Cocos's file shape (a flat array of objects pointing at each other by index), because the shape- * is the thing under test: a script component is named by its script's compressed uuid, and a node is named by an array index.- */-import { mkdtempSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';-import path from 'node:path';-import { afterAll, beforeAll, describe, expect, it } from 'vitest';-import { importCocosProject } from '../src/import/cocos';-import { buildCocosAssetIndex } from '../src/import/cocos/assets';-import { buildScriptIndex, compressUuid } from '../src/import/cocos/scripts';--const HUD = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';-const OTHER = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';-const PLAIN = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';-const unit = { __type__: 'cc.Vec3', x: 1, y: 1, z: 1 };-const zero = { __type__: 'cc.Vec3', x: 0, y: 0, z: 0 };-const ident = { __type__: 'cc.Quat', x: 0, y: 0, z: 0, w: 1 };--const node = (name: string, parent: number, children: number[], components: number[]): object => ({- __type__: 'cc.Node', _name: name, _parent: { __id__: parent }, _children: children.map((__id__) => ({ __id__ })), _active: true,- _components: components.map((__id__) => ({ __id__ })), _prefab: null, _lpos: zero, _lrot: ident, _lscale: unit, _layer: 33554432,-});-const ui = (n: number, w: number, h: number): object =>- ({ __type__: 'cc.UITransform', node: { __id__: n }, _enabled: true, _contentSize: { width: w, height: h }, _anchorPoint: { x: 0.5, y: 0.5 } });--/** Objects are numbered as the comments say; the references between them are indices into this array. */-const scene = [- { __type__: 'cc.SceneAsset', _name: 'main', scene: { __id__: 1 } }, // 0- { __type__: 'cc.Scene', _name: 'main', _children: [{ __id__: 2 }] }, // 1- node('Canvas', 1, [3, 4, 12], [5, 6]), // 2- node('Buy', 2, [], [7, 8]), // 3- node('Hud', 2, [], [9, 11]), // 4- ui(2, 960, 640), // 5- { __type__: 'cc.Widget', node: { __id__: 2 }, _enabled: true, _alignFlags: 45, _left: 10, _right: 10, _top: 5, _bottom: 5, _alignMode: 2, _isAbsLeft: true },- ui(3, 120, 48), // 7- { __type__: 'cc.Button', node: { __id__: 3 }, _enabled: true, _interactable: true, _transition: 3, _zoomScale: 1.1,- clickEvents: [{ __id__: 10 }], _normalColor: { __type__: 'cc.Color', r: 255, g: 255, b: 255, a: 255 } }, // 8- { __type__: compressUuid(HUD), node: { __id__: 4 }, _enabled: true, speed: 3, label: { __id__: 3 }, all: [{ __id__: 3 }, { __id__: 4 }],- buttonOf: { __id__: 8 }, icon: { __uuid__: PLAIN }, _hidden: { __id__: 99 } }, // 9- { __type__: 'cc.ClickEvent', target: { __id__: 4 }, component: '', _componentId: compressUuid(HUD), handler: 'onBuy', customEventData: 'gold' }, // 10- { __type__: 'cc.Layout', node: { __id__: 4 }, _enabled: true, _layoutType: 2, _resizeMode: 1, _spacingY: 8, _paddingTop: 4, _cellSize: { width: 50, height: 60 }, _verticalDirection: 1 }, // 11- node('Panel', 2, [], [13, 14, 15, 16, 17, 19]), // 12- ui(12, 80, 20), // 13- { __type__: 'cc.Toggle', node: { __id__: 12 }, _enabled: true, _isChecked: true, _checkMark: { __id__: 15 }, _interactable: true, _transition: 0,- clickEvents: [], checkEvents: [{ __id__: 18 }] }, // 14- { __type__: 'cc.Sprite', node: { __id__: 12 }, _enabled: true, _color: { r: 255, g: 255, b: 255, a: 255 } }, // 15- { __type__: 'cc.ScrollView', node: { __id__: 12 }, _enabled: true, _content: { __id__: 3 }, vertical: true, horizontal: false, brake: 0.75, bounceDuration: 0.23, scrollEvents: [] }, // 16- { __type__: 'cc.ProgressBar', node: { __id__: 12 }, _enabled: true, _barSprite: { __id__: 15 }, _progress: 0.4, _totalLength: 80, _mode: 0 }, // 17- { __type__: 'cc.ClickEvent', target: { __id__: 4 }, component: '', _componentId: compressUuid(HUD), handler: 'onPicked', customEventData: 'x' }, // 18- { __type__: 'cc.Mask', node: { __id__: 12 }, _enabled: true, _type: 0 }, // 19-];--describe('importing for the compatibility layer', () => {- let root: string;- let scenes: { entities: Array<{ id: number; name: string; components: Array<{ type: string; data: Record<string, any> }> }> };- let report: Awaited<ReturnType<typeof importCocosProject>>;-- beforeAll(async () => {- root = mkdtempSync(path.join(tmpdir(), 'cocos-layer-'));- const put = (rel: string, v: string | object): void => {- const f = path.join(root, 'creator', 'assets', rel);- mkdirSync(path.dirname(f), { recursive: true });- writeFileSync(f, typeof v === 'string' ? v : JSON.stringify(v));- };- const meta = (uuid: string, importer: string): object => ({ ver: '1', importer, uuid, subMetas: {}, userData: {} });- put('main.scene', scene);- put('main.scene.meta', meta('dddddddd-dddd-4ddd-8ddd-dddddddddddd', 'scene'));- put('scripts/Hud.ts', "import { _decorator, Component } from 'cc';\nconst { ccclass } = _decorator;\n@ccclass('Hud')\nexport class Hud extends Component {}\n");- put('scripts/Hud.ts.meta', meta(HUD, 'typescript'));- put('scripts/Other.ts', "@ccclass\n@menu('x')\n// a comment between\n@executionOrder(-1)\nexport default class Other extends Component {}\n");- put('scripts/Other.ts.meta', meta(OTHER, 'typescript'));- put('scripts/Globals.ts', "// @ts-ignore\nglobalThis.app_config = { area: 2 };\n");- put('scripts/Globals.ts.meta', meta('99999999-9999-4999-8999-999999999999', 'typescript'));- put('resources.meta', { ver: '1.2.0', importer: 'directory', uuid: 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', userData: { isBundle: true, bundleName: 'resources' } });- put('resources/cfg/rules.json', '{"a":1}');- put('resources/cfg/rules.json.meta', meta('f1f1f1f1-f1f1-4f1f-8f1f-f1f1f1f1f1f1', 'json'));- put('resources/ui/icon.png', 'not a png');- put('resources/ui/icon.png.meta', meta('f2f2f2f2-f2f2-4f2f-8f2f-f2f2f2f2f2f2', 'image'));- put('resources/prefab/thing.prefab', [{ __type__: 'cc.Prefab', _name: 'thing', data: { __id__: 1 } }, { ...node('Thing', 0, [], []), _prefab: { __id__: 2 } }, { __type__: 'cc.PrefabInfo', root: { __id__: 1 }, asset: { __id__: 0 }, fileId: 'thingRoot', instance: null }]);- put('resources/prefab/thing.prefab.meta', meta('f3f3f3f3-f3f3-4f3f-8f3f-f3f3f3f3f3f3', 'prefab'));- put('hero.meta', { ver: '1.2.0', importer: 'directory', uuid: 'f4f4f4f4-f4f4-4f4f-8f4f-f4f4f4f4f4f4', userData: { isBundle: true, bundleName: 'hero' } });- put('hero/skin.json', '{}');- put('hero/skin.json.meta', meta('f5f5f5f5-f5f5-4f5f-8f5f-f5f5f5f5f5f5', 'json'));- put('art/plain.json', '{}');- put('art/plain.json.meta', meta(PLAIN, 'json'));- // the starter project's entry, which the import points at the converted scripts- mkdirSync(path.join(root, 'out', 'src'), { recursive: true });- writeFileSync(path.join(root, 'out', 'project.esproject'), JSON.stringify({ formatVersion: '1', name: 'x', defaultScene: 'assets/scenes/main.esscene', designResolution: { width: 800, height: 600 } }));- mkdirSync(path.join(root, 'creator', 'settings', 'v2', 'packages'), { recursive: true });- writeFileSync(path.join(root, 'creator', 'settings', 'v2', 'packages', 'project.json'), JSON.stringify({ general: { designResolution: { width: 1080, height: 1920, fitWidth: true, fitHeight: false } } }));- writeFileSync(path.join(root, 'out', 'src', 'main.ts'), "// Game entry.\nimport './components';\n");- report = await importCocosProject({ source: path.join(root, 'creator'), out: path.join(root, 'out') });- scenes = JSON.parse(readFileSync(path.join(root, 'out', 'assets', 'cocos', 'main.esscene'), 'utf8'));- });- afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));-- const entity = (name: string) => scenes.entities.find((e) => e.name === name)!;- const comp = (name: string, type: string) => entity(name).components.find((c) => c.type === type)!;-- it('keeps a node\'s rectangle as a component of its own, as well as the size its renderers got', () => {- // a root pinned to the screen is stored as the engine will place it in the project's design box (1080x1920, centred on the origin)- expect(comp('Canvas', 'ContentRect').data).toEqual({ size: { x: 1060, y: 1910 }, pivot: { x: 0.5, y: 0.5 } });- expect(comp('Canvas', 'Transform').data.position).toMatchObject({ x: 0, y: 0 });- });-- it('carries a widget\'s and a layout\'s settings under the names the layer uses', () => {- const w = comp('Canvas', 'RectAnchors').data;- expect([w.alignFlags, w.left, w.right, w.top, w.bottom, w.alignMode, w.enabled]).toEqual([45, 10, 10, 5, 5, 2, true]);- const l = comp('Hud', 'Cocos.Layout').data;- expect([l.type, l.resizeMode, l.spacingY, l.paddingTop, l.cellWidth, l.cellHeight, l.verticalDirection]).toEqual([2, 1, 8, 4, 50, 60, 1]);- });-- it('splits a button\'s handlers into the entity they call and the rest, naming the script class from its uuid', () => {- const b = comp('Buy', 'Cocos.Button').data;- expect(b.transition).toBe(3);- expect(b.zoomScale).toBe(1.1);- expect(b.clickTargets).toEqual([entity('Hud').id]); // a node that comes LATER in the file- expect(b.clickHandlers).toEqual([{ component: 'Hud', handler: 'onBuy', customEventData: 'gold' }]);- });-- it('turns a script component into Cocos.<class>, with node references pointing at the entities those nodes became', () => {- const h = comp('Hud', 'Cocos.Hud').data;- expect(h.speed).toBe(3);- expect(h.label).toBe(entity('Buy').id);- expect(h.all).toEqual([entity('Buy').id, entity('Hud').id]);- // a component reference is its node- expect(h.buttonOf).toBe(entity('Buy').id);- // a reference to something that is not in the file is the engine's "no entity", not a stale index- expect(h._hidden).toBeNull();- // an asset reference is the copied file's project path- expect(h.icon).toBe('assets/cocos/art/plain.json');- });-- it('finds the class of a bare @ccclass among other decorators and comments', () => {- const classes = buildScriptIndex(buildCocosAssetIndex(path.join(root, 'creator', 'assets')));- expect(classes.get(compressUuid(OTHER))?.name).toBe('Other');- expect(report.components['script:Hud']).toEqual({ mapped: 1, partial: 0, unmapped: 0 });- });-- it('writes the entry that brings the scripts into the bundle, importing them where they are', () => {- const entry = readFileSync(path.join(root, 'out', 'src', 'cocos-scripts.ts'), 'utf8');- expect(entry).toContain("import 'esengine/cocos';");- const line = entry.split('\n').find((l) => l.includes("scripts/Hud'"))!;- expect(line).toBeDefined();- // each script loads on its own, so one that throws does not stop the others- expect(line).toMatch(/^load\(\(\) => require\('/);- expect(entry).toContain('try {');- // the path leads back to the Cocos project, which is not copied- const target = /require\('([^']+)'\)/.exec(line)![1]!;- expect(path.resolve(root, 'out', 'src', target + '.ts')).toBe(path.join(root, 'creator', 'assets', 'scripts', 'Hud.ts'));- });-- it('lists what scripts load by path in a manifest, by bundle, and copies those files', () => {- const manifest = JSON.parse(readFileSync(path.join(root, 'out', 'assets', 'cocos', 'resources.json'), 'utf8'));- // each entry also names the asset's Cocos uuid, which loadAny({ uuid }) resolves it by- expect(typeof manifest.resources['cfg/rules'].uuid).toBe('string');- expect(manifest.resources['cfg/rules']).toMatchObject({ path: 'assets/cocos/resources/cfg/rules.json', kind: 'json' });- expect(manifest.resources['ui/icon']).toMatchObject({ path: 'assets/cocos/resources/ui/icon.png', kind: 'texture' });- expect(manifest.resources['prefab/thing']).toMatchObject({ path: 'assets/cocos/resources/prefab/thing.esprefab', kind: 'prefab' });- expect(manifest.hero['skin']).toMatchObject({ path: 'assets/cocos/hero/skin.json', kind: 'json' });- expect(readFileSync(path.join(root, 'out', 'assets', 'cocos', 'resources', 'cfg', 'rules.json'), 'utf8')).toBe('{"a":1}');- });-- it('carries a toggle, a scroll view and a progress bar, with their node and component references mapped', () => {- const panel = entity('Panel').id;- const t = comp('Panel', 'Cocos.Toggle').data;- expect([t.isChecked, t.checkMark]).toEqual([true, panel]);- expect(t.checkTargets).toEqual([entity('Hud').id]);- expect(t.checkHandlers).toEqual([{ component: 'Hud', handler: 'onPicked', customEventData: 'x' }]);- const sv = comp('Panel', 'Cocos.ScrollView').data;- expect([sv.content, sv.vertical, sv.brake, sv.bounceDuration]).toEqual([entity('Buy').id, true, 0.75, 0.23]);- const bar = comp('Panel', 'Cocos.ProgressBar').data;- expect([bar.barSprite, bar.progress_, bar.totalLength]).toEqual([panel, 0.4, 80]);- });-- it('turns a rectangle mask into the engine UIMask, which clips to the ContentRect beside it', () => {- expect(comp('Panel', 'UIMask').data).toEqual({ enabled: true, mode: 0, alphaCutoff: 0 });- expect(comp('Panel', 'ContentRect').data.size).toEqual({ x: 80, y: 20 });- expect(report.components['cc.Mask']).toEqual({ mapped: 1, partial: 0, unmapped: 0 });- });-- it('declares the script classes the scenes use for the editor, and starts the project from the scripts themselves', () => {- const components = readFileSync(path.join(root, 'out', 'src', 'components.ts'), 'utf8');- expect(components).toContain("import 'esengine/cocos';");- expect(components).toMatch(/defineComponent\("Cocos\.Hud", \{ enabled: true,/);- expect(components).toContain('"speed": 0');- const main = readFileSync(path.join(root, 'out', 'src', 'main.ts'), 'utf8');- expect(main).toContain("import './cocos-scripts';");- expect(main).not.toMatch(/import '\.\/components';/);- });-- it('puts a source image in the project as a link to it, not a second copy, and never writes into it', () => {- const from = statSync(path.join(root, 'creator', 'assets', 'resources', 'ui', 'icon.png'));- const to = statSync(path.join(root, 'out', 'assets', 'cocos', 'resources', 'ui', 'icon.png'));- expect(to.size).toBe(from.size);- expect(to.ino === from.ino && to.dev === from.dev).toBe(true);- expect(readFileSync(path.join(root, 'creator', 'assets', 'resources', 'ui', 'icon.png'), 'utf8')).toBe('not a png');- });-- it('starts the converted project at the scene and design size of the game, not of the starter', () => {- const manifest = JSON.parse(readFileSync(path.join(root, 'out', 'project.esproject'), 'utf8')) as { defaultScene: string; designResolution: { width: number; height: number } };- expect(manifest.defaultScene).toBe('assets/cocos/main.esscene');- expect(manifest.designResolution).toEqual({ width: 1080, height: 1920 });- expect((manifest as { features?: { rendering?: { cameraScaleMode?: string } } }).features?.rendering?.cameraScaleMode).toBe('fixed-width');- });-- it('runs a script that only defines globals before the scripts scenes name', () => {- const entry = readFileSync(path.join(root, 'out', 'src', 'cocos-scripts.ts'), 'utf8').split('\n');- const at = (needle: string): number => entry.findIndex((l) => l.startsWith('load(') && l.includes(needle));- expect(at("scripts/Globals'")).toBeGreaterThan(-1);- expect(at("scripts/Globals'")).toBeLessThan(at("scripts/Hud'"));- });-- it('puts a renderer in the layer of its node, which is what a UI camera culls by', () => {- const sprites = scenes.entities.flatMap((e) => e.components.filter((c) => c.type === 'Sprite'));- expect(sprites.length).toBeGreaterThan(0);- for (const sprite of sprites) expect(sprite.data.layer).toBe(25);- });-- it('counts the components it maps', () => {- for (const type of ['cc.Widget', 'cc.Layout', 'cc.Button', 'cc.UITransform']) expect(report.components[type]!.unmapped).toBe(0);- });-});diff --git a/pipeline/tests/cocos-import-models.test.ts b/pipeline/tests/cocos-import-models.test.tsdeleted file mode 100644index 3c2a0f2be..000000000--- a/pipeline/tests/cocos-import-models.test.ts+++ /dev/null@@ -1,229 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file The models a Cocos project draws, taken in with the engine's own model import.- *- * The fixture is one glTF triangle standing in for an `.fbx`, a prefab that draws it two ways (a MeshRenderer on a node, and an instance of- * the model's scene), and a quad from Cocos's built-in shapes. The claims: the model is imported once and its products land beside where it- * lay in the Cocos project; a MeshRenderer takes the model's own mesh and material; an instance of the model keeps its root's name and place;- * a built-in shape becomes the engine's, resized so it stays the size the scene meant; and the source is never written to.- */-import { afterAll, beforeAll, describe, expect, it } from 'vitest';-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from 'node:fs';-import { tmpdir } from 'node:os';-import path from 'node:path';-import { importCocosProject } from '../src/import/cocos';--const MODEL = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';-const PREFAB = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';-const PRIMITIVES = '1263d74c-8167-4928-91a6-4e2672411f47';-const GROUND_IMG = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';-const GROUND_MAT = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd';-const STANDARD = 'a3cd009f-0ab0-420d-9278-b9fdab939bbc';--const vec = (x: number, y: number, z = 0) => ({ __type__: 'cc.Vec3', x, y, z });-const ident = { __type__: 'cc.Quat', x: 0, y: 0, z: 0, w: 1 };--function triangleGltf(): string {- const buffer = Buffer.alloc(44);- [0, 0, 0, 1, 0, 0, 0, 1, 0].forEach((v, i) => buffer.writeFloatLE(v, i * 4));- [0, 1, 2].forEach((v, i) => buffer.writeUInt16LE(v, 36 + i * 2));- return JSON.stringify({- asset: { version: '2.0' }, scene: 0, scenes: [{ nodes: [0] }],- nodes: [{ name: 'tri', mesh: 0 }],- meshes: [{ name: 'tri', primitives: [{ attributes: { POSITION: 0 }, indices: 1 }] }],- accessors: [- { bufferView: 0, componentType: 5126, count: 3, type: 'VEC3', min: [0, 0, 0], max: [1, 1, 0] },- { bufferView: 1, componentType: 5123, count: 3, type: 'SCALAR' },- ],- bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: 36 }, { buffer: 0, byteOffset: 36, byteLength: 6 }],- buffers: [{ byteLength: 44, uri: `data:application/octet-stream;base64,${buffer.toString('base64')}` }],- });-}--const node = (name: string, parent: number | null, children: number[], components: number[], prefab: number, pos = vec(0, 0), scale = vec(1, 1, 1)) => ({- __type__: 'cc.Node', _name: name, _parent: parent === null ? null : { __id__: parent }, _children: children.map((__id__) => ({ __id__ })), _active: true,- _components: components.map((__id__) => ({ __id__ })), _prefab: { __id__: prefab }, _lpos: pos, _lrot: ident, _lscale: scale, _layer: 1073741824,-});--/** props.prefab: a root with three children: a node drawing the model's mesh, a built-in quad, and an instance of the model's scene. */-const propsPrefab = [- { __type__: 'cc.Prefab', _name: 'props', data: { __id__: 1 } },- node('Props', null, [2, 5, 8], [], 4), // 1- node('Tri', 1, [], [3], 11, vec(5, 0)), // 2- { __type__: 'cc.MeshRenderer', node: { __id__: 2 }, _enabled: true, __prefab: { __id__: 12 }, _materials: [], _mesh: { __uuid__: `${MODEL}@00a01` } }, // 3- { __type__: 'cc.PrefabInfo', root: { __id__: 1 }, asset: { __id__: 0 }, fileId: 'propsRoot', instance: null }, // 4- node('Ground', 1, [], [6], 13, vec(0, 0), vec(2, 2, 2)), // 5- { __type__: 'cc.MeshRenderer', node: { __id__: 5 }, _enabled: true, __prefab: { __id__: 14 }, _materials: [{ __uuid__: GROUND_MAT }], _mesh: { __uuid__: `${PRIMITIVES}@fc873` } }, // 6- { __type__: 'cc.Node', _name: 'unused' }, // 7- { __type__: 'cc.Node', _objFlags: 0, _parent: { __id__: 1 }, _prefab: { __id__: 9 } }, // 8 (instance of the model's scene)- { __type__: 'cc.PrefabInfo', root: { __id__: 8 }, asset: { __uuid__: `${MODEL}@00b02` }, fileId: 'modelRoot', instance: { __id__: 10 } }, // 9- { __type__: 'cc.PrefabInstance', fileId: 'inst', prefabRootNode: { __id__: 1 }, mountedChildren: [], mountedComponents: [], removedComponents: [],- propertyOverrides: [{ __id__: 15 }, { __id__: 17 }, { __id__: 19 }] }, // 10- { __type__: 'cc.PrefabInfo', root: { __id__: 1 }, asset: { __id__: 0 }, fileId: 'triInfo', instance: null }, // 11- { __type__: 'cc.CompPrefabInfo', fileId: 'triMesh' }, // 12- { __type__: 'cc.PrefabInfo', root: { __id__: 1 }, asset: { __id__: 0 }, fileId: 'groundInfo', instance: null }, // 13- { __type__: 'cc.CompPrefabInfo', fileId: 'groundMesh' }, // 14- { __type__: 'CCPropertyOverrideInfo', targetInfo: { __id__: 16 }, propertyPath: ['_name'], value: 'renamed' }, // 15- { __type__: 'cc.TargetInfo', localID: ['sceneRootId'] }, // 16- { __type__: 'CCPropertyOverrideInfo', targetInfo: { __id__: 16 }, propertyPath: ['_lpos'], value: vec(3, 4, 5) }, // 17- { __type__: 'cc.TargetInfo', localID: ['sceneRootId', 'partId'] }, // 18 (a part of the model)- { __type__: 'CCPropertyOverrideInfo', targetInfo: { __id__: 18 }, propertyPath: ['_lpos'], value: vec(9, 9, 9) }, // 19-];--const meta = (uuid: string, importer: string, extra: object = {}) => ({ ver: '1', importer, uuid, subMetas: {}, userData: {}, ...extra });--let root: string;-let src: string;-let out: string;-let sourceBefore: string;-let report: Awaited<ReturnType<typeof importCocosProject>>;--beforeAll(async () => {- root = mkdtempSync(path.join(tmpdir(), 'cocos-models-'));- src = path.join(root, 'creator');- out = path.join(root, 'estella');- const put = (rel: string, v: unknown): void => {- const f = path.join(src, 'assets', rel);- mkdirSync(path.dirname(f), { recursive: true });- writeFileSync(f, typeof v === 'string' ? v : JSON.stringify(v));- };- put('models/tri/tri.gltf', triangleGltf());- put('models/tri/tri.gltf.meta', meta(MODEL, 'gltf', {- subMetas: {- '00a01': { importer: 'gltf-mesh', uuid: `${MODEL}@00a01`, name: 'tri.mesh', userData: { gltfIndex: 0 } },- '00b02': { importer: 'gltf-scene', uuid: `${MODEL}@00b02`, name: 'tri.prefab', userData: { gltfIndex: 0 } },- },- }));- put('tex/ground.png', 'not really a png');- put('tex/ground.png.meta', meta(GROUND_IMG, 'image', { subMetas: { '6c48a': { importer: 'texture', uuid: `${GROUND_IMG}@6c48a`, name: 'texture', userData: {} } } }));- put('mat/ground.mtl', {- __type__: 'cc.Material', _effectAsset: { __uuid__: STANDARD }, _techIdx: 0,- _props: [{ mainTexture: { __uuid__: `${GROUND_IMG}@6c48a` }, mainColor: { __type__: 'cc.Color', r: 255, g: 128, b: 0, a: 255 } }],- _states: [{ rasterizerState: { cullMode: 0 }, blendState: { targets: [{ blend: true, blendSrc: 2, blendDst: 4 }] } }],- });- put('mat/ground.mtl.meta', meta(GROUND_MAT, 'material'));- put('props/props.prefab', propsPrefab);- put('props/props.prefab.meta', meta(PREFAB, 'prefab'));- sourceBefore = readFileSync(path.join(src, 'assets', 'models/tri/tri.gltf'), 'utf8');- report = await importCocosProject({ source: src, out, only: ['props/'] });-});--afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));--const readJson = (rel: string): any => JSON.parse(readFileSync(path.join(out, rel), 'utf8'));-const entity = (doc: any, name: string): any => doc.entities.find((e: any) => e.name === name);--describe('a model a Cocos project draws', () => {- it('is imported once, with its products beside where it lay', () => {- expect(report.documents.failed).toEqual([]);- for (const f of ['tri.esprefab', 'tri.esmesh']) expect(existsSync(path.join(out, 'assets/cocos/models/tri', f))).toBe(true);- });-- it('never writes to the model it reads', () => {- expect(readFileSync(path.join(src, 'assets', 'models/tri/tri.gltf'), 'utf8')).toBe(sourceBefore);- });-- it('gives a MeshRenderer on a node the model\'s own mesh', () => {- const tri = entity(readJson('assets/cocos/props/props.esprefab'), 'Tri');- const mesh = tri.components.find((c: any) => c.type === 'MeshRenderer');- expect(mesh.data.mesh).toBe('assets/cocos/models/tri/tri.esmesh');- expect(mesh.data.enabled).toBe(true);- });-- it('turns an instance of the model\'s scene into a nested prefab that keeps the root\'s name and place', () => {- const doc = readJson('assets/cocos/props/props.esprefab');- const inst = doc.entities.find((e: any) => e.nestedPrefab);- expect(inst.nestedPrefab.prefabPath).toBe('assets/cocos/models/tri/tri.esprefab');- const modelRoot = readJson('assets/cocos/models/tri/tri.esprefab').rootEntityId;- const byProperty = (name: string) => inst.nestedPrefab.overrides.find((o: any) => o.type === name || o.propertyName === name);- expect(inst.nestedPrefab.overrides.every((o: any) => o.prefabEntityId === modelRoot)).toBe(true);- expect(byProperty('name').value).toBe('renamed');- expect(byProperty('position').value).toMatchObject({ x: 3, y: 4, z: 5 });- });-- it('counts what an instance changed on the model\'s own parts instead of losing it silently', () => {- expect(report.notes['model-instance-overrides']?.count).toBe(1);- });-});--describe('a Cocos built-in shape', () => {- it('becomes the engine\'s own, resized so the scene keeps its size', () => {- const ground = entity(readJson('assets/cocos/props/props.esprefab'), 'Ground');- const mesh = ground.components.find((c: any) => c.type === 'MeshRenderer');- expect(mesh.data.mesh).toBe('builtin:quad');- // the engine's quad is 100 across and Cocos's is 1: a node scaled 2 stands at 2 / 100 of the engine's- const transform = ground.components.find((c: any) => c.type === 'Transform');- expect(transform.data.scale.x).toBeCloseTo(0.02, 6);- });-- it('wears the Cocos material it was given: its image, tint, blending and culling', () => {- const ground = entity(readJson('assets/cocos/props/props.esprefab'), 'Ground');- const mesh = ground.components.find((c: any) => c.type === 'MeshRenderer').data;- expect(mesh.texture).toBe('assets/cocos/tex/ground.png');- expect(mesh.color.r).toBeCloseTo(1, 5);- expect(mesh.color.g).toBeCloseTo(128 / 255, 5);- expect(mesh.lit).toBe(true); // the built-in standard effect lights the surface- expect(mesh.opaque).toBe(false); // it blends- expect(mesh.cullBackfaces).toBe(false); // cull mode none- expect(report.components['cc.MeshRenderer']?.mapped).toBeGreaterThanOrEqual(1);- });-});--describe('a clip played on another skeleton', () => {- let dir: string;- const clip = (tracks: Array<{ childPath: string; keys: number[] }>) => ({- version: '1.3', type: 'timeline', duration: 4, wrapMode: 'once',- tracks: tracks.map((t) => ({- type: 'property', name: t.childPath.split('/').pop(), childPath: t.childPath, component: 'Transform',- channels: [{ property: 'position.x', keyframes: t.keys.map((time) => ({ time, value: time * 10, inTangent: 0, outTangent: 0, interpolation: 'linear' })) }],- })),- });- const write = (name: string, doc: unknown): string => {- mkdirSync(path.join(dir, 'clips'), { recursive: true });- writeFileSync(path.join(dir, 'clips', name), JSON.stringify(doc));- return `clips/${name}`;- };- const read = (ref: string): any => JSON.parse(readFileSync(path.join(dir, ref), 'utf8'));-- beforeAll(() => { dir = mkdtempSync(path.join(tmpdir(), 'cocos-clip-')); });- afterAll(() => rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));-- it('addresses each track by where its bone stands in the skeleton it is played on', async () => {- const { retargetClip } = await import('../src/import/cocos/models');- const ref = write('walk.estimeline', clip([{ childPath: 'Bone001', keys: [0, 1] }, { childPath: 'Bone001/Hand', keys: [0, 1] }]));- const copy = retargetClip(dir, ref, new Map([['Bone001', 'Root/Bone001'], ['Hand', 'Root/Bone001/Hand']]), 'rigA');- expect(copy?.dropped).toBe(0);- expect(read(copy!.ref).tracks.map((t: any) => t.childPath)).toEqual(['Root/Bone001', 'Root/Bone001/Hand']);- expect(existsSync(path.join(dir, `${copy!.ref}.meta`))).toBe(true);- });-- it('drops a track whose bone the skeleton does not have, and says how many', async () => {- const { retargetClip } = await import('../src/import/cocos/models');- const ref = write('run.estimeline', clip([{ childPath: 'Bone001', keys: [0, 1] }, { childPath: 'Bone001/Tail', keys: [0, 1] }]));- const copy = retargetClip(dir, ref, new Map([['Bone001', 'Bone001']]), 'rigB');- expect(copy?.dropped).toBe(1);- expect(read(copy!.ref).tracks).toHaveLength(1);- expect(retargetClip(dir, ref, new Map(), 'rigC')).toBeNull();- });-- it('plays a clip that animates a single object on the node it is put on, whatever that node is called', async () => {- const { retargetClip } = await import('../src/import/cocos/models');- const ref = write('spin.estimeline', clip([{ childPath: 'fx_moon', keys: [0, 2] }]));- const copy = retargetClip(dir, ref, new Map(), 'host');- expect(read(copy!.ref).tracks.map((t: any) => t.childPath)).toEqual(['']);- });-- it('keeps the part of the take a Cocos clip covers, starting at zero, and the wrap mode it asks for', async () => {- const { retargetClip, clipPlayOf } = await import('../src/import/cocos/models');- const ref = write('take.estimeline', clip([{ childPath: 'Bone001', keys: [0, 1, 2, 3, 4] }]));- const play = clipPlayOf({ span: { from: 1, to: 3 }, wrapMode: 2 });- const copy = retargetClip(dir, ref, new Map([['Bone001', 'Bone001']]), 'cut', play);- const doc = read(copy!.ref);- expect(doc.duration).toBe(2);- expect(doc.wrapMode).toBe('loop');- expect(doc.tracks[0].channels[0].keyframes.map((k: any) => k.time)).toEqual([0, 1, 2]);- expect(clipPlayOf({ wrapMode: 36 }).wrapMode).toBe('pingPong');- expect(clipPlayOf({ wrapMode: 1 }).wrapMode).toBe('once');- });-});diff --git a/pipeline/tests/cocos-import-multi-material.test.ts b/pipeline/tests/cocos-import-multi-material.test.tsdeleted file mode 100644index e0ce22d54..000000000--- a/pipeline/tests/cocos-import-multi-material.test.ts+++ /dev/null@@ -1,103 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A Cocos mesh of two primitives with a material in each slot is drawn whole: the first primitive on the node, the second on a part that- * stands with it, each with the material of its own slot.- */-import { afterAll, beforeAll, describe, expect, it } from 'vitest';-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';-import path from 'node:path';-import { importCocosProject } from '../src/import/cocos';--const MODEL = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';-const PREFAB = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';-const MAT_A = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd';-const MAT_B = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee';-const STANDARD = 'a3cd009f-0ab0-420d-9278-b9fdab939bbc';--const vec = (x: number, y: number, z = 0) => ({ __type__: 'cc.Vec3', x, y, z });-const ident = { __type__: 'cc.Quat', x: 0, y: 0, z: 0, w: 1 };--/** One mesh of two triangles, each its own primitive, each with its own glTF material. */-function twoPrimitiveGltf(): string {- const buffer = Buffer.alloc(80);- [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1].forEach((v, i) => buffer.writeFloatLE(v, i * 4));- [0, 1, 2, 0, 1, 2].forEach((v, i) => buffer.writeUInt16LE(v, 72 + (i % 3) * 2 + Math.floor(i / 3) * 0));- return JSON.stringify({- asset: { version: '2.0' }, scene: 0, scenes: [{ nodes: [0] }],- nodes: [{ name: 'pair', mesh: 0 }],- materials: [{ name: 'a' }, { name: 'b' }],- meshes: [{ name: 'pair', primitives: [- { attributes: { POSITION: 0 }, indices: 2, material: 0 },- { attributes: { POSITION: 1 }, indices: 2, material: 1 },- ] }],- accessors: [- { bufferView: 0, componentType: 5126, count: 3, type: 'VEC3', min: [0, 0, 0], max: [1, 1, 0] },- { bufferView: 1, componentType: 5126, count: 3, type: 'VEC3', min: [0, 0, 1], max: [1, 1, 1] },- { bufferView: 2, componentType: 5123, count: 3, type: 'SCALAR' },- ],- bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: 36 }, { buffer: 0, byteOffset: 36, byteLength: 36 }, { buffer: 0, byteOffset: 72, byteLength: 6 }],- buffers: [{ byteLength: 80, uri: `data:application/octet-stream;base64,${buffer.toString('base64')}` }],- });-}--const prefab = [- { __type__: 'cc.Prefab', _name: 'pair', data: { __id__: 1 } },- { __type__: 'cc.Node', _name: 'Pair', _parent: null, _children: [], _active: true, _components: [{ __id__: 2 }], _prefab: { __id__: 3 }, _lpos: vec(0, 0), _lrot: ident, _lscale: vec(1, 1, 1), _layer: 1073741824 },- { __type__: 'cc.MeshRenderer', node: { __id__: 1 }, _enabled: true, __prefab: { __id__: 4 }, _materials: [{ __uuid__: MAT_A }, { __uuid__: MAT_B }], _mesh: { __uuid__: `${MODEL}@00a01` } },- { __type__: 'cc.PrefabInfo', root: { __id__: 1 }, asset: { __id__: 0 }, fileId: 'pairRoot', instance: null },- { __type__: 'cc.CompPrefabInfo', fileId: 'pairMesh' },-];--const meta = (uuid: string, importer: string, extra: object = {}) => ({ ver: '1', importer, uuid, subMetas: {}, userData: {}, ...extra });-const material = (r: number) => ({- __type__: 'cc.Material', _effectAsset: { __uuid__: STANDARD }, _techIdx: 0,- _props: [{ mainColor: { __type__: 'cc.Color', r, g: 0, b: 0, a: 255 } }],- _states: [{ rasterizerState: { cullMode: 2 } }],-});--let root: string;-let out: string;--beforeAll(async () => {- root = mkdtempSync(path.join(tmpdir(), 'cocos-multi-'));- const src = path.join(root, 'creator');- out = path.join(root, 'estella');- const put = (rel: string, v: unknown): void => {- const f = path.join(src, 'assets', rel);- mkdirSync(path.dirname(f), { recursive: true });- writeFileSync(f, typeof v === 'string' ? v : JSON.stringify(v));- };- put('models/pair/pair.gltf', twoPrimitiveGltf());- put('models/pair/pair.gltf.meta', meta(MODEL, 'gltf', {- subMetas: { '00a01': { importer: 'gltf-mesh', uuid: `${MODEL}@00a01`, name: 'pair.mesh', userData: { gltfIndex: 0 } } },- }));- put('mat/a.mtl', material(255));- put('mat/a.mtl.meta', meta(MAT_A, 'material'));- put('mat/b.mtl', material(10));- put('mat/b.mtl.meta', meta(MAT_B, 'material'));- put('props/pair.prefab', prefab);- put('props/pair.prefab.meta', meta(PREFAB, 'prefab'));- await importCocosProject({ source: src, out, only: ['props/'] });-});--afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));--describe('a mesh of two primitives', () => {- it('is two renderers, one on the node and one on a part beside it', () => {- const doc = JSON.parse(readFileSync(path.join(out, 'assets/cocos/props/pair.esprefab'), 'utf8'));- const holders = doc.entities.filter((e: any) => e.components.some((c: any) => c.type === 'MeshRenderer'));- expect(holders.map((e: any) => e.name)).toEqual(['Pair', 'Pair_1']);- const part = holders[1];- expect(part.parent).toBe(holders[0].prefabEntityId);- expect(holders[0].children).toContain(part.prefabEntityId);- });-- it('draws each primitive with the colour of its own slot', () => {- const doc = JSON.parse(readFileSync(path.join(out, 'assets/cocos/props/pair.esprefab'), 'utf8'));- const colour = (name: string): number => doc.entities.find((e: any) => e.name === name).components.find((c: any) => c.type === 'MeshRenderer').data.color.r;- expect(colour('Pair')).toBeCloseTo(1, 2);- expect(colour('Pair_1')).toBeCloseTo(10 / 255, 2);- });-});diff --git a/pipeline/tests/cocos-import-outline.test.ts b/pipeline/tests/cocos-import-outline.test.tsdeleted file mode 100644index 85ef7cd04..000000000--- a/pipeline/tests/cocos-import-outline.test.ts+++ /dev/null@@ -1,153 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A material whose effect has an outline pass, switched on, draws the mesh a second time: the outline is a material of its own, with the width- * and colour the Cocos material gave it, on a renderer that stands with the first.- */-import { afterAll, beforeAll, describe, expect, it } from 'vitest';-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from 'node:fs';-import { tmpdir } from 'node:os';-import path from 'node:path';-import { importCocosProject } from '../src/import/cocos';--const MODEL = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';-const PREFAB = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';-const EFFECT = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';-const MAT_ON = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd';-const MAT_OFF = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee';--const vec = (x: number, y: number, z = 0) => ({ __type__: 'cc.Vec3', x, y, z });-const ident = { __type__: 'cc.Quat', x: 0, y: 0, z: 0, w: 1 };--const gltf = (): string => {- const buffer = Buffer.alloc(44);- [0, 0, 0, 1, 0, 0, 0, 1, 0].forEach((v, i) => buffer.writeFloatLE(v, i * 4));- [0, 1, 2].forEach((v, i) => buffer.writeUInt16LE(v, 36 + i * 2));- return JSON.stringify({- asset: { version: '2.0' }, scene: 0, scenes: [{ nodes: [0] }],- nodes: [{ name: 'tri', mesh: 0 }],- meshes: [{ name: 'tri', primitives: [{ attributes: { POSITION: 0 }, indices: 1 }] }],- accessors: [- { bufferView: 0, componentType: 5126, count: 3, type: 'VEC3', min: [0, 0, 0], max: [1, 1, 0] },- { bufferView: 1, componentType: 5123, count: 3, type: 'SCALAR' },- ],- bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: 36 }, { buffer: 0, byteOffset: 36, byteLength: 6 }],- buffers: [{ byteLength: 44, uri: `data:application/octet-stream;base64,${buffer.toString('base64')}` }],- });-};--const EFFECT_TEXT = `-CCEffect %{- techniques:- - name: opaque- passes:- - switch: USE_OUTLINE_PASS- vert: outline-vs:vert- frag: outline-fs:frag- rasterizerState: { cullMode: front }- properties:- lineWidth: { value: 10, target: outlineParams.x }- baseColor: { editor: { type: color } }- - vert: main-vs:vert- frag: main-fs:frag- properties:- mainColor: { value: [1, 1, 1, 1], editor: { type: color } }-}%-CCProgram outline-vs %{- precision highp float;- #include <builtin/uniforms/cc-global>- in vec3 a_position;- uniform OutlineVert { vec4 outlineParams; };- vec4 vert () { return cc_matViewProj * vec4(a_position, 1); }-}%-CCProgram outline-fs %{- precision highp float;- uniform OutlineFrag { vec4 baseColor; };- vec4 frag () { return vec4(baseColor.rgb, 1.0); }-}%-CCProgram main-vs %{- precision highp float;- #include <builtin/uniforms/cc-global>- in vec3 a_position;- in vec2 a_texCoord;- out vec2 uv0;- vec4 vert () { uv0 = a_texCoord; return cc_matViewProj * vec4(a_position, 1); }-}%-CCProgram main-fs %{- precision highp float;- in vec2 uv0;- uniform Constant { vec4 mainColor; };- vec4 frag () { return mainColor; }-}%-`;--const prefab = [- { __type__: 'cc.Prefab', _name: 'tri', data: { __id__: 1 } },- { __type__: 'cc.Node', _name: 'Drawn', _parent: null, _children: [], _active: true, _components: [{ __id__: 2 }], _prefab: { __id__: 3 }, _lpos: vec(0, 0), _lrot: ident, _lscale: vec(1, 1, 1), _layer: 1073741824 },- { __type__: 'cc.MeshRenderer', node: { __id__: 1 }, _enabled: true, __prefab: { __id__: 4 }, _materials: [{ __uuid__: MAT_ON }], _mesh: { __uuid__: `${MODEL}@00a01` } },- { __type__: 'cc.PrefabInfo', root: { __id__: 1 }, asset: { __id__: 0 }, fileId: 'triRoot', instance: null },- { __type__: 'cc.CompPrefabInfo', fileId: 'triMesh' },-];--const meta = (uuid: string, importer: string, extra: object = {}) => ({ ver: '1', importer, uuid, subMetas: {}, userData: {}, ...extra });-const material = (outline: boolean) => ({- __type__: 'cc.Material', _effectAsset: { __uuid__: EFFECT }, _techIdx: 0,- _defines: [{ USE_OUTLINE_PASS: outline }, {}],- _props: [{ lineWidth: 8, baseColor: { __type__: 'cc.Color', r: 255, g: 0, b: 0, a: 255 } }, { mainColor: { __type__: 'cc.Color', r: 255, g: 255, b: 255, a: 255 } }],-});--let root: string;-let out: string;--beforeAll(async () => {- root = mkdtempSync(path.join(tmpdir(), 'cocos-outline-'));- const src = path.join(root, 'creator');- out = path.join(root, 'estella');- const put = (rel: string, v: unknown): void => {- const f = path.join(src, 'assets', rel);- mkdirSync(path.dirname(f), { recursive: true });- writeFileSync(f, typeof v === 'string' ? v : JSON.stringify(v));- };- put('models/tri/tri.gltf', gltf());- put('models/tri/tri.gltf.meta', meta(MODEL, 'gltf', {- subMetas: { '00a01': { importer: 'gltf-mesh', uuid: `${MODEL}@00a01`, name: 'tri.mesh', userData: { gltfIndex: 0 } } },- }));- put('fx/outlined.effect', EFFECT_TEXT);- put('fx/outlined.effect.meta', meta(EFFECT, 'effect'));- put('mat/on.mtl', material(true));- put('mat/on.mtl.meta', meta(MAT_ON, 'material'));- put('mat/off.mtl', material(false));- put('mat/off.mtl.meta', meta(MAT_OFF, 'material'));- put('props/tri.prefab', prefab);- put('props/tri.prefab.meta', meta(PREFAB, 'prefab'));- await importCocosProject({ source: src, out, only: ['props/'] });-});--afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));--const json = (rel: string): any => JSON.parse(readFileSync(path.join(out, rel), 'utf8'));--describe('a material with its outline switched on', () => {- it('has an outline material with the width and colour it gave the pass', () => {- const m = json('assets/cocos/materials/mat/on.outline.esmaterial');- expect(m.properties.lineWidth).toBe(8);- expect(m.properties.baseColor).toMatchObject({ r: 1, g: 0, b: 0 });- expect(m.cull).toBe(2);- expect(existsSync(path.join(out, 'assets/cocos/effects/cocos-outline.esshader'))).toBe(true);- });-- it('draws the mesh a second time, on a renderer beside the first', () => {- const doc = json('assets/cocos/props/tri.esprefab');- const drawn = doc.entities.find((e: any) => e.name === 'Drawn');- const part = doc.entities.find((e: any) => e.name === 'Drawn_1');- expect(part.parent).toBe(drawn.prefabEntityId);- const first = drawn.components.find((c: any) => c.type === 'MeshRenderer').data;- const second = part.components.find((c: any) => c.type === 'MeshRenderer').data;- expect(second.mesh).toBe(first.mesh);- expect(second.material).toBe('assets/cocos/materials/mat/on.outline.esmaterial');- });-- it('is not made for a material that leaves the outline off', () => {- expect(existsSync(path.join(out, 'assets/cocos/materials/mat/off.outline.esmaterial'))).toBe(false);- });-});diff --git a/pipeline/tests/cocos-import.test.ts b/pipeline/tests/cocos-import.test.tsdeleted file mode 100644index 6da83cb2f..000000000--- a/pipeline/tests/cocos-import.test.ts+++ /dev/null@@ -1,340 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file What taking a Cocos project over must keep true.- *- * The fixture is a project written out by the test, small enough that every- * expectation can be checked by eye. The claims that carry the importer:- *- * - the source is never written to;- * - a nested prefab stays nested, and the engine's own `flattenPrefab` expands- * the converted files to the same entities the Cocos instance has — that is- * the test of the override diff, which has no table of its own to be checked- * against;- * - what is not mapped is counted, not dropped.- */-import { afterAll, beforeAll, describe, expect, it } from 'vitest';-import { createHash } from 'node:crypto';-import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';-import { tmpdir } from 'node:os';-import path from 'node:path';-import { COCOS_IMPORT_REVISION, cocosImportIsCurrent, importCocosProject } from '../src/import/cocos';--const IMG = '11111111-1111-4111-8111-111111111111';-const ITEM = '22222222-2222-4222-8222-222222222222';-const PANEL = '33333333-3333-4333-8333-333333333333';-const FONT = '44444444-4444-4444-8444-444444444444';-const MAT = '66666666-6666-4666-8666-666666666666';-const EFFECT = '77777777-7777-4777-8777-777777777777';--const vec = (x: number, y: number, z = 0) => ({ __type__: 'cc.Vec3', x, y, z });-const ident = { __type__: 'cc.Quat', x: 0, y: 0, z: 0, w: 1 };-const one = vec(1, 1, 1);--function node(name: string, parent: number | null, children: number[], components: number[], prefab: number, pos = vec(0, 0)): object {- return {- __type__: 'cc.Node', _name: name, _parent: parent === null ? null : { __id__: parent },- _children: children.map((__id__) => ({ __id__ })), _active: true,- _components: components.map((__id__) => ({ __id__ })), _prefab: { __id__: prefab },- _lpos: pos, _lrot: ident, _lscale: one, _layer: 33554432,- };-}-const uiT = (n: number, c: number, w: number, h: number) =>- [{ __type__: 'cc.UITransform', node: { __id__: n }, _enabled: true, __prefab: { __id__: c }, _contentSize: { width: w, height: h }, _anchorPoint: { x: 0.5, y: 0.5 } },- { __type__: 'cc.CompPrefabInfo', fileId: `ut${n}` }];--/** item.prefab: root "Item" (sprite 100x40, tinted white) with a Label child. */-const itemPrefab = [- { __type__: 'cc.Prefab', _name: 'item', data: { __id__: 1 } },- node('Item', null, [2], [4, 6], 8, vec(5, 6)), // 1- node('Caption', 1, [], [9, 11], 13), // 2- { __type__: 'cc.Node', _name: 'unused' }, // 3 (keeps ids stable)- ...uiT(1, 5, 100, 40), // 4,5- { __type__: 'cc.Sprite', node: { __id__: 1 }, _enabled: true, __prefab: { __id__: 7 }, _color: { r: 255, g: 255, b: 255, a: 255 }, _spriteFrame: { __uuid__: `${IMG}@f9941` }, _type: 0 }, // 6- { __type__: 'cc.CompPrefabInfo', fileId: 'spr' }, // 7- { __type__: 'cc.PrefabInfo', root: { __id__: 1 }, asset: { __id__: 0 }, fileId: 'itemRoot', instance: null }, // 8- { __type__: 'cc.UITransform', node: { __id__: 2 }, _enabled: true, __prefab: { __id__: 10 }, _contentSize: { width: 80, height: 20 }, _anchorPoint: { x: 0.5, y: 0.5 } }, // 9- { __type__: 'cc.CompPrefabInfo', fileId: 'ut2' }, // 10- { __type__: 'cc.Label', node: { __id__: 2 }, _enabled: true, __prefab: { __id__: 12 }, _string: 'hello', _fontSize: 20, _lineHeight: 24, _color: { r: 255, g: 0, b: 0, a: 255 }, _horizontalAlign: 1, _verticalAlign: 1, _isSystemFontUsed: false, _font: { __uuid__: FONT }, _customMaterial: { __uuid__: MAT }, _overflow: 0, _enableWrapText: true }, // 11- { __type__: 'cc.CompPrefabInfo', fileId: 'lab' }, // 12- { __type__: 'cc.PrefabInfo', root: { __id__: 1 }, asset: { __id__: 0 }, fileId: 'capt', instance: null }, // 13-];--const instOverrides = (extra: object[]) => extra;-/** panel.prefab: root "Panel" holding two instances of item, the second repositioned, tinted and renamed. */-const panelPrefab = [- { __type__: 'cc.Prefab', _name: 'panel', data: { __id__: 1 } },- node('Panel', null, [2, 6], [], 10), // 1- { __type__: 'cc.Node', _objFlags: 0, _parent: { __id__: 1 }, _prefab: { __id__: 3 } }, // 2 (instance A, untouched)- { __type__: 'cc.PrefabInfo', root: { __id__: 2 }, asset: { __uuid__: ITEM }, fileId: 'itemRoot', instance: { __id__: 4 } }, // 3- { __type__: 'cc.PrefabInstance', fileId: 'instA', prefabRootNode: { __id__: 1 }, mountedChildren: [], mountedComponents: [{ __id__: 18 }], propertyOverrides: [], removedComponents: [] }, // 4- { __type__: 'cc.Node', _name: 'pad' }, // 5- { __type__: 'cc.Node', _objFlags: 0, _parent: { __id__: 1 }, _prefab: { __id__: 7 } }, // 6 (instance B)- { __type__: 'cc.PrefabInfo', root: { __id__: 6 }, asset: { __uuid__: ITEM }, fileId: 'itemRoot', instance: { __id__: 8 } }, // 7- { __type__: 'cc.PrefabInstance', fileId: 'instB', prefabRootNode: { __id__: 1 }, mountedChildren: [], mountedComponents: [], removedComponents: [],- propertyOverrides: [{ __id__: 11 }, { __id__: 13 }, { __id__: 15 }, { __id__: 17 }] }, // 8- { __type__: 'cc.Node', _name: 'pad' }, // 9- { __type__: 'cc.PrefabInfo', root: { __id__: 1 }, asset: { __id__: 0 }, fileId: 'panelRoot', instance: null }, // 10- { __type__: 'CCPropertyOverrideInfo', targetInfo: { __id__: 12 }, propertyPath: ['_name'], value: 'second' }, // 11- { __type__: 'cc.TargetInfo', localID: ['itemRoot'] }, // 12- { __type__: 'CCPropertyOverrideInfo', targetInfo: { __id__: 12 }, propertyPath: ['_lpos'], value: vec(0, -50) }, // 13- { __type__: 'cc.TargetInfo', localID: ['spr'] }, // 14- { __type__: 'CCPropertyOverrideInfo', targetInfo: { __id__: 14 }, propertyPath: ['_color'], value: { __type__: 'cc.Color', r: 0, g: 255, b: 0, a: 255 } }, // 15- { __type__: 'cc.TargetInfo', localID: ['lab'] }, // 16- { __type__: 'CCPropertyOverrideInfo', targetInfo: { __id__: 16 }, propertyPath: ['_string'], value: 'changed' }, // 17- // instance A carries a component its file mounted on the item's root: a component the item prefab itself does not have- { __type__: 'cc.MountedComponentsInfo', targetInfo: { __id__: 19 }, components: [{ __id__: 20 }] }, // 18- { __type__: 'cc.TargetInfo', localID: ['itemRoot'] }, // 19- { __type__: 'cc.Button', node: { __id__: 2 }, _enabled: true, __prefab: { __id__: 21 }, _interactable: true, _transition: 0 }, // 20- { __type__: 'cc.CompPrefabInfo', fileId: 'mountedButton' }, // 21-];-void instOverrides;--/** main.scene: one root node holding an instance of panel whose item B is nudged once more. */-const scene = [- { __type__: 'cc.SceneAsset', _name: 'main', scene: { __id__: 1 } },- { __type__: 'cc.Scene', _name: 'main', _children: [{ __id__: 2 }], _globals: { __id__: 5 } },- { __type__: 'cc.Node', _name: 'Canvas', _parent: { __id__: 1 }, _children: [{ __id__: 3 }], _active: true, _components: [], _prefab: null, _lpos: vec(0, 0), _lrot: ident, _lscale: one, _layer: 33554432, _id: 'canvas' },- { __type__: 'cc.Node', _objFlags: 0, _parent: { __id__: 2 }, _prefab: { __id__: 4 }, _id: '' },- { __type__: 'cc.PrefabInfo', root: { __id__: 3 }, asset: { __uuid__: PANEL }, fileId: 'panelRoot', instance: { __id__: 6 } },- { __type__: 'cc.SceneGlobals', skybox: { __id__: 5 }, _enabled: true },- { __type__: 'cc.PrefabInstance', fileId: 'inst', prefabRootNode: { __id__: 2 }, mountedChildren: [], mountedComponents: [], removedComponents: [], propertyOverrides: [{ __id__: 7 }] },- { __type__: 'CCPropertyOverrideInfo', targetInfo: { __id__: 8 }, propertyPath: ['_lpos'], value: vec(9, 9) },- { __type__: 'cc.TargetInfo', localID: ['instB', 'itemRoot'] },-];--const meta = (uuid: string, importer: string, extra: object = {}) => ({ ver: '1', importer, uuid, subMetas: {}, userData: {}, ...extra });-const imageMeta = meta(IMG, 'image', {- subMetas: { f9941: { importer: 'sprite-frame', uuid: `${IMG}@f9941`, userData: { width: 64, height: 64, rawWidth: 64, rawHeight: 64, borderLeft: 8, borderRight: 8, borderTop: 8, borderBottom: 8 } } },-});--const sha = (f: string): string => createHash('sha1').update(readFileSync(f)).digest('hex');-function* files(dir: string): Generator<string> {- for (const e of readdirSync(dir, { withFileTypes: true })) {- const p = path.join(dir, e.name);- if (e.isDirectory()) yield* files(p);- else yield p;- }-}--// The engine's own expander, loaded by path: it is the reference the overrides are judged against, and importing it-// statically would put the whole SDK under this package's compiler settings.-type Flatten = (prefab: unknown, overrides: unknown[], ctx: { allocateId: () => number; loadPrefab: (p: string) => unknown }) => { entities: any[] };-const FLATTEN = path.resolve(__dirname, '../../sdk/src/prefab/flatten.ts');-let flattenPrefab: Flatten;-const SDK = path.resolve(__dirname, '../../sdk/src');--type Validate = (name: string, defaults: unknown, data: unknown, assetFields?: unknown) => { field: string; expected: string; value: unknown }[];-let validate: Validate;-let registry: Record<string, any>;--let root: string;-let src: string;-let out: string;-let report: Awaited<ReturnType<typeof importCocosProject>>;-let before: Record<string, string>;--beforeAll(async () => {- flattenPrefab = (await import(/* @vite-ignore */ FLATTEN)).flattenPrefab as Flatten;- validate = (await import(/* @vite-ignore */ path.join(SDK, 'util/validation.ts'))).validateComponentData as Validate;- registry = await import(/* @vite-ignore */ path.join(SDK, 'ecs/component.ts'));- registry.Text = (await import(/* @vite-ignore */ path.join(SDK, 'ui/core/text.ts'))).Text;- root = mkdtempSync(path.join(tmpdir(), 'cocos-import-'));- src = path.join(root, 'creator');- out = path.join(root, 'estella');- const put = (rel: string, v: unknown): void => {- const f = path.join(src, 'assets', rel);- mkdirSync(path.dirname(f), { recursive: true });- writeFileSync(f, typeof v === 'string' ? v : JSON.stringify(v));- };- put('ui/icon.png', 'not really a png');- put('ui/icon.png.meta', imageMeta);- put('ui/item.prefab', itemPrefab);- put('ui/item.prefab.meta', meta(ITEM, 'prefab'));- put('ui/panel.prefab', panelPrefab);- put('ui/panel.prefab.meta', meta(PANEL, 'prefab'));- put('ui/f.fnt', 'info face="f" size=20\ncommon lineHeight=20 base=16 scaleW=64 scaleH=64 pages=1 packed=0\npage id=0 file="f_0.png"\n');- put('ui/f_0.png', 'page');- put('ui/f.fnt.meta', meta(FONT, 'bitmap-font'));- // the outline effect mixes the outline colour in by the red channel; the material that uses it is what marks a font page as baked- put('ui/font.effect', 'vec4 frag () { float alphaLerp = o.r; return mix(outlineColor, color, alphaLerp); }');- put('ui/font.effect.meta', meta(EFFECT, 'effect'));- put('ui/font.mtl', { __type__: 'cc.Material', _effectAsset: { __uuid__: EFFECT } });- put('ui/font.mtl.meta', meta(MAT, 'material'));- put('main.scene', scene);- put('main.scene.meta', meta('55555555-5555-4555-8555-555555555555', 'scene'));- before = Object.fromEntries([...files(src)].map((f) => [f, sha(f)]));- report = await importCocosProject({ source: src, out });-});--afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));--const readJson = (rel: string): any => JSON.parse(readFileSync(path.join(out, rel), 'utf8'));--describe('importing a Cocos project', () => {- it('never writes to the source, and refuses an output inside it', async () => {- expect(Object.fromEntries([...files(src)].map((f) => [f, sha(f)]))).toEqual(before);- await expect(importCocosProject({ source: src, out: path.join(src, 'out') })).rejects.toThrow(/never written/);- });-- it('converts every prefab and scene without failures', () => {- expect(report.documents.failed).toEqual([]);- expect(report.documents.converted).toBe(3);- for (const f of ['item.esprefab', 'panel.esprefab', 'main.esscene']) expect(existsSync(path.join(out, 'assets/cocos', f.endsWith('scene') ? f : `ui/${f}`))).toBe(true);- });-- it('maps a Sprite with its size, anchor, tint, texture and nine-slice border', () => {- const item = readJson('assets/cocos/ui/item.esprefab');- const root = item.entities.find((e: any) => e.prefabEntityId === 'itemRoot');- const sprite = root.components.find((c: any) => c.type === 'Sprite').data;- expect(sprite).toMatchObject({ size: { x: 100, y: 40 }, pivot: { x: 0.5, y: 0.5 }, texture: 'assets/cocos/ui/icon.png' });- expect(root.components[0]).toEqual({ type: 'Transform', data: { position: { x: 5, y: 6, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 1, y: 1, z: 1 } } });- expect(existsSync(path.join(out, 'assets/cocos/ui/icon.png'))).toBe(true);- });-- it('maps a Label to Text with a bitmap font, and carries the font pages along', () => {- const caption = readJson('assets/cocos/ui/item.esprefab').entities.find((e: any) => e.prefabEntityId === 'capt');- expect(caption.components.find((c: any) => c.type === 'Text').data).toMatchObject({- content: 'hello', fontSize: 20, align: 1, verticalAlign: 1, overflow: 0, font: 'assets/cocos/ui/f.fnt',- // the Label's UITransform becomes its layout box, with the node origin at the anchor- boxWidth: 80, boxHeight: 20, boxPivot: { x: 0.5, y: 0.5 },- // no overflow rule: the node grows to its text, so nothing wraps in the box and the run is laid out from the anchor- wordWrap: false,- });- const written = [...files(out)].map((f) => path.relative(out, f).split(path.sep).join('/'));- expect(written, written.join(',')).toContain('assets/cocos/ui/f_0.png');- });-- it('declares a font page that its material draws as glyph and outline layers, in BMFont\'s own channel flags', () => {- const fnt = readFileSync(path.join(out, 'assets/cocos/ui/f.fnt'), 'utf8');- const common = fnt.split(/\r?\n/).find((l) => l.startsWith('common'))!;- expect(common).toContain('alphaChnl=2');- expect(common).toContain('redChnl=0');- // the rest of the file is as it was- expect(fnt).toContain('page id=0 file="f_0.png"');- expect(common).toContain('scaleW=64');- });-- it('keeps a nested prefab nested, with the instance\'s changes as overrides', () => {- const panel = readJson('assets/cocos/ui/panel.esprefab');- const b = panel.entities.find((e: any) => e.prefabEntityId === 'instB');- expect(b.nestedPrefab.prefabPath).toBe('assets/cocos/ui/item.esprefab');- const kinds = b.nestedPrefab.overrides.map((o: any) => `${o.type}:${o.prefabEntityId}:${o.componentType ?? ''}.${o.propertyName ?? ''}`);- expect(kinds).toEqual(expect.arrayContaining([- 'name:itemRoot:.', 'property:itemRoot:Transform.position', 'property:itemRoot:Sprite.color', 'property:capt:Text.content',- ]));- // nothing else changed, so nothing else is said- expect(kinds).toHaveLength(4);- });-- it("puts a component the instance's file mounted on the prefab it names, as an added component of that instance", () => {- const panel = readJson('assets/cocos/ui/panel.esprefab');- const a = panel.entities.find((e: any) => e.prefabEntityId === 'instA');- const added = a.nestedPrefab.overrides.filter((o: any) => o.type === 'component_added');- expect(added.map((o: any) => `${o.prefabEntityId}:${o.componentType}`)).toEqual(['itemRoot:Cocos.Button']);- expect(added[0].componentData.data).toMatchObject({ interactable: true });- });-- it('expands, through the engine\'s own flatten, to what the Cocos instance has', () => {- const panel = readJson('assets/cocos/ui/panel.esprefab');- const item = readJson('assets/cocos/ui/item.esprefab');- const load = (p: string): any => (p.endsWith('item.esprefab') ? item : null);- let id = 0;- const { entities } = flattenPrefab(panel, [], { allocateId: () => ++id, loadPrefab: load });- const byName = new Map(entities.map((e: any) => [e.name, e]));- const second = byName.get('second') as any;- expect(second.components.find((c: any) => c.type === 'Transform').data.position).toEqual({ x: 0, y: -50, z: 0 });- expect(second.components.find((c: any) => c.type === 'Sprite').data.color).toEqual({ r: 0, g: 1, b: 0, a: 1 });- const texts = entities.filter((e: any) => e.components.some((c: any) => c.type === 'Text')).map((e: any) => e.components.find((c: any) => c.type === 'Text').data.content);- expect(texts.sort()).toEqual(['changed', 'hello']);- });-- it('turns a scene\'s prefab instance into an entry with the overrides it applied', () => {- const scene = readJson('assets/cocos/main.esscene');- const entry = scene.entities.find((e: any) => typeof e.prefab === 'string');- expect(entry).toMatchObject({ prefab: 'assets/cocos/ui/panel.esprefab', parent: 1, added: [], removed: [] });- // 'instB/itemRoot' addresses the engine's composed id for the nested root: slot / local id- expect(entry.overrides).toEqual([- expect.objectContaining({ prefabEntityId: 'instB/itemRoot', type: 'property', componentType: 'Transform', propertyName: 'position', value: { x: 9, y: 9, z: 0 } }),- ]);- expect(scene.entities[0].children).toEqual([entry.id]);- expect(scene.version).toBe(4);- });-- it('counts what it did not map instead of dropping it', () => {- expect(report.components['cc.Sprite']).toEqual({ mapped: 1, partial: 0, unmapped: 0 });- expect(report.components['cc.Label']).toEqual({ mapped: 1, partial: 0, unmapped: 0 });- expect(report.notes['label-bitmap-font']).toBeUndefined();- expect(report.notes['scene-globals-dropped']?.count).toBe(1);- expect(report.prefabInstances).toBe(3);- });-- it('writes component data the engine accepts: every field has the type its component declares', () => {- // A string where the engine wants an enum number loads, warns, and falls back to the default — a UI that is- // wrong everywhere and says so only in a console. The engine's own validator is the judge.- const docs = ['assets/cocos/ui/item.esprefab', 'assets/cocos/ui/panel.esprefab', 'assets/cocos/main.esscene'].map(readJson);- const problems: string[] = [];- let checked = 0;- for (const doc of docs) {- for (const e of doc.entities) {- const all = [...(e.components ?? []), ...(e.nestedPrefab?.overrides ?? e.overrides ?? []).flatMap((o: any) => (o.type === 'property' ? [{ type: o.componentType, data: { [o.propertyName]: o.value } }] : o.componentData ? [o.componentData] : []))];- for (const c of all) {- const def = registry[c.type];- if (!def) continue;- checked++;- for (const err of validate(c.type, def._default, c.data, def.assetFields)) problems.push(`${c.type}.${err.field}: expected ${err.expected}, got ${JSON.stringify(err.value)}`);- }- }- }- expect(checked).toBeGreaterThan(5);- expect(problems).toEqual([]);- });-});--describe('importing again over the same project', () => {- const ITEM_REL = 'assets/cocos/ui/item.esprefab';- const stateOf = (): { documents: Record<string, string> } => readJson('assets/cocos/.import-state.json');-- it('records the importer revision, so a project written by an older importer is known to need bringing up', () => {- expect(cocosImportIsCurrent(out)).toBe(true);- const state = { ...readJson('assets/cocos/.import-state.json') } as { revision?: number };- expect(state.revision).toBe(COCOS_IMPORT_REVISION);- const file = path.join(out, 'assets/cocos/.import-state.json');- const text = readFileSync(file, 'utf8');- delete state.revision;- writeFileSync(file, JSON.stringify(state));- expect(cocosImportIsCurrent(out)).toBe(false);- writeFileSync(file, text);- expect(cocosImportIsCurrent(path.join(out, 'nowhere'))).toBe(true); // not converted: nothing to bring up- });-- it('finds nothing to do when neither side changed', async () => {- const again = await importCocosProject({ source: src, out });- expect(again.sync.added).toBe(0);- expect(again.sync.updated).toBe(0);- expect(again.sync.kept).toEqual([]);- expect(again.sync.unchanged).toBeGreaterThan(0);- });-- it('brings the Cocos side\'s change into a document nobody edited', async () => {- // the file as an earlier import wrote it, different from what the source converts to now- const file = path.join(out, ITEM_REL);- const stale = `${readFileSync(file, 'utf8').trimEnd()}\n\n`;- writeFileSync(file, stale);- const state = stateOf();- state.documents[ITEM_REL] = createHash('sha1').update(stale).digest('hex');- writeFileSync(path.join(out, 'assets/cocos/.import-state.json'), JSON.stringify(state));- const again = await importCocosProject({ source: src, out });- expect(again.sync.updated).toBe(1);- expect(readFileSync(file, 'utf8')).not.toBe(stale);- });-- it('keeps a document that was edited here, and says so', async () => {- const file = path.join(out, ITEM_REL);- const mine = `${JSON.stringify({ ...readJson(ITEM_REL), edited: true }, null, 2)}\n`;- writeFileSync(file, mine);- const again = await importCocosProject({ source: src, out });- expect(again.sync.kept).toEqual([ITEM_REL]);- expect(readFileSync(file, 'utf8')).toBe(mine);- });-});diff --git a/pipeline/tests/cocos-internal-assets.test.ts b/pipeline/tests/cocos-internal-assets.test.tsdeleted file mode 100644index 97f305ff9..000000000--- a/pipeline/tests/cocos-internal-assets.test.ts+++ /dev/null@@ -1,96 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A scene names the editor's built-in assets (the default progress bar images) by uuid and the project does not hold them: they are- * read from the Creator install, and come into the converted project like any image.- */-import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync, existsSync } from 'node:fs';-import { tmpdir } from 'node:os';-import path from 'node:path';-import { afterAll, beforeAll, describe, expect, it } from 'vitest';-import { importCocosProject } from '../src/import/cocos';-import { buildCocosAssetIndex, cocosEditorAssets, INTERNAL_FOLDER } from '../src/import/cocos/assets';-import { compressUuid } from '../src/import/cocos/scripts';--const BAR = '24a704da-2867-446d-8d1a-5e920c75e09d';-const HERO = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee';-const DEBUG = 'ffffffff-ffff-4fff-8fff-ffffffffffff';-const component = (name: string): string => `import { _decorator, Component } from 'cc';-const { ccclass } = _decorator;-@ccclass('${name}')-export class ${name} extends Component {}-`;-const meta = (uuid: string, importer: string, subMetas: object = {}): object => ({ ver: '1', importer, uuid, subMetas, userData: {} });--describe('built-in editor assets', () => {- let root: string;- let editor: string;- const saved = process.env.COCOS_EDITOR_ASSETS;-- beforeAll(async () => {- root = mkdtempSync(path.join(tmpdir(), 'cocos-internal-'));- editor = path.join(root, 'editor-assets');- mkdirSync(path.join(editor, 'default_ui'), { recursive: true });- writeFileSync(path.join(editor, 'default_ui', 'default_progressbar.png'), 'png');- writeFileSync(path.join(editor, 'default_ui', 'default_progressbar.png.meta'), JSON.stringify(meta('bbbbbbbb-1111-4111-8111-bbbbbbbbbbbb', 'image', { f9941: { importer: 'sprite-frame', uuid: BAR, name: 'spriteFrame', userData: {} } })));- // the editor's own tools hold a component class too- mkdirSync(path.join(editor, 'tools'), { recursive: true });- writeFileSync(path.join(editor, 'tools', 'debug-view.ts'), component('DebugView'));- writeFileSync(path.join(editor, 'tools', 'debug-view.ts.meta'), JSON.stringify(meta(DEBUG, 'typescript')));- process.env.COCOS_EDITOR_ASSETS = editor;-- const dir = path.join(root, 'creator', 'assets');- mkdirSync(dir, { recursive: true });- const unit = { __type__: 'cc.Vec3', x: 1, y: 1, z: 1 }, zero = { __type__: 'cc.Vec3', x: 0, y: 0, z: 0 };- const scene = [- { __type__: 'cc.SceneAsset', _name: 'main', scene: { __id__: 1 } },- { __type__: 'cc.Scene', _name: 'main', _children: [{ __id__: 2 }] },- { __type__: 'cc.Node', _name: 'Bar', _parent: { __id__: 1 }, _children: [], _active: true, _components: [{ __id__: 3 }], _prefab: null, _lpos: zero, _lrot: { __type__: 'cc.Quat', x: 0, y: 0, z: 0, w: 1 }, _lscale: unit, _layer: 1 },- { __type__: 'cc.Sprite', node: { __id__: 2 }, _enabled: true, _color: { __type__: 'cc.Color', r: 255, g: 255, b: 255, a: 255 }, _spriteFrame: { __uuid__: `${BAR}`, __expectedType__: 'cc.SpriteFrame' }, _type: 1, _sizeMode: 0 },- ];- scene.push({ __type__: 'cc.Node', _name: 'Hero', _parent: { __id__: 1 }, _children: [], _active: true, _components: [{ __id__: 5 }], _prefab: null, _lpos: zero, _lrot: { __type__: 'cc.Quat', x: 0, y: 0, z: 0, w: 1 }, _lscale: unit, _layer: 1 });- scene.push({ __type__: compressUuid(HERO), node: { __id__: 4 }, _enabled: true } as never);- (scene[1] as { _children: unknown[] })._children.push({ __id__: 4 });- writeFileSync(path.join(dir, 'Hero.ts'), component('Hero'));- writeFileSync(path.join(dir, 'Hero.ts.meta'), JSON.stringify(meta(HERO, 'typescript')));- writeFileSync(path.join(dir, 'main.scene'), JSON.stringify(scene));- writeFileSync(path.join(dir, 'main.scene.meta'), JSON.stringify(meta('dddddddd-dddd-4ddd-8ddd-dddddddddddd', 'scene')));- writeFileSync(path.join(root, 'creator', 'package.json'), JSON.stringify({ creator: { version: '3.7.3' } }));- await importCocosProject({ source: path.join(root, 'creator'), out: path.join(root, 'out') });- });- afterAll(() => {- if (saved === undefined) delete process.env.COCOS_EDITOR_ASSETS; else process.env.COCOS_EDITOR_ASSETS = saved;- rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });- });-- it('finds the install folder, and none for a version nobody has', () => {- expect(cocosEditorAssets('3.7.3')).toBe(editor);- delete process.env.COCOS_EDITOR_ASSETS;- expect(cocosEditorAssets('0.0.0-none')).toBeNull();- process.env.COCOS_EDITOR_ASSETS = editor;- });-- it('lets the project\'s own assets win over a built-in of the same uuid', () => {- const own = path.join(root, 'own');- mkdirSync(own, { recursive: true });- writeFileSync(path.join(own, 'mine.png.meta'), JSON.stringify(meta('bbbbbbbb-1111-4111-8111-bbbbbbbbbbbb', 'image')));- writeFileSync(path.join(own, 'mine.png'), 'png');- const index = buildCocosAssetIndex(own, editor);- expect(index.byUuid.get('bbbbbbbb-1111-4111-8111-bbbbbbbbbbbb')!.rel).toBe('mine.png');- expect(index.byUuid.get(BAR)!.rel).toBe(`${INTERNAL_FOLDER}/default_ui/default_progressbar.png`);- });-- it("leaves the editor's own scripts out of the entry, which loads the project's", () => {- const entry = readFileSync(path.join(root, 'out', 'src', 'cocos-scripts.ts'), 'utf8');- expect(entry).toContain('Hero');- expect(entry).not.toContain(INTERNAL_FOLDER);- });-- it('brings the image in and points the sprite at it', () => {- const scene = JSON.parse(readFileSync(path.join(root, 'out', 'assets', 'cocos', 'main.esscene'), 'utf8')) as { entities: Array<{ name: string; components: Array<{ type: string; data: Record<string, unknown> }> }> };- const sprite = scene.entities.find((e) => e.name === 'Bar')!.components.find((c) => c.type === 'Sprite')!;- expect(sprite.data.texture).toBe(`assets/cocos/${INTERNAL_FOLDER}/default_ui/default_progressbar.png`);- expect(sprite.data.enabled).not.toBe(false);- expect(existsSync(path.join(root, 'out', 'assets', 'cocos', INTERNAL_FOLDER, 'default_ui', 'default_progressbar.png'))).toBe(true);- });-});diff --git a/pipeline/tests/cocos-model-parts.test.ts b/pipeline/tests/cocos-model-parts.test.tsdeleted file mode 100644index 8cb936138..000000000--- a/pipeline/tests/cocos-model-parts.test.ts+++ /dev/null@@ -1,49 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file The mesh renderers of a model told apart by the id Cocos gave each component, so a material put on one part of a model instance reaches that part.- */-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';-import path from 'node:path';-import { afterAll, describe, expect, it } from 'vitest';-import { CocosModels } from '../src/import/cocos/models';-import type { CocosAssetEntry, CocosAssetIndex } from '../src/import/cocos/assets';--describe('the parts of a model', () => {- const roots: string[] = [];- afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }); });-- function models(withLibrary: boolean): { models: CocosModels; entry: CocosAssetEntry } {- const project = mkdtempSync(path.join(tmpdir(), 'cocos-parts-'));- roots.push(project);- const uuid = '0b66da8a-0278-47c3-968e-5e4325ae5482';- const scene = `${uuid}@8a0c4`;- if (withLibrary) {- mkdirSync(path.join(project, 'library', '0b'), { recursive: true });- writeFileSync(path.join(project, 'library', '0b', `${scene}.json`), JSON.stringify([- { __type__: 'cc.Prefab' },- { __type__: 'cc.Node', _name: 'room' },- { __type__: 'cc.Node', _name: 'wall' },- { __type__: 'cc.MeshRenderer', node: { __id__: 2 }, __prefab: { __id__: 4 } },- { __type__: 'cc.CompPrefabInfo', fileId: 'wallRenderer' },- ]));- }- const entry: CocosAssetEntry = {- uuid, file: path.join(project, 'assets', 'room.FBX'), rel: 'room.FBX', importer: 'fbx', userData: {},- subs: new Map([[scene, { importer: 'gltf-scene', name: 'room.prefab', userData: {} }]]),- };- const index: CocosAssetIndex = { root: path.join(project, 'assets'), byUuid: new Map([[uuid, entry]]), bundles: [] };- return { models: new CocosModels(index, path.join(project, 'out'), 'cocos', true), entry };- }-- it('are named by the id of their renderer, from the editor library', () => {- const { models: m, entry } = models(true);- expect([...m.partsOf(entry)]).toEqual([['wallRenderer', 'wall']]);- });-- it('stay unaddressed when the project has no library', () => {- const { models: m, entry } = models(false);- expect(m.partsOf(entry).size).toBe(0);- });-});diff --git a/pipeline/tests/cocos-particle.test.ts b/pipeline/tests/cocos-particle.test.tsdeleted file mode 100644index 709fb3888..000000000--- a/pipeline/tests/cocos-particle.test.ts+++ /dev/null@@ -1,231 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A Cocos particle system as the engine's ParticleEmitter.- *- * The data below is the shape of a real system (a stun effect from the client project): constants, a burst, a cone, a colour fade and a size- * curve. The output is checked against the engine's own validator, since the offline document validators do not look at field types.- */-import { beforeAll, describe, expect, it } from 'vitest';-import path from 'node:path';-import { ImportReport } from '../src/import/cocos/report';-import { curveRange, particleSystem, particleSystem2D, type ParticleContext } from '../src/import/cocos/particle';--const SDK = path.resolve(__dirname, '../../sdk/src');-type Validate = (name: string, defaults: unknown, data: unknown, assetFields?: unknown) => { field: string; expected: string; value: unknown }[];-let validate: Validate;-let registry: Record<string, { _default: unknown; assetFields?: unknown }>;--beforeAll(async () => {- validate = (await import(/* @vite-ignore */ path.join(SDK, 'util/validation.ts'))).validateComponentData as Validate;- registry = await import(/* @vite-ignore */ path.join(SDK, 'ecs/component.ts'));-});--const constant = (c: number) => ({ __type__: 'cc.CurveRange', mode: 0, constant: c, multiplier: 1 });-const between = (a: number, b: number) => ({ __type__: 'cc.CurveRange', mode: 3, constantMin: a, constantMax: b, multiplier: 1 });-const curve = (values: Array<[number, number]>, multiplier = 1) => ({- __type__: 'cc.CurveRange', mode: 1, multiplier, spline: { _values: values.map(([time, value]) => ({ time, value })) },-});-const rgba = (r: number, g: number, b: number, a: number) => ({ __type__: 'cc.Color', r, g, b, a });--function system(over: Record<string, unknown> = {}) {- return {- enabled: true,- data: {- startColor: { _mode: 0, color: rgba(255, 191, 112, 255) },- startSize: constant(0.6), startSpeed: between(1, 3), startRotationZ: constant(0), startLifetime: constant(1),- duration: 1, loop: false, playOnAwake: true, gravityModifier: constant(0.5), rateOverTime: constant(0),- bursts: [{ _time: 0, count: constant(12), repeatInterval: 0.5 }], _capacity: 30, _simulationSpace: 0,- _shapeModule: { _enable: true, _shapeType: 2, radius: 0.5, angle: 20 },- _colorOverLifetimeModule: {- _enable: true,- color: { _mode: 1, gradient: { colorKeys: [{ time: 0, color: rgba(255, 255, 255, 255) }, { time: 1, color: rgba(255, 128, 0, 255) }], alphaKeys: [{ time: 0, alpha: 255 }, { time: 1, alpha: 0 }] } },- },- _sizeOvertimeModule: { _enable: true, size: curve([[0, 1], [1, 0.5]]) },- _materials: [{ __uuid__: 'mat' }],- ...over,- },- };-}--function convert(over: Record<string, unknown> = {}) {- const report = new ImportReport();- const ctx: ParticleContext = {- report,- material: () => ({ texture: null, additive: true }),- assetRef: () => 'assets/cocos/spark.png',- };- const out = particleSystem(system(over), ctx, 'fx.prefab');- return { out, report: report.toJSON() };-}--describe('a particle system', () => {- it('becomes an emitter with the data the engine accepts', () => {- const { out } = convert();- expect(out.type).toBe('ParticleEmitter');- const def = registry.ParticleEmitter;- expect(def).toBeDefined();- const errors = validate('ParticleEmitter', def!._default, out.data, def!.assetFields);- expect(errors).toEqual([]);- });-- it('carries emission, lifetime, speed, size, gravity and space', () => {- const d = convert().out.data as Record<string, any>;- expect(d.maxParticles).toBe(30);- expect(d.looping).toBe(false);- expect(d.bursts).toEqual([{ time: 0, count: 12 }]);- expect([d.speedMin, d.speedMax]).toEqual([1, 3]);- expect(d.lifetimeMin).toBe(1);- expect(d.gravity.y).toBeCloseTo(-4.9, 5);- expect(d.simulationSpace).toBe(1); // Cocos Local is the engine's Local (1)- expect(d.shape).toBe(3); // Cone- expect(d.shapeRadius).toBe(0.5);- expect(d.blendMode).toBe(1);- });-- it('eases the colour and the size from their values at the two ends of a life', () => {- const d = convert().out.data as Record<string, any>;- expect(d.startColor.a).toBeCloseTo(1, 5);- expect(d.endColor.a).toBeCloseTo(0, 5);- expect(d.endColor.g).toBeCloseTo((191 / 255) * (128 / 255), 4);- expect([d.startSizeMin, d.endSizeMin]).toEqual([0.6, 0.3]);- });-- it('keeps a fade that rises and falls as a gradient the sim samples by age, and a size curve as keys', () => {- const fade = { _mode: 1, gradient: { colorKeys: [], alphaKeys: [{ time: 0, alpha: 0 }, { time: 0.5, alpha: 255 }, { time: 1, alpha: 0 }] } };- const swell = curve([[0, 0.2], [0.5, 1], [1, 0.1]]);- const { out, report } = convert({ _colorOverLifetimeModule: { _enable: true, color: fade }, _sizeOvertimeModule: { _enable: true, size: swell } });- const d = out.data as Record<string, any>;- expect(d.colorGradient.stops.map((s: any) => [s.t, Math.round(s.color.a * 100) / 100])).toEqual([[0, 0], [0.5, 1], [1, 0]]);- expect(d.sizeCurve.keys.map((k: any) => [k.time, k.value])).toEqual([[0, 0.2], [0.5, 1], [1, 0.1]]);- expect(report.components['cc.ParticleSystem']).toEqual({ mapped: 1, partial: 0, unmapped: 0 });- const def = registry.ParticleEmitter!;- expect(validate('ParticleEmitter', def._default, d, def.assetFields)).toEqual([]);- });-- it('carries the start delay, taking the middle of a range of them', () => {- expect((convert({ startDelay: constant(0.4) }).out.data as Record<string, any>).startDelay).toBeCloseTo(0.4, 5);- expect((convert({ startDelay: between(0.2, 0.6) }).out.data as Record<string, any>).startDelay).toBeCloseTo(0.4, 5);- expect(convert().report.notes['particle-start-delay']).toBeUndefined();- });-- it('maps a stretched billboard with its scales, and counts the render modes it cannot draw', () => {- const stretched = convert({ renderer: { _renderMode: 1, _velocityScale: 1, _lengthScale: 7 } });- const d = stretched.out.data as Record<string, any>;- expect([d.renderMode, d.velocityScale, d.lengthScale]).toEqual([1, 1, 7]);- expect(stretched.report.components['cc.ParticleSystem']).toEqual({ mapped: 1, partial: 0, unmapped: 0 });- const def = registry.ParticleEmitter!;- expect(validate('ParticleEmitter', def._default, d, def.assetFields)).toEqual([]);-- const mesh = convert({ renderer: { _renderMode: 4 } });- expect(mesh.report.notes['particle-render-mode']?.count).toBe(1);- expect((mesh.out.data as Record<string, any>).renderMode).toBeUndefined();- });-- it('maps added velocity, a speed limit and a force, and counts the curves it cannot hold', () => {- const { out, report } = convert({- _velocityOvertimeModule: { _enable: true, x: between(-0.2, 0.2), y: constant(1), z: constant(0), speedModifier: constant(1) },- _limitVelocityOvertimeModule: { _enable: true, limit: constant(3), dampen: 0.2, separateAxes: false },- _forceOvertimeModule: { _enable: true, x: constant(0), y: constant(-30), z: constant(0) },- });- const d = out.data as Record<string, any>;- expect(d.addedVelocityMin).toEqual({ x: -0.2, y: 1, z: 0 });- expect(d.addedVelocityMax).toEqual({ x: 0.2, y: 1, z: 0 });- expect([d.speedLimit, d.limitDampen]).toEqual([3, 0.2]);- expect(d.gravity.y).toBeCloseTo(-4.9 - 30, 5); // the system's own gravity plus the force- expect(report.components['cc.ParticleSystem']).toEqual({ mapped: 1, partial: 0, unmapped: 0 });- const def = registry.ParticleEmitter!;- expect(validate('ParticleEmitter', def._default, d, def.assetFields)).toEqual([]);-- const bent = convert({ _velocityOvertimeModule: { _enable: true, x: curve([[0, 0], [1, 5]]), y: constant(0), z: constant(0), speedModifier: constant(1) } });- expect(bent.report.notes['particle-velocity-curve']?.count).toBe(1);- const axes = convert({ _limitVelocityOvertimeModule: { _enable: true, separateAxes: true } });- expect(axes.report.notes['particle-limit-per-axis']?.count).toBe(1);- });-- it('maps simulation speed, turbulence and a trail, and a burst scheduled at its time', () => {- const { out, report } = convert({- simulationSpeed: 2,- bursts: [{ _time: 0.4, count: constant(5), repeatInterval: 1 }],- _noiseModule: { _enable: true, _strengthX: 0.8, _strengthY: 0.4, _noiseFrequency: 0.5, _noiseSpeedX: 1, _noiseSpeedY: 3, _octaves: 2 },- _trailModule: { _enable: true, lifeTime: constant(0.35), _minParticleDistance: 0.1, widthFromParticle: false, widthRatio: constant(0.8), colorOverTrail: { _mode: 0 } },- });- const d = out.data as Record<string, any>;- expect(d.simulationSpeed).toBe(2);- expect(d.bursts).toEqual([{ time: 0.4, count: 5 }]);- expect([d.noiseStrength, d.noiseFrequency, d.noiseScrollSpeed, d.noiseOctaves]).toEqual([0.6000000000000001, 0.5, 2, 2]);- expect([d.trailEnabled, d.trailPoints, d.trailWidth, d.trailMinDistance]).toEqual([true, 7, 0.8, 0.1]);- expect(report.components['cc.ParticleSystem']).toEqual({ mapped: 1, partial: 0, unmapped: 0 });- const def = registry.ParticleEmitter!;- expect(validate('ParticleEmitter', def._default, d, def.assetFields)).toEqual([]);- });-- it('schedules several bursts and a repeating one, in time order', () => {- const { out } = convert({- bursts: [{ _time: 1, count: constant(4), repeatInterval: 1 }, { _time: 0, _repeatCount: 3, count: constant(5), repeatInterval: 0.5 }],- });- expect((out.data as Record<string, any>).bursts).toEqual([- { time: 0, count: 5 }, { time: 0.5, count: 5 }, { time: 1, count: 4 }, { time: 1, count: 5 },- ]);- });-- it('counts what the emitter has no field for: a trail coloured along its length', () => {- const { report } = convert({- _trailModule: { _enable: true, lifeTime: constant(0.3), widthRatio: constant(1), colorOverTrail: { _mode: 1 } },- });- expect(report.notes['particle-trail-colour']?.count).toBe(1);- });-- it('is fully mapped when nothing was left out', () => {- const { report } = convert();- expect(report.components['cc.ParticleSystem']).toEqual({ mapped: 1, partial: 0, unmapped: 0 });- });-});--describe('a curve range', () => {- it('is read as a constant, two constants, or a curve at the asked time', () => {- expect(curveRange(constant(2), 0)).toEqual({ min: 2, max: 2 });- expect(curveRange(between(1, 3), 0)).toEqual({ min: 1, max: 3 });- expect(curveRange(curve([[0, 0], [1, 10]], 2), 0.5).min).toBeCloseTo(10, 5);- });-});--describe('a 2D particle system', () => {- const color = (r: number, g: number, b: number, a: number) => ({ __type__: 'cc.Color', r, g, b, a });- const convert2D = (over: Record<string, unknown> = {}) => {- const report = new ImportReport();- const out = particleSystem2D({- enabled: true,- data: {- duration: -1, emissionRate: 50, life: 1, lifeVar: 0.25, angle: 90, angleVar: 10, speed: 100, speedVar: 20, startSize: 30, startSizeVar: 10, endSize: 5, endSizeVar: 0,- startSpin: 0, endSpin: 90, emitterMode: 0, gravity: { x: 0, y: -50 }, _totalParticles: 200, _dstBlendFactor: 1, _positionType: 0,- _startColor: color(255, 128, 0, 255), _endColor: color(255, 0, 0, 0), _spriteFrame: { __uuid__: 'frame@f9941' }, ...over,- },- }, { report, assetRef: () => 'x', frame: () => 'assets/cocos/spark.png' }, 'fx.scene');- return { out, report: report.toJSON() };- };-- it('maps the start and end ranges, the gravity, the colour and the picture, and validates', () => {- const { out, report } = convert2D();- const d = out.data as Record<string, any>;- expect([d.lifetimeMin, d.lifetimeMax]).toEqual([0.75, 1.25]);- expect([d.speedMin, d.speedMax]).toEqual([80, 120]);- expect([d.angleSpreadMin, d.angleSpreadMax]).toEqual([80, 100]);- expect([d.startSizeMin, d.startSizeMax, d.endSizeMin]).toEqual([20, 40, 5]);- expect(d.looping).toBe(true);- expect(d.gravity).toEqual({ x: 0, y: -50, z: 0 });- expect(d.endColor.a).toBe(0);- expect(d.texture).toBe('assets/cocos/spark.png');- expect(d.angularVelocityMin).toBeCloseTo(90, 3);- expect(report.components['cc.ParticleSystem2D']).toEqual({ mapped: 1, partial: 0, unmapped: 0 });- const def = registry.ParticleEmitter!;- expect(validate('ParticleEmitter', def._default, d, def.assetFields)).toEqual([]);- });-- it('counts the radius mode and the accelerations the emitter has no model for', () => {- const radius = convert2D({ emitterMode: 1 });- expect(radius.report.notes['particle2d-radius-mode']?.count).toBe(1);- const accel = convert2D({ radialAccel: -100 });- expect(accel.report.notes['particle2d-accel']?.count).toBe(1);- });-});diff --git a/pipeline/tests/cocos-scene-ambient.test.ts b/pipeline/tests/cocos-scene-ambient.test.tsdeleted file mode 100644index 7a7c4bdf5..000000000--- a/pipeline/tests/cocos-scene-ambient.test.ts+++ /dev/null@@ -1,48 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file The ambient most of a project's game scenes set is what a converted effect's scene parameters start at.- */-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';-import path from 'node:path';-import { afterAll, describe, expect, it } from 'vitest';-import { ambientOfScene, dominantAmbient } from '../src/import/cocos/sceneAmbient';-import type { CocosAssetEntry, CocosAssetIndex } from '../src/import/cocos/assets';--const v4 = (x: number, y: number, z: number) => ({ __type__: 'cc.Vec4', x, y, z, w: 0 });-const scene = (sky: [number, number, number], illum: number, ground: [number, number, number]) => [- { __type__: 'cc.SceneAsset', scene: { __id__: 1 } },- { __type__: 'cc.Scene', _globals: { __id__: 2 } },- { __type__: 'cc.SceneGlobals', ambient: { __id__: 3 } },- { __type__: 'cc.AmbientInfo', _skyColorLDR: v4(...sky), _skyIllumLDR: illum, _groundAlbedoLDR: v4(...ground) },-];--describe('the ambient of a project', () => {- const dir = mkdtempSync(path.join(tmpdir(), 'cocos-ambient-scenes-'));- afterAll(() => rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));-- const entries: CocosAssetEntry[] = [];- const put = (rel: string, content: unknown): void => {- const file = path.join(dir, rel.replace(/\//g, '_'));- writeFileSync(file, JSON.stringify(content));- entries.push({ uuid: String(entries.length), file, rel, importer: 'scene', userData: {}, subs: new Map() });- };- const index = (): CocosAssetIndex => ({ root: dir, byUuid: new Map(entries.map((e) => [e.uuid, e])), bundles: [] });-- it('reads the sky colour with its illumination, and the ground', () => {- put('a/one.scene', scene([0.5, 0.6, 1], 0.8, [1, 1, 1]));- expect(ambientOfScene(entries[0]!.file)).toEqual({ sky: [0.5, 0.6, 1, 0.8], ground: [1, 1, 1, 1] });- });-- it('is the one most game scenes set, and not what the editor tools set', () => {- put('a/two.scene', scene([0.5, 0.6, 1], 0.8, [1, 1, 1]));- put('a/three.scene', scene([1, 1, 1], 1, [0.6, 0.6, 0.5]));- for (const n of ['x', 'y', 'z', 'w']) put(`editor/${n}.scene`, scene([0.2, 0.2, 0.2], 0.5, [0.1, 0.1, 0.1]));- expect(dominantAmbient(index())).toEqual({ sky: [0.5, 0.6, 1, 0.8], ground: [1, 1, 1, 1] });- });-- it('is null for a project whose scenes set none', () => {- expect(dominantAmbient({ root: dir, byUuid: new Map(), bundles: [] })).toBeNull();- });-});diff --git a/pipeline/tests/cocos-widget-migration.test.ts b/pipeline/tests/cocos-widget-migration.test.tsdeleted file mode 100644index 7e3336057..000000000--- a/pipeline/tests/cocos-widget-migration.test.ts+++ /dev/null@@ -1,55 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A document the creator edited keeps what they did, and still moves to the engine's `RectAnchors` from the compatibility layer's- * `Cocos.Widget`: only the component's name changes.- */-import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';-import path from 'node:path';-import { afterAll, beforeAll, describe, expect, it } from 'vitest';-import { importCocosProject } from '../src/import/cocos';--const meta = (uuid: string, importer: string): object => ({ ver: '1', importer, uuid, subMetas: {}, userData: {} });--describe('a kept document that holds a Cocos.Widget', () => {- let root: string;- let file: string;- let second: Awaited<ReturnType<typeof importCocosProject>>;-- beforeAll(async () => {- root = mkdtempSync(path.join(tmpdir(), 'cocos-migrate-'));- const dir = path.join(root, 'creator', 'assets');- mkdirSync(dir, { recursive: true });- const zero = { __type__: 'cc.Vec3', x: 0, y: 0, z: 0 };- writeFileSync(path.join(dir, 'main.scene'), JSON.stringify([- { __type__: 'cc.SceneAsset', _name: 'main', scene: { __id__: 1 } },- { __type__: 'cc.Scene', _name: 'main', _children: [{ __id__: 2 }] },- { __type__: 'cc.Node', _name: 'N', _parent: { __id__: 1 }, _children: [], _active: true, _components: [], _prefab: null, _lpos: zero, _lrot: { __type__: 'cc.Quat', x: 0, y: 0, z: 0, w: 1 }, _lscale: { __type__: 'cc.Vec3', x: 1, y: 1, z: 1 }, _layer: 1 },- ]));- writeFileSync(path.join(dir, 'main.scene.meta'), JSON.stringify(meta('dddddddd-dddd-4ddd-8ddd-dddddddddddd', 'scene')));- const source = path.join(root, 'creator'), out = path.join(root, 'out');- await importCocosProject({ source, out });- // the creator edits it, and it was written back when widgets were the layer's- file = path.join(out, 'assets', 'cocos', 'main.esscene');- const doc = JSON.parse(readFileSync(file, 'utf8')) as { entities: Array<{ name: string; components: unknown[] }> };- doc.entities.find((e) => e.name === 'N')!.components.push({ type: 'Cocos.Widget', data: { enabled: true, alignFlags: 45, left: 5, target: 3 } }, { type: 'Name', data: { value: 'edited by hand' } });- writeFileSync(file, `${JSON.stringify(doc, null, 2)}\n`);- second = await importCocosProject({ source, out });- });- afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));-- it('is kept, and says it was migrated', () => {- expect(second.sync.kept).toContain('assets/cocos/main.esscene');- expect(second.notes['widget-migrated']?.count).toBe(1);- });-- it('holds a RectAnchors with the same fields (and no target), and nothing else changed', () => {- const doc = JSON.parse(readFileSync(file, 'utf8')) as { entities: Array<{ name: string; components: Array<{ type: string; data: Record<string, unknown> }> }> };- const components = doc.entities.find((e) => e.name === 'N')!.components;- const anchors = components.find((c) => c.type === 'RectAnchors')!;- expect(anchors.data).toEqual({ enabled: true, alignFlags: 45, left: 5 });- expect(components.some((c) => c.type === 'Cocos.Widget')).toBe(false);- expect(components.find((c) => c.type === 'Name')!.data.value).toBe('edited by hand');- });-});diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 841ee5457..3d107b37e 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 161 beta · 1975 experimental · 3 deprecated+Symbols: 115 public · 161 beta · 1978 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -5744,7 +5744,7 @@ y: number## Material — const @experimental```-{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; materialsDeclaring(param: string): MaterialHandle[]; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }+{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; materialsDeclaring(param: string): MaterialHandle[]; noteProgram(shader: ShaderHandle, features: readonly string[], esshaderSource: string, compile: (features: string[]) => ShaderHandle): void; recompile(material: MaterialHandle, changes: Record<string, boolean>): boolean; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }```## MaterialAssetData — interface @experimental@@ -5773,6 +5773,7 @@ depthTest: booleandepthWrite: booleandirty_: booleanoverrides: Set<string>+ownShader: number | undefinedparent: number | undefinedpushed_: boolean | undefinedsent_: Map<string, number[]> | undefined@@ -11071,6 +11072,26 @@ maxSize: number | undefinedpadding: number | undefined```+## TextureCanvas — const @experimental+```+{ create(width: number, height: number, options?: TextureCanvasOptions): TextureCanvasHandle | null; }+```++## TextureCanvasHandle — interface @experimental+```+clear: () => void+draw: (source: number, x: number, y: number, width?: number, height?: number) => void+height: number+release: () => void+texture: number+width: number+```++## TextureCanvasOptions — interface @experimental+```+filter: "linear" | "nearest" | undefined+```+## TextureFilter — type @experimental```(typeof TextureFilter)[keyof typeof TextureFilter]diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 269bc4eed..ce31b3d15 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 166 beta · 1994 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 1997 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -5752,7 +5752,7 @@ y: number## Material — const @experimental```-{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; materialsDeclaring(param: string): MaterialHandle[]; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }+{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; materialsDeclaring(param: string): MaterialHandle[]; noteProgram(shader: ShaderHandle, features: readonly string[], esshaderSource: string, compile: (features: string[]) => ShaderHandle): void; recompile(material: MaterialHandle, changes: Record<string, boolean>): boolean; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }```## MaterialAssetData — interface @experimental@@ -5781,6 +5781,7 @@ depthTest: booleandepthWrite: booleandirty_: booleanoverrides: Set<string>+ownShader: number | undefinedparent: number | undefinedpushed_: boolean | undefinedsent_: Map<string, number[]> | undefined@@ -11284,6 +11285,26 @@ maxSize: number | undefinedpadding: number | undefined```+## TextureCanvas — const @experimental+```+{ create(width: number, height: number, options?: TextureCanvasOptions): TextureCanvasHandle | null; }+```++## TextureCanvasHandle — interface @experimental+```+clear: () => void+draw: (source: number, x: number, y: number, width?: number, height?: number) => void+height: number+release: () => void+texture: number+width: number+```++## TextureCanvasOptions — interface @experimental+```+filter: "linear" | "nearest" | undefined+```+## TextureFilter — type @experimental```(typeof TextureFilter)[keyof typeof TextureFilter]diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex e6e3f2a06..188512976 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 163 beta · 1974 experimental · 3 deprecated+Symbols: 115 public · 163 beta · 1977 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -5739,7 +5739,7 @@ y: number## Material — const @experimental```-{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; materialsDeclaring(param: string): MaterialHandle[]; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }+{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; materialsDeclaring(param: string): MaterialHandle[]; noteProgram(shader: ShaderHandle, features: readonly string[], esshaderSource: string, compile: (features: string[]) => ShaderHandle): void; recompile(material: MaterialHandle, changes: Record<string, boolean>): boolean; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }```## MaterialAssetData — interface @experimental@@ -5768,6 +5768,7 @@ depthTest: booleandepthWrite: booleandirty_: booleanoverrides: Set<string>+ownShader: number | undefinedparent: number | undefinedpushed_: boolean | undefinedsent_: Map<string, number[]> | undefined@@ -11066,6 +11067,26 @@ maxSize: number | undefinedpadding: number | undefined```+## TextureCanvas — const @experimental+```+{ create(width: number, height: number, options?: TextureCanvasOptions): TextureCanvasHandle | null; }+```++## TextureCanvasHandle — interface @experimental+```+clear: () => void+draw: (source: number, x: number, y: number, width?: number, height?: number) => void+height: number+release: () => void+texture: number+width: number+```++## TextureCanvasOptions — interface @experimental+```+filter: "linear" | "nearest" | undefined+```+## TextureFilter — type @experimental```(typeof TextureFilter)[keyof typeof TextureFilter]diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex dbb7fcea2..265caa068 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 161 beta · 1996 experimental · 3 deprecated+Symbols: 115 public · 161 beta · 1999 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -5739,7 +5739,7 @@ y: number## Material — const @experimental```-{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; materialsDeclaring(param: string): MaterialHandle[]; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }+{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; materialsDeclaring(param: string): MaterialHandle[]; noteProgram(shader: ShaderHandle, features: readonly string[], esshaderSource: string, compile: (features: string[]) => ShaderHandle): void; recompile(material: MaterialHandle, changes: Record<string, boolean>): boolean; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }```## MaterialAssetData — interface @experimental@@ -5768,6 +5768,7 @@ depthTest: booleandepthWrite: booleandirty_: booleanoverrides: Set<string>+ownShader: number | undefinedparent: number | undefinedpushed_: boolean | undefinedsent_: Map<string, number[]> | undefined@@ -11361,6 +11362,26 @@ maxSize: number | undefinedpadding: number | undefined```+## TextureCanvas — const @experimental+```+{ create(width: number, height: number, options?: TextureCanvasOptions): TextureCanvasHandle | null; }+```++## TextureCanvasHandle — interface @experimental+```+clear: () => void+draw: (source: number, x: number, y: number, width?: number, height?: number) => void+height: number+release: () => void+texture: number+width: number+```++## TextureCanvasOptions — interface @experimental+```+filter: "linear" | "nearest" | undefined+```+## TextureFilter — type @experimental```(typeof TextureFilter)[keyof typeof TextureFilter]diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 1710d5a6a..9e6ac05b4 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 161 beta · 1987 experimental · 3 deprecated+Symbols: 115 public · 161 beta · 1990 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -5746,7 +5746,7 @@ y: number## Material — const @experimental```-{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; materialsDeclaring(param: string): MaterialHandle[]; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }+{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; materialsDeclaring(param: string): MaterialHandle[]; noteProgram(shader: ShaderHandle, features: readonly string[], esshaderSource: string, compile: (features: string[]) => ShaderHandle): void; recompile(material: MaterialHandle, changes: Record<string, boolean>): boolean; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">, textureLeases?: ReadonlyMap<string, TextureLease>): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number, shape?: { mesh?: number; texture?: number; }): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }```## MaterialAssetData — interface @experimental@@ -5775,6 +5775,7 @@ depthTest: booleandepthWrite: booleandirty_: booleanoverrides: Set<string>+ownShader: number | undefinedparent: number | undefinedpushed_: boolean | undefinedsent_: Map<string, number[]> | undefined@@ -11073,6 +11074,26 @@ maxSize: number | undefinedpadding: number | undefined```+## TextureCanvas — const @experimental+```+{ create(width: number, height: number, options?: TextureCanvasOptions): TextureCanvasHandle | null; }+```++## TextureCanvasHandle — interface @experimental+```+clear: () => void+draw: (source: number, x: number, y: number, width?: number, height?: number) => void+height: number+release: () => void+texture: number+width: number+```++## TextureCanvasOptions — interface @experimental+```+filter: "linear" | "nearest" | undefined+```+## TextureFilter — type @experimental```(typeof TextureFilter)[keyof typeof TextureFilter]diff --git a/sdk/package.json b/sdk/package.jsonindex 057b7b1eb..9441a6df1 100644--- a/sdk/package.json+++ b/sdk/package.json@@ -33,7 +33,6 @@"./dist/net/replication/index.js","./dist/net/session/index.js","./dist/gameplay/index.js",- "./dist/cocos/index.js","./dist/physics/index.js","./dist/physics3d/index.js","./dist/douyin/index.js",@@ -148,10 +147,6 @@"import": "./dist/gameplay/index.js","types": "./dist/gameplay/index.d.ts"},- "./cocos": {- "import": "./dist/cocos/index.js",- "types": "./dist/cocos/index.d.ts"- },"./physics": {"import": "./dist/physics/index.js","types": "./dist/physics/index.d.ts"diff --git a/sdk/rolldown.config.js b/sdk/rolldown.config.jsindex d2fce7a23..e64bd2ab8 100644--- a/sdk/rolldown.config.js+++ b/sdk/rolldown.config.js@@ -119,7 +119,6 @@ export default defineConfig(['net/replication/index': 'src/net/replication/index.ts','net/session/index': 'src/net/session/index.ts','gameplay/index': 'src/gameplay/index.ts',- 'cocos/index': 'src/cocos/index.ts','dragonbones/index': 'src/dragonbones/index.ts','douyin/index': 'src/platform/douyin/index.ts','kuaishou/index': 'src/platform/kuaishou/index.ts',diff --git a/sdk/rollup.config.js b/sdk/rollup.config.jsindex 019d09b30..442fc9f61 100644--- a/sdk/rollup.config.js+++ b/sdk/rollup.config.js@@ -41,7 +41,6 @@ export default ['net/replication/index': 'src/net/replication/index.ts','net/session/index': 'src/net/session/index.ts','gameplay/index': 'src/gameplay/index.ts',- 'cocos/index': 'src/cocos/index.ts','dragonbones/index': 'src/dragonbones/index.ts','wasm': 'src/wasm.ts',},diff --git a/sdk/src/asset/builtinMeshes.ts b/sdk/src/asset/builtinMeshes.tsindex 3508d2404..57c14399e 100644--- a/sdk/src/asset/builtinMeshes.ts+++ b/sdk/src/asset/builtinMeshes.ts@@ -66,13 +66,12 @@ function tri(b: Builder, a: number, c: number, d: number): void {b.idx.push(a, c, d);}-/** A flat quad from four corners wound counter-clockwise seen from `n`. `flipV` runs the texture's v the other way along the face. */-function quadFace(b: Builder, corners: readonly (readonly number[])[], n: readonly number[], flipV = false): void {- const [top, bottom] = flipV ? [1, 0] : [0, 1];- const a = vertex(b, corners[0]!, 0, top, n);- const c = vertex(b, corners[1]!, 1, top, n);- const d = vertex(b, corners[2]!, 1, bottom, n);- const e = vertex(b, corners[3]!, 0, bottom, n);+/** A flat quad from four corners wound counter-clockwise seen from `n`. */+function quadFace(b: Builder, corners: readonly (readonly number[])[], n: readonly number[]): void {+ const a = vertex(b, corners[0]!, 0, 0, n);+ const c = vertex(b, corners[1]!, 1, 0, n);+ const d = vertex(b, corners[2]!, 1, 1, n);+ const e = vertex(b, corners[3]!, 0, 1, n);tri(b, a, c, d);tri(b, a, d, e);}@@ -201,14 +200,6 @@ function plane(size: number): Builder {return b;}-/** The plane of Cocos Creator: v runs along +z, so a picture laid over it reads as a map seen from above with +z towards the viewer. */-function cocosPlane(size: number): Builder {- const b = newBuilder();- const h = size / 2;- quadFace(b, [[-h, 0, h], [h, 0, h], [h, 0, -h], [-h, 0, -h]], [0, 1, 0], true);- return b;-}-function quad(size: number): Builder {const b = newBuilder();const h = size / 2;@@ -276,9 +267,6 @@ export const BUILTIN_MESH_TEMPLATES: readonly BuiltinMeshTemplate[] = [() => cone(UNIT / 2, UNIT)),template('plane', 'Plane', `A ${UNIT}-unit ground square in XZ, facing up.`, false,() => plane(UNIT)),- // Its own size, not the others': an effect of Cocos reads positions in the mesh's own space, so the plane it was written against is 10 across.- template('cocos-plane', 'Cocos Plane', 'The ground square of Cocos Creator: 10 units across in XZ, facing up, the v of its texture running along +z as a map\'s does.', false,- () => cocosPlane(10)),template('quad', 'Quad', `A ${UNIT}-unit square in XY, facing the camera.`, false,() => quad(UNIT)),];diff --git a/sdk/src/asset/glTextureUpload.ts b/sdk/src/asset/glTextureUpload.tsindex d907013cf..9a09c1a66 100644--- a/sdk/src/asset/glTextureUpload.ts+++ b/sdk/src/asset/glTextureUpload.ts@@ -22,6 +22,7 @@ import { samplesAsSrgb } from '../ecs/env';import { glWrapMode, type TextureWrap } from './glTexParams';import type { PlatformCanvas, PlatformImage } from '../platform/types';import { requireResourceManager } from '../wasm/resourceManager';+import { platformCreateCanvas } from '../platform/base';import type { ESEngineModule, TextureContent } from '../wasm';/** Anything WebGL will take directly as texture content. */@@ -177,3 +178,52 @@ export function writeDeviceTexture(write(gl);return true;}++/** The GL context pixels are read through, made once; null where there is none (a host without WebGL2, a test). */+// A context of its own, never the device's: nothing it makes is a texture the device can lose.+let readbackGl: WebGL2RenderingContext | null | undefined;+function readbackContext(): WebGL2RenderingContext | null {+ if (readbackGl !== undefined) return readbackGl;+ readbackGl = null;+ try {+ const canvas = platformCreateCanvas(1, 1);+ // A platform canvas is typed for 2D alone; on the hosts that have WebGL it is a DOM or offscreen canvas and answers for it too.+ const gl = (canvas as unknown as { getContext(kind: string, options?: object): unknown })+ .getContext('webgl2', { alpha: true, premultipliedAlpha: false, antialias: false, depth: false, stencil: false }) as WebGL2RenderingContext | null;+ if (gl && typeof gl.texImage2D === 'function' && typeof gl.readPixels === 'function') readbackGl = gl;+ } catch {+ readbackGl = null;+ }+ return readbackGl;+}++/**+ * The texels of a decoded bitmap exactly as the file has them, through a texture rather than a canvas. A 2D canvas keeps its pixels premultiplied, so+ * the colour of a texel that is clear is gone by the time it is read back, and a texture that carries data in its colour under a clear alpha (a weight map+ * the ground is mixed by) comes out black. A texture keeps what it is given.+ */+export function readBitmapTexels(image: ImageBitmap, width: number, height: number): Uint8Array | null {+ const gl = readbackContext();+ if (!gl || width > gl.getParameter(gl.MAX_TEXTURE_SIZE) || height > gl.getParameter(gl.MAX_TEXTURE_SIZE)) return null;+ const texture = gl.createTexture();+ const framebuffer = gl.createFramebuffer();+ try {+ gl.bindTexture(gl.TEXTURE_2D, texture);+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);+ gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);+ if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) return null;+ const pixels = new Uint8Array(width * height * 4);+ gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);+ return gl.getError() === gl.NO_ERROR ? pixels : null;+ } catch {+ return null;+ } finally {+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ gl.deleteFramebuffer(framebuffer);+ gl.deleteTexture(texture);+ }+}diff --git a/sdk/src/asset/imageDecode.ts b/sdk/src/asset/imageDecode.tsindex d1585accb..b4d797760 100644--- a/sdk/src/asset/imageDecode.ts+++ b/sdk/src/asset/imageDecode.ts@@ -11,6 +11,7 @@* `ImageBitmap` sources (uploads every texture upside-down otherwise).*/import { platformCreateCanvas } from '../platform/base';+import { readBitmapTexels } from './glTextureUpload';import type { PlatformImage } from '../platform/types';/**@@ -83,54 +84,6 @@ export async function shrinkBitmap(bitmap: ImageBitmap, maxEdge: number): Promisreturn smaller;}-/** The GL context pixels are read through, made once; null where there is none (a host without WebGL2, a test). */-let readbackGl: WebGL2RenderingContext | null | undefined;-function readbackContext(): WebGL2RenderingContext | null {- if (readbackGl !== undefined) return readbackGl;- readbackGl = null;- try {- const canvas = platformCreateCanvas(1, 1);- // A platform canvas is typed for 2D alone; on the hosts that have WebGL it is a DOM or offscreen canvas and answers for it too.- const gl = (canvas as unknown as { getContext(kind: string, options?: object): unknown })- .getContext('webgl2', { alpha: true, premultipliedAlpha: false, antialias: false, depth: false, stencil: false }) as WebGL2RenderingContext | null;- if (gl && typeof gl.texImage2D === 'function' && typeof gl.readPixels === 'function') readbackGl = gl;- } catch {- readbackGl = null;- }- return readbackGl;-}--/**- * The texels of a decoded bitmap exactly as the file has them, through a texture rather than a canvas. A 2D canvas keeps its pixels premultiplied, so- * the colour of a texel that is clear is gone by the time it is read back, and a texture that carries data in its colour under a clear alpha (a weight map- * the ground is mixed by) comes out black. A texture keeps what it is given.- */-function readTexels(image: ImageBitmap, width: number, height: number): Uint8Array | null {- const gl = readbackContext();- if (!gl || width > gl.getParameter(gl.MAX_TEXTURE_SIZE) || height > gl.getParameter(gl.MAX_TEXTURE_SIZE)) return null;- const texture = gl.createTexture();- const framebuffer = gl.createFramebuffer();- try {- gl.bindTexture(gl.TEXTURE_2D, texture);- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);- gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);- gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);- if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) return null;- const pixels = new Uint8Array(width * height * 4);- gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);- return gl.getError() === gl.NO_ERROR ? pixels : null;- } catch {- return null;- } finally {- gl.bindFramebuffer(gl.FRAMEBUFFER, null);- gl.deleteFramebuffer(framebuffer);- gl.deleteTexture(texture);- }-}-/*** The RGBA of an image that is already decoded, in its own row order.*@@ -144,7 +97,7 @@ export function readImagePixels(image: PlatformImage | ImageBitmap, maxEdge = 0)const height = Math.max(1, Math.round(image.height * scale));// A bitmap of the size asked for is read as the texels it holds; anything else goes through a canvas, which scales and which is what hosts without GL have.if (typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap && width === image.width && height === image.height) {- const texels = readTexels(image, width, height);+ const texels = readBitmapTexels(image, width, height);if (texels) return { width, height, pixels: texels };}const canvas = platformCreateCanvas(width, height);diff --git a/sdk/src/cocos/assetManager.ts b/sdk/src/cocos/assetManager.tsdeleted file mode 100644index 38fc631a5..000000000--- a/sdk/src/cocos/assetManager.ts+++ /dev/null@@ -1,405 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/assetManager.ts- * @brief `resources.load`, `assetManager.loadBundle` / `loadRemote` / `loadAny`, and `Bundle`.- *- * In Cocos a path under a `resources` folder (or a bundle) names an asset by its location, resolved at run time. The engine has no- * such folder convention, so the importer writes a *manifest* — `assets/cocos/resources.json`, bundle name → path inside the- * bundle → the project file and its kind — and this layer resolves a Cocos path through it.- *- * Kinds that load: **prefab** (prepared, so a following `instantiate` works), **json** and **text**. Textures, sprite frames,- * audio and the rest come back with an error that says so, since a loaded asset of those kinds must be bound to the engine's- * resource tables and that binding is not made here yet; a script gets a failure it can handle rather than an empty object.- *- * The cache objects (`assetManager.assets`, `.bundles`, `.cacheManager`) have the shape scripts iterate; what is in them is what- * this layer has loaded.- */-import { platformFetch } from '../platform';-import { log } from '../util/logger';-import { Asset, AudioClip, ImageAsset, JsonAsset, Material, Prefab, SceneAsset, SpriteFrame, TextAsset, Texture2D } from './assets';-import { getCurrentWorld } from './node';-import { assetsFor, loadPrefab, onNewSession } from './prefabs';--export interface ResourceEntry {- /** The project-relative path of the file. */- path: string;- /** What kind of asset it is: `prefab`, `json`, `text`, or another the layer cannot load. */- kind: string;- /** The Cocos uuid of the asset, which `loadAny({ uuid })` names it by. */- uuid?: string;- /** For a sub-asset of an image named by a path suffix (`icon/spriteFrame`): which asset of the file it is. @internal */- as?: 'SpriteFrame' | 'Texture2D';-}-export type ResourceManifest = Record<string, Record<string, ResourceEntry>>;--type Callback<T> = (err: Error | null, data: T) => void;-type AssetCtor = new (...args: any[]) => Asset;--/** A Map with the extra reads Cocos's `Cache` has. */-export class Cache<T> {- private readonly map_ = new Map<string, T>();- get count(): number { return this.map_.size; }- get(key: string): T | undefined { return this.map_.get(key); }- has(key: string): boolean { return this.map_.has(key); }- add(key: string, value: T): T { this.map_.set(key, value); return value; }- remove(key: string): T | undefined { const v = this.map_.get(key); this.map_.delete(key); return v; }- clear(): void { this.map_.clear(); }- entries(): IterableIterator<[string, T]> { return this.map_.entries(); }- forEach(fn: (value: T, key: string) => void): void { this.map_.forEach(fn); }- find(predicate: (value: T, key: string) => boolean): T | null {- for (const [k, v] of this.map_) if (predicate(v, k)) return v;- return null;- }- destroy(): void { this.map_.clear(); }-}--let manifest: ResourceManifest | null = null;-let manifestLoad: Promise<ResourceManifest> | null = null;-const MANIFEST_PATH = 'assets/cocos/resources.json';--/** Provide the manifest directly (a host that has it, or a test). */-export function setResourceManifest(m: ResourceManifest): void { manifest = m; manifestLoad = null; }--async function theManifest(): Promise<ResourceManifest> {- if (manifest) return manifest;- manifestLoad ??= (async () => {- const assets = assetsFor(getCurrentWorld());- if (!assets) throw new Error("the engine's asset loader is not running");- const loaded = await assets.loadJson<ResourceManifest>(MANIFEST_PATH);- manifest = loaded.data;- return manifest;- })();- try {- return await manifestLoad;- } catch (err) {- manifestLoad = null;- throw new Error(`cocos compat: cannot read the resource manifest ${MANIFEST_PATH}: ${String((err as Error).message ?? err)}`);- }-}--const stripExt = (p: string): string => p.replace(/\.[^./]+$/, '');--/** `(path, type?, onProgress?, onComplete?)` in every order Cocos accepts. */-function parseLoadArgs<T>(args: unknown[]): { type: AssetCtor | null; onProgress: ((a: number, b: number, item: unknown) => void) | null; onComplete: Callback<T> | null } {- let type: AssetCtor | null = null;- const fns: Function[] = [];- for (const a of args) {- if (typeof a !== 'function') continue;- if ((a as { prototype?: unknown }).prototype instanceof Asset || a === Asset) type = a as AssetCtor;- else fns.push(a);- }- return { type, onProgress: fns.length > 1 ? (fns[0] as never) : null, onComplete: (fns.length > 1 ? fns[1] : fns[0] ?? null) as Callback<T> | null };-}--const loaded = new Cache<Asset>();-// What the layer loaded belongs to the session that loaded it.-onNewSession(() => { loaded.clear(); manifest = null; manifestLoad = null; });--/** An asset is named for its file, without the extension: the name a script keys what it loads by (`asset.name`). */-function named<T extends Asset>(asset: T, entry: ResourceEntry): T {- if (!asset.name) asset.name = (entry.path.split('/').pop() ?? '').replace(/\.[^.]+$/, '');- return asset;-}--/** An asset of a kind the layer does not load: not a fault of the asset, so a directory load goes on without it. */-export class UnsupportedAssetKind extends Error {}--async function loadEntry(entry: ResourceEntry, asked: AssetCtor | null): Promise<Asset> {- const type = asked ?? (entry.as === 'SpriteFrame' ? SpriteFrame : entry.as === 'Texture2D' ? Texture2D : null);- const assets = assetsFor(getCurrentWorld());- switch (entry.kind) {- case 'prefab': {- if (type && type !== Prefab && !(Prefab.prototype instanceof type)) break;- return loadPrefab(entry.path);- }- case 'json': {- if (!assets) throw new Error("the engine's asset loader is not running");- const a = new JsonAsset(entry.path);- a.json = (await assets.loadJson(entry.path)).data;- return a;- }- case 'text': {- const response = await platformFetch(entry.path);- if (!response.ok) throw new Error(`could not read ${entry.path}: ${response.status}`);- const a = new TextAsset(entry.path);- a.text = await response.text();- return a;- }- case 'texture': {- if (!assets) throw new Error("the engine's asset loader is not running");- // The asked-for class decides what a script gets: a frame is the usual ask, an image the Cocos default.- const wantsFrame = !!type && (type === SpriteFrame || SpriteFrame.prototype instanceof type);- const wantsTexture = !!type && type !== ImageAsset && (type === Texture2D || Texture2D.prototype instanceof type);- const loadedTexture = await assets.loadTexture(entry.path);- const image = wantsFrame || wantsTexture ? new Texture2D(entry.path) : new ImageAsset(entry.path);- image._handle = loadedTexture.handle;- image.width = loadedTexture.width;- image.height = loadedTexture.height;- if (!wantsFrame) return image;- const frame = new SpriteFrame(entry.path);- frame.texture = image as Texture2D;- return frame;- }- case 'audio': {- if (type && type !== AudioClip && !(AudioClip.prototype instanceof type)) break;- if (!assets) throw new Error("the engine's asset loader is not running");- const clip = new AudioClip(entry.path);- clip._bufferId = (await assets.loadAudio(entry.path)).bufferId;- return clip;- }- case 'mtl':- case 'material': {- // a Cocos material file is not converted: a script that asks for one gets a Material with no engine material behind it, which takes- // properties and holds them, so what loads it carries on- if (type && type !== Material && !(Material.prototype instanceof type)) break;- return new Material(entry.path);- }- default:- }- throw new UnsupportedAssetKind(`cocos compat: loading "${entry.path}" (${entry.kind}${type ? `, as ${type.name}` : ''}) is not supported by the compatibility layer yet; prefabs, JSON, text, images and audio are`);-}--/** The scenes of the project, by the name a script runs them by: the file's name, without its folders or extension. */-export async function listScenes(): Promise<Array<{ name: string; path: string }>> {- const manifest = await theManifest();- const out = new Map<string, string>();- for (const bundle of Object.values(manifest)) {- for (const [key, entry] of Object.entries(bundle)) {- if (entry.kind !== 'scene' || !entry.path) continue;- const name = key.slice(key.lastIndexOf('/') + 1);- if (!out.has(name)) out.set(name, entry.path);- }- }- return [...out].map(([name, path]) => ({ name, path }));-}--export class Bundle {- readonly base = '';- constructor(readonly name: string, private readonly entries_: () => Promise<Record<string, ResourceEntry>>) {}-- private async entry_(path: string): Promise<ResourceEntry> {- const entries = await this.entries_();- const found = entries[stripExt(path)] ?? entries[path];- if (found) return found;- // An image is one file here and three assets in Cocos: the image (`icon`), its texture (`icon/texture`) and its sprite frame- // (`icon/spriteFrame`). The suffix names which one a script wants, and the file is the same.- const sub = /^(.*)\/(spriteFrame|texture)$/.exec(path);- const image = sub ? entries[sub[1]!] : undefined;- if (sub && image?.kind === 'texture') return { ...image, as: sub[2] === 'spriteFrame' ? 'SpriteFrame' : 'Texture2D' };- throw new Error(`cocos compat: bundle "${this.name}" has no asset "${path}"`);- }-- load(...args: unknown[]): void {- const paths = args[0];- const { type, onProgress, onComplete } = parseLoadArgs<Asset | Asset[]>(args.slice(1));- const list = Array.isArray(paths) ? paths as string[] : [paths as string];- (async () => {- const out: Asset[] = [];- for (let i = 0; i < list.length; i++) {- const entry = await this.entry_(list[i]!);- const key = `${this.name}/${entry.path}#${entry.as ?? type?.name ?? ''}`;- let asset = loaded.get(key);- if (!asset) loaded.add(key, (asset = named(await loadEntry(entry, type), entry)));- out.push(asset);- onProgress?.(i + 1, list.length, entry);- }- return Array.isArray(paths) ? out : out[0]!;- })().then(- (r) => onComplete?.(null, r),- (e: Error) => { if (onComplete) onComplete(e, null as never); else log.warn('cocos', e.message); },- );- }-- loadDir(...args: unknown[]): void {- const dir = String(args[0]).replace(/\/$/, '');- const { type, onProgress, onComplete } = parseLoadArgs<Asset[]>(args.slice(1));- (async () => {- const entries = await this.entries_();- const keys = Object.keys(entries).filter((k) => dir === '' || k === dir || k.startsWith(`${dir}/`));- const out: Asset[] = [];- const skipped = new Set<string>();- for (let i = 0; i < keys.length; i++) {- const entry = entries[keys[i]!]!;- try {- const key = `${this.name}/${entry.path}#${entry.as ?? type?.name ?? ''}`;- let asset = loaded.get(key);- if (!asset) loaded.add(key, (asset = named(await loadEntry(entry, type), entry)));- out.push(asset);- } catch (err) {- // an entry of a kind that does not load, or of another type than asked for, is left out: a directory of configs holds a readme too- if (type) continue;- if (err instanceof UnsupportedAssetKind) { skipped.add(entry.kind); continue; }- throw err;- }- onProgress?.(i + 1, keys.length, entry);- }- if (skipped.size > 0) log.info('cocos', `loadDir("${dir}") left out the assets of kind ${[...skipped].join(', ')}, which the layer does not load`);- return out;- })().then(- (r) => onComplete?.(null, r),- (e: Error) => { if (onComplete) onComplete(e, null as never); else log.warn('cocos', e.message); },- );- }-- /** A scene of the bundle as an asset: what `director.runScene` takes. The scene's content is the engine's scene manager's to load. */- loadScene(name: string, ...rest: unknown[]): void {- const fns = rest.filter((a): a is (...args: unknown[]) => void => typeof a === 'function');- const done = fns[fns.length - 1] as ((error: Error | null, asset?: SceneAsset) => void) | undefined;- listScenes().then((scenes) => {- if (!scenes.some((s) => s.name === name)) throw new Error(`cocos compat: bundle "${this.name}" has no scene "${name}"`);- const asset = new SceneAsset(name);- asset.name = name;- return asset;- }).then((asset) => done?.(null, asset), (error: Error) => done?.(error));- }- /** Preparing a scene is finding it, here: the scene manager readies what it loads when it loads it. */- preloadScene(name: string, ...rest: unknown[]): void { this.loadScene(name, ...rest); }-- /** Preparing is loading, here. */- preload(...args: unknown[]): void { this.load(...args); }- preloadDir(...args: unknown[]): void { this.loadDir(...args); }-- /** The asset at @p path if it has been loaded. */- get<T extends Asset>(path: string, _type?: AssetCtor): T | null {- for (const [key, asset] of loaded.entries()) {- if (key.startsWith(`${this.name}/`) && stripExt(key.slice(this.name.length + 1)).endsWith(stripExt(path))) return asset as T;- }- return null;- }- getInfoWithPath(path: string): { path: string; kind: string } | null {- const m = manifest?.[this.name]?.[stripExt(path)];- return m ? { path: m.path, kind: m.kind } : null;- }- getDirWithPath(dir: string): Array<{ path: string; kind: string }> {- const entries = manifest?.[this.name] ?? {};- return Object.entries(entries).filter(([k]) => k === dir || k.startsWith(`${dir.replace(/\/$/, '')}/`)).map(([path, e]) => ({ path, kind: e.kind }));- }- release(path: string): void { const a = this.get(path); if (a) loaded.remove(`${this.name}/${(a as Asset).path}`); }- releaseAll(): void { for (const [k] of [...loaded.entries()]) if (k.startsWith(`${this.name}/`)) loaded.remove(k); }-}--const bundleOf = (name: string): Bundle => new Bundle(name, async () => (await theManifest())[name] ?? {});--const bundles = new Cache<Bundle>();-const resources = bundleOf('resources');-bundles.add('resources', resources);--class AssetManager {- /** The cache class, as `AssetManager.Cache`: scripts derive their own caches from it. */- static readonly Cache = Cache;- static readonly Bundle = Bundle;- /** The names Cocos gives its own bundles. */- static readonly BuiltinBundleName = Object.freeze({ INTERNAL: 'internal', MAIN: 'main', RESOURCES: 'resources', START_SCENE: 'start-scene' });- /** The one asset manager, as `AssetManager.instance`: the same object the module exports as `assetManager`. */- static get instance(): AssetManager { return assetManager; }- /** `factory`: how a downloaded file is made into an object, by kind. The registrations a game makes are held; files here are made by the layer's own loaders. */- readonly factory = {- _creators: {} as Record<string, unknown>,- register(type: string | Record<string, unknown>, handler?: unknown): void {- if (typeof type === 'string') this._creators[type] = handler;- else Object.assign(this._creators, type);- },- };- readonly assets = loaded;- readonly bundles = bundles;- readonly resources = resources;- readonly presets: Record<string, { priority: number; maxConcurrency: number }> = {- default: { priority: 0, maxConcurrency: 6 }, preload: { priority: -1, maxConcurrency: 2 }, scene: { priority: 1, maxConcurrency: 6 }, bundle: { priority: 2, maxConcurrency: 6 }, remote: { priority: 0, maxConcurrency: 6 },- };- /**- * `assetManager.downloader`: how Cocos fetches a file of each kind. Here a file is read from the project or by URL, so it takes the registrations- * a game makes (its own scheme for remote bundles) and holds them, and says what it is told about where remote bundles live.- */- readonly downloader = {- remoteServerAddress: '',- bundleVers: {} as Record<string, string>,- maxConcurrency: 6,- maxRequestsPerFrame: 6,- _downloaders: {} as Record<string, unknown>,- _remoteBundles: [] as string[],- register(type: string | Record<string, unknown>, handler?: unknown): void {- if (typeof type === 'string') this._downloaders[type] = handler;- else Object.assign(this._downloaders, type);- },- loadSubpackage(_name: string, _onProgress?: unknown, _onComplete?: unknown): void { /* every file is in the project */ },- };-- readonly cacheManager = {- cacheDir: '', cachedFiles: new Cache<unknown>(), tempFiles: new Cache<unknown>(), cacheInterval: 500, cacheEnabled: false,- clearCache(): void { this.cachedFiles.clear(); },- clearLRU(): void { /* no persistent cache */ },- removeCache(url: string): void { this.cachedFiles.remove(url); },- getCache(url: string): unknown { return this.cachedFiles.get(url); },- getTemp(url: string): unknown { return this.tempFiles.get(url); },- };-- getBundle(name: string): Bundle | null { return bundles.get(name) ?? null; }- removeBundle(bundle: Bundle): void { bundles.remove(bundle.name); }-- /** A bundle by name; the manifest says what is in it. */- loadBundle(nameOrUrl: string, ...rest: unknown[]): void {- const onComplete = rest.find((a) => typeof a === 'function') as Callback<Bundle> | undefined;- const name = nameOrUrl.replace(/\/+$/, '').split('/').pop() ?? nameOrUrl;- theManifest().then((m) => {- if (!m[name]) throw new Error(`cocos compat: no bundle "${name}" in the resource manifest`);- const bundle = bundles.get(name) ?? bundles.add(name, bundleOf(name));- onComplete?.(null, bundle);- }).catch((e: Error) => { if (onComplete) onComplete(e, null as never); else log.warn('cocos', e.message); });- }-- /** A file by URL. JSON and text are read; an image or binary is not made into an asset here. */- loadRemote(url: string, ...rest: unknown[]): void {- const onComplete = rest.find((a) => typeof a === 'function') as Callback<Asset> | undefined;- const ext = (rest.find((a) => typeof a === 'object' && a !== null) as { ext?: string } | undefined)?.ext ?? (/\.([a-z0-9]+)(?:\?|$)/i.exec(url)?.[1] ?? '');- (async () => {- if (!/^\.?(json|txt|text|atlas|xml|csv)$/i.test(ext)) {- throw new Error(`cocos compat: loadRemote of "${ext || 'this kind of'}" files is not supported by the compatibility layer yet; JSON and text are`);- }- const response = await platformFetch(url);- if (!response.ok) throw new Error(`could not read ${url}: ${response.status}`);- if (/json/i.test(ext)) { const a = new JsonAsset(url); a.json = await response.json(); return a; }- const a = new TextAsset(url); a.text = await response.text(); return a;- })().then((a) => { loaded.add(url, a); onComplete?.(null, a); }, (e: Error) => { if (onComplete) onComplete(e, null as never); else log.warn('cocos', e.message); });- }-- /** Requests in the shapes a script writes: `{ url }` remote, `{ path, bundle?, type? }` a bundle's asset, `{ uuid }` or a bare uuid (by the manifest's listing). */- loadAny(requests: unknown, ...rest: unknown[]): void {- const onComplete = rest.find((a) => typeof a === 'function') as Callback<unknown> | undefined;- const one = (r: any): Promise<Asset> => new Promise((resolve, reject) => {- const done: Callback<Asset> = (e, a) => (e ? reject(e) : resolve(a));- if (r && typeof r === 'object' && typeof r.url === 'string') this.loadRemote(r.url, r, done);- else if (r && typeof r === 'object' && typeof r.path === 'string') (bundles.get(r.bundle ?? 'resources') ?? resources).load(r.path, r.type ?? null, done);- else if (r && typeof r === 'object' && typeof r.uuid === 'string') {- this.loadByUuid_(r.uuid, r.type ?? null).then(resolve, reject);- } else if (typeof r === 'string') this.loadByUuid_(r, null).then(resolve, reject);- else reject(new Error('cocos compat: loadAny takes a uuid, a bundle path or a url'));- });- const list = Array.isArray(requests) ? requests : [requests];- Promise.all(list.map(one)).then(- (r) => onComplete?.(null, Array.isArray(requests) ? r : r[0]),- (e: Error) => { if (onComplete) onComplete(e, null); else log.warn('cocos', e.message); },- );- }-- /** The bundle and key a uuid is listed under in the resource manifest. */- private async loadByUuid_(uuid: string, type: AssetCtor | null): Promise<Asset> {- const m = await theManifest();- for (const [bundle, entries] of Object.entries(m)) {- for (const [key, entry] of Object.entries(entries)) {- if (entry.uuid !== uuid) continue;- return new Promise<Asset>((resolve, reject) => {- (bundles.get(bundle) ?? resources).load(key, type, (e: Error | null, a: Asset) => (e ? reject(e) : resolve(a)));- });- }- }- throw new Error(`cocos compat: no asset with uuid ${uuid} is listed in the project's bundles`);- }-- releaseAsset(asset: Asset): void { for (const [k, v] of [...loaded.entries()]) if (v === asset) loaded.remove(k); }- releaseAll(): void { loaded.clear(); }-}--export { AssetManager };-export const assetManager = new AssetManager();-export { resources };diff --git a/sdk/src/cocos/assets.ts b/sdk/src/cocos/assets.tsdeleted file mode 100644index 0b188b802..000000000--- a/sdk/src/cocos/assets.ts+++ /dev/null@@ -1,145 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/assets.ts- * @brief The asset classes a script names in a `@property` type: `SpriteFrame`, `Prefab`, `AudioClip`, ….- *- * In the engine an asset reference is a project-relative path, so these are markers: the class exists so that- * `@property(SpriteFrame)` can say "this field is a sprite frame", and a value held in such a field is the path (loading it is- * the asset system's job). They carry no behaviour.- */-import { Material as EngineMaterial } from '../render/material';--export class Asset {- constructor(public path = '') {}- /** The Cocos uuid and display name of the asset, where the project's manifest gave one. */- uuid = '';- name = '';- private refCount_ = 0;- /** How many holders have asked to keep it. An asset here lives as long as the engine's own resource table holds it, so the count is advice. */- get refCount(): number { return this.refCount_; }- addRef(): this { this.refCount_++; return this; }- decRef(_autoRelease = true): this { if (this.refCount_ > 0) this.refCount_--; return this; }- get isDefault(): boolean { return false; }- get nativeUrl(): string { return this.path; }- get loaded(): boolean { return true; }- destroy(): boolean { return true; }-}-/** A decoded image: the engine's texture the file loaded to (a handle), and its size. @internal for the handle */-export class ImageAsset extends Asset {- /** The engine texture handle; 0 before the load has bound one. @internal */- _handle = 0;- width = 0;- height = 0;-}-export class Texture2D extends ImageAsset {- get image(): ImageAsset { return this; }- getHash(): number { return this._handle; }-}-/** A texture to draw from. The importer keeps one frame per image, so the frame is the whole of its texture. */-export class SpriteFrame extends Asset {- /** The texture this frame draws from, once bound. @internal */- texture: Texture2D | null = null;- get width(): number { return this.texture?.width ?? 0; }- get height(): number { return this.texture?.height ?? 0; }- getOriginalSize(): { width: number; height: number } { return { width: this.width, height: this.height }; }- get originalSize(): { width: number; height: number } { return this.getOriginalSize(); }- get rect(): { x: number; y: number; width: number; height: number } { return { x: 0, y: 0, width: this.width, height: this.height }; }-}-export class SpriteAtlas extends Asset {}-/** Prepared prefabs by path: shared by every `Prefab` handle that names the path. */-export const preparedPrefabs = new Map<string, unknown>();--/**- * A prefab a script holds. `instantiate` is synchronous in Cocos, which is only possible because the prefab was loaded first; here- * that is the prepared form (see prefabs.ts), made once per path as soon as a script holds the handle.- */-export class Prefab extends Asset {- /** The engine's prepared prefab, once it has loaded. @internal */- get _prepared(): unknown { return preparedPrefabs.get(this.path); }- /** Why preparing failed, when it did. @internal */- _failed = '';-}-export class AudioClip extends Asset {- /** The engine's audio buffer id, once the clip has loaded. @internal */- _bufferId = '';-}-/** A property value as the engine's material takes it: a number, or a vector of up to four. Colours are 0..255 here and 0..1 there. */-/** A texture a script hands a material (`setProperty('regionMask', texture)`): the engine texture behind a loaded image or the frame that holds one. */-function textureOf(value: unknown): { __textureRef: true; textureId: number } | null {- const image = value instanceof SpriteFrame ? value.texture : value;- if (!(image instanceof ImageAsset) || image._handle <= 0) return null;- return { __textureRef: true, textureId: image._handle };-}--function uniformOf(value: unknown): number | { x: number; y: number; z: number; w: number } | null {- if (typeof value === 'number') return value;- if (typeof value === 'boolean') return value ? 1 : 0;- if (typeof value !== 'object' || value === null) return null;- const v = value as Record<string, unknown>;- if (typeof v.r === 'number' && typeof v.g === 'number' && typeof v.b === 'number') {- return { x: v.r / 255, y: v.g / 255, z: v.b / 255, w: typeof v.a === 'number' ? v.a / 255 : 1 };- }- if (typeof v.x === 'number' && typeof v.y === 'number') {- return { x: v.x, y: v.y, z: typeof v.z === 'number' ? v.z : 0, w: typeof v.w === 'number' ? v.w : 0 };- }- return null;-}--/**- * `Material`: the engine's material (`handle`) with Cocos's property calls. A value is written to the engine material under the name the- * script gives it, and kept here so `getProperty` answers; a project effect's own property names are not the engine shader's, so a- * write the shader does not declare is the engine's to report and ignore.- */-export class Material extends Asset {- /** The engine material this stands for; 0 for one the engine has not loaded. @internal */- _handle = 0;- private readonly props_ = new Map<string, unknown>();-- /**- * Where a property goes that is not a shader parameter here: the renderer an instance belongs to holds its colour itself. Answers whether it- * took the property. @internal- */- _take?: (name: string, value: unknown) => boolean;-- setProperty(name: string, value: unknown, _passIndex?: number): void {- this.props_.set(name, value);- if (this._take?.(name, value)) return;- const uniform = textureOf(value) ?? uniformOf(value);- if (this._handle > 0 && uniform !== null) EngineMaterial.setUniform(this._handle, name, uniform);- }-- /**- * Switch the shader's macros. The engine material takes the permutation of its shader that has them applied, now: a macro the effect never- * branched on has no permutation of its own, so it is kept on the record and changes nothing drawn.- */- recompileShaders(defines: Record<string, unknown>, _passIndex?: number): void {- if (this._handle <= 0) return;- const changes: Record<string, boolean> = {};- for (const [name, value] of Object.entries(defines)) changes[name] = !!value && value !== '0';- EngineMaterial.recompile(this._handle, changes);- }-- /** What the property was last set to. @internal */- _give?: (name: string) => unknown;-- getProperty(name: string, _passIndex?: number): unknown {- return this._give?.(name) ?? this.props_.get(name);- }-- /** The material's passes: there is one, and it has no state a script can read. */- get passes(): never[] { return []; }-}-export class JsonAsset extends Asset { json: unknown = null; }-export class TextAsset extends Asset { text = ''; }-export class BitmapFont extends Asset {}-export class Font extends Asset {}-export class AnimationClip extends Asset {}-export class SceneAsset extends Asset {}-export class EffectAsset extends Asset {}-export class Mesh extends Asset {}--/** Whether a `@property` type names an asset class. */-export function isAssetClass(type: unknown): boolean {- return typeof type === 'function' && (type === Asset || type.prototype instanceof Asset);-}diff --git a/sdk/src/cocos/builtinScripts.ts b/sdk/src/cocos/builtinScripts.tsdeleted file mode 100644index d4e135459..000000000--- a/sdk/src/cocos/builtinScripts.ts+++ /dev/null@@ -1,64 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/builtinScripts.ts- * @brief The parts of the layer that are scripts and systems rather than views: `Button`, and the touch system.- *- * A script class and a system are declared into the engine's current context, and a context is what a running app owns — so these- * are declared once for the one a game runs in, which importing the layer does. A test that replaces the context has to declare them- * again, and does so here; asking twice for the same context is harmless.- */-import { getDefaultContext } from '../ecs/context';-import { registerComponent } from '../ecs/component';-import { ContentRect } from '../ui/core/content-rect';-import { declareButton } from './ui/button';-import { declareInputSystem } from './input';-import { declareUiPass } from './ui/pass';-import { declareDirector } from './director';-import { declareTweenSystem } from './tween';-import { declarePrefabSystem } from './prefabs';-import { declareGameSystem } from './game';-import { declareStartPhase } from './host';-import { resetClassRegistry, setBuiltinDeclarer } from './registry';--const declared = new WeakSet<object>();-/** What the layer queued into a context, and the queue's epoch when it did: queued again for each App that takes the queues after that. */-const queued = new WeakMap<object, { systems: unknown[]; plugins: unknown[]; epoch: number }>();--function requeue(context: ReturnType<typeof getDefaultContext>): void {- const kept = queued.get(context);- if (!kept || kept.epoch === context.queueEpoch) return;- context.pendingSystems.push(...(kept.systems as never[]));- context.pendingPlugins.push(...kept.plugins);- kept.epoch = context.queueEpoch;-}--/** Declare the layer's own classes and systems into the current context, once per context. */-export function declareBuiltinScripts(): void {- const context = getDefaultContext();- if (declared.has(context)) { requeue(context); return; }- declared.add(context);- const systemsBefore = context.pendingSystems.length;- const pluginsBefore = context.pendingPlugins.length;- // `UITransform` is a view on the engine's rectangle; a scene that holds one needs it registered even in an app without the UI pipeline.- registerComponent('ContentRect', ContentRect);- declareButton();- declareInputSystem();- declareUiPass();- declareDirector();- declareTweenSystem();- declarePrefabSystem();- declareGameSystem();- declareStartPhase();- queued.set(context, {- systems: context.pendingSystems.slice(systemsBefore), plugins: context.pendingPlugins.slice(pluginsBefore), epoch: context.queueEpoch,- });-}--setBuiltinDeclarer(declareBuiltinScripts);--/** Test seam: forget the registry and declare again into the (possibly new) current context. */-export function redeclareBuiltinScripts(): void {- resetClassRegistry();- declareBuiltinScripts();-}diff --git a/sdk/src/cocos/builtins.ts b/sdk/src/cocos/builtins.tsdeleted file mode 100644index ac02bd658..000000000--- a/sdk/src/cocos/builtins.ts+++ /dev/null@@ -1,46 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/builtins.ts- * @brief The Cocos classes the engine already has under another name — `Label`, `Sprite`, `UITransform`, `Button`.- *- * A script asks `node.getComponent(Label)` and then sets `label.string`. There is no script class behind it: the answer is a- * view on an Estella component (`Text`), whose fields it reads and writes under Cocos's names. An adapter says how to find- * that view on an entity and how to make one; the classes that use it live beside it and register themselves.- */-import type { World } from '../ecs/world';-import type { Entity } from '../types';-import type { Component } from './component';--export interface BuiltinAdapter {- /** The view on @p entity's component, or null when it has none. */- get(world: World, entity: Entity): Component | null;- /** Give @p entity the component (with the engine's defaults) and return the view. */- add(world: World, entity: Entity): Component | null;-}--const adapters = new Map<unknown, BuiltinAdapter>();--/** Register an adapter under its class and the names a script or a scene may use for it (`'cc.Label'`, `'Label'`). */-export function registerBuiltinComponent(ctor: Function, names: string[], adapter: BuiltinAdapter): void {- adapters.set(ctor, adapter);- for (const n of names) adapters.set(n, adapter);-}--export function builtinAdapterFor(type: unknown): BuiltinAdapter | undefined {- return adapters.get(type);-}--/** The adapters of the built-in classes that derive from @p base (`UIRenderer` is the base of `Label` and `Sprite`, and has no view of its own). */-export function builtinAdaptersDerivedFrom(base: Function): BuiltinAdapter[] {- const out: BuiltinAdapter[] = [];- for (const [key, adapter] of adapters) {- if (typeof key === 'function' && key !== base && key.prototype instanceof base) out.push(adapter);- }- return out;-}--/** Test seam. */-export function resetBuiltinAdapters(): void {- adapters.clear();-}diff --git a/sdk/src/cocos/collider.ts b/sdk/src/cocos/collider.tsdeleted file mode 100644index b6617ce53..000000000--- a/sdk/src/cocos/collider.ts+++ /dev/null@@ -1,73 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/collider.ts- * @brief `Collider` and `BoxCollider`: views on the engine's `BoxCollider3D`.- *- * A Cocos box is described in the node's own units (`size`, `center`) and takes the node's scale on top; the engine's box holds its half- * extents already scaled, which is how the importer writes it. The view converts at the boundary, so a script that reads `size` gets what it- * set and the engine's box is the size it is drawn at. A collider with no rigid body is a static one in Cocos; the engine spells that as a static- * body beside the box, which adding the collider here puts there.- */-import { BoxCollider3D, RigidBody3D } from '../physics3d/Physics3DComponents';-import type { World } from '../ecs/world';-import type { Entity } from '../types';-import { Component } from './component';-import { registerBuiltinComponent } from './builtins';-import { Vec3 } from './math';-import { viewAdapter } from './ui/view';--/** The base of every collider a script asks for. */-export class Collider extends Component {}--const axes = ['x', 'y', 'z'] as const;--export class BoxCollider extends Collider {- private data_() { return this._world.get(this._entity, BoxCollider3D); }- private patch_(fields: Record<string, unknown>): void {- this._world.set(this._entity, BoxCollider3D, { ...this.data_(), ...fields } as never);- }- /** The node's scale along an axis; a flat axis would divide by nothing, so it counts as one. */- private scaleOf_(axis: 'x' | 'y' | 'z'): number {- const s = Math.abs(this.node.scale[axis]);- return s > 1e-6 ? s : 1;- }-- /** Whether the collider takes part. */- get enabled(): boolean { return this.data_().enabled; }- set enabled(v: boolean) { this.patch_({ enabled: v }); }-- /** A trigger reports overlaps and pushes nothing. */- get isTrigger(): boolean { return this.data_().isSensor; }- set isTrigger(v: boolean) { this.patch_({ isSensor: v }); }-- /** The full size of the box, in the node's units. */- get size(): Vec3 {- const h = this.data_().halfExtents;- return new Vec3((h.x * 2) / this.scaleOf_('x'), (h.y * 2) / this.scaleOf_('y'), (h.z * 2) / this.scaleOf_('z'));- }- set size(v: Vec3) {- const half = {} as Record<string, number>;- for (const a of axes) half[a] = (Math.abs(v[a]) * this.scaleOf_(a)) / 2;- this.patch_({ halfExtents: half });- }-- /** Where the box stands from the node's origin, in the node's units. */- get center(): Vec3 {- const c = this.data_().center ?? { x: 0, y: 0, z: 0 };- return new Vec3(c.x / this.scaleOf_('x'), c.y / this.scaleOf_('y'), c.z / this.scaleOf_('z'));- }- set center(v: Vec3) {- const at = {} as Record<string, number>;- for (const a of axes) at[a] = v[a] * this.scaleOf_(a);- this.patch_({ center: at });- }-}--const hasBox = (world: World, entity: Entity): boolean => world.has(entity, BoxCollider3D);-const addBox = (world: World, entity: Entity): void => {- if (!world.has(entity, RigidBody3D)) world.insert(entity, RigidBody3D, { bodyType: 0 });- // Cocos's default box is one unit each way- world.insert(entity, BoxCollider3D, { halfExtents: { x: 0.5, y: 0.5, z: 0.5 } });-};-registerBuiltinComponent(BoxCollider, ['cc.BoxCollider', 'BoxCollider'], viewAdapter(BoxCollider, hasBox, addBox));diff --git a/sdk/src/cocos/component.ts b/sdk/src/cocos/component.tsdeleted file mode 100644index 10470e384..000000000--- a/sdk/src/cocos/component.ts+++ /dev/null@@ -1,127 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/component.ts- * @brief `Component`, the base class a Cocos script extends.- *- * The lifecycle methods are not defined here — a subclass declares the ones it wants, and the host calls whichever exist, in- * Cocos's order: `onLoad` once when the instance is made, `onEnable` when it becomes active, `start` once before its first- * `update`, `update(dt)` and `lateUpdate(dt)` each frame while active, `onDisable` when it stops being active and- * `onDestroy` when the component or its entity goes. Declaring them as optional members (rather than empty methods) keeps a- * subclass's own `override` honest and lets the host skip the call when nothing is there.- */-import type { World } from '../ecs/world';-import type { Entity } from '../types';-import { classInfoOf, type ComponentCtor } from './registry';-import type { Node } from './node';--/** One `schedule` / `scheduleOnce` registration. */-interface Timer {- callback: (dt: number) => void;- /** Seconds between calls. */- interval: number;- /** Calls after the first; `Infinity` for forever. */- repeat: number;- /** Seconds until the next call. */- remaining: number;- /** Seconds since this timer last fired (what `dt` is). */- since: number;- calls: number;-}--export class Component {- /** The node this component is on. Set before `onLoad`. */- node!: Node;- private enabled_ = true;- /**- * Whether the component takes part: a disabled one gets no `update`, and `onDisable` has run. An accessor, so the built-in views- * (`Label`, `Sprite`) can answer it from the engine component they stand for.- */- get enabled(): boolean { return this.enabled_; }- set enabled(value: boolean) { this.enabled_ = value; }-- /** @internal */ _world!: World;- /** @internal */ _entity!: Entity;- /** @internal */ _loaded = false;- /** @internal */ _started = false;- /** @internal */ _enabledApplied = false;- /** @internal */ _destroyed = false;- /** @internal */ _timers: Timer[] = [];-- onLoad?(): void;- onEnable?(): void;- start?(): void;- update?(dt: number): void;- lateUpdate?(dt: number): void;- onDisable?(): void;- onDestroy?(): void;-- get uuid(): string { return `${this._entity}:${this.constructor.name}`; }-- /** See {@link Node.toJSON}: a component holds the world too. */- toJSON(): { component: string; entity: number } { return { component: this.constructor.name, entity: this._entity }; }- [Symbol.for('nodejs.util.inspect.custom')](): string { return `${this.constructor.name}(#${this._entity})`; }- /** A script that names its component (`comp.name = 'UILogin'`) is believed; otherwise it is the node's name and the class. */- get name(): string { return this.name_ ?? `${this.node?.name ?? ''}<${this.constructor.name}>`; }- set name(value: string) { this.name_ = value; }- private name_: string | undefined;-- /** False once the component or its entity has gone. */- get isValid(): boolean { return !this._destroyed && !!this._world?.valid(this._entity); }-- /** Enabled, and so is every node above it. */- get enabledInHierarchy(): boolean { return this.enabled && !!this._world?.isEntityActive(this._entity); }-- getComponent<T extends Component>(type: ComponentCtor<T> | string): T | null { return this.node.getComponent(type); }- getComponents<T extends Component>(type: ComponentCtor<T> | string): T[] { return this.node.getComponents(type); }- getComponentInChildren<T extends Component>(type: ComponentCtor<T> | string): T | null { return this.node.getComponentInChildren(type); }- getComponentsInChildren<T extends Component>(type: ComponentCtor<T> | string): T[] { return this.node.getComponentsInChildren(type); }- addComponent<T extends Component>(type: ComponentCtor<T> | string): T | null { return this.node.addComponent(type); }-- /**- * Call @p callback every @p interval seconds, @p repeat more times after the first call (forever by default), the first- * after @p delay seconds. The callback gets the seconds since its last call.- */- schedule(callback: (dt: number) => void, interval = 0, repeat = Infinity, delay = 0): void {- this.unschedule(callback);- this._timers.push({ callback, interval, repeat, remaining: delay > 0 ? delay : interval, since: 0, calls: 0 });- }-- scheduleOnce(callback: (dt: number) => void, delay = 0): void {- this.schedule(callback, 0, 0, delay);- }-- unschedule(callback: (dt: number) => void): void {- this._timers = this._timers.filter((t) => t.callback !== callback);- }-- unscheduleAllCallbacks(): void {- this._timers.length = 0;- }-- /** Remove this component from its node. `onDestroy` runs on the next frame, as in Cocos. */- destroy(): boolean {- if (this._destroyed) return false;- const info = classInfoOf(this.constructor);- if (info && this._world?.valid(this._entity)) this._world.remove(this._entity, info.def);- return true;- }-- /** @internal Advance this component's timers; called by the host, once a frame, while the component is active. */- _tickTimers(dt: number): void {- if (this._timers.length === 0) return;- // A callback may schedule or unschedule: walk a copy, and skip a timer that was removed meanwhile.- for (const timer of [...this._timers]) {- if (!this._timers.includes(timer)) continue;- timer.since += dt;- timer.remaining -= dt;- if (timer.remaining > 0) continue;- const elapsed = timer.since;- timer.since = 0;- timer.calls++;- timer.remaining = timer.interval > 0 ? timer.remaining + timer.interval : 0;- if (timer.calls > timer.repeat) this._timers = this._timers.filter((t) => t !== timer);- timer.callback.call(this, elapsed);- }- }-}diff --git a/sdk/src/cocos/decorators.ts b/sdk/src/cocos/decorators.tsdeleted file mode 100644index 7a9e2fe4c..000000000--- a/sdk/src/cocos/decorators.ts+++ /dev/null@@ -1,143 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/decorators.ts- * @brief `@ccclass`, `@property` and the rest of Cocos's `_decorator` namespace.- *- * The scripts are written with TypeScript's legacy (experimental) decorators, which run when the class is defined: each- * `@property` records a field on the class, and `@ccclass` — which runs last — declares the class (host.ts). Everything else in- * the namespace configures the Cocos editor and is accepted and ignored, because a script that names it must still load.- */-import { Component } from './component';-import { Color, Vec2, Vec3 } from './math';-import { Node } from './node';-import { isAssetClass } from './assets';-import { declareClass, type RawPropertySpec } from './host';-import type { PropertyKind } from './registry';--/** The numeric and string marker types Cocos offers for `@property({ type: ... })`. */-export class CCInteger {}-export class CCFloat {}-export class CCString {}-export class CCBoolean {}--const ENUM_TAG = Symbol('cocos.enum');--/** An enum object, tagged so a `@property({ type: MyEnum })` is known to be a number. TypeScript's own `enum` works unchanged. */-export function Enum<T extends object>(obj: T): T {- Object.defineProperty(obj, ENUM_TAG, { value: true, enumerable: false });- return obj;-}--/** What a `@property` type argument names. Undefined when it is not one this layer recognises, so the field's value decides. */-function kindOfType(type: unknown): PropertyKind | undefined {- if (type === undefined || type === null) return undefined;- if (type === Node) return 'node';- if (type === Number || type === CCInteger || type === CCFloat) return 'number';- if (type === String || type === CCString) return 'string';- if (type === Boolean || type === CCBoolean) return 'boolean';- if (type === Vec2) return 'vec2';- if (type === Vec3) return 'vec3';- if (type === Color) return 'color';- if (isAssetClass(type)) return 'asset';- if (typeof type === 'function' && (type === Component || type.prototype instanceof Component)) return 'component';- if (typeof type === 'object' && (type as Record<symbol, unknown>)[ENUM_TAG]) return 'number';- // A TypeScript enum that was not wrapped: an object whose values are numbers.- if (typeof type === 'object') return 'number';- return 'json';-}--const recorded = new WeakMap<Function, Map<string, RawPropertySpec>>();--function record(ctor: Function, spec: RawPropertySpec): void {- let fields = recorded.get(ctor);- if (!fields) recorded.set(ctor, (fields = new Map()));- fields.set(spec.name, spec);-}--/** The properties of a class, base classes first, a subclass's declaration of a name replacing its base's. */-function propertiesOf(ctor: Function): RawPropertySpec[] {- const chain: Function[] = [];- for (let c: Function | null = ctor; c && c !== Function.prototype; c = Object.getPrototypeOf(c)) chain.unshift(c);- const merged = new Map<string, RawPropertySpec>();- for (const c of chain) for (const [name, spec] of recorded.get(c) ?? []) merged.set(name, spec);- return [...merged.values()];-}--interface PropertyOptions {- type?: unknown;- visible?: unknown;- displayName?: string;- tooltip?: string;- [key: string]: unknown;-}--function specFor(name: string, options: PropertyOptions | unknown[] | Function | undefined): RawPropertySpec {- let type: unknown;- let array = false;- if (Array.isArray(options)) { type = options[0]; array = true; }- else if (typeof options === 'function') type = options;- else if (options && typeof options === 'object') {- const t = (options as PropertyOptions).type;- if (Array.isArray(t)) { type = t[0]; array = true; } else type = t;- }- const kind = kindOfType(type);- return { name, ...(kind ? { kind } : {}), ...(type !== undefined ? { type } : {}), ...(array ? { array } : {}) };-}--/**- * `@property`, in every form a script writes it: bare, with a type (`@property(Node)`), with options (`@property({ type: Label })`),- * or with a list (`@property([Node])`).- */-export function property(...args: unknown[]): any {- // Bare: `@property` is the decorator itself, called with (prototype, key).- if (args.length >= 2 && typeof args[1] === 'string' && args[0] && typeof args[0] === 'object') {- record((args[0] as object).constructor, specFor(args[1], undefined));- return undefined;- }- const options = args[0] as PropertyOptions | unknown[] | Function | undefined;- return (target: object, key: string): void => { record(target.constructor, specFor(key, options)); };-}--/** `@ccclass('Name')` or bare `@ccclass`: declare the class, under its own name if none is given. */-export function ccclass(arg?: string | Function): any {- const declare = (ctor: Function, name?: string): void => {- // A class that is not a component (a plain data class, or one whose base the layer does not provide) is not driven: it has no hooks to run, and nothing to put on a node.- if (!(ctor.prototype instanceof Component)) return;- declareClass(ctor as never, name || ctor.name, propertiesOf(ctor));- };- if (typeof arg === 'function') { declare(arg); return undefined; }- return (ctor: Function): void => declare(ctor, arg);-}--/** The editor-only decorators: accepted so a script that uses them loads, and otherwise without effect here. */-function inert(..._args: unknown[]): any {- return (..._inner: unknown[]): void => {};-}--/** A decorator that is applied bare (`@executeInEditMode`) or as a call (`@menu('x')`), and does nothing either way. */-function inertEither(...args: unknown[]): any {- if (args.length >= 1 && typeof args[0] === 'function' && args.length === 1) return undefined;- return inert();-}--export const requireComponent = inert;-export const executionOrder = inert;-export const menu = inert;-export const help = inert;-export const icon = inert;-export const inspector = inert;-export const playOnFocus = inertEither;-export const executeInEditMode = inertEither;-export const disallowMultiple = inertEither;-export const type = (t: unknown) => (target: object, key: string): void => { record(target.constructor, specFor(key, { type: t })); };-export const integer = (target: object, key: string): void => { record(target.constructor, { name: key, kind: 'number' }); };-export const float = integer;-export const string = (target: object, key: string): void => { record(target.constructor, { name: key, kind: 'string' }); };-export const boolean = (target: object, key: string): void => { record(target.constructor, { name: key, kind: 'boolean' }); };--/** Cocos exposes these under `_decorator`; scripts import the namespace and write `@_decorator.ccclass`, or destructure it. */-export const _decorator = {- ccclass, property, requireComponent, executionOrder, menu, help, icon, inspector, playOnFocus, executeInEditMode, disallowMultiple,- type, integer, float, string, boolean,-};diff --git a/sdk/src/cocos/director.ts b/sdk/src/cocos/director.tsdeleted file mode 100644index 5ff3995a1..000000000--- a/sdk/src/cocos/director.ts+++ /dev/null@@ -1,257 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/director.ts- * @brief The scene-level entry points of Cocos: `director`, `find`, `isValid`.- *- * Cocos has one active scene with a root; the engine has a world with several root entities. `Scene` is the view a script- * expects over that: its children are the world's parentless named entities, so `director.getScene().getChildByName('Canvas')`- * and `find('Canvas/Panel')` mean what they say.- */-import { Children, Name, Parent, SceneOwner } from '../ecs/component';-import { log } from '../util/logger';-import type { World } from '../ecs/world';-import { INVALID_ENTITY, type Entity } from '../types';-import { Schedule, defineSystem, addSystemToSchedule, GetWorld } from '../ecs/system';-import { Res, Time } from '../ecs/resource';-import { Node, getCurrentWorld } from './node';-import { Scheduler, scheduler } from './scheduler';-import { SceneManager, type SceneManagerState } from '../scene/sceneManager';-import { listScenes } from './assetManager';-import { syncActivity } from './registry';-import { SceneAsset } from './assets';--/** The root of the running scene: a stand-in for the parent the world's top-level entities do not have. */-export class Scene {- constructor(private readonly world: World) {}-- private name_ = 'Scene';- get name(): string { return this.name_; }- set name(value: string) { this.name_ = value; }- get active(): boolean { return true; }- /** A scene is a root, not a node: it holds no components. */- getComponent(_type?: unknown): null { return null; }- get isValid(): boolean { return true; }-- get children(): Node[] {- const roots: Entity[] = [];- for (const e of this.world.getEntitiesWithComponents([Name])) {- const parent = this.world.tryGet(e, Parent)?.entity;- if (!parent || parent === INVALID_ENTITY) roots.push(e);- }- // A node kept across scenes is moved under the new scene after the scene's own, so the new scene's come first- const kept = (e: Entity): boolean => this.world.tryGet(e, SceneOwner)?.persistent === true;- roots.sort((a, b) => Number(kept(a)) - Number(kept(b)));- return roots.map((e) => Node.for(this.world, e));- }- get childrenCount(): number { return this.children.length; }-- getChildByName(name: string): Node | null {- return this.children.find((c) => c.name === name) ?? null;- }-- /** `Canvas/Panel/Button`: the first segment names a root, the rest descend. */- getChildByPath(path: string): Node | null {- const [first, ...rest] = path.split('/').filter((s) => s.length > 0);- if (first === undefined) return null;- const root = this.getChildByName(first);- return root ? (rest.length ? root.getChildByPath(rest.join('/')) : root) : null;- }-}--type DirectorListener = { callback: (...args: any[]) => void; target?: unknown };--const directorListeners = new Map<string, DirectorListener[]>();--function requireWorld(what: string): World {- const world = getCurrentWorld();- if (!world) throw new Error(`cocos compat: ${what} outside a running scene (no world is current)`);- return world;-}--/** The engine's scene manager of each world, learned from the frame loop (see {@link declareDirector}). */-const sceneManagers = new WeakMap<World, SceneManagerState>();-const registeredScenes = new WeakMap<World, Set<string>>();-let loadingScene = '';--/** What a scene's nodes keep across a scene change: the engine's `SceneOwner.persistent`, set on the node and what is under it. */-function setPersistent(node: Node, persistent: boolean): void {- const world = node._world;- const visit = (e: Entity): void => {- const owner = world.tryGet(e, SceneOwner);- if (owner && owner.persistent !== persistent) world.set(e, SceneOwner, { ...owner, persistent });- for (const child of world.tryGet(e, Children)?.entities ?? []) visit(child);- };- visit(node._entity);-}--/** Give the scene manager every scene of the project by name, once. */-async function registerScenes(world: World, manager: SceneManagerState): Promise<void> {- let done = registeredScenes.get(world);- if (!done) registeredScenes.set(world, (done = new Set()));- for (const scene of await listScenes()) {- if (done.has(scene.name)) continue;- done.add(scene.name);- manager.register({ name: scene.name, path: scene.path });- }-}--function sceneManagerOf(world: World): SceneManagerState {- const manager = sceneManagers.get(world);- if (!manager) throw new Error('cocos compat: the engine\'s scene manager is not running');- return manager;-}--/** Run @p name as the scene: the one before it goes, what the game marked persistent stays, and @p done hears how it went. */-function runScene(name: string, done?: (error: Error | null, scene?: Scene) => void): void {- const world = requireWorld('director.loadScene');- loadingScene = name;- director.emit(Director.EVENT_BEFORE_SCENE_LOADING, name);- (async () => {- const manager = sceneManagerOf(world);- await registerScenes(world, manager);- // The scene before this one goes (what the game kept stays); asked for the scene already running, it starts over, as Cocos does- if (manager.getActive() === name) await manager.reload();- else await manager.switchTo(name);- const scene = new Scene(world);- // The scene is launched with its scripts loaded and enabled: a script added to it right after (as the game does) finds them there- for (const root of scene.children) syncActivity(world, root._entity);- return scene;- })().then(- (scene) => { loadingScene = ''; director.emit(Director.EVENT_AFTER_SCENE_LAUNCH, scene); done?.(null, scene); },- (error: Error) => { loadingScene = ''; log.warn('cocos', `scene "${name}" did not load: ${String(error.message ?? error)}`); done?.(error); },- );-}--/** The parts of `director` scripts actually call. */-export const director = {- /** The name of the scene being loaded, or empty: a game reads it to refuse a second load while one is under way. */- get _loadingScene(): string { return loadingScene; },- /** Run a scene by its name. `onLaunched(error, scene)` hears the result. */- loadScene(name: string, onLaunched?: (error: Error | null, scene?: Scene) => void): boolean {- runScene(name, onLaunched);- return true;- },- /** Run a scene a bundle's `loadScene` gave. */- runScene(scene: SceneAsset | string, _onBeforeLoad?: () => void, onLaunched?: (error: Error | null, scene?: Scene) => void): void {- runScene(typeof scene === 'string' ? scene : scene.name, onLaunched);- },- /** Ready a scene so running it is quick. */- preloadScene(name: string, onProgress?: unknown, onLoaded?: (error: Error | null, scene?: SceneAsset) => void): void {- const done = (typeof onProgress === 'function' && onLoaded === undefined ? onProgress : onLoaded) as ((error: Error | null, scene?: SceneAsset) => void) | undefined;- const world = requireWorld('director.preloadScene');- (async () => {- const manager = sceneManagerOf(world);- await registerScenes(world, manager);- await manager.prepare(name);- const asset = new SceneAsset(name);- asset.name = name;- return asset;- })().then((asset) => done?.(null, asset), (error: Error) => done?.(error));- },- getScene(): Scene | null {- const world = getCurrentWorld();- return world ? new Scene(world) : null;- },- /** The time of the last frame, in seconds. */- getDeltaTime(): number { return lastDelta; },- getTotalFrames(): number { return totalFrames; },- /** The timers kept by target: the ones a game's own timer service runs on. */- getScheduler(): Scheduler { return scheduler; },- getAnimationManager(): undefined { return undefined; },- on(type: string, callback: (...args: any[]) => void, target?: unknown): void {- const list = directorListeners.get(type);- if (list) list.push({ callback, target }); else directorListeners.set(type, [{ callback, target }]);- },- once(type: string, callback: (...args: any[]) => void, target?: unknown): void {- const wrapper = (...args: any[]): void => { director.off(type, wrapper, target); callback.apply(target, args); };- director.on(type, wrapper, target);- },- off(type: string, callback?: (...args: any[]) => void, target?: unknown): void {- const list = directorListeners.get(type);- if (!list) return;- directorListeners.set(type, list.filter((l) => (callback && l.callback !== callback) || (target !== undefined && l.target !== target)));- },- emit(type: string, ...args: any[]): void {- for (const l of [...(directorListeners.get(type) ?? [])]) l.callback.apply(l.target, args);- },- /** Keep a node (and what is under it) through scene changes. */- addPersistRootNode(node: Node): void { setPersistent(node, true); },- removePersistRootNode(node: Node): void { setPersistent(node, false); },- isPersistRootNode(node: Node): boolean { return node._world.tryGet(node._entity, SceneOwner)?.persistent === true; },-};--let lastDelta = 0;-let totalFrames = 0;-/** @internal The host reports each frame, so `director.getDeltaTime()` and the frame events mean something. */-export function reportFrame(delta: number): void {- lastDelta = delta;- totalFrames++;- scheduler.update(delta);-}--/**- * `Director`: its event names, and the class the singleton `director` is an instance of. Scripts patch `Director.prototype.tick` to hook the- * frame; here the frame is the engine's, so a patched `tick` is never called, but the patch itself has somewhere to land.- */-export class Director {- static readonly EVENT_BEFORE_UPDATE = 'director_before_update';- static readonly EVENT_AFTER_UPDATE = 'director_after_update';- static readonly EVENT_BEFORE_SCENE_LOADING = 'director_before_scene_loading';- static readonly EVENT_AFTER_SCENE_LAUNCH = 'director_after_scene_launch';- static readonly EVENT_BEFORE_DRAW = 'director_before_draw';- static readonly EVENT_AFTER_DRAW = 'director_after_draw';- static readonly EVENT_END_FRAME = 'director_end_frame';- static get instance(): typeof director { return director; }- static getInstance(): typeof director { return director; }- tick(_now?: number): void { /* the engine runs the frame */ }-}--/** A node by absolute path from the scene roots: `find('Canvas/Panel')`. A name with no slash searches the roots, then everything. */-export function find(path: string, referenceNode?: Node): Node | null {- if (referenceNode) return referenceNode.getChildByPath(path);- const world = requireWorld('find');- const scene = new Scene(world);- const direct = scene.getChildByPath(path);- if (direct || path.includes('/')) return direct;- // A bare name: the first node anywhere with it.- for (const e of world.getEntitiesWithComponents([Name])) {- if (world.tryGet(e, Name)?.value === path) return Node.for(world, e);- }- return null;-}--/** Whether a node or component (or anything that says) is still usable. */-export function isValid(value: unknown, _strict = false): boolean {- if (value === null || value === undefined) return false;- const v = value as { isValid?: boolean };- return typeof v.isValid === 'boolean' ? v.isValid : true;-}--/**- * The director's frame, which scripts hook: the delta it reports and the events around the update and the draw. The frame is the- * engine's; these systems mark its start (before the scripts run), the end of the update and the end of the frame, in the order Cocos- * emits them.- */-export function declareDirector(): void {- addSystemToSchedule(Schedule.First, defineSystem(- [Res(SceneManager), GetWorld()],- (manager, world) => { if (manager) sceneManagers.set(world, manager as SceneManagerState); },- { name: 'Cocos:SceneManager', touches: { opaque: true } },- ));- addSystemToSchedule(Schedule.First, defineSystem(- [Res(Time)],- (time) => { reportFrame(time.delta); director.emit(Director.EVENT_BEFORE_UPDATE); },- { name: 'Cocos:DirectorBegin', touches: { opaque: true } },- ));- addSystemToSchedule(Schedule.Last, defineSystem(- [],- () => {- director.emit(Director.EVENT_AFTER_UPDATE);- director.emit(Director.EVENT_BEFORE_DRAW);- director.emit(Director.EVENT_AFTER_DRAW);- director.emit(Director.EVENT_END_FRAME);- },- { name: 'Cocos:DirectorEnd', touches: { opaque: true } },- ));-}diff --git a/sdk/src/cocos/easing.ts b/sdk/src/cocos/easing.tsdeleted file mode 100644index 0cbb45575..000000000--- a/sdk/src/cocos/easing.ts+++ /dev/null@@ -1,55 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/easing.ts- * @brief The easing names a Cocos tween uses (`'sineOut'`, `'backInOut'`) and the `easing` functions, over the engine's curves.- *- * There are no curves here: each name is an `EasingType` of the engine's animation module, and the function is the engine's- * `applyEasing`. A tween on a Cocos object and a tween the engine runs on a component field ease the same way because they are- * the same curve.- *- * Not carried: the `...OutIn` curves, which the engine has no member for. A script that names one gets a linear ease and a warning.- * Cocos's elastic curves have their own constants; the engine's elastic is the standard one, so they differ a little in overshoot.- */-import { EasingType, applyEasing } from '../animation/Easing';-import { log } from '../util/logger';--export type EasingFunction = (k: number) => number;--const E = EasingType;--/** Cocos's name for each curve the engine has. */-const NAMES: Readonly<Record<string, EasingType>> = {- linear: E.Linear, constant: E.Step, smooth: E.Smoothstep, fade: E.Smootherstep,- quadIn: E.EaseInQuad, quadOut: E.EaseOutQuad, quadInOut: E.EaseInOutQuad,- cubicIn: E.EaseInCubic, cubicOut: E.EaseOutCubic, cubicInOut: E.EaseInOutCubic,- quartIn: E.EaseInQuart, quartOut: E.EaseOutQuart, quartInOut: E.EaseInOutQuart,- quintIn: E.EaseInQuint, quintOut: E.EaseOutQuint, quintInOut: E.EaseInOutQuint,- sineIn: E.EaseInSine, sineOut: E.EaseOutSine, sineInOut: E.EaseInOutSine,- expoIn: E.EaseInExpo, expoOut: E.EaseOutExpo, expoInOut: E.EaseInOutExpo,- circIn: E.EaseInCirc, circOut: E.EaseOutCirc, circInOut: E.EaseInOutCirc,- elasticIn: E.EaseInElastic, elasticOut: E.EaseOutElastic, elasticInOut: E.EaseInOutElastic,- backIn: E.EaseInBack, backOut: E.EaseOutBack, backInOut: E.EaseInOutBack,- bounceIn: E.EaseInBounce, bounceOut: E.EaseOutBounce, bounceInOut: E.EaseInOutBounce,-};--export const easing: Readonly<Record<string, EasingFunction>> = Object.freeze(- Object.fromEntries(Object.entries(NAMES).map(([name, type]) => [name, (k: number): number => applyEasing(type, k)])),-);--export type EasingName = keyof typeof NAMES;--const warned = new Set<string>();--/** A curve by name or function; an unknown name is linear, with a warning once. */-export function resolveEasing(e: EasingName | EasingFunction | string | undefined): EasingFunction {- if (typeof e === 'function') return e;- if (e === undefined) return easing.linear!;- const known = easing[e];- if (known) return known;- if (!warned.has(e)) {- warned.add(e);- log.warn('cocos', `easing "${e}" is not supported (the engine has no such curve); using linear`);- }- return easing.linear!;-}diff --git a/sdk/src/cocos/emitter.ts b/sdk/src/cocos/emitter.tsdeleted file mode 100644index f62441577..000000000--- a/sdk/src/cocos/emitter.ts+++ /dev/null@@ -1,54 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/emitter.ts- * @brief The `on` / `once` / `off` / `emit` that `game`, `input`, `view` and `screen` share.- *- * Cocos's `EventTarget`: a listener is a callback with an optional `this`, `off` removes by callback and/or target, and one- * listener throwing does not keep the rest from hearing the event.- */-import { log } from '../util/logger';--type Listener = { callback: (...args: any[]) => void; target?: unknown };--export class Emitter {- private readonly listeners_ = new Map<string, Listener[]>();-- on(type: string, callback: (...args: any[]) => void, target?: unknown): typeof callback {- const list = this.listeners_.get(type);- if (list) list.push({ callback, target }); else this.listeners_.set(type, [{ callback, target }]);- return callback;- }-- once(type: string, callback: (...args: any[]) => void, target?: unknown): typeof callback {- const wrapper = (...args: any[]): void => { this.off(type, wrapper, target); callback.apply(target, args); };- return this.on(type, wrapper, target);- }-- /** With a callback: that listener (of that target, if given). With only a target: all of its listeners. With neither: the type's. */- off(type: string, callback?: (...args: any[]) => void, target?: unknown): void {- const list = this.listeners_.get(type);- if (!list) return;- this.listeners_.set(type, list.filter((l) => {- if (callback && l.callback !== callback) return true;- if (target !== undefined && l.target !== target) return true;- return false;- }));- }-- targetOff(target: unknown): void {- for (const [type, list] of this.listeners_) this.listeners_.set(type, list.filter((l) => l.target !== target));- }-- hasEventListener(type: string): boolean { return (this.listeners_.get(type)?.length ?? 0) > 0; }-- emit(type: string, ...args: any[]): void {- for (const l of [...(this.listeners_.get(type) ?? [])]) {- try {- l.callback.apply(l.target, args);- } catch (err) {- log.error('cocos', `a ${type} listener threw`, err);- }- }- }-}diff --git a/sdk/src/cocos/env.ts b/sdk/src/cocos/env.tsdeleted file mode 100644index 79477ec39..000000000--- a/sdk/src/cocos/env.ts+++ /dev/null@@ -1,44 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/env.ts- * @brief The build-time flags a Cocos script imports from `cc/env`.- *- * Scripts guard editor-only and debug-only code with these (`if (EDITOR) ...`, `DEV && console.log(...)`). In the engine's runtime- * none of the editor ones is true, which is what lets that code fall away. The platform flags say "browser", the closest honest- * answer for a build that is not a Cocos one; a script that needs to know more asks the engine's own platform API.- */-export const EDITOR = false;-export const EDITOR_NOT_IN_PREVIEW = false;-export const PREVIEW = false;-export const BUILD = true;-export const TEST = false;-export const DEBUG = false;-export const DEV = false;-export const SERVER_MODE = false;-export const HTML5 = true;-export const NATIVE = false;-export const JSB = false;-export const RUNTIME_BASED = false;-export const MINIGAME = false;-export const WECHAT = false;-export const WECHAT_MINI_PROGRAM = false;-export const BYTEDANCE = false;-export const ALIPAY = false;-export const XIAOMI = false;-export const HUAWEI = false;-export const OPPO = false;-export const VIVO = false;-export const COCOSPLAY = false;-export const ANDROID = false;-export const IOS = false;-export const WINDOWS = false;-export const MAC = false;-export const LINUX = false;-export const OHOS = false;-export const SUPPORT_JIT = true;-export const PHYSICS_BUILTIN = false;-export const PHYSICS_CANNON = false;-export const PHYSICS_AMMO = false;-export const PHYSICS_PHYSX = false;-export const NET_MODE = 0;diff --git a/sdk/src/cocos/game.ts b/sdk/src/cocos/game.tsdeleted file mode 100644index ed26ec0b8..000000000--- a/sdk/src/cocos/game.ts+++ /dev/null@@ -1,131 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/game.ts- * @brief `game` / `Game`: the running application — its frame clock and its show / hide / low-memory events.- *- * The clock is fed by the frame loop (`Cocos:Game`, below). The lifecycle events are the platform's, and are bound the first time a- * script listens for one: a mini-game host and a browser tab both report being shown and hidden, and a script that never asks- * costs the platform nothing. `restart` and `end` ask the host, since the application is not this layer's to restart.- */-import { Schedule, defineSystem, addSystemToSchedule } from '../ecs/system';-import { Res, Time } from '../ecs/resource';-import { isPlatformInitialized, platformNow, platformOnAppHide, platformOnAppShow, platformOnMemoryWarning } from '../platform';-import { Emitter } from './emitter';-import { Node } from './node';--const EVENTS = Object.freeze({- EVENT_HIDE: 'game_on_hide',- EVENT_SHOW: 'game_on_show',- EVENT_LOW_MEMORY: 'game_on_low_memory',- EVENT_GAME_INITED: 'game_inited',- EVENT_ENGINE_INITED: 'engine_inited',- EVENT_PRE_BASE_INIT: 'pre_base_init',- EVENT_POST_BASE_INIT: 'post_base_init',- EVENT_PRE_SUBSYSTEM_INIT: 'pre_subsystem_init',- EVENT_POST_SUBSYSTEM_INIT: 'post_subsystem_init',- EVENT_PRE_PROJECT_INIT: 'pre_project_init',- EVENT_POST_PROJECT_INIT: 'post_project_init',- EVENT_RENDERER_INITED: 'renderer_inited',- EVENT_RESTART: 'game_on_restart',-});--const RendererType = Object.freeze({ UNKNOWN: 0, CANVAS: 1, WEBGL: 2, OPENGL: 3, HEADLESS: 4, WEBGPU: 5 });--export class Game extends Emitter {- static readonly EVENT_HIDE = EVENTS.EVENT_HIDE;- static readonly EVENT_SHOW = EVENTS.EVENT_SHOW;- static readonly EVENT_LOW_MEMORY = EVENTS.EVENT_LOW_MEMORY;- static readonly EVENT_GAME_INITED = EVENTS.EVENT_GAME_INITED;- static readonly EVENT_ENGINE_INITED = EVENTS.EVENT_ENGINE_INITED;- static readonly EVENT_PRE_BASE_INIT = EVENTS.EVENT_PRE_BASE_INIT;- static readonly EVENT_POST_BASE_INIT = EVENTS.EVENT_POST_BASE_INIT;- static readonly EVENT_PRE_SUBSYSTEM_INIT = EVENTS.EVENT_PRE_SUBSYSTEM_INIT;- static readonly EVENT_POST_SUBSYSTEM_INIT = EVENTS.EVENT_POST_SUBSYSTEM_INIT;- static readonly EVENT_PRE_PROJECT_INIT = EVENTS.EVENT_PRE_PROJECT_INIT;- static readonly EVENT_POST_PROJECT_INIT = EVENTS.EVENT_POST_PROJECT_INIT;- static readonly EVENT_RENDERER_INITED = EVENTS.EVENT_RENDERER_INITED;- static readonly EVENT_RESTART = EVENTS.EVENT_RESTART;- static readonly RendererType = RendererType;-- readonly RendererType = RendererType;-- frameRate = 60;- /** Seconds since the previous frame. */- deltaTime = 0;- /** Seconds the application has run. */- totalTime = 0;- /** The time the current frame began, in milliseconds. */- frameStartTime = 0;- renderType = RendererType.WEBGL;- config: Record<string, unknown> = {};-- private paused_ = false;- private inited_ = true;- private bound_ = false;- private readonly persist_ = new Set<Node>();-- get isInited(): boolean { return this.inited_; }- get isPaused(): boolean { return this.paused_; }-- /** The page's canvas, when there is a page. */- get canvas(): HTMLCanvasElement | null {- if (typeof document === 'undefined') return null;- return (document.getElementById('GameCanvas') ?? document.querySelector('canvas')) as HTMLCanvasElement | null;- }- get container(): HTMLElement | null { return this.canvas?.parentElement ?? null; }-- pause(): void { this.paused_ = true; }- resume(): void { this.paused_ = false; }- step(): void { /* a frame is the engine's to run */ }-- restart(): Promise<void> {- this.emit(EVENTS.EVENT_RESTART);- if (typeof location !== 'undefined' && typeof location.reload === 'function') location.reload();- return Promise.resolve();- }- end(): void {- if (typeof window !== 'undefined' && typeof window.close === 'function') window.close();- }-- addPersistRootNode(node: Node): void { this.persist_.add(node); }- removePersistRootNode(node: Node): void { this.persist_.delete(node); }- isPersistRootNode(node: Node): boolean { return this.persist_.has(node); }-- /** The platform's show / hide / low-memory notices are bound when a script first asks to hear one. */- override on(type: string, callback: (...args: any[]) => void, target?: unknown): typeof callback {- this.bind_();- return super.on(type, callback, target);- }-- private bind_(): void {- if (this.bound_ || !isPlatformInitialized()) return;- this.bound_ = true;- try {- platformOnAppShow(() => this.emit(EVENTS.EVENT_SHOW));- platformOnAppHide(() => this.emit(EVENTS.EVENT_HIDE));- platformOnMemoryWarning(() => this.emit(EVENTS.EVENT_LOW_MEMORY));- } catch {- // a platform without these notices: the events simply never fire- }- }-- /** @internal Called by the frame loop. */- _tick(delta: number, elapsed: number): void {- this.deltaTime = delta;- this.totalTime = elapsed;- this.frameStartTime = isPlatformInitialized() ? platformNow() : (typeof performance !== 'undefined' ? performance.now() : Date.now());- }-}--export const game = new Game();--/** Register the system that feeds the game clock. */-export function declareGameSystem(): void {- const system = defineSystem(- [Res(Time)],- (time) => { game._tick(time.delta, time.elapsed); },- { name: 'Cocos:Game', touches: { opaque: true } },- );- addSystemToSchedule(Schedule.First, system);-}diff --git a/sdk/src/cocos/geometry.ts b/sdk/src/cocos/geometry.tsdeleted file mode 100644index 888075c7d..000000000--- a/sdk/src/cocos/geometry.ts+++ /dev/null@@ -1,142 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/geometry.ts- * @brief `cc.geometry`: the boxes, rays and planes scripts test against, and the intersection tests between them.- *- * Plain maths on the layer's `Vec3`; nothing here touches the engine. Only the shapes and tests scripts actually reach for are here.- */-import { Vec3 } from './math';--/** An axis-aligned box: its centre and half the size along each axis. */-export class AABB {- center: Vec3;- halfExtents: Vec3;-- constructor(px = 0, py = 0, pz = 0, hw = 1, hh = 1, hl = 1) {- this.center = new Vec3(px, py, pz);- this.halfExtents = new Vec3(hw, hh, hl);- }-- static create(px = 0, py = 0, pz = 0, hw = 1, hh = 1, hl = 1): AABB { return new AABB(px, py, pz, hw, hh, hl); }- static clone(a: AABB): AABB { return new AABB(a.center.x, a.center.y, a.center.z, a.halfExtents.x, a.halfExtents.y, a.halfExtents.z); }- static copy(out: AABB, a: AABB): AABB { out.center.set(a.center); out.halfExtents.set(a.halfExtents); return out; }-- /** The box that spans two corners. */- static fromPoints(minPos: Vec3, maxPos: Vec3, out: AABB = new AABB()): AABB {- out.center.set((maxPos.x + minPos.x) * 0.5, (maxPos.y + minPos.y) * 0.5, (maxPos.z + minPos.z) * 0.5);- out.halfExtents.set((maxPos.x - minPos.x) * 0.5, (maxPos.y - minPos.y) * 0.5, (maxPos.z - minPos.z) * 0.5);- return out;- }-- /** The box that holds both. */- static merge(out: AABB, a: AABB, b: AABB): AABB {- const min = new Vec3(Math.min(a.center.x - a.halfExtents.x, b.center.x - b.halfExtents.x), Math.min(a.center.y - a.halfExtents.y, b.center.y - b.halfExtents.y), Math.min(a.center.z - a.halfExtents.z, b.center.z - b.halfExtents.z));- const max = new Vec3(Math.max(a.center.x + a.halfExtents.x, b.center.x + b.halfExtents.x), Math.max(a.center.y + a.halfExtents.y, b.center.y + b.halfExtents.y), Math.max(a.center.z + a.halfExtents.z, b.center.z + b.halfExtents.z));- return AABB.fromPoints(min, max, out);- }-- set(px: number, py: number, pz: number, hw: number, hh: number, hl: number): void {- this.center.set(px, py, pz);- this.halfExtents.set(hw, hh, hl);- }-- clone(): AABB { return AABB.clone(this); }- copy(a: AABB): AABB { return AABB.copy(this, a); }- getBoundary(minPos: Vec3, maxPos: Vec3): void {- minPos.set(this.center.x - this.halfExtents.x, this.center.y - this.halfExtents.y, this.center.z - this.halfExtents.z);- maxPos.set(this.center.x + this.halfExtents.x, this.center.y + this.halfExtents.y, this.center.z + this.halfExtents.z);- }-}--/** A ray from `o` along `d`. */-export class Ray {- o: Vec3;- d: Vec3;-- constructor(ox = 0, oy = 0, oz = 0, dx = 0, dy = 0, dz = -1) {- this.o = new Vec3(ox, oy, oz);- this.d = new Vec3(dx, dy, dz);- }-- static create(ox = 0, oy = 0, oz = 0, dx = 0, dy = 0, dz = -1): Ray { return new Ray(ox, oy, oz, dx, dy, dz); }- static clone(r: Ray): Ray { return new Ray(r.o.x, r.o.y, r.o.z, r.d.x, r.d.y, r.d.z); }- static copy(out: Ray, r: Ray): Ray { out.o.set(r.o); out.d.set(r.d); return out; }-- /** The ray from one point towards another. */- static fromPoints(out: Ray, origin: Vec3, target: Vec3): Ray {- out.o.set(origin);- out.d.set(target.x - origin.x, target.y - origin.y, target.z - origin.z).normalize();- return out;- }-- /** The point `distance` along the ray. */- computeHit(out: Vec3, distance: number): void {- out.set(this.o.x + this.d.x * distance, this.o.y + this.d.y * distance, this.o.z + this.d.z * distance);- }-- clone(): Ray { return Ray.clone(this); }- copy(r: Ray): Ray { return Ray.copy(this, r); }-}--/** The plane `n · p = d`. */-export class Plane {- n: Vec3;- d: number;-- constructor(nx = 0, ny = 1, nz = 0, d = 0) {- this.n = new Vec3(nx, ny, nz);- this.d = d;- }-- static create(nx = 0, ny = 1, nz = 0, d = 0): Plane { return new Plane(nx, ny, nz, d); }- static clone(p: Plane): Plane { return new Plane(p.n.x, p.n.y, p.n.z, p.d); }- static copy(out: Plane, p: Plane): Plane { out.n.set(p.n); out.d = p.d; return out; }-- /** The plane through @p point with the given normal. */- static fromNormalAndPoint(out: Plane, normal: Vec3, point: Vec3): Plane {- out.n.set(normal);- out.d = normal.x * point.x + normal.y * point.y + normal.z * point.z;- return out;- }-- clone(): Plane { return Plane.clone(this); }-}--const dot = (a: Vec3, b: Vec3): number => a.x * b.x + a.y * b.y + a.z * b.z;--/** The intersection tests. A ray test answers the distance along the ray, or 0 when it misses. */-export const intersect = {- aabbWithAABB(a: AABB, b: AABB): boolean {- return Math.abs(a.center.x - b.center.x) <= a.halfExtents.x + b.halfExtents.x- && Math.abs(a.center.y - b.center.y) <= a.halfExtents.y + b.halfExtents.y- && Math.abs(a.center.z - b.center.z) <= a.halfExtents.z + b.halfExtents.z;- },-- rayPlane(ray: Ray, plane: Plane): number {- const denom = dot(ray.d, plane.n);- if (Math.abs(denom) < 1e-12) return 0;- const t = (plane.d - dot(ray.o, plane.n)) / denom;- return t < 0 ? 0 : t;- },-- rayAABB(ray: Ray, aabb: AABB): number {- let tmin = -Infinity, tmax = Infinity;- for (const axis of ['x', 'y', 'z'] as const) {- const lo = aabb.center[axis] - aabb.halfExtents[axis], hi = aabb.center[axis] + aabb.halfExtents[axis];- const o = ray.o[axis], d = ray.d[axis];- if (Math.abs(d) < 1e-12) {- if (o < lo || o > hi) return 0;- continue;- }- const t1 = (lo - o) / d, t2 = (hi - o) / d;- tmin = Math.max(tmin, Math.min(t1, t2));- tmax = Math.min(tmax, Math.max(t1, t2));- }- if (tmax < Math.max(tmin, 0)) return 0;- return tmin > 0 ? tmin : tmax > 0 ? tmax : 0;- },-};--/** `cc.geometry`. */-export const geometry = { AABB, Ray, Plane, intersect };diff --git a/sdk/src/cocos/host.ts b/sdk/src/cocos/host.tsdeleted file mode 100644index a9e414339..000000000--- a/sdk/src/cocos/host.ts+++ /dev/null@@ -1,331 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/host.ts- * @brief Declaring a script class, and running its lifecycle.- *- * Declaring a class (`@ccclass`) does two things, both through the engine's own mechanisms. It defines an Estella component- * carrying the class's `@property` values — the data a scene or prefab stores and the inspector edits — and it registers a- * system, the way `defineBehavior` does, that finds the entities carrying that component and drives the instances' lifecycle.- * There is no second runtime: the instances are plain objects held in `registry.ts`, and the frame loop is the engine's.- *- * Lifecycle is presence-diffed against the live query rather than tracked by events, so a component removed or an entity- * despawned by a system that ran earlier is still seen, and an entity switched off (which drops out of the query but keeps its- * component) is told apart from one that is gone.- */-import { defineComponent } from '../ecs/component';-import { Schedule, defineSystem, addSystemToSchedule, GetWorld } from '../ecs/system';-import { Children } from '../ecs/component';-import { Query, Mut } from '../ecs/query';-import { Res, Time } from '../ecs/resource';-import type { World } from '../ecs/world';-import type { Entity } from '../types';-import { log } from '../util/logger';-import { Color, Vec2, Vec3 } from './math';-import { Node, setCurrentWorld } from './node';-import {- COMPONENT_PREFIX, classInfoNamed, ensureBuiltinsDeclared, classInfoOf, dropInstance, instancesOfClass, instancesOn, nodeOf, registerClassInfo, setActivitySync, setInstantiator, storeInstance, awaitStart, pendingStarts,- type ClassInfo, type ComponentCtor, type PropertyKind, type PropertySpec,-} from './registry';--/** A property as the decorator recorded it: its kind may still be unknown, to be read off the class's own initializer. */-export interface RawPropertySpec {- name: string;- kind?: PropertyKind;- type?: unknown;- array?: boolean;-}--/** The kind a value implies, for a property that named no type. */-function inferKind(value: unknown): PropertyKind {- if (typeof value === 'number') return 'number';- if (typeof value === 'string') return 'string';- if (typeof value === 'boolean') return 'boolean';- if (value instanceof Vec3) return 'vec3';- if (value instanceof Vec2) return 'vec2';- if (value instanceof Color) return 'color';- if (value instanceof Node) return 'node';- return 'json';-}-import type { Component } from './component';-import { Prefab, type Asset } from './assets';-import { requestPrepare } from './prefabs';--/** The value a freshly declared component carries for one property: what the class's own initializer gave, in the form the engine stores. */-function storedDefault(spec: PropertySpec, value: unknown): unknown {- if (spec.array) return Array.isArray(value) && spec.kind !== 'node' && spec.kind !== 'component' ? structuredClone(value) : [];- switch (spec.kind) {- case 'number': return typeof value === 'number' ? value : 0;- case 'string': return typeof value === 'string' ? value : '';- case 'boolean': return typeof value === 'boolean' ? value : false;- case 'node':- case 'component': return 0;- case 'asset': return '';- case 'vec2': return value instanceof Vec2 ? { x: value.x, y: value.y } : { x: 0, y: 0 };- case 'vec3': return value instanceof Vec3 ? { x: value.x, y: value.y, z: value.z } : { x: 0, y: 0, z: 0 };- case 'color': return value instanceof Color ? { r: value.r, g: value.g, b: value.b, a: value.a } : { r: 255, g: 255, b: 255, a: 255 };- default: return value === undefined ? null : structuredClone(value);- }-}--/** An asset path as the asset class the script named; a prefab starts loading the moment a script holds it. */-function asAsset(type: Function, path: string): unknown {- const asset = new (type as new (path: string) => Asset)(path);- if (asset instanceof Prefab) requestPrepare(path);- return asset;-}--/** What a stored value becomes on an instance. */-function liveValue(world: World, spec: PropertySpec, stored: unknown): unknown {- const one = (v: unknown): unknown => {- switch (spec.kind) {- case 'node': return typeof v === 'number' && v > 0 ? nodeOf(world, v as Entity) : null;- case 'component': {- if (typeof v !== 'number' || v <= 0) return null;- const node = nodeOf(world, v as Entity);- return typeof spec.type === 'function' ? node.getComponent(spec.type as ComponentCtor) : null;- }- case 'vec2': return v && typeof v === 'object' ? new Vec2((v as Vec2).x, (v as Vec2).y) : new Vec2();- case 'vec3': return v && typeof v === 'object' ? new Vec3((v as Vec3).x, (v as Vec3).y, (v as Vec3).z) : new Vec3();- case 'color': return v && typeof v === 'object' ? new Color((v as Color).r, (v as Color).g, (v as Color).b, (v as Color).a) : new Color();- case 'asset': return typeof v === 'string' && v !== '' && typeof spec.type === 'function' ? asAsset(spec.type, v) : v;- default: return v;- }- };- return spec.array && Array.isArray(stored) ? stored.map(one) : one(stored);-}--function call(inst: Component, hook: 'onLoad' | 'onEnable' | 'start' | 'onDisable' | 'onDestroy'): void;-function call(inst: Component, hook: 'update' | 'lateUpdate', dt: number): void;-function call(inst: Component, hook: keyof Component, dt?: number): void {- const fn = (inst as unknown as Record<string, ((dt?: number) => void) | undefined>)[hook];- if (typeof fn !== 'function') return;- try {- fn.call(inst, dt);- } catch (err) {- log.error('cocos', `${inst.name}.${String(hook)} threw`, err);- }-}--function instantiate(world: World, entity: Entity, ctor: ComponentCtor): Component | null {- const info = classInfoOf(ctor);- if (!info || !world.valid(entity) || !world.has(entity, info.def)) return null;- const previous = setCurrentWorld(world);- try {- const inst = new ctor();- inst._world = world;- inst._entity = entity;- inst.node = nodeOf(world, entity);- // Stored before `onLoad`: a `getComponent` inside it must find this instance, not make a second.- storeInstance(world, entity, ctor, inst);-- const data = world.get(entity, info.def) as Record<string, unknown>;- if (typeof data.enabled === 'boolean') inst.enabled = data.enabled;- for (const spec of info.props) {- if (spec.name in data) (inst as unknown as Record<string, unknown>)[spec.name] = liveValue(world, spec, data[spec.name]);- }- // A component added to a node that is not active in the hierarchy (a prefab instance not yet given a parent) is there to be read and set, and- // loads when the node becomes active, as in Cocos.- if (world.isEntityActive(entity)) loadInstance(world, inst);- return inst;- } finally {- setCurrentWorld(previous);- }-}-setInstantiator(instantiate);--/** Run the load part of a component's life: `onLoad` now, `start` in the start phase. */-function loadInstance(world: World, inst: Component): void {- inst._loaded = true;- call(inst, 'onLoad');- // `start` belongs to the start phase, which runs before the frame's updates; what has no `start` has started- if (typeof (inst as unknown as { start?: unknown }).start === 'function') awaitStart(world, inst);- else inst._started = true;-}--/**- * Bring the scripts of a node and everything under it to the state its activity says, at once: the classes it carries are made (`onLoad`)- * while it is active, and `onEnable` / `onDisable` run as the switch changed. `start` and `update` stay with the frame.- */-function syncSubtree(world: World, root: Entity): void {- const previous = setCurrentWorld(world);- try {- const stack: Entity[] = [root];- // As Cocos activates a tree: every component's `onLoad` first, in node order, then every `onEnable`- const made: Component[] = [];- while (stack.length > 0) {- const entity = stack.pop()!;- if (!world.valid(entity)) continue;- const active = world.isEntityActive(entity);- for (const type of world.getComponentTypes(entity)) {- if (!type.startsWith(COMPONENT_PREFIX)) continue;- const info = classInfoNamed(type.slice(COMPONENT_PREFIX.length));- if (!info) continue;- const inst = instancesOn(world, entity)?.get(info.ctor) ?? (active ? instantiate(world, entity, info.ctor) : null);- if (inst && active && !inst._loaded) loadInstance(world, inst);- if (inst) made.push(inst);- }- const children = world.tryGet(entity, Children)?.entities;- if (children) for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]!);- }- for (const inst of made) {- if (!world.valid(inst._entity)) continue;- const on = inst.enabled && world.isEntityActive(inst._entity);- if (on && !inst._enabledApplied) {- inst._enabledApplied = true;- call(inst, 'onEnable');- } else if (!on && inst._enabledApplied) {- inst._enabledApplied = false;- call(inst, 'onDisable');- }- }- } finally {- setCurrentWorld(previous);- }-}-setActivitySync(syncSubtree);--/** Run the per-frame part of one instance: enable/disable as its activity changes, then `start` once, then the timers and `update`. */-function drive(world: World, entity: Entity, inst: Component, dt: number, fresh = false): void {- const active = inst.enabled && world.isEntityActive(entity);- if (active && !inst._loaded) loadInstance(world, inst);- if (active && !inst._enabledApplied) {- inst._enabledApplied = true;- call(inst, 'onEnable');- } else if (!active && inst._enabledApplied) {- inst._enabledApplied = false;- call(inst, 'onDisable');- }- if (!active) return;- if (!inst._started) {- // A component made by this very pass has no earlier life to be ordered against: it starts here, as one that existed when the frame began.- // Any other waits for the start phase, which gives every enabled component its `start` ahead of the frame's updates.- if (!fresh) return;- pendingStarts(world)?.delete(inst);- inst._started = true;- call(inst, 'start');- }- try {- inst._tickTimers(dt);- } catch (err) {- log.error('cocos', `${inst.name} timer threw`, err);- }- call(inst, 'update', dt);-}--function destroyInstance(world: World, entity: Entity, ctor: Function, inst: Component): void {- if (inst._enabledApplied) {- inst._enabledApplied = false;- call(inst, 'onDisable');- }- inst._destroyed = true;- inst.unscheduleAllCallbacks();- call(inst, 'onDestroy');- dropInstance(world, entity, ctor);-}--/**- * The start phase of a frame. Cocos calls `start` on every component enabled since the last frame before it calls any `update`, so a script- * that sets another component up in its `start` is read by that component's `update` of the same frame, whichever of them was declared first.- */-export function declareStartPhase(): void {- addSystemToSchedule(Schedule.PreUpdate, defineSystem(- [GetWorld()],- (world) => {- const waiting = pendingStarts(world);- if (!waiting || waiting.size === 0) return;- const previous = setCurrentWorld(world);- try {- // `start` may enable more components; those wait for the next phase- for (const inst of [...waiting]) {- if (inst._destroyed) { waiting.delete(inst); continue; }- if (!world.valid(inst._entity) || !inst.enabled || !world.isEntityActive(inst._entity)) continue;- // enabled by the time the frame begins, whether or not its class has had a pass yet- if (!inst._enabledApplied) {- inst._enabledApplied = true;- call(inst, 'onEnable');- }- waiting.delete(inst);- inst._started = true;- call(inst, 'start');- }- } finally {- setCurrentWorld(previous);- }- },- { name: 'Cocos:Start', touches: { opaque: true } },- ));-}--/**- * Declare a script class: define its component, register it, and register the system that drives it.- * @param specs The class's `@property` fields, with their kinds settled.- */-export function declareClass(ctor: ComponentCtor, name: string, raw: RawPropertySpec[]): ClassInfo {- ensureBuiltinsDeclared();- // The class's own initializers say what each property starts as, which is what Cocos reads to fill its inspector.- let probe: Record<string, unknown> | null = null;- try { probe = new ctor() as unknown as Record<string, unknown>; } catch { probe = null; }-- const specs: PropertySpec[] = raw.map((r) => ({ ...r, kind: r.kind ?? inferKind(probe?.[r.name]) }));- const defaults: Record<string, unknown> = { enabled: true };- for (const spec of specs) defaults[spec.name] = storedDefault(spec, probe?.[spec.name]);-- const componentName = COMPONENT_PREFIX + name;- const entityFields = specs.filter((s) => s.kind === 'node' || s.kind === 'component').map((s) => s.name);- const def = defineComponent(componentName, defaults, entityFields.length ? { entityFields } : undefined);- const info: ClassInfo = { ctor, name, componentName, def, props: specs };- registerClassInfo(info);-- const hasLate = typeof (ctor.prototype as Component).lateUpdate === 'function';-- const update = defineSystem(- [Query(Mut(def)), Res(Time), GetWorld()],- (q, time, world) => {- const previous = setCurrentWorld(world);- try {- const seen = new Set<Entity>();- // The entities first, then the scripts: a script that switches a node on or off adds and removes components, which a query being- // walked does not allow.- for (const [entity] of [...q]) {- seen.add(entity);- const existing = instancesOn(world, entity)?.get(ctor);- const inst = existing ?? instantiate(world, entity, ctor);- if (inst) drive(world, entity, inst, time.delta, !existing);- }- // Instances the query did not return are either switched off (still carrying the component) or gone.- for (const [entity, inst] of instancesOfClass(world, ctor)) {- if (seen.has(entity)) continue;- if (world.valid(entity) && world.has(entity, def)) drive(world, entity, inst, time.delta);- else destroyInstance(world, entity, ctor, inst);- }- } finally {- setCurrentWorld(previous);- }- },- { name: `Cocos:${name}`, touches: { opaque: true } },- );- addSystemToSchedule(Schedule.Update, update);-- if (hasLate) {- const late = defineSystem(- [Query(Mut(def)), Res(Time), GetWorld()],- (q, time, world) => {- const previous = setCurrentWorld(world);- try {- for (const [entity] of [...q]) {- const inst = instancesOn(world, entity)?.get(ctor);- if (inst && inst._started && inst.enabled && world.isEntityActive(entity)) call(inst, 'lateUpdate', time.delta);- }- } finally {- setCurrentWorld(previous);- }- },- { name: `Cocos:${name}:late`, touches: { opaque: true } },- );- addSystemToSchedule(Schedule.PostUpdate, late);- }- return info;-}--export { Node };diff --git a/sdk/src/cocos/index.ts b/sdk/src/cocos/index.tsdeleted file mode 100644index ef339c9a1..000000000--- a/sdk/src/cocos/index.ts+++ /dev/null@@ -1,59 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/index.ts- * @brief `esengine/cocos`: the Cocos Creator `cc` module, for scripts that were written against it.- *- * A project that brings Cocos scripts across builds them with `cc` aliased to this entry (the project-script bundler does that- * for a project that asks for it), so `import { Component, Node, _decorator } from 'cc'` resolves here. The names exported are- * the ones a Cocos script imports; what stands behind them is the engine — a `Node` is an entity, a `Component` subclass is an- * Estella component with an instance — and the parts of Cocos that have no counterpart are not simulated (see each file).- */-export { Vec2, Vec3, Quat, Color, Size, Rect, v2, v3, color, size, rect, math, toRadian, toDegree, clamp, clamp01, lerp } from './math';-export { Vec4, Mat4 } from './mat4';-export { Component } from './component';-export { Node, NodeSpace, setCurrentWorld, getCurrentWorld } from './node';-import { Node as NodeClass } from './node';-/** The event names, under the name scripts import them by. */-export const NodeEventType = NodeClass.EventType;-export {- _decorator, ccclass, property, requireComponent, executionOrder, menu, help, icon, inspector, playOnFocus, executeInEditMode,- disallowMultiple, type, integer, float, string, boolean, CCInteger, CCFloat, CCString, CCBoolean, Enum,-} from './decorators';-export { director, Director, Scene, find, isValid, reportFrame } from './director';-export { Scheduler } from './scheduler';-export {- Asset, ImageAsset, Texture2D, SpriteFrame, SpriteAtlas, Prefab, AudioClip, Material, JsonAsset, TextAsset, BitmapFont, Font,- AnimationClip, SceneAsset, EffectAsset, Mesh,-} from './assets';-export { registerBuiltinComponent, type BuiltinAdapter } from './builtins';-export { unsupported } from './unsupported';-export { renderer } from './renderer';-export { ccenum, js, NodePool, profiler } from './misc';-export { MeshRenderer, ModelRenderer, UIMeshRenderer } from './meshRenderer';-export { Collider, BoxCollider } from './collider';-export { PhysicsSystem, PhysicsRayResult } from './physicsSystem';-export { UIRenderer } from './ui/renderer';-export { geometry } from './geometry';-export { UITransform, Label, LabelOutline, LabelShadow, Sprite, UIOpacity, Button, EventHandler, Widget, Layout, Camera, RichText, Mask, Toggle, ToggleContainer, ProgressBar, Slider, BlockInputEvents, ScrollView, Graphics, Line, EditBox, PageView, PageViewIndicator, ScrollBar, SafeArea, WebView, getVisibleSize, setVisibleSize } from './ui';-export { Touch, EventTouch } from './input';-export { tween, Tween, tweenUtil, easing, updateTweens } from './tween';-export { instantiate, loadPrefab, providePrefab } from './prefabs';-export { sys } from './sys';-export { macro } from './macro';-export { Layers } from './layers';-export { view, View, ResolutionPolicy, screen } from './view';-export { game, Game } from './game';-export { input, Input, KeyCode, EventKeyboard, EventMouse } from './inputApi';-export { Emitter as EventTarget } from './emitter';-export { assetManager, AssetManager, Bundle, Cache, resources, setResourceManifest, type ResourceManifest, type ResourceEntry } from './assetManager';-export { declareBuiltinScripts, redeclareBuiltinScripts } from './builtinScripts';-/** `cc/env` is the same module here: its flags are named exports beside the rest. */-export * from './env';-export { classInfoNamed, classInfoOf, allClassInfos, COMPONENT_PREFIX, resetClassRegistry } from './registry';--import { declareBuiltinScripts as declare } from './builtinScripts';-import { declareAsEngineComponents } from '../ecs/component';-// Declared once, into the context a game runs in, when the layer is imported. They are the engine's components as far as a reload goes: the layer-// does not load again, so what it declared has to be put back with the rest of them.-declareAsEngineComponents(declare);diff --git a/sdk/src/cocos/input.ts b/sdk/src/cocos/input.tsdeleted file mode 100644index 4a033c7b2..000000000--- a/sdk/src/cocos/input.ts+++ /dev/null@@ -1,304 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/input.ts- * @brief Touch events on nodes: `Node.on(TOUCH_START, ...)`, `EventTouch`, and the translation from the engine's pointer events.- *- * The engine already decides who a pointer is on (the topmost interactable under it), lets that entity hold the gesture, and says- * what happens to it: `press`, `pointer_move`, `release`, `press_cancel`, each with where the pointer is. A node that listens for- * touches is made interactable, and those events are handed to it here as Cocos's: the touch starts on the topmost listening node,- * the rest of the gesture goes to that same node wherever the finger goes, and the event travels the node's ancestors — the- * capture listeners from the top down, then the target's own, then the bubbling ones back up — until one stops it.- *- * Because it is the engine's pointer, a touch on a Cocos node also counts as "over the UI" for gameplay input, and anything the- * engine's own UI does with pointers (hover, focus) sees these nodes too.- *- * A touch has two places, as in Cocos: the SCREEN point (`getLocation`, the surface in pixels from its bottom-left corner — what a- * camera's `screenToWorld` takes) and the CANVAS point (`getUILocation`, where the UI is laid out; in an imported scene, the world).- */-import { Schedule, defineSystem, addSystemToSchedule, GetWorld } from '../ecs/system';-import { Res } from '../ecs/resource';-import { Input, type InputState } from '../input/input';-import { EntityEvents, type EntityEvent, type EntityEventQueue } from '../ecs/entityEvents';-import { UIEventType } from '../ui/core/events';-import { UIControlPointers, type ControlPointer, type UIControlPointersData, type UiPointerEventData } from '../ui/input/control-pointers';-import { Interactable } from '../ui/input/interactable';-import { MOUSE_POINTER, uiPointersOf } from '../ui/input/pointerBook';-import { SystemLabel } from '../ecs/systemLabels';-import type { World } from '../ecs/world';-import type { Entity } from '../types';-import { Vec2 } from './math';-import { Node, touchListeningEntities } from './node';-import { ensureUITransform } from './ui/uiTransform';-import { log } from '../util/logger';-import { EventKeyboard, EventMouse, input as globalInput, keyCodeOf, Input as InputApi } from './inputApi';--interface Point { x: number; y: number; sx: number; sy: number }--/**- * One finger (or the mouse button) as a script sees it, at two kinds of place as in Cocos: the SCREEN point- * (`getLocation`: pixels of the drawing surface, origin bottom-left — what a camera's `screenToWorld` takes), and the CANVAS point- * (`getUILocation`: the space the UI is laid out in, which in an imported scene is the world's).- */-export class Touch {- private cur_: Point;- private readonly start_: Point;- private prev_: Point;-- constructor(public readonly id: number, x: number, y: number, sx: number = x, sy: number = y) {- this.cur_ = { x, y, sx, sy };- this.start_ = { ...this.cur_ };- this.prev_ = { ...this.cur_ };- }-- /** @internal */- _move(x: number, y: number, sx: number = x, sy: number = y): void { this.prev_ = this.cur_; this.cur_ = { x, y, sx, sy }; }-- getID(): number { return this.id; }-- getLocation(out: Vec2 = new Vec2()): Vec2 { return out.set(this.cur_.sx, this.cur_.sy); }- getLocationX(): number { return this.cur_.sx; }- getLocationY(): number { return this.cur_.sy; }- getStartLocation(out: Vec2 = new Vec2()): Vec2 { return out.set(this.start_.sx, this.start_.sy); }- getPreviousLocation(out: Vec2 = new Vec2()): Vec2 { return out.set(this.prev_.sx, this.prev_.sy); }- getDelta(out: Vec2 = new Vec2()): Vec2 { return out.set(this.cur_.sx - this.prev_.sx, this.cur_.sy - this.prev_.sy); }-- getUILocation(out: Vec2 = new Vec2()): Vec2 { return out.set(this.cur_.x, this.cur_.y); }- getUILocationX(): number { return this.cur_.x; }- getUILocationY(): number { return this.cur_.y; }- getUIStartLocation(out: Vec2 = new Vec2()): Vec2 { return out.set(this.start_.x, this.start_.y); }- getUIPreviousLocation(out: Vec2 = new Vec2()): Vec2 { return out.set(this.prev_.x, this.prev_.y); }- getUIDelta(out: Vec2 = new Vec2()): Vec2 { return out.set(this.cur_.x - this.prev_.x, this.cur_.y - this.prev_.y); }-}--/** The event a touch listener receives. */-export class EventTouch {- /** Always bubbles, as in Cocos. */- readonly bubbles = true;- target: Node | null = null;- currentTarget: Node | null = null;- private stopped_ = false;- /** @internal Set by the dispatcher: cancels the touch for the node that claimed it. */- _cancelTarget: (() => void) | null = null;-- constructor(public readonly type: string, public readonly touch: Touch, private readonly all_: Touch[]) {}-- /**- * Tell the node the touch started on that it is cancelled, and stop sending it the rest of the gesture. A scroll view calls this- * once a drag is clearly a drag, so a button under the finger does not also click when it is lifted.- */- cancelInner(): void { this._cancelTarget?.(); }-- get propagationStopped(): boolean { return this.stopped_; }- stopPropagation(): void { this.stopped_ = true; }- stopPropagationImmediate(): void { this.stopped_ = true; }- getTouches(): Touch[] { return this.all_; }-- getID(): number { return this.touch.id; }- getLocation(out?: Vec2): Vec2 { return this.touch.getLocation(out); }- getLocationX(): number { return this.touch.getLocationX(); }- getLocationY(): number { return this.touch.getLocationY(); }- getUILocation(out?: Vec2): Vec2 { return this.touch.getUILocation(out); }- getUIStartLocation(out?: Vec2): Vec2 { return this.touch.getUIStartLocation(out); }- getUIPreviousLocation(out?: Vec2): Vec2 { return this.touch.getUIPreviousLocation(out); }- getUIDelta(out?: Vec2): Vec2 { return this.touch.getUIDelta(out); }- getUILocationX(): number { return this.touch.getUILocationX(); }- getUILocationY(): number { return this.touch.getUILocationY(); }- getStartLocation(out?: Vec2): Vec2 { return this.touch.getStartLocation(out); }- getPreviousLocation(out?: Vec2): Vec2 { return this.touch.getPreviousLocation(out); }- getDelta(out?: Vec2): Vec2 { return this.touch.getDelta(out); }-}--// ----------------------------------------------------------------------------------------------------------------------// Making listening nodes interactable.-// -----------------------------------------------------------------------------------------------------------------------/** The entities this layer has made interactable, per world, so it can take the mark away again from ones that stopped listening. */-const equipped = new WeakMap<World, Set<Entity>>();--/**- * A node that listens for touches is a thing a pointer can land on: it gets a rectangle (the node's `UITransform`) and the engine's- * `Interactable`, which lets events pass through to its ancestors (the bubbling here is the node tree's, not the engine's). A node- * that stops listening gives the mark back, so it does not keep catching touches that belong to what is under it.- */-function syncInteractables(world: World): void {- const have = equipped.get(world) ?? new Set<Entity>();- equipped.set(world, have);- const want = new Set<Entity>();- for (const entity of touchListeningEntities(world)) if (world.valid(entity)) want.add(entity);- for (const entity of want) {- if (have.has(entity)) continue;- ensureUITransform(world, entity);- if (!world.has(entity, Interactable)) world.insert(entity, Interactable, { enabled: true, blockRaycast: false, raycastTarget: true });- have.add(entity);- }- for (const entity of [...have]) {- if (want.has(entity)) continue;- have.delete(entity);- if (world.valid(entity) && world.has(entity, Interactable)) world.remove(entity, Interactable);- }-}--// ----------------------------------------------------------------------------------------------------------------------// Delivering a touch: capture down, target, bubble up.-// -----------------------------------------------------------------------------------------------------------------------/**- * Hand an event down and up the node tree: the capture listeners of the ancestors from the top, then the target's own capture and- * normal listeners, then the normal listeners from the target's parent up, until one stops it.- */-function dispatch(event: EventTouch, target: Node): void {- const path: Node[] = [];- for (let n: Node | null = target; n; n = n.parent) path.unshift(n);- event.target = target;- const guard = (fn: () => void, node: Node): void => {- try { fn(); } catch (err) { log.error('cocos', `${node.name} ${event.type} listener threw`, err); }- };- for (const node of path) {- if (event.propagationStopped) return;- event.currentTarget = node;- guard(() => node._emitCapture(event.type, event), node);- }- for (let node: Node | null = target; node && !event.propagationStopped; node = node.parent) {- event.currentTarget = node;- if (!node.hasEventListener(event.type, false)) continue;- guard(() => node!.emit(event.type, event), node);- }-}--const TO_COCOS: Record<string, string> = {- [UIEventType.Press]: Node.EventType.TOUCH_START,- [UIEventType.PointerMove]: Node.EventType.TOUCH_MOVE,- [UIEventType.Release]: Node.EventType.TOUCH_END,- [UIEventType.PressCancel]: Node.EventType.TOUCH_CANCEL,-};--interface TouchState { nodeTouches: Map<number, Touch>; globalTouches: Map<number, Touch>; subscribed: WeakSet<object> }-const states = new WeakMap<World, TouchState>();-const stateOf = (world: World): TouchState => {- let s = states.get(world);- if (!s) states.set(world, (s = { nodeTouches: new Map(), globalTouches: new Map(), subscribed: new WeakSet() }));- return s;-};--/** Turn one of the engine's pointer events on an entity into the Cocos touch event for its node. */-function onPointerEvent(world: World, controls: UIControlPointersData, e: EntityEvent): void {- // an engine event bubbles to interactable ancestors as copies; the node tree does its own bubbling, from the original only- if (e.currentTarget !== e.target) return;- const type = TO_COCOS[e.type];- const data = e.data as UiPointerEventData | undefined;- if (!type || !data || !world.valid(e.target)) return;- const { nodeTouches } = stateOf(world);- let touch = nodeTouches.get(data.pointer);- if (!touch || type === Node.EventType.TOUCH_START) {- touch = new Touch(data.pointer, data.worldX, data.worldY, data.screenX, data.screenY);- nodeTouches.set(data.pointer, touch);- } else {- touch._move(data.worldX, data.worldY, data.screenX, data.screenY);- }- const event = new EventTouch(type, touch, [...nodeTouches.values()]);- // giving the gesture to the node that is cancelling it (the one whose capture listener is running)- event._cancelTarget = () => {- const taker = event.currentTarget;- if (taker && taker !== event.target) controls.cancelHold(data.pointer, taker._entity);- };- dispatch(event, Node.for(world, e.target));- if (event.propagationStopped) e.stopPropagation();- if (type === Node.EventType.TOUCH_END || type === Node.EventType.TOUCH_CANCEL) {- // a cancel that hands the gesture to another node does not end the touch- if (!controls.pointers.get(data.pointer)?.down || type === Node.EventType.TOUCH_END) nodeTouches.delete(data.pointer);- }-}--function subscribe(world: World, events: EntityEventQueue, controls: UIControlPointersData): void {- const state = stateOf(world);- if (state.subscribed.has(events)) return;- state.subscribed.add(events);- for (const type of Object.keys(TO_COCOS)) events.on(type, (e) => onPointerEvent(world, controls, e));-}--/** The global `input` hears every pointer, whether or not a node is under it. */-function pumpGlobalTouches(world: World, input: InputState, controls: UIControlPointersData): void {- const { globalTouches } = stateOf(world);- for (const p of uiPointersOf(input)) {- const c = controls.pointers.get(p.id);- if (!c) continue;- let touch = globalTouches.get(p.id);- const live = (): Touch[] => [...globalTouches.values()];- if (p.pressed && !touch) {- touch = new Touch(p.id, c.worldX, c.worldY, c.screenX, c.screenY);- globalTouches.set(p.id, touch);- globalInput.emit(Node.EventType.TOUCH_START, new EventTouch(Node.EventType.TOUCH_START, touch, live()));- }- if (!touch) continue;- if (p.down && (c.worldX !== touch.getUILocationX() || c.worldY !== touch.getUILocationY())) {- touch._move(c.worldX, c.worldY, c.screenX, c.screenY);- globalInput.emit(Node.EventType.TOUCH_MOVE, new EventTouch(Node.EventType.TOUCH_MOVE, touch, live()));- }- if (p.released) {- touch._move(c.worldX, c.worldY, c.screenX, c.screenY);- const type = p.cancelled ? Node.EventType.TOUCH_CANCEL : Node.EventType.TOUCH_END;- globalInput.emit(type, new EventTouch(type, touch, live()));- globalTouches.delete(p.id);- }- }-}--// ----------------------------------------------------------------------------------------------------------------------// Keyboard and mouse, to the global `input`.-// -----------------------------------------------------------------------------------------------------------------------/** Where each input state's mouse was last frame, so a move is a change and the first frame is not one. */-const lastMouseOf = new WeakMap<InputState, { x: number; y: number }>();--/**- * Turn this frame's key, button and wheel state into events on the global `input`. @p mouse is the engine's resolved mouse pointer- * (null when there is none, as on a touch device), which is where the position comes from.- */-export function pumpKeysAndMouse(input: InputState, mouse: ControlPointer | null): void {- for (const code of input.keysPressed) globalInput.emit(InputApi.EventType.KEY_DOWN, new EventKeyboard(keyCodeOf(code), InputApi.EventType.KEY_DOWN));- for (const code of input.keysDown) {- if (!input.keysPressed.has(code)) globalInput.emit(InputApi.EventType.KEY_PRESSING, new EventKeyboard(keyCodeOf(code), InputApi.EventType.KEY_PRESSING));- }- for (const code of input.keysReleased) globalInput.emit(InputApi.EventType.KEY_UP, new EventKeyboard(keyCodeOf(code), InputApi.EventType.KEY_UP));-- const at = mouse ? { x: mouse.worldX, y: mouse.worldY, sx: mouse.screenX, sy: mouse.screenY } : { x: 0, y: 0, sx: 0, sy: 0 };- const lastMouse = lastMouseOf.get(input);- const previous = lastMouse ?? at;- const moved = lastMouse !== undefined && (at.x !== lastMouse.x || at.y !== lastMouse.y);- const prev = new Vec2(previous.x, previous.y);- const event = (type: string): EventMouse => new EventMouse(type, at.x, at.y, prev, at.sx, at.sy);- for (const b of input.mouseButtonsPressed) globalInput.emit(InputApi.EventType.MOUSE_DOWN, event(InputApi.EventType.MOUSE_DOWN)._button(b));- if (moved) globalInput.emit(InputApi.EventType.MOUSE_MOVE, event(InputApi.EventType.MOUSE_MOVE));- for (const b of input.mouseButtonsReleased) globalInput.emit(InputApi.EventType.MOUSE_UP, event(InputApi.EventType.MOUSE_UP)._button(b));- if (input.scrollDeltaX !== 0 || input.scrollDeltaY !== 0) {- // Cocos reports a wheel turned away from the player as positive; a DOM delta is the other way.- globalInput.emit(InputApi.EventType.MOUSE_WHEEL, event(InputApi.EventType.MOUSE_WHEEL)._scroll(-input.scrollDeltaX, -input.scrollDeltaY));- }- lastMouseOf.set(input, { x: at.x, y: at.y });-}--/**- * Register the systems that wire Cocos touches to the engine's pointer: one before the engine's UI interaction pass that makes- * listening nodes interactable and subscribes to its events, one after it that feeds the global `input`.- */-export function declareInputSystem(): void {- addSystemToSchedule(Schedule.PreUpdate, defineSystem(- [Res(EntityEvents), Res(UIControlPointers), GetWorld()],- (events, controls, world) => {- syncInteractables(world);- // subscribed before the interaction pass, so the very first press already reaches a node- if (events) subscribe(world, events as EntityEventQueue, controls);- },- { name: 'Cocos:Interactables', touches: { opaque: true }, runBefore: [SystemLabel.UIInteraction] },- ));- addSystemToSchedule(Schedule.PreUpdate, defineSystem(- [Res(Input), Res(EntityEvents), Res(UIControlPointers), GetWorld()],- (input, events, controls, world) => {- if (!events) return; // no UI pipeline: nothing resolves a pointer- pumpGlobalTouches(world, input, controls);- pumpKeysAndMouse(input, controls.pointers.get(MOUSE_POINTER) ?? null);- },- { name: 'Cocos:Input', touches: { opaque: true }, runAfter: [SystemLabel.UIInteraction] },- ));-}diff --git a/sdk/src/cocos/inputApi.ts b/sdk/src/cocos/inputApi.tsdeleted file mode 100644index e071f1cf8..000000000--- a/sdk/src/cocos/inputApi.ts+++ /dev/null@@ -1,124 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/inputApi.ts- * @brief The global `input`: `input.on(Input.EventType.KEY_DOWN, ...)`, the event classes it delivers, and `KeyCode`.- *- * Unlike a touch listener on a node, a listener on `input` hears every event whether or not anything is under the pointer. The- * frame's pointer, key and wheel state is turned into these events by the input system (input.ts); this file is the vocabulary:- * the event names, `KeyCode` with the numbers Cocos uses, and the objects a handler receives.- *- * `KeyCode` has one entry per physical key, and the engine names keys by their DOM `code` (`'KeyA'`, `'ArrowUp'`), so the table- * below is the pairing of the two; a key the table lacks is delivered as `KeyCode.NONE`.- */-import { Emitter } from './emitter';-import { Vec2 } from './math';--const KEYS: Array<[name: string, value: number, code: string]> = [];-const key = (name: string, value: number, code: string): void => { KEYS.push([name, value, code]); };--for (let i = 0; i < 26; i++) { const c = String.fromCharCode(65 + i); key(`KEY_${c}`, 65 + i, `Key${c}`); }-for (let i = 0; i < 10; i++) { key(`DIGIT_${i}`, 48 + i, `Digit${i}`); key(`NUM_${i}`, 96 + i, `Numpad${i}`); }-for (let i = 1; i <= 12; i++) key(`F${i}`, 111 + i, `F${i}`);-key('ARROW_LEFT', 37, 'ArrowLeft'); key('ARROW_UP', 38, 'ArrowUp'); key('ARROW_RIGHT', 39, 'ArrowRight'); key('ARROW_DOWN', 40, 'ArrowDown');-key('SPACE', 32, 'Space'); key('ENTER', 13, 'Enter'); key('ESCAPE', 27, 'Escape'); key('TAB', 9, 'Tab'); key('BACKSPACE', 8, 'Backspace');-key('DELETE', 46, 'Delete'); key('INSERT', 45, 'Insert'); key('HOME', 36, 'Home'); key('END', 35, 'End');-key('PAGE_UP', 33, 'PageUp'); key('PAGE_DOWN', 34, 'PageDown'); key('CAPS_LOCK', 20, 'CapsLock');-key('SHIFT_LEFT', 1016, 'ShiftLeft'); key('SHIFT_RIGHT', 2016, 'ShiftRight');-key('CTRL_LEFT', 1017, 'ControlLeft'); key('CTRL_RIGHT', 2017, 'ControlRight');-key('ALT_LEFT', 1018, 'AltLeft'); key('ALT_RIGHT', 2018, 'AltRight');-key('SEMICOLON', 186, 'Semicolon'); key('EQUAL', 187, 'Equal'); key('COMMA', 188, 'Comma'); key('DASH', 189, 'Minus');-key('PERIOD', 190, 'Period'); key('SLASH', 191, 'Slash'); key('BACKQUOTE', 192, 'Backquote'); key('BRACKET_LEFT', 219, 'BracketLeft');-key('BACKSLASH', 220, 'Backslash'); key('BRACKET_RIGHT', 221, 'BracketRight'); key('QUOTE', 222, 'Quote');-key('NUM_ADD', 107, 'NumpadAdd'); key('NUM_SUBTRACT', 109, 'NumpadSubtract'); key('NUM_MULTIPLY', 106, 'NumpadMultiply');-key('NUM_DIVIDE', 111, 'NumpadDivide'); key('NUM_DECIMAL', 110, 'NumpadDecimal'); key('NUM_LOCK', 144, 'NumLock');--export const KeyCode: Readonly<Record<string, number>> = Object.freeze({- NONE: 0,- ...Object.fromEntries(KEYS.map(([name, value]) => [name, value])),-});--const CODE_TO_KEYCODE = new Map(KEYS.map(([, value, code]) => [code, value]));--/** The Cocos key code of a DOM key `code`; `KeyCode.NONE` for a key the table lacks. */-export function keyCodeOf(domCode: string): number { return CODE_TO_KEYCODE.get(domCode) ?? 0; }--const EventType = Object.freeze({- TOUCH_START: 'touch-start',- TOUCH_MOVE: 'touch-move',- TOUCH_END: 'touch-end',- TOUCH_CANCEL: 'touch-cancel',- MOUSE_DOWN: 'mouse-down',- MOUSE_MOVE: 'mouse-move',- MOUSE_UP: 'mouse-up',- MOUSE_WHEEL: 'mouse-wheel',- KEY_DOWN: 'keydown',- KEY_PRESSING: 'key-pressing',- KEY_UP: 'keyup',- DEVICEMOTION: 'devicemotion',- GAMEPAD_INPUT: 'gamepad-input',- GAMEPAD_CHANGE: 'gamepad-change',- HANDLE_INPUT: 'handle-input',- HMD_INPUT: 'hmd-input',-});--export class EventKeyboard {- stopped = false;- constructor(public readonly keyCode: number, public readonly type: string) {}- get isPressed(): boolean { return this.type !== EventType.KEY_UP; }- stopPropagation(): void { this.stopped = true; }- stopPropagationImmediate(): void { this.stopped = true; }-}--export class EventMouse {- static readonly BUTTON_LEFT = 0;- static readonly BUTTON_MIDDLE = 1;- static readonly BUTTON_RIGHT = 2;- stopped = false;- private readonly location_: Vec2;- private prev_: Vec2;- private readonly screen_: Vec2;- private scrollX_ = 0;- private scrollY_ = 0;- private button_ = 0;-- /** @p x / @p y are the canvas (UI) point, @p sx / @p sy the screen point (pixels of the surface, origin bottom-left). */- constructor(public readonly type: string, x = 0, y = 0, prev?: Vec2, sx: number = x, sy: number = y) {- this.location_ = new Vec2(x, y);- this.prev_ = prev ?? new Vec2(x, y);- this.screen_ = new Vec2(sx, sy);- }-- /** @internal */ _button(b: number): this { this.button_ = b; return this; }- /** @internal */ _scroll(x: number, y: number): this { this.scrollX_ = x; this.scrollY_ = y; return this; }-- getButton(): number { return this.button_; }- getLocation(out: Vec2 = new Vec2()): Vec2 { return out.set(this.screen_.x, this.screen_.y); }- getLocationX(): number { return this.screen_.x; }- getLocationY(): number { return this.screen_.y; }- getUILocation(out: Vec2 = new Vec2()): Vec2 { return out.set(this.location_.x, this.location_.y); }- getUILocationX(): number { return this.location_.x; }- getUILocationY(): number { return this.location_.y; }- getPreviousLocation(out: Vec2 = new Vec2()): Vec2 { return out.set(this.prev_.x, this.prev_.y); }- getDelta(out: Vec2 = new Vec2()): Vec2 { return out.set(this.location_.x - this.prev_.x, this.location_.y - this.prev_.y); }- getDeltaX(): number { return this.location_.x - this.prev_.x; }- getDeltaY(): number { return this.location_.y - this.prev_.y; }- getScrollX(): number { return this.scrollX_; }- getScrollY(): number { return this.scrollY_; }- stopPropagation(): void { this.stopped = true; }- stopPropagationImmediate(): void { this.stopped = true; }-}--class InputTarget extends Emitter {- static readonly EventType = EventType;- readonly EventType = EventType;- /** Whether the device sends orientation / motion; there is no sensor feed behind it. */- setAccelerometerEnabled(_enabled: boolean): void { /* no sensor source */ }- setAccelerometerInterval(_interval: number): void { /* no sensor source */ }- /** Cocos's private hook for a game that routes input itself. Input here is the engine's pointer pipeline, which nothing else dispatches. */- _registerEventDispatcher(_dispatcher: unknown): void { /* the engine dispatches */ }-}--/** The `Input` class scripts name for its `EventType`, and the instance `input`. */-export const Input = InputTarget;-export const input = new InputTarget();diff --git a/sdk/src/cocos/layers.ts b/sdk/src/cocos/layers.tsdeleted file mode 100644index 72f386526..000000000--- a/sdk/src/cocos/layers.ts+++ /dev/null@@ -1,53 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/layers.ts- * @brief `Layers`: the layer bitmask names (`Layers.Enum.UI_2D`), with Cocos's numbers.- *- * A node's `layer` is carried as the number a script set; the engine does not cull by it. The numbers matter because scripts- * compare and combine them (`node.layer & Layers.Enum.UI_2D`).- */-const Enum = {- NONE: 0,- IGNORE_RAYCAST: 1 << 20,- GIZMOS: 1 << 21,- EDITOR: 1 << 22,- UI_3D: 1 << 23,- SCENE_GIZMO: 1 << 24,- UI_2D: 1 << 25,- PROFILER: 1 << 28,- DEFAULT: 1 << 30,- ALL: 0xffffffff,-} as Record<string, number>;--const names = new Map<string, number>(Object.entries(Enum));-const bits = new Map<number, string>(Object.entries(Enum).map(([k, v]) => [v, k]));--export const Layers = {- Enum,- BitMask: Enum,- /** The mask of a layer's name, or undefined when there is none. */- nameToLayer(name: string): number | undefined { return names.get(name); },- layerToName(layer: number): string | undefined { return bits.get(layer); },- /** Name a user layer (bit 0..19). */- addLayer(name: string, bitNum: number): void {- if (bitNum < 0 || bitNum > 19 || names.has(name)) return;- const value = 1 << bitNum;- Enum[name] = value;- names.set(name, value);- bits.set(value, name);- },- deleteLayer(bitNum: number): void {- const value = 1 << bitNum;- const name = bits.get(value);- if (name === undefined) return;- delete Enum[name];- names.delete(name);- bits.delete(value);- },- /** A mask with the given layer names set. */- makeMaskInclude(includes: number[]): number { return includes.reduce((a, b) => a | b, 0); },- /** A mask with everything but the given layers set. */- makeMaskExclude(excludes: number[]): number { return ~excludes.reduce((a, b) => a | b, 0); },- check(layer: number, mask: number): boolean { return (layer & mask) !== 0; },-};diff --git a/sdk/src/cocos/macro.ts b/sdk/src/cocos/macro.tsdeleted file mode 100644index 4b32de344..000000000--- a/sdk/src/cocos/macro.ts+++ /dev/null@@ -1,49 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/macro.ts- * @brief `macro`: the constants and engine switches a Cocos script reads.- *- * The values are Cocos's. The ones that are switches in Cocos (`ENABLE_MULTI_TOUCH`, the antialiasing flags) are plain properties- * here, so reading and writing them works; whether they change anything is the engine's own configuration, not this object's.- */-export const macro = {- /** `repeat` count that means forever. */- REPEAT_FOREVER: Number.MAX_VALUE - 1,- INVALID_INDEX: -1,- NODE_TAG_INVALID: -1,- PI: Math.PI,- PI2: Math.PI * 2,- FLT_MAX: Number.MAX_VALUE,- FLT_MIN: Number.MIN_VALUE,- RAD: Math.PI / 180,- DEG: 180 / Math.PI,- UINT_MAX: 0xffffffff,-- ENABLE_MULTI_TOUCH: true,- ENABLE_TILEDMAP_CULLING: true,- ENABLE_TRANSPARENT_CANVAS: false,- ENABLE_WEBGL_ANTIALIAS: true,- ENABLE_ANTIALIAS_FXAA: false,- ENABLE_BLOOM: false,- ENABLE_WEBGL_HIGHP_STRUCT_VALUES: false,- ENABLE_CULLING: false,- CLEANUP_IMAGE_CACHE: false,- SHOW_MESH_WIREFRAME: false,- SHOW_MESH_NORMAL: false,- ALLOW_IMAGE_BITMAP: true,- DOWNLOAD_MAX_CONCURRENT: 64,- BATCHER2D_MEM_INCREMENT: 144,- CUSTOM_PIPELINE_NAME: '',- SUPPORT_TEXTURE_FORMATS: ['.astc', '.pkm', '.pvr', '.webp', '.jpg', '.jpeg', '.bmp', '.png'],-- ORIENTATION_PORTRAIT: 1,- ORIENTATION_LANDSCAPE: 2,- ORIENTATION_AUTO: 3,-- TextAlignment: Object.freeze({ LEFT: 0, CENTER: 1, RIGHT: 2 }),- VerticalTextAlignment: Object.freeze({ TOP: 0, CENTER: 1, BOTTOM: 2 }),-- /** Cocos reads these from a settings file; scripts rarely set them, and a script that does gets what it set back. */- FIX_ARTIFACTS_BY_STRECHING_TEXEL_TMX: true,-};diff --git a/sdk/src/cocos/mat4.ts b/sdk/src/cocos/mat4.tsdeleted file mode 100644index 00374e23b..000000000--- a/sdk/src/cocos/mat4.ts+++ /dev/null@@ -1,215 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/mat4.ts- * @brief `Vec4` and `Mat4`, with Cocos's layout.- *- * `Mat4.m00..m03` is the first COLUMN, so the translation is `m12, m13, m14` and a point is transformed as `M * p`. The static- * forms write to `out` and return it, as the other value types do.- */-import { Quat, Vec3 } from './math';--export class Vec4 {- static readonly ZERO = Object.freeze(new Vec4(0, 0, 0, 0)) as Vec4;- static readonly ONE = Object.freeze(new Vec4(1, 1, 1, 1)) as Vec4;-- constructor(public x = 0, public y = 0, public z = 0, public w = 0) {}-- set(x: number | Vec4, y?: number, z?: number, w?: number): this {- if (typeof x === 'object') { this.x = x.x; this.y = x.y; this.z = x.z; this.w = x.w; } else { this.x = x; this.y = y ?? 0; this.z = z ?? 0; this.w = w ?? 0; }- return this;- }- clone(): Vec4 { return new Vec4(this.x, this.y, this.z, this.w); }- add(v: Vec4): this { this.x += v.x; this.y += v.y; this.z += v.z; this.w += v.w; return this; }- subtract(v: Vec4): this { this.x -= v.x; this.y -= v.y; this.z -= v.z; this.w -= v.w; return this; }- multiplyScalar(s: number): this { this.x *= s; this.y *= s; this.z *= s; this.w *= s; return this; }- length(): number { return Math.hypot(this.x, this.y, this.z, this.w); }- lengthSqr(): number { return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; }- normalize(): this { const l = this.length(); if (l > 0) { this.x /= l; this.y /= l; this.z /= l; this.w /= l; } return this; }- dot(v: Vec4): number { return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; }- equals(v: Vec4, epsilon = 1e-6): boolean {- return Math.abs(this.x - v.x) <= epsilon && Math.abs(this.y - v.y) <= epsilon && Math.abs(this.z - v.z) <= epsilon && Math.abs(this.w - v.w) <= epsilon;- }- toString(): string { return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)}, ${this.z.toFixed(2)}, ${this.w.toFixed(2)})`; }-- static copy(out: Vec4, a: Vec4): Vec4 { out.x = a.x; out.y = a.y; out.z = a.z; out.w = a.w; return out; }- static toArray<T extends number[]>(out: T, v: Vec4, ofs = 0): T { out[ofs] = v.x; out[ofs + 1] = v.y; out[ofs + 2] = v.z; out[ofs + 3] = v.w; return out; }- static fromArray(out: Vec4, arr: ArrayLike<number>, ofs = 0): Vec4 { out.x = arr[ofs]!; out.y = arr[ofs + 1]!; out.z = arr[ofs + 2]!; out.w = arr[ofs + 3]!; return out; }- static add(out: Vec4, a: Vec4, b: Vec4): Vec4 { out.x = a.x + b.x; out.y = a.y + b.y; out.z = a.z + b.z; out.w = a.w + b.w; return out; }- static subtract(out: Vec4, a: Vec4, b: Vec4): Vec4 { out.x = a.x - b.x; out.y = a.y - b.y; out.z = a.z - b.z; out.w = a.w - b.w; return out; }- static lerp(out: Vec4, a: Vec4, b: Vec4, t: number): Vec4 {- out.x = a.x + (b.x - a.x) * t; out.y = a.y + (b.y - a.y) * t; out.z = a.z + (b.z - a.z) * t; out.w = a.w + (b.w - a.w) * t;- return out;- }- static transformMat4(out: Vec4, a: Vec4, m: Mat4): Vec4 {- const { x, y, z, w } = a;- out.x = m.m00 * x + m.m04 * y + m.m08 * z + m.m12 * w;- out.y = m.m01 * x + m.m05 * y + m.m09 * z + m.m13 * w;- out.z = m.m02 * x + m.m06 * y + m.m10 * z + m.m14 * w;- out.w = m.m03 * x + m.m07 * y + m.m11 * z + m.m15 * w;- return out;- }-}--type Sixteen = [number, number, number, number, number, number, number, number, number, number, number, number, number, number, number, number];--export class Mat4 {- static readonly IDENTITY = Object.freeze(new Mat4()) as Mat4;-- constructor(- public m00 = 1, public m01 = 0, public m02 = 0, public m03 = 0,- public m04 = 0, public m05 = 1, public m06 = 0, public m07 = 0,- public m08 = 0, public m09 = 0, public m10 = 1, public m11 = 0,- public m12 = 0, public m13 = 0, public m14 = 0, public m15 = 1,- ) {}-- private a_(): Sixteen {- return [this.m00, this.m01, this.m02, this.m03, this.m04, this.m05, this.m06, this.m07, this.m08, this.m09, this.m10, this.m11, this.m12, this.m13, this.m14, this.m15];- }- private load_(a: ArrayLike<number>): this {- this.m00 = a[0]!; this.m01 = a[1]!; this.m02 = a[2]!; this.m03 = a[3]!;- this.m04 = a[4]!; this.m05 = a[5]!; this.m06 = a[6]!; this.m07 = a[7]!;- this.m08 = a[8]!; this.m09 = a[9]!; this.m10 = a[10]!; this.m11 = a[11]!;- this.m12 = a[12]!; this.m13 = a[13]!; this.m14 = a[14]!; this.m15 = a[15]!;- return this;- }-- set(other: Mat4): this { return this.load_(other.a_()); }- clone(): Mat4 { return new Mat4().load_(this.a_()); }- identity(): this { return this.load_([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); }- equals(o: Mat4, epsilon = 1e-6): boolean { const a = this.a_(), b = o.a_(); return a.every((v, i) => Math.abs(v - b[i]!) <= epsilon); }- toArray(out: number[] = []): number[] { const a = this.a_(); for (let i = 0; i < 16; i++) out[i] = a[i]!; return out; }-- determinant(): number {- const [a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23, a30, a31, a32, a33] = this.a_();- const b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10;- const b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12;- const b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30;- const b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32;- return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;- }-- invert(): this { Mat4.invert(this, this); return this; }- transpose(): this { Mat4.transpose(this, this); return this; }- multiply(other: Mat4): this { Mat4.multiply(this, this, other); return this; }-- getTranslation(out: Vec3 = new Vec3()): Vec3 { out.x = this.m12; out.y = this.m13; out.z = this.m14; return out; }- getScale(out: Vec3 = new Vec3()): Vec3 {- out.x = Math.hypot(this.m00, this.m01, this.m02);- out.y = Math.hypot(this.m04, this.m05, this.m06);- out.z = Math.hypot(this.m08, this.m09, this.m10);- return out;- }- getRotation(out: Quat = new Quat()): Quat {- const s = this.getScale();- const r00 = this.m00 / s.x, r01 = this.m01 / s.x, r02 = this.m02 / s.x;- const r10 = this.m04 / s.y, r11 = this.m05 / s.y, r12 = this.m06 / s.y;- const r20 = this.m08 / s.z, r21 = this.m09 / s.z, r22 = this.m10 / s.z;- const trace = r00 + r11 + r22;- if (trace > 0) {- const k = Math.sqrt(trace + 1) * 2;- out.w = 0.25 * k; out.x = (r12 - r21) / k; out.y = (r20 - r02) / k; out.z = (r01 - r10) / k;- } else if (r00 > r11 && r00 > r22) {- const k = Math.sqrt(1 + r00 - r11 - r22) * 2;- out.w = (r12 - r21) / k; out.x = 0.25 * k; out.y = (r10 + r01) / k; out.z = (r20 + r02) / k;- } else if (r11 > r22) {- const k = Math.sqrt(1 + r11 - r00 - r22) * 2;- out.w = (r20 - r02) / k; out.x = (r10 + r01) / k; out.y = 0.25 * k; out.z = (r21 + r12) / k;- } else {- const k = Math.sqrt(1 + r22 - r00 - r11) * 2;- out.w = (r01 - r10) / k; out.x = (r20 + r02) / k; out.y = (r21 + r12) / k; out.z = 0.25 * k;- }- return out;- }-- static copy(out: Mat4, a: Mat4): Mat4 { return out.load_(a.a_()); }- static strictEquals(a: Mat4, b: Mat4): boolean { const A = a.a_(), B = b.a_(); return A.every((v, i) => v === B[i]); }- static toArray<T extends number[]>(out: T, m: Mat4, ofs = 0): T { const a = m.a_(); for (let i = 0; i < 16; i++) out[ofs + i] = a[i]!; return out; }- static fromArray(out: Mat4, arr: ArrayLike<number>, ofs = 0): Mat4 {- const a = new Array<number>(16);- for (let i = 0; i < 16; i++) a[i] = arr[ofs + i]!;- return out.load_(a);- }- static getTranslation(out: Vec3, m: Mat4): Vec3 { return m.getTranslation(out); }- static getScaling(out: Vec3, m: Mat4): Vec3 { return m.getScale(out); }- static getRotation(out: Quat, m: Mat4): Quat { return m.getRotation(out); }- /** Rotation, translation and scale composed (the order Cocos's argument list has them in). */- static fromRTS(out: Mat4, q: Quat, t: Vec3, s: Vec3): Mat4 { return Mat4.fromTRS(out, t, q, s); }- /** Take a matrix apart into its rotation, translation and scale. */- static toRTS(m: Mat4, q: Quat, v: Vec3, s: Vec3): void {- m.getScale(s);- m.getTranslation(v);- m.getRotation(q);- }- /** @p a turned by @p rad about Y (applied after @p a's own transform, as gl-matrix does). */- static rotateY(out: Mat4, a: Mat4, rad: number): Mat4 {- const s = Math.sin(rad), c = Math.cos(rad);- return Mat4.multiply(out, a, new Mat4(c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1));- }- static rotateX(out: Mat4, a: Mat4, rad: number): Mat4 {- const s = Math.sin(rad), c = Math.cos(rad);- return Mat4.multiply(out, a, new Mat4(1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1));- }- static rotateZ(out: Mat4, a: Mat4, rad: number): Mat4 {- const s = Math.sin(rad), c = Math.cos(rad);- return Mat4.multiply(out, a, new Mat4(c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1));- }- /** A perspective projection; @p minClipZ is -1 for GL clip space and 0 for the others. */- static perspective(out: Mat4, fov: number, aspect: number, near: number, far: number, isFOVY = true, minClipZ = -1, projectionSignY = 1): Mat4 {- const f = 1 / Math.tan(fov / 2), nf = 1 / (near - far);- const x = isFOVY ? f / aspect : f;- const y = (isFOVY ? f : f * aspect) * projectionSignY;- return out.load_([x, 0, 0, 0, 0, y, 0, 0, 0, 0, (far - minClipZ * near) * nf, -1, 0, 0, far * near * nf * (1 - minClipZ), 0]);- }-- static multiply(out: Mat4, a: Mat4, b: Mat4): Mat4 {- const A = a.a_(), B = b.a_(), R = new Array<number>(16);- for (let col = 0; col < 4; col++) {- for (let row = 0; row < 4; row++) {- let sum = 0;- for (let k = 0; k < 4; k++) sum += A[k * 4 + row]! * B[col * 4 + k]!;- R[col * 4 + row] = sum;- }- }- return out.load_(R);- }-- static transpose(out: Mat4, a: Mat4): Mat4 {- const A = a.a_();- return out.load_([A[0], A[4], A[8], A[12], A[1], A[5], A[9], A[13], A[2], A[6], A[10], A[14], A[3], A[7], A[11], A[15]] as Sixteen);- }-- /** The inverse; a singular matrix leaves @p out as it was. */- static invert(out: Mat4, a: Mat4): Mat4 {- const [a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23, a30, a31, a32, a33] = a.a_();- const b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10;- const b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12;- const b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30;- const b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32;- let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;- if (det === 0) return out;- det = 1 / det;- return out.load_([- (a11 * b11 - a12 * b10 + a13 * b09) * det, (a02 * b10 - a01 * b11 - a03 * b09) * det, (a31 * b05 - a32 * b04 + a33 * b03) * det, (a22 * b04 - a21 * b05 - a23 * b03) * det,- (a12 * b08 - a10 * b11 - a13 * b07) * det, (a00 * b11 - a02 * b08 + a03 * b07) * det, (a32 * b02 - a30 * b05 - a33 * b01) * det, (a20 * b05 - a22 * b02 + a23 * b01) * det,- (a10 * b10 - a11 * b08 + a13 * b06) * det, (a01 * b08 - a00 * b10 - a03 * b06) * det, (a30 * b04 - a31 * b02 + a33 * b00) * det, (a21 * b02 - a20 * b04 - a23 * b00) * det,- (a11 * b07 - a10 * b09 - a12 * b06) * det, (a00 * b09 - a01 * b07 + a02 * b06) * det, (a31 * b01 - a30 * b03 - a32 * b00) * det, (a20 * b03 - a21 * b01 + a22 * b00) * det,- ]);- }-- /** Translation, rotation and scale composed as `T * R * S`. */- static fromTRS(out: Mat4, t: Vec3, q: Quat, s: Vec3): Mat4 {- const { x, y, z, w } = q;- const x2 = x + x, y2 = y + y, z2 = z + z;- const xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2, wx = w * x2, wy = w * y2, wz = w * z2;- return out.load_([- (1 - (yy + zz)) * s.x, (xy + wz) * s.x, (xz - wy) * s.x, 0,- (xy - wz) * s.y, (1 - (xx + zz)) * s.y, (yz + wx) * s.y, 0,- (xz + wy) * s.z, (yz - wx) * s.z, (1 - (xx + yy)) * s.z, 0,- t.x, t.y, t.z, 1,- ]);- }- static fromTranslation(out: Mat4, t: Vec3): Mat4 { return out.load_([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, t.x, t.y, t.z, 1]); }- static fromScaling(out: Mat4, s: Vec3): Mat4 { return out.load_([s.x, 0, 0, 0, 0, s.y, 0, 0, 0, 0, s.z, 0, 0, 0, 0, 1]); }- static fromQuat(out: Mat4, q: Quat): Mat4 { return Mat4.fromTRS(out, Vec3.ZERO, q, Vec3.ONE); }-}diff --git a/sdk/src/cocos/math.ts b/sdk/src/cocos/math.tsdeleted file mode 100644index 0385f0143..000000000--- a/sdk/src/cocos/math.ts+++ /dev/null@@ -1,412 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/math.ts- * @brief The value types a Cocos Creator script reaches for: `Vec2`, `Vec3`, `Quat`, `Color`, `Size`, `Rect`, `math`.- *- * These are classes with public mutable fields, as in Cocos, because that is what the scripts are written against: they- * copy them (`v.clone()`), mutate them in place (`v.x += 1`, `v.add(w)`), and pass an `out` parameter to the static forms.- * They are not the engine's own `{x, y, z}` plain objects, and nothing here touches the engine: a {@link Node} converts at- * its boundary.- */--export class Vec2 {- static readonly ZERO = Object.freeze(new Vec2(0, 0)) as Vec2;- static readonly ONE = Object.freeze(new Vec2(1, 1)) as Vec2;- static readonly UP = Object.freeze(new Vec2(0, 1)) as Vec2;- static readonly RIGHT = Object.freeze(new Vec2(1, 0)) as Vec2;-- constructor(public x = 0, public y = 0) {}-- set(x: number | Vec2, y?: number): this {- if (typeof x === 'object') { this.x = x.x; this.y = x.y; } else { this.x = x; this.y = y ?? 0; }- return this;- }- clone(): Vec2 { return new Vec2(this.x, this.y); }- add(v: Vec2): this { this.x += v.x; this.y += v.y; return this; }- subtract(v: Vec2): this { this.x -= v.x; this.y -= v.y; return this; }- multiplyScalar(s: number): this { this.x *= s; this.y *= s; return this; }- length(): number { return Math.hypot(this.x, this.y); }- lengthSqr(): number { return this.x * this.x + this.y * this.y; }- normalize(): this { const l = this.length(); if (l > 0) { this.x /= l; this.y /= l; } return this; }- dot(v: Vec2): number { return this.x * v.x + this.y * v.y; }- lerp(to: Vec2, ratio: number): this { this.x += (to.x - this.x) * ratio; this.y += (to.y - this.y) * ratio; return this; }- multiply(v: Vec2): this { this.x *= v.x; this.y *= v.y; return this; }- angle(v: Vec2): number { return Vec2.angle(this, v); }- equals(v: Vec2, epsilon = 1e-6): boolean { return Math.abs(this.x - v.x) <= epsilon && Math.abs(this.y - v.y) <= epsilon; }- toString(): string { return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)})`; }-- static distance(a: Vec2, b: Vec2): number { return Math.hypot(a.x - b.x, a.y - b.y); }- static add(out: Vec2, a: Vec2, b: Vec2): Vec2 { out.x = a.x + b.x; out.y = a.y + b.y; return out; }- static subtract(out: Vec2, a: Vec2, b: Vec2): Vec2 { out.x = a.x - b.x; out.y = a.y - b.y; return out; }- static multiplyScalar(out: Vec2, a: Vec2, s: number): Vec2 { out.x = a.x * s; out.y = a.y * s; return out; }- static lerp(out: Vec2, a: Vec2, b: Vec2, t: number): Vec2 { out.x = a.x + (b.x - a.x) * t; out.y = a.y + (b.y - a.y) * t; return out; }- static set(out: Vec2, x: number, y: number): Vec2 { out.x = x; out.y = y; return out; }- static copy(out: Vec2, a: Vec2): Vec2 { out.x = a.x; out.y = a.y; return out; }- static len(a: Vec2): number { return Math.hypot(a.x, a.y); }- static dot(a: Vec2, b: Vec2): number { return a.x * b.x + a.y * b.y; }- static squaredDistance(a: Vec2, b: Vec2): number { return (a.x - b.x) ** 2 + (a.y - b.y) ** 2; }- /** The angle between two vectors, in radians; 0 if either has no length. */- static angle(a: Vec2, b: Vec2): number {- const m = Math.hypot(a.x, a.y) * Math.hypot(b.x, b.y);- return m === 0 ? 0 : Math.acos(Math.min(Math.max((a.x * b.x + a.y * b.y) / m, -1), 1));- }- static normalize(out: Vec2, a: Vec2): Vec2 { out.x = a.x; out.y = a.y; return out.normalize(); }-}--export class Vec3 {- static readonly ZERO = Object.freeze(new Vec3(0, 0, 0)) as Vec3;- static readonly ONE = Object.freeze(new Vec3(1, 1, 1)) as Vec3;- static readonly UP = Object.freeze(new Vec3(0, 1, 0)) as Vec3;- static readonly RIGHT = Object.freeze(new Vec3(1, 0, 0)) as Vec3;- static readonly FORWARD = Object.freeze(new Vec3(0, 0, -1)) as Vec3;-- constructor(public x = 0, public y = 0, public z = 0) {}-- set(x: number | Vec3, y?: number, z?: number): this {- if (typeof x === 'object') { this.x = x.x; this.y = x.y; this.z = x.z; } else { this.x = x; this.y = y ?? 0; this.z = z ?? 0; }- return this;- }- clone(): Vec3 { return new Vec3(this.x, this.y, this.z); }- /** A vector turned by a unit quaternion. */- static transformQuat(out: Vec3, a: Vec3, q: { x: number; y: number; z: number; w: number }): Vec3 {- const ix = q.w * a.x + q.y * a.z - q.z * a.y;- const iy = q.w * a.y + q.z * a.x - q.x * a.z;- const iz = q.w * a.z + q.x * a.y - q.y * a.x;- const iw = -q.x * a.x - q.y * a.y - q.z * a.z;- out.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;- out.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;- out.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;- return out;- }- /** A point through a matrix (w = 1), with the perspective divide. */- static transformMat4(out: Vec3, a: Vec3, m: { m00: number; m01: number; m02: number; m03: number; m04: number; m05: number; m06: number; m07: number; m08: number; m09: number; m10: number; m11: number; m12: number; m13: number; m14: number; m15: number }): Vec3 {- const x = a.x, y = a.y, z = a.z;- let w = m.m03 * x + m.m07 * y + m.m11 * z + m.m15;- w = w ? 1 / w : 1;- out.x = (m.m00 * x + m.m04 * y + m.m08 * z + m.m12) * w;- out.y = (m.m01 * x + m.m05 * y + m.m09 * z + m.m13) * w;- out.z = (m.m02 * x + m.m06 * y + m.m10 * z + m.m14) * w;- return out;- }- add(v: Vec3): this { this.x += v.x; this.y += v.y; this.z += v.z; return this; }- subtract(v: Vec3): this { this.x -= v.x; this.y -= v.y; this.z -= v.z; return this; }- multiplyScalar(s: number): this { this.x *= s; this.y *= s; this.z *= s; return this; }- negative(): this { this.x = -this.x; this.y = -this.y; this.z = -this.z; return this; }- length(): number { return Math.hypot(this.x, this.y, this.z); }- lengthSqr(): number { return this.x * this.x + this.y * this.y + this.z * this.z; }- normalize(): this { const l = this.length(); if (l > 0) { this.x /= l; this.y /= l; this.z /= l; } return this; }- dot(v: Vec3): number { return this.x * v.x + this.y * v.y + this.z * v.z; }- cross(v: Vec3): this {- const { x, y, z } = this;- this.x = y * v.z - z * v.y; this.y = z * v.x - x * v.z; this.z = x * v.y - y * v.x;- return this;- }- lerp(to: Vec3, ratio: number): this { this.x += (to.x - this.x) * ratio; this.y += (to.y - this.y) * ratio; this.z += (to.z - this.z) * ratio; return this; }- multiply(v: Vec3): this { this.x *= v.x; this.y *= v.y; this.z *= v.z; return this; }- divide(v: Vec3): this { this.x /= v.x; this.y /= v.y; this.z /= v.z; return this; }- clampf(min: Vec3, max: Vec3): this {- this.x = Math.min(Math.max(this.x, min.x), max.x); this.y = Math.min(Math.max(this.y, min.y), max.y); this.z = Math.min(Math.max(this.z, min.z), max.z);- return this;- }- /** The angle to @p v, in radians; 0 if either has no length. */- angle(v: Vec3): number { return Vec3.angle(this, v); }- strictEquals(v: Vec3): boolean { return this.x === v.x && this.y === v.y && this.z === v.z; }- equals(v: Vec3, epsilon = 1e-6): boolean {- return Math.abs(this.x - v.x) <= epsilon && Math.abs(this.y - v.y) <= epsilon && Math.abs(this.z - v.z) <= epsilon;- }- toString(): string { return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)}, ${this.z.toFixed(2)})`; }-- static distance(a: Vec3, b: Vec3): number { return Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z); }- static add(out: Vec3, a: Vec3, b: Vec3): Vec3 { out.x = a.x + b.x; out.y = a.y + b.y; out.z = a.z + b.z; return out; }- static subtract(out: Vec3, a: Vec3, b: Vec3): Vec3 { out.x = a.x - b.x; out.y = a.y - b.y; out.z = a.z - b.z; return out; }- static multiplyScalar(out: Vec3, a: Vec3, s: number): Vec3 { out.x = a.x * s; out.y = a.y * s; out.z = a.z * s; return out; }- static copy(out: Vec3, a: Vec3): Vec3 { out.x = a.x; out.y = a.y; out.z = a.z; return out; }- static normalize(out: Vec3, a: Vec3): Vec3 { out.set(a); return out.normalize(); }- static lerp(out: Vec3, a: Vec3, b: Vec3, t: number): Vec3 {- out.x = a.x + (b.x - a.x) * t; out.y = a.y + (b.y - a.y) * t; out.z = a.z + (b.z - a.z) * t;- return out;- }- static clone(a: Vec3): Vec3 { return new Vec3(a.x, a.y, a.z); }- static set(out: Vec3, x: number, y: number, z: number): Vec3 { out.x = x; out.y = y; out.z = z; return out; }- static zero(out: Vec3): Vec3 { out.x = 0; out.y = 0; out.z = 0; return out; }- static len(a: Vec3): number { return Math.hypot(a.x, a.y, a.z); }- static lengthSqr(a: Vec3): number { return a.x * a.x + a.y * a.y + a.z * a.z; }- static squaredDistance(a: Vec3, b: Vec3): number { return (a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2; }- static dot(a: Vec3, b: Vec3): number { return a.x * b.x + a.y * b.y + a.z * b.z; }- static multiply(out: Vec3, a: Vec3, b: Vec3): Vec3 { out.x = a.x * b.x; out.y = a.y * b.y; out.z = a.z * b.z; return out; }- static divide(out: Vec3, a: Vec3, b: Vec3): Vec3 { out.x = a.x / b.x; out.y = a.y / b.y; out.z = a.z / b.z; return out; }- static negate(out: Vec3, a: Vec3): Vec3 { out.x = -a.x; out.y = -a.y; out.z = -a.z; return out; }- static inverse(out: Vec3, a: Vec3): Vec3 { out.x = 1 / a.x; out.y = 1 / a.y; out.z = 1 / a.z; return out; }- static min(out: Vec3, a: Vec3, b: Vec3): Vec3 { out.x = Math.min(a.x, b.x); out.y = Math.min(a.y, b.y); out.z = Math.min(a.z, b.z); return out; }- static max(out: Vec3, a: Vec3, b: Vec3): Vec3 { out.x = Math.max(a.x, b.x); out.y = Math.max(a.y, b.y); out.z = Math.max(a.z, b.z); return out; }- static clampf(out: Vec3, a: Vec3, min: Vec3, max: Vec3): Vec3 {- out.x = Math.min(Math.max(a.x, min.x), max.x); out.y = Math.min(Math.max(a.y, min.y), max.y); out.z = Math.min(Math.max(a.z, min.z), max.z);- return out;- }- /** @p a plus @p b scaled by @p scale. */- static scaleAndAdd(out: Vec3, a: Vec3, b: Vec3, scale: number): Vec3 {- out.x = a.x + b.x * scale; out.y = a.y + b.y * scale; out.z = a.z + b.z * scale;- return out;- }- static cross(out: Vec3, a: Vec3, b: Vec3): Vec3 {- const x = a.y * b.z - a.z * b.y, y = a.z * b.x - a.x * b.z, z = a.x * b.y - a.y * b.x;- out.x = x; out.y = y; out.z = z;- return out;- }- /** The angle between two vectors, in radians; 0 if either has no length. */- static angle(a: Vec3, b: Vec3): number {- const m = Math.hypot(a.x, a.y, a.z) * Math.hypot(b.x, b.y, b.z);- return m === 0 ? 0 : Math.acos(Math.min(Math.max((a.x * b.x + a.y * b.y + a.z * b.z) / m, -1), 1));- }- static equals(a: Vec3, b: Vec3, epsilon = 1e-6): boolean {- return Math.abs(a.x - b.x) <= epsilon * Math.max(1, Math.abs(a.x), Math.abs(b.x))- && Math.abs(a.y - b.y) <= epsilon * Math.max(1, Math.abs(a.y), Math.abs(b.y))- && Math.abs(a.z - b.z) <= epsilon * Math.max(1, Math.abs(a.z), Math.abs(b.z));- }- static strictEquals(a: Vec3, b: Vec3): boolean { return a.x === b.x && a.y === b.y && a.z === b.z; }- static toArray<T extends number[]>(out: T, v: Vec3, ofs = 0): T { out[ofs] = v.x; out[ofs + 1] = v.y; out[ofs + 2] = v.z; return out; }- static fromArray(out: Vec3, arr: ArrayLike<number>, ofs = 0): Vec3 { out.x = arr[ofs]!; out.y = arr[ofs + 1]!; out.z = arr[ofs + 2]!; return out; }-}--export class Quat {- static readonly IDENTITY = Object.freeze(new Quat(0, 0, 0, 1)) as Quat;-- constructor(public x = 0, public y = 0, public z = 0, public w = 1) {}-- set(x: number | Quat, y?: number, z?: number, w?: number): this {- if (typeof x === 'object') { this.x = x.x; this.y = x.y; this.z = x.z; this.w = x.w; } else {- this.x = x; this.y = y ?? 0; this.z = z ?? 0; this.w = w ?? 1;- }- return this;- }- clone(): Quat { return new Quat(this.x, this.y, this.z, this.w); }-- /** The rotation of @p x, @p y, @p z degrees about those axes — Cocos's own formula, so a script's angles mean what they meant there. */- /** Spherical interpolation from @p a to @p b, written to @p out. */- static slerp(out: Quat, a: Quat, b: Quat, t: number): Quat {- let cosom = a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;- let bx = b.x, by = b.y, bz = b.z, bw = b.w;- if (cosom < 0) { cosom = -cosom; bx = -bx; by = -by; bz = -bz; bw = -bw; }- let scale0 = 1 - t, scale1 = t;- if (1 - cosom > 1e-6) {- const omega = Math.acos(cosom);- const sinom = Math.sin(omega);- scale0 = Math.sin((1 - t) * omega) / sinom;- scale1 = Math.sin(t * omega) / sinom;- }- out.x = scale0 * a.x + scale1 * bx;- out.y = scale0 * a.y + scale1 * by;- out.z = scale0 * a.z + scale1 * bz;- out.w = scale0 * a.w + scale1 * bw;- return out;- }-- static fromEuler(out: Quat, x: number, y: number, z: number): Quat {- const hx = (x * Math.PI) / 360, hy = (y * Math.PI) / 360, hz = (z * Math.PI) / 360;- const sx = Math.sin(hx), cx = Math.cos(hx), sy = Math.sin(hy), cy = Math.cos(hy), sz = Math.sin(hz), cz = Math.cos(hz);- out.x = sx * cy * cz + cx * sy * sz;- out.y = cx * sy * cz + sx * cy * sz;- out.z = cx * cy * sz - sx * sy * cz;- out.w = cx * cy * cz - sx * sy * sz;- return out;- }-- /** The Euler angles, in degrees, of a rotation: Cocos's `Quat.toEuler`, the inverse of {@link Quat.fromEuler} (x in [-90, 90]). */- static toEuler(out: Vec3, q: Quat, outerZ = false): Vec3 {- const { x, y, z, w } = q;- const deg = (r: number): number => (r * 180) / Math.PI;- let bank = 0, heading = 0, attitude = 0;- const test = x * y + z * w;- if (test > 0.499999) {- heading = deg(2 * Math.atan2(x, w));- attitude = 90;- } else if (test < -0.499999) {- heading = -deg(2 * Math.atan2(x, w));- attitude = -90;- } else {- const sqx = x * x, sqy = y * y, sqz = z * z;- bank = deg(Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz));- heading = deg(Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz));- attitude = deg(Math.asin(2 * test));- if (outerZ) {- bank = -180 * Math.sign(bank + 1e-6) + bank;- heading = -180 * Math.sign(heading + 1e-6) + heading;- attitude = 180 * Math.sign(attitude + 1e-6) - attitude;- }- }- out.x = bank; out.y = heading; out.z = attitude;- return out;- }-- static copy(out: Quat, a: Quat): Quat { out.x = a.x; out.y = a.y; out.z = a.z; out.w = a.w; return out; }- static set(out: Quat, x: number, y: number, z: number, w: number): Quat { out.x = x; out.y = y; out.z = z; out.w = w; return out; }- static dot(a: Quat, b: Quat): number { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; }- static normalize(out: Quat, a: Quat): Quat {- const len = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;- if (len > 0) {- const k = 1 / Math.sqrt(len);- out.x = a.x * k; out.y = a.y * k; out.z = a.z * k; out.w = a.w * k;- } else {- out.x = 0; out.y = 0; out.z = 0; out.w = 0;- }- return out;- }- /** The inverse of a rotation (its conjugate over its squared length). */- static invert(out: Quat, a: Quat): Quat {- const dot = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;- const inv = dot ? 1 / dot : 0;- out.x = -a.x * inv; out.y = -a.y * inv; out.z = -a.z * inv; out.w = a.w * inv;- return out;- }- static conjugate(out: Quat, a: Quat): Quat { out.x = -a.x; out.y = -a.y; out.z = -a.z; out.w = a.w; return out; }- static fromAxisAngle(out: Quat, axis: Vec3, rad: number): Quat {- const half = rad * 0.5, s = Math.sin(half);- out.x = s * axis.x; out.y = s * axis.y; out.z = s * axis.z; out.w = Math.cos(half);- return out;- }- /** The rotation that turns +Z to @p view with @p up (default +Y) kept upright, as Cocos's `lookAt` builds it. */- static fromViewUp(out: Quat, view: Vec3, up: Vec3 = Vec3.UP): Quat {- if (view.x * view.x + view.y * view.y + view.z * view.z < 1e-12) return Quat.set(out, 0, 0, 0, 1);- const right = Vec3.normalize(new Vec3(), Vec3.cross(new Vec3(), up, view));- if (right.lengthSqr() < 1e-12) return Quat.set(out, 0, 0, 0, 1);- const upper = Vec3.cross(new Vec3(), view, right);- // the columns right / upper / view, as a rotation matrix- const m00 = right.x, m01 = right.y, m02 = right.z, m03 = upper.x, m04 = upper.y, m05 = upper.z, m06 = view.x, m07 = view.y, m08 = view.z;- const trace = m00 + m04 + m08;- if (trace > 0) {- const k = 0.5 / Math.sqrt(trace + 1);- out.w = 0.25 / k; out.x = (m05 - m07) * k; out.y = (m06 - m02) * k; out.z = (m01 - m03) * k;- } else if (m00 > m04 && m00 > m08) {- const k = 2 * Math.sqrt(1 + m00 - m04 - m08);- out.w = (m05 - m07) / k; out.x = 0.25 * k; out.y = (m01 + m03) / k; out.z = (m06 + m02) / k;- } else if (m04 > m08) {- const k = 2 * Math.sqrt(1 + m04 - m00 - m08);- out.w = (m06 - m02) / k; out.x = (m01 + m03) / k; out.y = 0.25 * k; out.z = (m05 + m07) / k;- } else {- const k = 2 * Math.sqrt(1 + m08 - m00 - m04);- out.w = (m01 - m03) / k; out.x = (m06 + m02) / k; out.y = (m05 + m07) / k; out.z = 0.25 * k;- }- return Quat.normalize(out, out);- }- /** The shortest rotation from direction @p a to direction @p b (both unit length). */- static rotationTo(out: Quat, a: Vec3, b: Vec3): Quat {- const dot = a.dot(b);- if (dot < -0.999999) {- const axis = Vec3.cross(new Vec3(), Vec3.RIGHT, a);- if (axis.length() < 1e-6) Vec3.cross(axis, Vec3.UP, a);- axis.normalize();- return Quat.fromAxisAngle(out, axis, Math.PI);- }- if (dot > 0.999999) return Quat.set(out, 0, 0, 0, 1);- const axis = Vec3.cross(new Vec3(), a, b);- return Quat.normalize(out, Quat.set(out, axis.x, axis.y, axis.z, 1 + dot));- }- static fromArray(out: Quat, arr: ArrayLike<number>, ofs = 0): Quat { out.x = arr[ofs]!; out.y = arr[ofs + 1]!; out.z = arr[ofs + 2]!; out.w = arr[ofs + 3]!; return out; }- static toArray<T extends number[]>(out: T, q: Quat, ofs = 0): T { out[ofs] = q.x; out[ofs + 1] = q.y; out[ofs + 2] = q.z; out[ofs + 3] = q.w; return out; }- static equals(a: Quat, b: Quat, epsilon = 1e-6): boolean {- return Math.abs(a.x - b.x) <= epsilon && Math.abs(a.y - b.y) <= epsilon && Math.abs(a.z - b.z) <= epsilon && Math.abs(a.w - b.w) <= epsilon;- }-- static multiply(out: Quat, a: Quat, b: Quat): Quat {- const x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;- const y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;- const z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;- const w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;- out.x = x; out.y = y; out.z = z; out.w = w;- return out;- }-}--export class Color {- static readonly WHITE = Object.freeze(new Color(255, 255, 255, 255)) as Color;- static readonly BLACK = Object.freeze(new Color(0, 0, 0, 255)) as Color;- static readonly TRANSPARENT = Object.freeze(new Color(0, 0, 0, 0)) as Color;- static readonly GRAY = Object.freeze(new Color(127, 127, 127, 255)) as Color;- static readonly RED = Object.freeze(new Color(255, 0, 0, 255)) as Color;- static readonly GREEN = Object.freeze(new Color(0, 255, 0, 255)) as Color;- static readonly BLUE = Object.freeze(new Color(0, 0, 255, 255)) as Color;- static readonly YELLOW = Object.freeze(new Color(255, 235, 4, 255)) as Color;-- constructor(public r = 0, public g = 0, public b = 0, public a = 255) {}-- set(r: number | Color, g?: number, b?: number, a?: number): this {- if (typeof r === 'object') { this.r = r.r; this.g = r.g; this.b = r.b; this.a = r.a; } else {- this.r = r; this.g = g ?? 0; this.b = b ?? 0; this.a = a ?? 255;- }- return this;- }- clone(): Color { return new Color(this.r, this.g, this.b, this.a); }- equals(c: Color): boolean { return this.r === c.r && this.g === c.g && this.b === c.b && this.a === c.a; }-- /** The channels of @p c as 0..1 floats written to @p out at @p ofs. */- static toArray<T extends number[]>(out: T, c: Color, ofs = 0): T {- out[ofs] = c.r / 255; out[ofs + 1] = c.g / 255; out[ofs + 2] = c.b / 255; out[ofs + 3] = c.a / 255;- return out;- }- static lerp(out: Color, from: Color, to: Color, ratio: number): Color {- out.r = from.r + ratio * (to.r - from.r); out.g = from.g + ratio * (to.g - from.g);- out.b = from.b + ratio * (to.b - from.b); out.a = from.a + ratio * (to.a - from.a);- return out;- }- static copy(out: Color, a: Color): Color { return out.set(a); }- static fromHEX(out: Color, hex: string): Color { return out.fromHEX(hex); }-- /** From `#rgb`, `#rrggbb` or `#rrggbbaa`. */- fromHEX(hex: string): this {- let h = hex.replace(/^#/, '');- if (h.length === 3) h = h.split('').map((c) => c + c).join('');- this.r = Number.parseInt(h.slice(0, 2), 16) || 0;- this.g = Number.parseInt(h.slice(2, 4), 16) || 0;- this.b = Number.parseInt(h.slice(4, 6), 16) || 0;- this.a = h.length >= 8 ? Number.parseInt(h.slice(6, 8), 16) || 0 : 255;- return this;- }- toHEX(fmt: '#rrggbb' | '#rrggbbaa' = '#rrggbb'): string {- const two = (n: number): string => Math.round(Math.max(0, Math.min(255, n))).toString(16).padStart(2, '0');- return `#${two(this.r)}${two(this.g)}${two(this.b)}${fmt === '#rrggbbaa' ? two(this.a) : ''}`;- }-}--export class Size {- constructor(public width = 0, public height = 0) {}- clone(): Size { return new Size(this.width, this.height); }- set(w: number | Size, h?: number): this {- if (typeof w === 'object') { this.width = w.width; this.height = w.height; } else { this.width = w; this.height = h ?? 0; }- return this;- }-}--export class Rect {- constructor(public x = 0, public y = 0, public width = 0, public height = 0) {}- clone(): Rect { return new Rect(this.x, this.y, this.width, this.height); }- contains(p: Vec2): boolean { return p.x >= this.x && p.x <= this.x + this.width && p.y >= this.y && p.y <= this.y + this.height; }- get xMax(): number { return this.x + this.width; }- get yMax(): number { return this.y + this.height; }-}--export function v2(x = 0, y = 0): Vec2 { return new Vec2(x, y); }-export function v3(x = 0, y = 0, z = 0): Vec3 { return new Vec3(x, y, z); }-export function color(r = 0, g = 0, b = 0, a = 255): Color { return new Color(r, g, b, a); }-export function size(width = 0, height = 0): Size { return new Size(width, height); }-export function rect(x = 0, y = 0, width = 0, height = 0): Rect { return new Rect(x, y, width, height); }--/** Cocos's `math` namespace: the scalar helpers its scripts import alongside the value types. */-export const math = {- EPSILON: 1e-6,- toRadian: (degrees: number): number => (degrees * Math.PI) / 180,- toDegree: (radians: number): number => (radians * 180) / Math.PI,- clamp: (v: number, min: number, max: number): number => Math.min(Math.max(v, min), max),- clamp01: (v: number): number => Math.min(Math.max(v, 0), 1),- lerp: (from: number, to: number, t: number): number => from + (to - from) * t,- approx: (a: number, b: number, epsilon = 1e-6): boolean => Math.abs(a - b) <= epsilon,- random: (): number => Math.random(),- randomRange: (min: number, max: number): number => min + Math.random() * (max - min),- randomRangeInt: (min: number, max: number): number => Math.floor(min + Math.random() * (max - min)),- pingPong: (t: number, length: number): number => { const k = t % (length * 2); return length - Math.abs(k - length); },-};-export const toRadian = math.toRadian;-export const toDegree = math.toDegree;-export const clamp = math.clamp;-export const clamp01 = math.clamp01;-export const lerp = math.lerp;diff --git a/sdk/src/cocos/meshRenderer.ts b/sdk/src/cocos/meshRenderer.tsdeleted file mode 100644index 82ec85c60..000000000--- a/sdk/src/cocos/meshRenderer.ts+++ /dev/null@@ -1,114 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/meshRenderer.ts- * @brief `MeshRenderer`, `ModelRenderer` and `UIMeshRenderer`: views on the engine's mesh renderer, and the material calls scripts make through it.- *- * What a script does with a mesh renderer is almost always its material: `getSharedMaterial(0)` to set a property for every renderer that- * shares it, `getMaterialInstance(0)` to set one for this renderer alone. The engine's renderer holds one material handle, so a- * renderer has one material; an instance is the engine's own (`Material.createInstance`), made once and kept on the renderer.- */-import { MeshRenderer as EngineMeshRenderer } from '../ecs/component';-import { Material as EngineMaterial } from '../render/material';-import type { World } from '../ecs/world';-import type { Entity } from '../types';-import { Material } from './assets';-import { Component } from './component';-import { registerBuiltinComponent } from './builtins';-import { toCocosColor, viewAdapter } from './ui/view';--/** The layer's material objects, one per engine material, so the same material is the same object. */-const wrappers = new Map<number, Material>();-function wrap(handle: number): Material | null {- if (handle <= 0) return null;- let m = wrappers.get(handle);- if (!m) {- m = new Material();- m._handle = handle;- wrappers.set(handle, m);- }- return m;-}--/** The names a Cocos effect gives the colour that multiplies what a surface draws. */-const TINT_PROPERTIES = new Set(['mainColor', 'albedo', 'baseColor', 'color']);--/** The base of every renderer that draws a model. */-export class ModelRenderer extends Component {}--export class MeshRenderer extends ModelRenderer {- private instance_ = 0;-- private data_() { return this._world.get(this._entity, EngineMeshRenderer); }- private patch_(fields: Record<string, unknown>): void {- this._world.set(this._entity, EngineMeshRenderer, { ...this.data_(), ...fields } as never);- }-- /** Whether the renderer draws. */- get enabled(): boolean { return this.data_().enabled; }- set enabled(v: boolean) { this.patch_({ enabled: v }); }-- /** The material every renderer sharing it draws with. */- get sharedMaterial(): Material | null { return wrap(this.instance_ > 0 ? this.sourceOf_() : this.data_().material); }- get sharedMaterials(): Material[] { const m = this.sharedMaterial; return m ? [m] : []; }- /** This renderer's own material: the instance when one was made, else the shared one. */- get material(): Material | null { return wrap(this.data_().material); }- set material(m: Material | null) { this.setMaterial(m, 0); }- get materials(): Material[] { const m = this.material; return m ? [m] : []; }- set materials(list: Material[]) { this.setMaterial(list[0] ?? null, 0); }-- getSharedMaterial(index: number): Material | null { return index === 0 ? this.sharedMaterial : null; }- getRenderMaterial(index: number): Material | null { return index === 0 ? this.material : null; }-- /** A material of this renderer alone, made from the shared one the first time and kept after. */- getMaterialInstance(index: number): Material | null {- if (index !== 0) return null;- const current = this.data_().material;- if (current <= 0) return null;- if (this.instance_ <= 0 || this.instance_ !== current) {- this.instance_ = EngineMaterial.createInstance(current);- this.patch_({ material: this.instance_ });- this.source_ = current;- }- const own = wrap(this.instance_)!;- this.bind_(own);- return own;- }-- /** An instance is this renderer's own, so the colour a script gives it is the renderer's tint. */- private bind_(material: Material): void {- material._take = (name, value) => {- if (!TINT_PROPERTIES.has(name) || typeof value !== 'object' || value === null) return false;- const c = value as { r?: number; g?: number; b?: number; a?: number };- if (typeof c.r !== 'number') return false;- this.patch_({ color: { r: c.r / 255, g: c.g! / 255, b: c.b! / 255, a: (c.a ?? 255) / 255 } });- return true;- };- material._give = (name) => (TINT_PROPERTIES.has(name) ? toCocosColor(this.data_().color) : undefined);- }-- setMaterial(material: Material | null, index: number): void {- if (index !== 0) return;- this.instance_ = 0;- this.source_ = 0;- this.patch_({ material: material ? material._handle : 0 });- }- setSharedMaterial(material: Material | null, index: number): void { this.setMaterial(material, index); }- setMaterialInstance(material: Material | null, index: number): void { this.setMaterial(material, index); }-- get receiveShadow(): boolean { return true; }- set receiveShadow(_v: boolean) { /* shadows are the scene's lighting, not a renderer's switch */ }- get shadowCastingMode(): number { return this.data_().castShadows ? 1 : 0; }- set shadowCastingMode(v: number) { this.patch_({ castShadows: v !== 0 }); }-- private source_ = 0;- private sourceOf_(): number { return this.source_; }-}--/** `UIMeshRenderer`: draws a mesh inside the UI. The engine's UI draws meshes as part of the scene, so this is a place for the call to land. */-export class UIMeshRenderer extends ModelRenderer {}--const hasMesh = (world: World, entity: Entity): boolean => world.has(entity, EngineMeshRenderer);-const addMesh = (world: World, entity: Entity): void => { world.insert(entity, EngineMeshRenderer, {}); };-registerBuiltinComponent(MeshRenderer, ['cc.MeshRenderer', 'MeshRenderer'], viewAdapter(MeshRenderer, hasMesh, addMesh));-registerBuiltinComponent(UIMeshRenderer, ['cc.UIMeshRenderer', 'UIMeshRenderer'], viewAdapter(UIMeshRenderer, () => true, () => { /* nothing stands behind it */ }));diff --git a/sdk/src/cocos/misc.ts b/sdk/src/cocos/misc.tsdeleted file mode 100644index d6ed67442..000000000--- a/sdk/src/cocos/misc.ts+++ /dev/null@@ -1,113 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/misc.ts- * @brief Small parts of `cc` that need no engine behind them: `ccenum`, the `js` helpers and `NodePool`.- */-import type { Component } from './component';-import type { Node } from './node';-import { classInfoNamed, classInfoOf } from './registry';--/** `ccenum(MyEnum)`: Cocos marks an enum so its inspector shows a dropdown. The layer's `@property` reads a TypeScript enum as it is. */-export function ccenum<T extends object>(enumObject: T): T {- return enumObject;-}--/** The parts of `cc.js` scripts call: class names and lookup, and the property helpers. */-export const js = {- /** The name a class or an instance's class goes by: the `@ccclass` name when it has one, else its own. */- getClassName(objOrCtor: unknown): string {- if (objOrCtor === null || objOrCtor === undefined) return '';- const ctor = typeof objOrCtor === 'function' ? objOrCtor : (objOrCtor as { constructor?: Function }).constructor;- if (!ctor) return '';- return classInfoOf(ctor)?.name ?? ctor.name ?? '';- },- /** A script class by the name it was declared under. */- getClassByName(name: string): Function | undefined {- return classInfoNamed(name)?.ctor;- },- getSuper(ctor: Function): Function | undefined {- const proto = Object.getPrototypeOf(ctor.prototype);- return proto && proto.constructor !== Object ? proto.constructor : undefined;- },- isChildClassOf(subclass: Function | undefined, superclass: Function | undefined): boolean {- if (!subclass || !superclass) return false;- if (subclass === superclass) return true;- for (let c: Function | undefined = js.getSuper(subclass); c; c = js.getSuper(c)) if (c === superclass) return true;- return false;- },- /** Copy the properties of the sources onto the target, replacing what it has. */- mixin<T extends object>(target: T, ...sources: object[]): T {- for (const source of sources) for (const key of Object.getOwnPropertyNames(source)) {- const descriptor = Object.getOwnPropertyDescriptor(source, key);- if (descriptor) Object.defineProperty(target, key, descriptor);- }- return target;- },- /** Copy the properties of the sources the target does not have. */- addon<T extends object>(target: T, ...sources: object[]): T {- for (const source of sources) for (const key of Object.getOwnPropertyNames(source)) {- if (key in target) continue;- const descriptor = Object.getOwnPropertyDescriptor(source, key);- if (descriptor) Object.defineProperty(target, key, descriptor);- }- return target;- },- value(object: object, name: string, value: unknown, writable = false, enumerable = false): void {- Object.defineProperty(object, name, { value, writable, enumerable, configurable: true });- },- get(object: object, name: string, getter: () => unknown, enumerable = false): void {- Object.defineProperty(object, name, { get: getter, enumerable, configurable: true });- },- getset(object: object, name: string, getter: () => unknown, setter?: (value: unknown) => void, enumerable = false): void {- Object.defineProperty(object, name, { get: getter, set: setter, enumerable, configurable: true });- },-};--/**- * `NodePool`: nodes kept to be used again. `put` takes a node out of the scene and keeps it; `get` hands one back (or null when none is- * kept). A node whose pool names a handler component is told `unuse()` as it goes in and `reuse(...args)` as it comes out.- */-export class NodePool {- private readonly nodes_: Node[] = [];-- constructor(private readonly handler_?: string | (abstract new () => Component)) {}-- size(): number {- return this.nodes_.length;- }-- clear(): void {- for (const node of this.nodes_.splice(0)) node.destroy();- }-- put(node: Node): void {- if (!node || this.nodes_.includes(node)) return;- node.removeFromParent();- this.handler(node)?.unuse?.();- this.nodes_.push(node);- }-- get(...args: unknown[]): Node | null {- const node = this.nodes_.pop() ?? null;- if (node) this.handler(node)?.reuse?.(args);- return node;- }-- private handler(node: Node): { unuse?(): void; reuse?(args: unknown[]): void } | null {- if (!this.handler_) return null;- return node.getComponent(this.handler_ as never) as unknown as { unuse?(): void; reuse?(args: unknown[]): void } | null;- }-}--/**- * `profiler`: the engine's on-screen statistics panel. Showing it is the editor's profiler and the host's overlay here, not a node a script- * owns, so the calls are accepted and the state is only remembered for `isShowingStats`.- */-let showingStats = false;-export const profiler = {- showStats(): void { showingStats = true; },- hideStats(): void { showingStats = false; },- isShowingStats(): boolean { return showingStats; },- generateNode(): void { /* the panel is not a node here */ },-};diff --git a/sdk/src/cocos/node.ts b/sdk/src/cocos/node.tsdeleted file mode 100644index c8af9e527..000000000--- a/sdk/src/cocos/node.ts+++ /dev/null@@ -1,594 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/node.ts- * @brief `Node`: a Cocos scene-graph node, as a thin handle on an Estella entity.- *- * There is one scene graph — the engine's. A `Node` owns nothing: it is `(world, entity)`, cached so the same entity is the- * same `Node` (scripts compare nodes with `===`), and every property reads or writes the entity's own components. A node a- * script makes with `new Node('name')` is an entity spawned in the world the host is currently running.- *- * Transform values cross the boundary as Cocos's value classes (`Vec3`, `Quat`) in and out; the engine's components are plain- * objects and a copy comes back from a read, so a write is always a `set` of the whole component.- */-import { Children, Disabled, Name, Parent, Transform, type TransformData } from '../ecs/component';-import { setEntityActive } from '../ecs/entityUtils';-import type { World } from '../ecs/world';-import { INVALID_ENTITY, type Entity } from '../types';-import { Quat, Vec3 } from './math';-import { Mat4 } from './mat4';-import {- COMPONENT_PREFIX, classInfoNamed, classInfoOf, ensureInstance, instancesOn, nodeOf, setNodeFactory, syncActivity,- type ComponentCtor,-} from './registry';-import type { Component } from './component';-import { builtinAdapterFor, builtinAdaptersDerivedFrom } from './builtins';--/** The world a `new Node()` spawns into: set by whatever is running script code (the host, a test). */-let currentWorld: World | null = null;-/** Make @p world current, and return the one that was, so a caller can put it back. */-// A node made by `instantiate` is not in the scene until it is given a parent. The entity exists in the world from the start, so it-// is held switched off, and `active` keeps answering what the node itself was made as; the first `addChild` lets it in.-const detached = new WeakMap<World, Map<Entity, boolean>>();--/** Hold a freshly instantiated root out of the scene until it has a parent. @internal */-export function markDetached(world: World, entity: Entity): void {- let perWorld = detached.get(world);- if (!perWorld) detached.set(world, (perWorld = new Map()));- perWorld.set(entity, !world.has(entity, Disabled));- setEntityActive(world, entity, false);-}-function detachedActive(world: World, entity: Entity): boolean | undefined { return detached.get(world)?.get(entity); }-function setDetachedActive(world: World, entity: Entity, value: boolean): boolean {- const perWorld = detached.get(world);- if (!perWorld?.has(entity)) return false;- perWorld.set(entity, value);- return true;-}-function releaseDetached(world: World, entity: Entity): void {- const perWorld = detached.get(world);- const wasActive = perWorld?.get(entity);- if (wasActive === undefined) return;- perWorld!.delete(entity);- setEntityActive(world, entity, wasActive);-}--/** The world a script last ran in: what an `await`, a timer or a callback — which run between frames — still belong to. */-let lastWorld: World | null = null;-const worldChangeListeners: Array<() => void> = [];-/**- * Run @p fn when scripts begin to run in another world than the one they last ran in. A play session is a world, and a host may keep the- * script runtime (its modules, what they kept) from one session to the next: what was kept of the last world names things that are gone.- */-export function onWorldChanged(fn: () => void): void { worldChangeListeners.push(fn); }-export function setCurrentWorld(world: World | null): World | null {- const previous = currentWorld;- currentWorld = world;- if (world) {- const changed = lastWorld !== null && lastWorld !== world;- lastWorld = world;- if (changed) for (const fn of worldChangeListeners) fn();- }- return previous;-}-/**- * The world being run now; between frames (a continuation after an `await`, a timer), the one scripts last ran in, while it is still running.- * Cocos has one running game, so a node made in a callback belongs to it.- */-export function getCurrentWorld(): World | null { return currentWorld ?? (lastWorld?.hasCpp ? lastWorld : null); }--const cache = new WeakMap<World, Map<Entity, Node>>();--/** The entities that have registered a touch listener: the only ones a touch has to be tested against. */-const touchListeners = new WeakMap<World, Set<Entity>>();-export function touchListeningEntities(world: World): Iterable<Entity> {- return touchListeners.get(world) ?? [];-}--type Listener = { callback: (...args: any[]) => void; target?: unknown; once: boolean };--/** Which axes a turn or a move is about. */-export enum NodeSpace { LOCAL = 0, WORLD = 1 }--export class Node {- static readonly NodeSpace = NodeSpace;- /** The event names Cocos scripts register for. Only the ones the engine raises are delivered; see the host. */- static readonly EventType = Object.freeze({- TOUCH_START: 'touch-start', TOUCH_MOVE: 'touch-move', TOUCH_END: 'touch-end', TOUCH_CANCEL: 'touch-cancel',- MOUSE_DOWN: 'mouse-down', MOUSE_MOVE: 'mouse-move', MOUSE_UP: 'mouse-up', MOUSE_WHEEL: 'mouse-wheel',- MOUSE_ENTER: 'mouse-enter', MOUSE_LEAVE: 'mouse-leave',- TRANSFORM_CHANGED: 'transform-changed', SIZE_CHANGED: 'size-changed', ANCHOR_CHANGED: 'anchor-changed',- CHILD_ADDED: 'child-added', CHILD_REMOVED: 'child-removed',- PARENT_CHANGED: 'parent-changed', ACTIVE_IN_HIERARCHY_CHANGED: 'active-in-hierarchy-changed',- SIBLING_ORDER_CHANGED: 'sibling-order-changed', LAYER_CHANGED: 'layer-changed',- });-- /** @internal */ readonly _world: World;- /** @internal */ readonly _entity: Entity;- private listeners_: Map<string, Listener[]> | null = null;- /** Listeners registered for the capture phase: they hear a touch on the way DOWN to its target, before the target does. */- private captureListeners_: Map<string, Listener[]> | null = null;- /** Cocos's `layer` bitmask: carried, not interpreted. */- layer = 1 << 25;-- /** The node for an entity; the same object every time. */- static for(world: World, entity: Entity): Node {- let perWorld = cache.get(world);- if (!perWorld) cache.set(world, (perWorld = new Map()));- let node = perWorld.get(entity);- if (!node) {- node = new Node(undefined, world, entity);- perWorld.set(entity, node);- }- return node;- }-- /**- * A new, parentless node in the world the running script is in. The `world` and `entity` parameters are how the engine side- * builds a handle on one that already exists; a script never passes them.- */- constructor(name?: string, world?: World, entity?: Entity) {- if (world && entity !== undefined) {- this._world = world;- this._entity = entity;- return;- }- const running = getCurrentWorld();- if (!running) throw new Error('cocos compat: new Node() outside a running scene (no world is current)');- this._world = running;- this._entity = running.spawn(name ?? 'New Node');- let perWorld = cache.get(running);- if (!perWorld) cache.set(running, (perWorld = new Map()));- perWorld.set(this._entity, this);- }-- // ---- identity ---------------------------------------------------------------------------------------------------- get uuid(): string { return String(this._entity); }- get isValid(): boolean { return this._world.valid(this._entity); }-- /**- * What a node prints and serializes as. Without it `console.log(node)` and a failed assertion walk `_world` — the whole- * engine — and the process runs out of memory before it says anything.- */- toJSON(): { node: string; entity: number } { return { node: this.name, entity: this._entity }; }- [Symbol.for('nodejs.util.inspect.custom')](): string { return `Node(${this.name}#${this._entity})`; }-- get name(): string { return this._world.tryGet(this._entity, Name)?.value ?? ''; }- set name(value: string) { this._world.set(this._entity, Name, { value }); }-- // ---- activity ---------------------------------------------------------------------------------------------------- /** This node's own switch. */- get active(): boolean { return detachedActive(this._world, this._entity) ?? !this._world.has(this._entity, Disabled); }- set active(value: boolean) {- if (setDetachedActive(this._world, this._entity, value)) return;- setEntityActive(this._world, this._entity, value);- syncActivity(this._world, this._entity);- }-- /** This node's switch and every ancestor's. */- get activeInHierarchy(): boolean { return this._world.isEntityActive(this._entity); }-- // ---- hierarchy --------------------------------------------------------------------------------------------------- get parent(): Node | null {- const p = this._world.tryGet(this._entity, Parent)?.entity;- return p && p !== INVALID_ENTITY ? Node.for(this._world, p) : null;- }- set parent(value: Node | null) { this.setParent(value); }- getParent(): Node | null { return this.parent; }-- get children(): Node[] {- const ids = this._world.tryGet(this._entity, Children)?.entities ?? [];- return ids.map((id) => Node.for(this._world, id));- }- get childrenCount(): number { return this._world.tryGet(this._entity, Children)?.entities.length ?? 0; }-- setParent(parent: Node | null, _keepWorldTransform = false): void {- if (parent) {- this._world.setParent(this._entity, parent._entity);- releaseDetached(this._world, this._entity);- syncActivity(this._world, this._entity);- } else this._world.removeParent(this._entity);- }-- addChild(child: Node): void { child.setParent(this); }- /** Add @p child at place @p index among this node's children (the end when it is past it). */- insertChild(child: Node, index: number): void {- child.setParent(this);- child.setSiblingIndex(index);- }- removeChild(child: Node): void { if (child.parent === this) child.setParent(null); }- removeFromParent(): void { this.setParent(null); }- removeAllChildren(): void { for (const c of this.children) c.setParent(null); }-- getChildByName(name: string): Node | null {- for (const c of this.children) if (c.name === name) return c;- return null;- }-- /** `a/b/c`, each segment a child's name; an empty path is this node. */- getChildByPath(path: string): Node | null {- let node: Node | null = this;- for (const segment of path.split('/')) {- if (segment === '') continue;- node = node.getChildByName(segment);- if (!node) return null;- }- return node;- }-- getSiblingIndex(): number {- const p = this.parent;- return p ? (this._world.tryGet(p._entity, Children)?.entities.indexOf(this._entity) ?? -1) : 0;- }- /**- * Move this node among its siblings (-1 is the last place). The engine keeps the child order and the draw order together, in the storage- * order of its entities, so the siblings swap their places there and the engine re-establishes both from it: the same operation an- * outliner drag is.- */- setSiblingIndex(index: number): void {- const parent = this.parent;- if (!parent) return;- const siblings = [...(this._world.tryGet(parent._entity, Children)?.entities ?? [])];- const from = siblings.indexOf(this._entity);- if (from < 0) return;- const to = Math.max(0, Math.min(siblings.length - 1, index < 0 ? siblings.length - 1 : index));- if (to === from) return;- siblings.splice(from, 1);- siblings.splice(to, 0, this._entity);- const taken = new Set<Entity>(siblings);- const order = this._world.getAllEntities();- let next = 0;- for (let i = 0; i < order.length; i++) if (taken.has(order[i]!)) order[i] = siblings[next++]!;- this._world.applyEntityOrder(order);- }-- /** Whether @p other is this node or below it. */- isChildOf(other: Node): boolean {- for (let n: Node | null = this; n; n = n.parent) if (n === other) return true;- return false;- }-- /** Remove this node and everything under it; its components get `onDestroy` on the next frame. */- destroy(): boolean {- if (!this.isValid) return false;- this._world.despawn(this._entity);- return true;- }- destroyAllChildren(): void { for (const c of this.children) c.destroy(); }-- // ---- transform --------------------------------------------------------------------------------------------------- private transform_(): TransformData { return this._world.get(this._entity, Transform); }- /** The transform with its world fields current: a script that moves a node and reads where it ended up in the same frame must see the move. */- private composedTransform_(): TransformData {- this._world.ensureTransformsComposed();- return this.transform_();- }- private writeTransform_(patch: Partial<Pick<TransformData, 'position' | 'rotation' | 'scale'>>): void {- this._world.set(this._entity, Transform, { ...this.transform_(), ...patch });- }-- get position(): Vec3 { const p = this.transform_().position; return new Vec3(p.x, p.y, p.z); }- set position(v: Vec3) { this.setPosition(v); }-- /** `setPosition(vec3)` or `setPosition(x, y, z?)`; z is left alone when omitted. */- setPosition(x: number | Vec3, y?: number, z?: number): void {- const cur = this.transform_().position;- const next = typeof x === 'object' ? { x: x.x, y: x.y, z: x.z } : { x, y: y ?? cur.y, z: z ?? cur.z };- this.writeTransform_({ position: next });- }- getPosition(out?: Vec3): Vec3 { const p = this.transform_().position; return (out ?? new Vec3()).set(p.x, p.y, p.z); }-- get scale(): Vec3 { const s = this.transform_().scale; return new Vec3(s.x, s.y, s.z); }- set scale(v: Vec3) { this.setScale(v); }- setScale(x: number | Vec3, y?: number, z?: number): void {- const cur = this.transform_().scale;- const next = typeof x === 'object' ? { x: x.x, y: x.y, z: x.z } : { x, y: y ?? cur.y, z: z ?? cur.z };- this.writeTransform_({ scale: next });- }- getScale(out?: Vec3): Vec3 { const s = this.transform_().scale; return (out ?? new Vec3()).set(s.x, s.y, s.z); }-- get rotation(): Quat { const q = this.transform_().rotation; return new Quat(q.x, q.y, q.z, q.w); }- set rotation(q: Quat) { this.setRotation(q); }- setRotation(x: number | Quat, y?: number, z?: number, w?: number): void {- const q = typeof x === 'object' ? x : new Quat(x, y, z, w);- this.writeTransform_({ rotation: { x: q.x, y: q.y, z: q.z, w: q.w } });- }- getRotation(out?: Quat): Quat { const q = this.transform_().rotation; return (out ?? new Quat()).set(q.x, q.y, q.z, q.w); }-- get eulerAngles(): Vec3 { return Quat.toEuler(new Vec3(), this.rotation); }- set eulerAngles(v: Vec3) { this.setRotationFromEuler(v.x, v.y, v.z); }- setRotationFromEuler(x: number, y: number, z: number): void { this.setRotation(Quat.fromEuler(new Quat(), x, y, z)); }-- /** The rotation about z, in degrees: the one that matters for a 2D node. */- get angle(): number { return this.eulerAngles.z; }- set angle(degrees: number) { const e = this.eulerAngles; this.setRotationFromEuler(e.x, e.y, degrees); }-- get worldScale(): Vec3 { const s = this.composedTransform_().worldScale; return new Vec3(s.x, s.y, s.z); }- get worldRotation(): Quat { const q = this.composedTransform_().worldRotation; return new Quat(q.x, q.y, q.z, q.w); }- get worldPosition(): Vec3 { const p = this.composedTransform_().worldPosition; return new Vec3(p.x, p.y, p.z); }- set worldPosition(v: Vec3) { this.setWorldPosition(v); }- getWorldRotation(out?: Quat): Quat { const q = this.composedTransform_().worldRotation; return (out ?? new Quat()).set(q.x, q.y, q.z, q.w); }- /** The node's world transform as a matrix (translation, rotation and scale composed). */- get worldMatrix(): Mat4 { return this.getWorldMatrix(); }- getWorldMatrix(out: Mat4 = new Mat4()): Mat4 {- const t = this.composedTransform_();- return Mat4.fromTRS(out, t.worldPosition as Vec3, t.worldRotation as Quat, t.worldScale as Vec3);- }- /** The world-space directions of this node's axes: forward is -Z, as in Cocos. */- get forward(): Vec3 { return Vec3.transformQuat(new Vec3(), new Vec3(0, 0, -1), this.composedTransform_().worldRotation); }- get up(): Vec3 { return Vec3.transformQuat(new Vec3(), new Vec3(0, 1, 0), this.composedTransform_().worldRotation); }- get right(): Vec3 { return Vec3.transformQuat(new Vec3(), new Vec3(1, 0, 0), this.composedTransform_().worldRotation); }- set worldRotation(q: Quat) { this.setWorldRotation(q); }- set worldScale(v: Vec3) { this.setWorldScale(v); }- getWorldScale(out?: Vec3): Vec3 { const s = this.composedTransform_().worldScale; return (out ?? new Vec3()).set(s.x, s.y, s.z); }- get worldEulerAngles(): Vec3 { return Quat.toEuler(new Vec3(), this.worldRotation); }- set worldEulerAngles(v: Vec3) { this.setWorldRotationFromEuler(v.x, v.y, v.z); }-- /** Turn this node so its world rotation is @p x; under a rotated parent the local rotation is solved for. */- setWorldRotation(x: number | Quat, y?: number, z?: number, w?: number): void {- const world = typeof x === 'object' ? x : new Quat(x, y, z, w);- const parent = this.parent;- if (!parent) { this.setRotation(world); return; }- const inverse = Quat.invert(new Quat(), parent.worldRotation);- this.setRotation(Quat.multiply(new Quat(), inverse, world));- }- setWorldRotationFromEuler(x: number, y: number, z: number): void { this.setWorldRotation(Quat.fromEuler(new Quat(), x, y, z)); }-- /** Scale this node so its world scale is @p x; the parent's scale is divided out. */- setWorldScale(x: number | Vec3, y?: number, z?: number): void {- const world = typeof x === 'object' ? x : new Vec3(x, y ?? 0, z ?? 0);- const parent = this.parent;- if (!parent) { this.setScale(world); return; }- const s = parent.worldScale;- this.setScale(world.x / (s.x || 1), world.y / (s.y || 1), world.z / (s.z || 1));- }-- /** Turn by @p rot about the node's own axes (local) or about the world's. */- rotate(rot: Quat, ns: number = NodeSpace.LOCAL): void {- if (ns === NodeSpace.WORLD) this.setWorldRotation(Quat.multiply(new Quat(), rot, this.worldRotation));- else this.setRotation(Quat.multiply(new Quat(), this.rotation, rot));- }-- /** Move by @p trans, in the node's own axes (local) or the world's. */- translate(trans: Vec3, ns: number = NodeSpace.LOCAL): void {- if (ns === NodeSpace.WORLD) {- const p = this.worldPosition;- this.setWorldPosition(p.x + trans.x, p.y + trans.y, p.z + trans.z);- } else {- const d = Vec3.transformQuat(new Vec3(), trans, this.rotation);- const p = this.position;- this.setPosition(p.x + d.x, p.y + d.y, p.z + d.z);- }- }-- /** Face -Z towards @p target, with @p up kept upright. */- lookAt(target: Vec3, up: Vec3 = Vec3.UP): void {- const from = this.worldPosition;- const view = new Vec3(from.x - target.x, from.y - target.y, from.z - target.z).normalize();- this.setWorldRotation(Quat.fromViewUp(new Quat(), view, up));- }-- /** A world point as this node sees it: the inverse of the node's world transform applied to it. */- inverseTransformPoint(out: Vec3, p: Vec3): Vec3 {- const t = this.composedTransform_();- const d = new Vec3(p.x - t.worldPosition.x, p.y - t.worldPosition.y, p.z - t.worldPosition.z);- Vec3.transformQuat(d, d, Quat.invert(new Quat(), this.worldRotation));- return out.set(d.x / (t.worldScale.x || 1), d.y / (t.worldScale.y || 1), d.z / (t.worldScale.z || 1));- }-- /** What changed since the last frame: nothing is tracked here, and a script that asks is told nothing did. */- get hasChangedFlags(): number { return 0; }- set hasChangedFlags(_v: number) { /* nothing is tracked */ }- /** The world transform is composed when it is read, so there is nothing to bring up to date. */- updateWorldTransform(): void {}-- /** Visit this node and everything under it: @p before on the way in, @p after on the way out. */- walk(before: (node: Node) => void, after?: (node: Node) => void): void {- before(this);- for (const c of this.children) c.walk(before, after);- after?.(this);- }-- getWorldPosition(out?: Vec3): Vec3 { const p = this.composedTransform_().worldPosition; return (out ?? new Vec3()).set(p.x, p.y, p.z); }-- /** Place this node so its world position is @p x. Under a parent that is rotated or scaled, the local position is solved for. */- setWorldPosition(x: number | Vec3, y?: number, z?: number): void {- const world = typeof x === 'object' ? x : new Vec3(x, y ?? 0, z ?? 0);- const parent = this.parent;- if (!parent) { this.setPosition(world); return; }- const pt = parent.composedTransform_();- const dx = world.x - pt.worldPosition.x, dy = world.y - pt.worldPosition.y, dz = world.z - pt.worldPosition.z;- // inverse parent rotation, then inverse parent scale- const { x: qx, y: qy, z: qz, w: qw } = pt.worldRotation;- const ix = -qx, iy = -qy, iz = -qz;- const tx = 2 * (iy * dz - iz * dy), ty = 2 * (iz * dx - ix * dz), tz = 2 * (ix * dy - iy * dx);- const rx = dx + qw * tx + (iy * tz - iz * ty);- const ry = dy + qw * ty + (iz * tx - ix * tz);- const rz = dz + qw * tz + (ix * ty - iy * tx);- const s = pt.worldScale;- this.setPosition(rx / (s.x || 1), ry / (s.y || 1), rz / (s.z || 1));- }-- // ---- components -------------------------------------------------------------------------------------------------- /** The component of a class (or class name) on this node, or null. */- getComponent<T extends Component>(type: ComponentCtor<T> | string): T | null {- const ctor = this.resolveCtor_(type);- if (ctor) {- const info = classInfoOf(ctor);- if (info) {- if (this._world.has(this._entity, info.def)) return ensureInstance(this._world, this._entity, ctor) as T | null;- // the component asked for may be a base of the one the node holds (a Button on a node that has a Toggle, which is one)- return this.subclassInstances_(ctor)[0] as T | undefined ?? null;- }- }- const own = builtinAdapterFor(type)?.get(this._world, this._entity) as T | null | undefined;- if (own) return own;- // the base of built-in views (`UIRenderer`) is found by the one the node holds- return (typeof type === 'function' ? this.derivedViews_(type)[0] : undefined) as T | undefined ?? null;- }-- /** The views on this node of the built-in classes that derive from @p base. */- private derivedViews_(base: Function): Component[] {- const out: Component[] = [];- for (const adapter of builtinAdaptersDerivedFrom(base)) {- const view = adapter.get(this._world, this._entity);- if (view) out.push(view);- }- return out;- }-- getComponents<T extends Component>(type: ComponentCtor<T> | string): T[] {- const ctor = this.resolveCtor_(type);- const info = ctor ? classInfoOf(ctor) : undefined;- if (ctor && info) {- const own = this._world.has(this._entity, info.def) ? [ensureInstance(this._world, this._entity, ctor) as T] : [];- return [...own, ...(this.subclassInstances_(ctor) as T[])];- }- const one = this.getComponent<T>(type);- return one ? [one] : [];- }-- /** The script components on this node whose class derives from @p base, other than @p base itself. */- private subclassInstances_(base: ComponentCtor): Component[] {- const out: Component[] = [];- for (const type of this._world.getComponentTypes(this._entity)) {- if (!type.startsWith(COMPONENT_PREFIX)) continue;- const info = classInfoNamed(type.slice(COMPONENT_PREFIX.length));- if (!info || info.ctor === base || !(info.ctor.prototype instanceof base)) continue;- const inst = ensureInstance(this._world, this._entity, info.ctor);- if (inst) out.push(inst);- }- return out;- }-- getComponentInChildren<T extends Component>(type: ComponentCtor<T> | string): T | null {- const own = this.getComponent<T>(type);- if (own) return own;- for (const c of this.children) {- const found = c.getComponentInChildren<T>(type);- if (found) return found;- }- return null;- }-- getComponentsInChildren<T extends Component>(type: ComponentCtor<T> | string): T[] {- const out = this.getComponents<T>(type);- for (const c of this.children) out.push(...c.getComponentsInChildren<T>(type));- return out;- }-- /** Add a component of a class to this node and return it, its `onLoad` already run. */- addComponent<T extends Component>(type: ComponentCtor<T> | string): T | null {- const ctor = this.resolveCtor_(type);- const info = ctor ? classInfoOf(ctor) : undefined;- if (ctor && info) {- if (!this._world.has(this._entity, info.def)) this._world.insert(this._entity, info.def, structuredClone(info.def._default));- return ensureInstance(this._world, this._entity, ctor) as T | null;- }- const adapter = builtinAdapterFor(type);- if (adapter) return adapter.add(this._world, this._entity) as T | null;- throw new Error(`cocos compat: addComponent: no component class "${typeof type === 'string' ? type : type?.name}"`);- }-- private resolveCtor_(type: ComponentCtor | string): ComponentCtor | undefined {- // A scene and a script say `'cc.Button'`; the layer declares the class as `Button`.- if (typeof type === 'string') return (classInfoNamed(type) ?? classInfoNamed(type.replace(/^cc\./, '')))?.ctor;- return type;- }-- /**- * Every script component on this node, made if it was not yet and not loaded: Cocos keeps them on the node as `_components`, and a project reads- * them to prepare a freshly made instance (parse its nodes) before the node is given a parent that would load it.- */- get _components(): Component[] {- const out: Component[] = [];- for (const type of this._world.getComponentTypes(this._entity)) {- if (!type.startsWith(COMPONENT_PREFIX)) continue;- const info = classInfoNamed(type.slice(COMPONENT_PREFIX.length));- const inst = info ? ensureInstance(this._world, this._entity, info.ctor) : null;- if (inst) out.push(inst);- }- return out;- }-- /** @internal Every live script component on this node. */- _allInstances(): Component[] { return [...(instancesOn(this._world, this._entity)?.values() ?? [])]; }-- // ---- events ------------------------------------------------------------------------------------------------------ on(type: string, callback: (...args: any[]) => void, target?: unknown, useCapture = false): typeof callback {- this.addListener_(type, { callback, target, once: false }, useCapture);- return callback;- }- once(type: string, callback: (...args: any[]) => void, target?: unknown): void {- this.addListener_(type, { callback, target, once: true });- }- off(type: string, callback?: (...args: any[]) => void, target?: unknown, useCapture = false): void {- const map = useCapture ? this.captureListeners_ : this.listeners_;- const list = map?.get(type);- if (!list) return;- map!.set(type, list.filter((l) => (callback && l.callback !== callback) || (target !== undefined && l.target !== target)));- this.forgetTouchIfSilent_();- }- /** Remove every listener that was registered with @p target. */- targetOff(target: unknown): void {- for (const map of [this.listeners_, this.captureListeners_]) {- if (!map) continue;- for (const [type, list] of map) map.set(type, list.filter((l) => l.target !== target));- }- this.forgetTouchIfSilent_();- }-- /** An entity with no touch listener left is not one a pointer can land on any more. */- private forgetTouchIfSilent_(): void {- const set = touchListeners.get(this._world);- if (!set?.has(this._entity)) return;- for (const map of [this.listeners_, this.captureListeners_]) {- if (!map) continue;- for (const [type, list] of map) if (type.startsWith('touch-') && list.length > 0) return;- }- set.delete(this._entity);- }- hasEventListener(type: string, useCapture?: boolean): boolean {- if (useCapture === true) return (this.captureListeners_?.get(type)?.length ?? 0) > 0;- if (useCapture === false) return (this.listeners_?.get(type)?.length ?? 0) > 0;- return (this.listeners_?.get(type)?.length ?? 0) > 0 || (this.captureListeners_?.get(type)?.length ?? 0) > 0;- }- /** @internal Call the capture-phase listeners for @p type. */- _emitCapture(type: string, ...args: any[]): void {- const list = this.captureListeners_?.get(type);- if (!list) return;- for (const l of [...list]) l.callback.call(l.target, ...args);- }- emit(type: string, ...args: any[]): void {- const list = this.listeners_?.get(type);- if (!list) return;- for (const l of [...list]) {- if (l.once) this.off(type, l.callback, l.target);- l.callback.call(l.target, ...args);- }- }- dispatchEvent(event: { type: string }): void { this.emit(event.type, event); }-- private addListener_(type: string, listener: Listener, useCapture = false): void {- if (type.startsWith('touch-')) {- let set = touchListeners.get(this._world);- if (!set) touchListeners.set(this._world, (set = new Set()));- set.add(this._entity);- }- const map = useCapture ? (this.captureListeners_ ??= new Map()) : (this.listeners_ ??= new Map());- const list = map.get(type);- if (list) list.push(listener); else map.set(type, [listener]);- }-}--setNodeFactory((world, entity) => Node.for(world, entity));---/** The node for an entity, for the parts of the layer that hold only an entity id. */-export function nodeForEntity(world: World, entity: Entity): Node { return nodeOf(world, entity); }diff --git a/sdk/src/cocos/physicsSystem.ts b/sdk/src/cocos/physicsSystem.tsdeleted file mode 100644index 996112740..000000000--- a/sdk/src/cocos/physicsSystem.ts+++ /dev/null@@ -1,102 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/physicsSystem.ts- * @brief `PhysicsSystem.instance.raycast`: which colliders a ray crosses, nearest first.- *- * A Cocos game asks the physics system one thing of its colliders: what did this touch ray hit. The answer is a walk over the world's box- * colliders, each tested as the oriented box it is, so a project that only picks does not have to load a solver and step bodies for it.- */-import { BoxCollider3D } from '../physics3d/Physics3DComponents';-import { BoxCollider } from './collider';-import { getCurrentWorld, nodeForEntity } from './node';-import { Quat, Vec3 } from './math';-import { Ray } from './geometry';--/** One collider a ray crossed. */-export class PhysicsRayResult {- collider!: BoxCollider;- /** Where the ray met it. */- hitPoint = new Vec3();- /** How far along the ray. */- distance = 0;- /** The side that was met, pointing out of the box. */- hitNormal = new Vec3();-}--/** The nearest distance at which @p ray crosses the box, or -1; the normal of the face goes to @p normal. */-function crossBox(ray: Ray, centre: Vec3, half: Vec3, rotation: Quat, position: Vec3, normal: Vec3): number {- const inverse = Quat.invert(new Quat(), rotation);- const o = Vec3.transformQuat(new Vec3(), new Vec3(ray.o.x - position.x, ray.o.y - position.y, ray.o.z - position.z), inverse);- const d = Vec3.transformQuat(new Vec3(), ray.d, inverse);- let near = -Infinity, far = Infinity, axisHit: 'x' | 'y' | 'z' = 'y', sign = 1;- for (const axis of ['x', 'y', 'z'] as const) {- const lo = centre[axis] - half[axis], hi = centre[axis] + half[axis];- if (Math.abs(d[axis]) < 1e-12) {- if (o[axis] < lo || o[axis] > hi) return -1;- continue;- }- let t1 = (lo - o[axis]) / d[axis], t2 = (hi - o[axis]) / d[axis];- let s = -1;- if (t1 > t2) { [t1, t2] = [t2, t1]; s = 1; }- if (t1 > near) { near = t1; axisHit = axis; sign = s; }- far = Math.min(far, t2);- }- if (far < Math.max(near, 0)) return -1;- // a ray that starts inside a box meets nothing on the way in: it leaves, and is reported at the origin, as the engine reports an inside start- const t = near >= 0 ? near : 0;- const local = new Vec3();- local[axisHit] = sign;- Vec3.transformQuat(normal, local, rotation);- return t;-}--export class PhysicsSystem {- private static instance_: PhysicsSystem | null = null;- static get instance(): PhysicsSystem { return (PhysicsSystem.instance_ ??= new PhysicsSystem()); }-- /** Every collider the last `raycast` crossed, nearest first. */- readonly raycastResults: PhysicsRayResult[] = [];- readonly raycastClosestResult = new PhysicsRayResult();-- /** Whether the ray crosses any collider the mask lets in; the crossings are `raycastResults`. */- raycast(worldRay: Ray, _mask = 0xffffffff, maxDistance = 10000000, queryTrigger = true): boolean {- this.raycastResults.length = 0;- const world = getCurrentWorld();- if (!world) return false;- const found: PhysicsRayResult[] = [];- for (const entity of world.getEntitiesWithComponents([BoxCollider3D])) {- const data = world.get(entity, BoxCollider3D);- if (!data.enabled || (data.isSensor && !queryTrigger) || !world.isEntityActive(entity)) continue;- const node = nodeForEntity(world, entity);- const scaleRatio = new Vec3(1, 1, 1);- const local = node.scale, wide = node.worldScale;- for (const a of ['x', 'y', 'z'] as const) if (Math.abs(local[a]) > 1e-6) scaleRatio[a] = Math.abs(wide[a] / local[a]);- const centre = new Vec3((data.center?.x ?? 0) * scaleRatio.x, (data.center?.y ?? 0) * scaleRatio.y, (data.center?.z ?? 0) * scaleRatio.z);- const half = new Vec3(data.halfExtents.x * scaleRatio.x, data.halfExtents.y * scaleRatio.y, data.halfExtents.z * scaleRatio.z);- const normal = new Vec3();- const t = crossBox(worldRay, centre, half, node.worldRotation, node.worldPosition, normal);- if (t < 0 || t > maxDistance) continue;- const result = new PhysicsRayResult();- result.collider = node.getComponent(BoxCollider)!;- result.distance = t;- worldRay.computeHit(result.hitPoint, t);- result.hitNormal = normal;- found.push(result);- }- found.sort((a, b) => a.distance - b.distance);- this.raycastResults.push(...found);- return found.length > 0;- }-- /** Whether the ray crosses any; the nearest is `raycastClosestResult`. */- raycastClosest(worldRay: Ray, mask = 0xffffffff, maxDistance = 10000000, queryTrigger = true): boolean {- if (!this.raycast(worldRay, mask, maxDistance, queryTrigger)) return false;- const nearest = this.raycastResults[0]!;- this.raycastClosestResult.collider = nearest.collider;- this.raycastClosestResult.distance = nearest.distance;- this.raycastClosestResult.hitPoint.set(nearest.hitPoint);- this.raycastClosestResult.hitNormal.set(nearest.hitNormal);- return true;- }-}diff --git a/sdk/src/cocos/prefabs.ts b/sdk/src/cocos/prefabs.tsdeleted file mode 100644index 36ec27bac..000000000--- a/sdk/src/cocos/prefabs.ts+++ /dev/null@@ -1,221 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/prefabs.ts- * @brief `instantiate(prefab)` and `instantiate(node)`.- *- * Cocos's `instantiate` answers a node at once, because its prefabs are loaded before a script can hold them. The engine's- * prefab spawn is asynchronous for the same reason the other way round: loading is what it does. The bridge is the engine's- * *prepared prefab* (prefab/preparedPrefab.ts) — load once, with every asset the prefab names, then spawn synchronously any- * number of times. A script that holds a `Prefab` (a `@property(Prefab)` field) causes that preparation to start, so by the time- * a click handler runs it is ready; an `instantiate` before then says so rather than returning something half made.- *- * What comes back is out of the scene until it is given a parent, as in Cocos: the entity is made, held switched off, and let in- * by the first `addChild` (see `markDetached` in node.ts).- */-import { Schedule, defineSystem, addSystemToSchedule, GetWorld } from '../ecs/system';-import { Res } from '../ecs/resource';-import { Assets } from '../asset/AssetPlugin';-import type { Assets as AssetsClass } from '../asset/Assets';-import { preparePrefab, spawnPrepared, type PreparedPrefab } from '../prefab/preparedPrefab';-import { getComponent } from '../ecs/component';-import { Children, Name, Parent } from '../ecs/component';-import { loadSceneData, serializeEntityComponents, SCENE_FORMAT_VERSION, type SceneData } from '../scene/scene';-import type { World } from '../ecs/world';-import type { Entity } from '../types';-import { log } from '../util/logger';-import { Node, getCurrentWorld, markDetached, onWorldChanged } from './node';-import { Prefab, preparedPrefabs } from './assets';-import { COMPONENT_PREFIX, classInfoNamed } from './registry';--const assetsOf = new WeakMap<World, AssetsClass>();-let currentAssets: AssetsClass | null = null;-let currentEpoch = -1;-const sessionListeners: Array<() => void> = [];--/**- * Run @p fn when a play session ends and another begins: the engine releases the session's resources, so what the layer kept of- * them (a prepared prefab, a loaded asset) names things that are gone. Told as the new session's asset loader is first seen.- */-export function onNewSession(fn: () => void): void { sessionListeners.push(fn); }-const wanted = new Set<string>();-const inFlight = new Set<string>();--/** The engine's asset loader for a world, once the frame loop has seen it. */-export function assetsFor(world: World | null): AssetsClass | undefined { return world ? assetsOf.get(world) : undefined; }--/** Start preparing the prefab at @p path, once the engine's asset loader is there to do it. */-export function requestPrepare(path: string): void {- if (path && !preparedPrefabs.has(path) && !inFlight.has(path)) wanted.add(path);-}--/** Drop what the layer kept of the session that ended, and tell whoever else kept something. */-function endSession(): void {- preparedPrefabs.clear();- preparing.clear();- wanted.clear();- inFlight.clear();- currentAssets = null;- for (const fn of sessionListeners) fn();-}-// A script that begins to run in another world is in another session, before any frame has told the loader so: a game asks for what it-// loaded last time at start-up, and must not be handed that.-onWorldChanged(endSession);--/** What the layer kept is of the session that kept it: when the loader has given everything back since, it is dropped. */-function syncSession(assets: AssetsClass): void {- const epoch = assets.epoch;- if (currentAssets && (currentAssets !== assets || currentEpoch !== epoch)) endSession();- currentAssets = assets;- currentEpoch = epoch;-}--/** Hand the layer a prefab already prepared (a host that loaded it its own way, or a test). */-export function providePrefab(path: string, prepared: PreparedPrefab): void {- preparedPrefabs.set(path, prepared);-}--/** The prefabs a prepared prefab's script components hold in `@property(Prefab)` fields: what Cocos loads before it hands the prefab over. */-/** @internal */-export function prefabsHeldBy(prepared: PreparedPrefab): string[] {- const held = new Set<string>();- for (const entity of prepared.scene.entities) {- for (const component of entity.components) {- if (!component.type.startsWith(COMPONENT_PREFIX)) continue;- const info = classInfoNamed(component.type.slice(COMPONENT_PREFIX.length));- for (const spec of info?.props ?? []) {- if (spec.kind !== 'asset' || typeof spec.type !== 'function' || !(spec.type === Prefab || spec.type.prototype instanceof Prefab)) continue;- const value = component.data[spec.name];- for (const path of Array.isArray(value) ? value : [value]) if (typeof path === 'string' && path !== '') held.add(path);- }- }- }- return [...held];-}--const preparing = new Map<string, Promise<void>>();--/** Prepare a prefab and the prefabs its scripts hold, and answer when all of them are ready. A prefab that holds itself is waited for once. */-function prepareWithHeld(assets: AssetsClass, path: string): Promise<void> {- if (preparedPrefabs.has(path)) return Promise.resolve();- let pending = preparing.get(path);- if (!pending) {- pending = preparePrefab(assets, path)- .then((p) => { preparedPrefabs.set(path, p); return p; })- .then(async (p) => {- // the held ones are best effort: one that cannot be prepared is reported where the script uses it, not here- await Promise.all(prefabsHeldBy(p).map((held) => prepareWithHeld(assets, held).catch(() => undefined)));- })- .finally(() => { preparing.delete(path); });- preparing.set(path, pending);- }- return pending;-}--/** Prepare a prefab and answer when it is ready to `instantiate`. */-export function loadPrefab(path: string, world: World | null = getCurrentWorld()): Promise<Prefab> {- const assets = world ? assetsOf.get(world) : undefined;- if (assets) syncSession(assets);- if (preparedPrefabs.has(path)) return Promise.resolve(new Prefab(path));- if (!assets) return Promise.reject(new Error(`cocos compat: cannot load prefab "${path}": the engine's asset loader is not running`));- return prepareWithHeld(assets, path).then(() => new Prefab(path));-}--function drain(assets: AssetsClass): void {- for (const path of wanted) {- wanted.delete(path);- inFlight.add(path);- prepareWithHeld(assets, path)- .catch((err) => { log.warn('cocos', `prefab "${path}" could not be prepared: ${String(err)}`); })- .finally(() => { inFlight.delete(path); });- }-}--/** The system that learns where the asset loader is and starts the preparations scripts asked for. */-export function declarePrefabSystem(): void {- const system = defineSystem(- [Res(Assets), GetWorld()],- (assets, world) => {- if (!assets) return;- syncSession(assets as AssetsClass);- assetsOf.set(world, assets as AssetsClass);- if (wanted.size > 0) drain(assets as AssetsClass);- },- { name: 'Cocos:Prefabs', touches: { opaque: true } },- );- addSystemToSchedule(Schedule.First, system);-}--// ----------------------------------------------------------------------------------------------------------------------// instantiate-// -----------------------------------------------------------------------------------------------------------------------function subtreeOf(world: World, root: Entity): Entity[] {- const out: Entity[] = [];- const visit = (e: Entity): void => {- out.push(e);- for (const c of world.tryGet(e, Children)?.entities ?? []) visit(c);- };- visit(root);- return out;-}--/** A copy of a node and everything under it, as a new parentless node. References to nodes outside the subtree are kept. */-function cloneNode(src: Node): Node {- const world = src._world;- const ids = subtreeOf(world, src._entity);- const inside = new Set<number>(ids as unknown as number[]);- const external = new Map<number, Entity>();- const entities = ids.map((entity) => {- const components = serializeEntityComponents(world, entity);- for (const c of components) {- const def = getComponent(c.type);- for (const field of def?.entityFields ?? []) {- const value = (c.data as Record<string, unknown>)[field];- for (const ref of Array.isArray(value) ? value : [value]) {- if (typeof ref === 'number' && ref > 0 && !inside.has(ref) && world.valid(ref as Entity)) external.set(ref, ref as Entity);- }- }- }- const parent = entity === src._entity ? null : (world.tryGet(entity, Parent)?.entity ?? null);- return {- id: entity as unknown as number,- name: world.tryGet(entity, Name)?.value ?? '',- parent: parent as unknown as number | null,- children: (world.tryGet(entity, Children)?.entities ?? []) as unknown as number[],- components,- visible: true,- };- });- const scene = { version: SCENE_FORMAT_VERSION, name: src.name, entities } as unknown as SceneData;- const map = loadSceneData(world, scene, external);- return Node.for(world, map.get(src._entity as unknown as number)!);-}--/**- * A new node from a prefab or a copy of an existing node.- *- * @throws when given a prefab that has not finished loading: unlike Cocos, which has loaded it by the time a script holds it, the- * engine loads on demand, and returning an empty node would hide that.- */-export function instantiate<T extends Node | Prefab>(original: T): Node;-export function instantiate(original: Node | Prefab | null | undefined): Node {- if (original instanceof Node) {- const copy = cloneNode(original);- markDetached(original._world, copy._entity);- return copy;- }- if (original instanceof Prefab) {- const prepared = original._prepared as PreparedPrefab | undefined;- if (!prepared) {- requestPrepare(original.path);- throw new Error(`cocos compat: instantiate: prefab "${original.path}" is not loaded yet — hold it in a @property(Prefab) field so it loads with the scene, or await loadPrefab(path) first`);- }- const world = getCurrentWorld();- if (!world) throw new Error('cocos compat: instantiate outside a running scene (no world is current)');- const { root } = spawnPrepared(world, prepared);- markDetached(world, root);- return Node.for(world, root);- }- throw new Error('cocos compat: instantiate takes a Prefab or a Node');-}diff --git a/sdk/src/cocos/registry.ts b/sdk/src/cocos/registry.tsdeleted file mode 100644index b2b999f1e..000000000--- a/sdk/src/cocos/registry.ts+++ /dev/null@@ -1,178 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/registry.ts- * @brief What the compatibility layer knows: the script classes that were declared, and the live instance of each on each entity.- *- * A Cocos component is a class instance per node; Estella's components are data. The bridge is two-sided: a declared class- * becomes an Estella component carrying its `@property` values (so a scene, a prefab and the inspector can hold them, and the- * ordinary save/load/undo machinery applies), and the instance lives here, created the first time something asks for it and- * dropped when the entity or the component goes.- *- * This file holds data and the two operations on it that everything else needs. It imports no engine system, so the classes in- * `component.ts` and `node.ts` can both depend on it without depending on each other.- */-import type { World } from '../ecs/world';-import type { ComponentDef } from '../ecs/component';-import type { Entity } from '../types';-import type { Component } from './component';-import type { Node } from './node';--/** A script class, as `new` sees it. */-export type ComponentCtor<T extends Component = Component> = new (...args: any[]) => T;--/** What a `@property` field holds, which decides how its stored value becomes the instance's value. */-export type PropertyKind =- | 'number' | 'string' | 'boolean'- | 'node' // an entity reference, made a Node- | 'component' // an entity reference, made the instance of `type` on it- | 'asset' // a project-relative path- | 'vec2' | 'vec3' | 'color'- | 'json'; // anything else: kept as it is--export interface PropertySpec {- name: string;- kind: PropertyKind;- /** The class a `node`/`component`/`asset` property names, when it named one. */- type?: unknown;- /** For a list of values, the kind of each. */- array?: boolean;-}--export interface ClassInfo {- ctor: ComponentCtor;- /** The class name as the script wrote it (`@ccclass('Name')` or the class's own name). */- name: string;- /** The Estella component name a scene stores: the class name under a prefix that keeps it clear of the engine's own. */- componentName: string;- def: ComponentDef<any>;- props: PropertySpec[];-}--/** Every Estella component name a compat class takes starts with this, so a script class named like an engine component cannot collide. */-export const COMPONENT_PREFIX = 'Cocos.';--const byCtor = new Map<Function, ClassInfo>();-const byName = new Map<string, ClassInfo>();--export function registerClassInfo(info: ClassInfo): void {- byCtor.set(info.ctor, info);- byName.set(info.name, info);- byName.set(info.componentName, info);-}--export function classInfoOf(ctor: Function): ClassInfo | undefined {- return byCtor.get(ctor);-}--/** A class by the name a script or a scene gives it: either the class name or the component name. */-export function classInfoNamed(name: string): ClassInfo | undefined {- return byName.get(name);-}--export function allClassInfos(): IterableIterator<ClassInfo> {- return byCtor.values();-}--/** Forget every declaration (a test seam: classes are process-wide, as they are in Cocos). */-export function resetClassRegistry(): void {- byCtor.clear();- byName.clear();-}--// ----------------------------------------------------------------------------------------------------------------------// Live instances.-// -----------------------------------------------------------------------------------------------------------------------const instances = new WeakMap<World, Map<Entity, Map<Function, Component>>>();--export function instancesOn(world: World, entity: Entity): Map<Function, Component> | undefined {- return instances.get(world)?.get(entity);-}--/** Every live instance of one class in a world, by entity. */-export function instancesOfClass(world: World, ctor: Function): Array<[Entity, Component]> {- const out: Array<[Entity, Component]> = [];- const perEntity = instances.get(world);- if (!perEntity) return out;- for (const [entity, byClass] of perEntity) {- const inst = byClass.get(ctor);- if (inst) out.push([entity, inst]);- }- return out;-}--export function storeInstance(world: World, entity: Entity, ctor: Function, inst: Component): void {- let perEntity = instances.get(world);- if (!perEntity) instances.set(world, (perEntity = new Map()));- let byClass = perEntity.get(entity);- if (!byClass) perEntity.set(entity, (byClass = new Map()));- byClass.set(ctor, inst);-}--/** The instances waiting for their `start`, by world, in the order they were made. */-const awaitingStart = new WeakMap<World, Set<Component>>();-/** An instance with a `start` waits for the start phase, which runs before any `update` of the frame. */-export function awaitStart(world: World, inst: Component): void {- let set = awaitingStart.get(world);- if (!set) awaitingStart.set(world, (set = new Set()));- set.add(inst);-}-export function pendingStarts(world: World): Set<Component> | undefined { return awaitingStart.get(world); }--export function dropInstance(world: World, entity: Entity, ctor: Function): void {- const perEntity = instances.get(world);- const byClass = perEntity?.get(entity);- if (!byClass) return;- byClass.delete(ctor);- if (byClass.size === 0) perEntity!.delete(entity);-}--// ----------------------------------------------------------------------------------------------------------------------// The two late-bound pieces. `Node` and `ensureInstance` need each other, and a cycle of imports is worse than a setter.-// -----------------------------------------------------------------------------------------------------------------------let nodeFactory: ((world: World, entity: Entity) => Node) | null = null;-export function setNodeFactory(factory: (world: World, entity: Entity) => Node): void {- nodeFactory = factory;-}-export function nodeOf(world: World, entity: Entity): Node {- if (!nodeFactory) throw new Error('cocos compat: Node was not loaded; import from "esengine/cocos"');- return nodeFactory(world, entity);-}--let instantiator: ((world: World, entity: Entity, ctor: ComponentCtor) => Component | null) | null = null;-export function setInstantiator(fn: (world: World, entity: Entity, ctor: ComponentCtor) => Component | null): void {- instantiator = fn;-}-let builtinDeclarer: (() => void) | null = null;-export function setBuiltinDeclarer(fn: () => void): void {- builtinDeclarer = fn;-}-/**- * Make sure the layer's own classes and systems are declared in the context now current. The layer declares them once, when it is first- * imported; a host that keeps the script runtime from one play session to the next gives the next session a new context and does not- * import the layer again, so a game's own classes, declared as its scripts run, ask for them.- */-export function ensureBuiltinsDeclared(): void {- builtinDeclarer?.();-}--let activitySync: ((world: World, entity: Entity) => void) | null = null;-export function setActivitySync(fn: (world: World, entity: Entity) => void): void {- activitySync = fn;-}-/**- * A node joined an active parent, or was switched on or off: its scripts' `onLoad`, `onEnable` and `onDisable` run now, as they do in- * Cocos, and not on the next frame (a script that sets a value right after `addChild` would otherwise be undone by an `onEnable` that- * runs later).- */-export function syncActivity(world: World, entity: Entity): void {- activitySync?.(world, entity);-}-/** The instance of @p ctor on @p entity, made (and its `onLoad` run) if the entity has the component and it has none yet; null if the entity does not have it. */-export function ensureInstance(world: World, entity: Entity, ctor: ComponentCtor): Component | null {- const existing = instancesOn(world, entity)?.get(ctor);- if (existing) return existing;- return instantiator ? instantiator(world, entity, ctor) : null;-}diff --git a/sdk/src/cocos/renderer.ts b/sdk/src/cocos/renderer.tsdeleted file mode 100644index 46b913b4b..000000000--- a/sdk/src/cocos/renderer.ts+++ /dev/null@@ -1,27 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/renderer.ts- * @brief `cc.renderer`: the render-scene namespace, of which scripts read the constants.- *- * A script asks `camera.projection == renderer.scene.CameraProjection.ORTHO` to tell the two kinds of camera apart, so the numbers must be- * Cocos's: a stand-in there compares unequal to everything and sends an orthographic camera down the perspective path. The scene objects- * of Cocos's own renderer (`renderer.scene.Camera`, `Model`) are not here, and say so by name when used.- */-import { unsupported } from './unsupported';--/** An object that answers what it has and a named stand-in for the rest. */-function withStandIns<T extends object>(path: string, known: T): T {- return new Proxy(known, {- get(target, key, receiver) {- if (typeof key === 'symbol' || key in target) return Reflect.get(target, key, receiver);- return unsupported(`${path}.${key}`);- },- });-}--const CameraProjection = Object.freeze({ ORTHO: 0, PERSPECTIVE: 1 });--export const renderer = withStandIns('renderer', {- scene: withStandIns('renderer.scene', { CameraProjection }),-});diff --git a/sdk/src/cocos/scheduler.ts b/sdk/src/cocos/scheduler.tsdeleted file mode 100644index 8b14f75a3..000000000--- a/sdk/src/cocos/scheduler.ts+++ /dev/null@@ -1,103 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/scheduler.ts- * @brief `director.getScheduler()`: timers kept by target rather than by component.- *- * A component's own `schedule` stops with the component; the director's scheduler serves anything a script holds, a plain object or a- * singleton, and is how a game's timer service ticks. It runs once a frame from the frame the host reports, scaled by `setTimeScale`.- */--interface Entry {- callback: (dt: number) => void;- target: object;- interval: number;- repeat: number;- delay: number;- /** Time since the last fire (or since the delay began). */- elapsed: number;- fired: number;- started: boolean;- paused: boolean;-}--export class Scheduler {- static readonly ID = 'scheduler';- static readonly PRIORITY_SYSTEM = -(2 ** 31);- static readonly PRIORITY_NON_SYSTEM = Scheduler.PRIORITY_SYSTEM + 1;- static readonly REPEAT_FOREVER = Number.MAX_VALUE - 1;- static enableForTarget(_target: unknown): void { /* a target needs no marking here */ }-- private entries_: Entry[] = [];- private updates_ = new Map<object, { priority: number; paused: boolean }>();- private pausedTargets_ = new Set<object>();- private timeScale_ = 1;-- /** Call @p callback on @p target every @p interval seconds (every frame at 0), @p repeat more times after the first, after @p delay. */- schedule(callback: (dt: number) => void, target: object, interval = 0, repeat = Scheduler.REPEAT_FOREVER, delay = 0, paused = false): void {- if (typeof callback !== 'function') return;- this.unschedule(callback, target);- this.entries_.push({ callback, target, interval, repeat, delay, elapsed: 0, fired: 0, started: delay <= 0, paused });- }- scheduleOnce(callback: (dt: number) => void, target: object, delay = 0): void { this.schedule(callback, target, 0, 0, delay); }- /** Call `target.update(dt)` every frame, lowest priority first. */- scheduleUpdate(target: object, priority = 0, paused = false): void { this.updates_.set(target, { priority, paused }); }- unscheduleUpdate(target: object): void { this.updates_.delete(target); }- unschedule(callback: (dt: number) => void, target: object): void {- this.entries_ = this.entries_.filter((e) => !(e.callback === callback && e.target === target));- }- unscheduleAllForTarget(target: object): void {- this.entries_ = this.entries_.filter((e) => e.target !== target);- this.updates_.delete(target);- }- unscheduleAll(): void { this.entries_ = []; this.updates_.clear(); }- unscheduleAllWithMinPriority(minPriority: number): void {- if (minPriority <= Scheduler.PRIORITY_SYSTEM) { this.unscheduleAll(); return; }- for (const [target, u] of [...this.updates_]) if (u.priority >= minPriority) this.updates_.delete(target);- this.entries_ = [];- }- isScheduled(callback: (dt: number) => void, target: object): boolean {- return this.entries_.some((e) => e.callback === callback && e.target === target);- }- pauseTarget(target: object): void { this.pausedTargets_.add(target); }- resumeTarget(target: object): void { this.pausedTargets_.delete(target); }- isTargetPaused(target: object): boolean { return this.pausedTargets_.has(target); }- setTimeScale(scale: number): void { this.timeScale_ = scale; }- getTimeScale(): number { return this.timeScale_; }-- /** @internal Advance by one frame's @p delta seconds. */- update(delta: number): void {- const dt = delta * this.timeScale_;- const updates = [...this.updates_].sort((a, b) => a[1].priority - b[1].priority);- for (const [target, u] of updates) {- if (u.paused || this.pausedTargets_.has(target) || !this.updates_.has(target)) continue;- (target as { update?: (dt: number) => void }).update?.(dt);- }- // A callback may schedule or unschedule: walk a copy, and skip an entry that was removed meanwhile.- for (const e of [...this.entries_]) {- if (e.paused || this.pausedTargets_.has(e.target) || !this.entries_.includes(e)) continue;- e.elapsed += dt;- if (!e.started) {- if (e.elapsed < e.delay) continue;- e.started = true;- e.elapsed -= e.delay;- this.fire_(e, e.elapsed);- continue;- }- if (e.interval <= 0) { this.fire_(e, dt); continue; }- while (e.elapsed >= e.interval && this.entries_.includes(e)) {- e.elapsed -= e.interval;- this.fire_(e, e.interval);- }- }- }-- private fire_(e: Entry, dt: number): void {- e.fired++;- // `repeat` counts the fires after the first, so a once-timer (0) ends with its first- if (e.fired > e.repeat) this.entries_ = this.entries_.filter((x) => x !== e);- try { e.callback.call(e.target, dt); } catch (err) { console.error('[cocos] a scheduled callback threw', err); }- }-}--export const scheduler = new Scheduler();diff --git a/sdk/src/cocos/sys.ts b/sdk/src/cocos/sys.tsdeleted file mode 100644index 078f3bde6..000000000--- a/sdk/src/cocos/sys.ts+++ /dev/null@@ -1,122 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/sys.ts- * @brief `sys`: what the machine and platform are.- *- * Scripts branch on `sys.platform` and `sys.os` to choose paths, payment flows and sdk calls, so the answers have to be the- * platform the engine is actually running on: the mini-game hosts report themselves, a browser is told apart by its user agent,- * and `localStorage` is the platform's storage (a mini-game has no `window.localStorage`).- *- * Constants keep Cocos's names and its string values for `OS` and `Language`; the `Platform` numbers are this layer's own, since- * scripts compare them to the enum's members and never to a literal.- */-import { getPlatformType, platformGetStorageItem, platformNow, platformRemoveStorageItem, platformSetStorageItem } from '../platform';-import { Rect } from './math';--const OS = Object.freeze({- UNKNOWN: 'Unknown', IOS: 'iOS', ANDROID: 'Android', WINDOWS: 'Windows', LINUX: 'Linux', OSX: 'OS X', OHOS: 'OHOS', OPENHARMONY: 'OpenHarmony',-});--const Platform = Object.freeze({- UNKNOWN: 0, EDITOR_PAGE: 1, EDITOR_CORE: 2, MOBILE_BROWSER: 3, DESKTOP_BROWSER: 4, WIN32: 5, MACOS: 6, IOS: 7, ANDROID: 8, OHOS: 9,- OPENHARMONY: 10, WECHAT_GAME: 11, WECHAT_MINI_PROGRAM: 12, BAIDU_MINI_GAME: 13, XIAOMI_QUICK_GAME: 14, ALIPAY_MINI_GAME: 15,- BYTEDANCE_MINI_GAME: 16, OPPO_MINI_GAME: 17, VIVO_MINI_GAME: 18, HUAWEI_QUICK_GAME: 19, COCOSPLAY: 20, LINKSURE_MINI_GAME: 21,- QTT_MINI_GAME: 22, XR_VR_MIRROR: 23, XR_AR_MIRROR: 24, XR_HMD: 25,-});--const Language = Object.freeze({- ENGLISH: 'en', CHINESE: 'zh', FRENCH: 'fr', ITALIAN: 'it', GERMAN: 'de', SPANISH: 'es', DUTCH: 'du', RUSSIAN: 'ru', KOREAN: 'ko',- JAPANESE: 'ja', HUNGARIAN: 'hu', PORTUGUESE: 'pt', ARABIC: 'ar', NORWEGIAN: 'no', POLISH: 'pl', TURKISH: 'tr', UKRAINIAN: 'uk',- ROMANIAN: 'ro', BULGARIAN: 'bg', UNKNOWN: 'unknown',-});--const BrowserType = Object.freeze({- WECHAT: 'wechat', ANDROID: 'androidbrowser', IE: 'ie', EDGE: 'edge', QQ: 'qqbrowser', MOBILE_QQ: 'mqqbrowser', UC: 'ucbrowser',- UCBS: 'ucbs', BAIDU_APP: 'baiduboxapp', BAIDU: 'baidubrowser', MAXTHON: 'maxthon', OPERA: 'opera', OUPENG: 'oupeng', MIUI: 'miuibrowser',- FIREFOX: 'firefox', SAFARI: 'safari', CHROME: 'chrome', LIEBAO: 'liebao', QZONE: 'qzone', SOUGOU: 'sogou', HUAWEI: 'huawei', UNKNOWN: 'unknown',-});--const userAgent = (): string => (typeof navigator !== 'undefined' && navigator.userAgent ? navigator.userAgent : '');--function detectOS(): string {- const ua = userAgent();- if (/iPhone|iPad|iPod/i.test(ua)) return OS.IOS;- if (/Android/i.test(ua)) return OS.ANDROID;- if (/OpenHarmony/i.test(ua)) return OS.OPENHARMONY;- if (/HarmonyOS|OHOS/i.test(ua)) return OS.OHOS;- if (/Windows/i.test(ua)) return OS.WINDOWS;- if (/Mac OS X|Macintosh/i.test(ua)) return OS.OSX;- if (/Linux|X11/i.test(ua)) return OS.LINUX;- return OS.UNKNOWN;-}--const MINI_GAME: Record<string, number> = {- wechat: Platform.WECHAT_GAME, douyin: Platform.BYTEDANCE_MINI_GAME, kuaishou: Platform.BYTEDANCE_MINI_GAME, alipay: Platform.ALIPAY_MINI_GAME,- huawei: Platform.HUAWEI_QUICK_GAME, bilibili: Platform.UNKNOWN, quickgame: Platform.XIAOMI_QUICK_GAME,-};--function detectPlatform(os: string): number {- const name = getPlatformType();- if (name && name in MINI_GAME) return MINI_GAME[name]!;- if (name === 'native') {- return os === OS.IOS ? Platform.IOS : os === OS.ANDROID ? Platform.ANDROID : os === OS.WINDOWS ? Platform.WIN32- : os === OS.OSX ? Platform.MACOS : os === OS.OHOS ? Platform.OHOS : Platform.UNKNOWN;- }- if (name === 'web') return os === OS.IOS || os === OS.ANDROID ? Platform.MOBILE_BROWSER : Platform.DESKTOP_BROWSER;- return Platform.UNKNOWN;-}--/** Storage that falls back to memory where the platform has none, as Cocos's does outside a browser. */-const memory = new Map<string, string>();-const localStorage = {- getItem(key: string): string | null {- try { const v = platformGetStorageItem(key); if (v !== null) return v; } catch { /* fall through to memory */ }- return memory.get(key) ?? null;- },- setItem(key: string, value: string): void {- memory.set(key, String(value));- try { platformSetStorageItem(key, String(value)); } catch { /* memory holds it */ }- },- removeItem(key: string): void {- memory.delete(key);- try { platformRemoveStorageItem(key); } catch { /* nothing to remove */ }- },- clear(): void { for (const key of [...memory.keys()]) localStorage.removeItem(key); },-};--const os = detectOS();-const platform = detectPlatform(os);-const isMobilePlatform = platform === Platform.MOBILE_BROWSER || platform === Platform.IOS || platform === Platform.ANDROID- || platform === Platform.OHOS || platform === Platform.OPENHARMONY || (platform >= Platform.WECHAT_GAME && platform <= Platform.QTT_MINI_GAME);--export const sys = {- OS, Platform, Language, BrowserType,- os,- platform,- language: typeof navigator !== 'undefined' && navigator.language ? navigator.language.toLowerCase() : 'en',- languageCode: typeof navigator !== 'undefined' && navigator.language ? navigator.language.toLowerCase() : 'en',- isNative: getPlatformType() === 'native',- isBrowser: getPlatformType() === 'web',- isMobile: isMobilePlatform,- isXR: false,- isLittleEndian: new Uint8Array(new Uint16Array([1]).buffer)[0] === 1,- browserType: BrowserType.UNKNOWN as string,- browserVersion: '',- osVersion: '',- osMainVersion: 0,- isOnline: typeof navigator === 'undefined' || navigator.onLine !== false,- capabilities: { canvas: true, opengl: true, webp: true, imageBitmap: typeof createImageBitmap !== 'undefined', touches: platform !== Platform.DESKTOP_BROWSER, mouse: platform === Platform.DESKTOP_BROWSER, keyboard: platform === Platform.DESKTOP_BROWSER, accelerometer: false },- localStorage,- /** The `width`/`height` of the area free of notches and system bars, in canvas units. */- getSafeAreaRect(): Rect { return new Rect(0, 0, 0, 0); },- now(): number { return platformNow(); },- openURL(url: string): void {- if (typeof window !== 'undefined' && typeof window.open === 'function') window.open(url);- },- dumpRoot(): void { /* the root is the engine's; nothing to dump */ },- garbageCollect(): void { /* the host's */ },- restartVM(): void { /* the host's */ },- getNetworkType(): number { return 0; },- getBatteryLevel(): number { return 1; },-};diff --git a/sdk/src/cocos/tween.ts b/sdk/src/cocos/tween.tsdeleted file mode 100644index 0590488ed..000000000--- a/sdk/src/cocos/tween.ts+++ /dev/null@@ -1,366 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/tween.ts- * @brief `tween(target).to(...).by(...).delay(...).call(...)`: Cocos's chainable property animation.- *- * A tween is a recipe — a list of steps — and `start()` turns it into a running tree of actions that the frame loop advances by- * the frame's delta. The shapes Cocos scripts use are all here: `to` / `by` / `set` / `delay` / `call`, `then`, `union`,- * `sequence` / `parallel`, `repeat` / `repeatForever`, easing by name or function, `progress` and the `onStart` / `onUpdate` /- * `onComplete` hooks, and `Tween.stopAll*`.- *- * What it animates is whatever the target's properties are: numbers lerp, and the value types (`Vec2`, `Vec3`, `Quat`, `Color`)- * lerp per component and are assigned back as new values, so a `Node` accessor like `position` sees every change. A tween on a- * `Node` stops when the node is destroyed and waits while it is inactive, which is what Cocos's action manager does.- */-import { Schedule, defineSystem, addSystemToSchedule, GetWorld } from '../ecs/system';-import { Res, Time } from '../ecs/resource';-import { log } from '../util/logger';-import { easing, resolveEasing, type EasingFunction, type EasingName } from './easing';-import { Node } from './node';-import { Quat } from './math';--type Props = Record<string, unknown>;--export interface TweenOptions<T = unknown> {- easing?: EasingName | EasingFunction | string;- /** Replace the interpolation: given a start, an end, the current value and the eased ratio, return the next value. */- progress?: (start: number, end: number, current: number, ratio: number) => number;- onStart?: (target?: T) => void;- onUpdate?: (target: T, ratio: number) => void;- onComplete?: (target?: T) => void;-}--// ----------------------------------------------------------------------------------------------------------------------// Values.-// -----------------------------------------------------------------------------------------------------------------------const isObject = (v: unknown): v is Record<string, number> => typeof v === 'object' && v !== null;--/** A copy that is safe to hold while the target's own value changes underneath. */-function snapshot(v: unknown): unknown {- if (!isObject(v)) return v;- const clone = (v as { clone?: () => unknown }).clone;- if (typeof clone === 'function') return clone.call(v);- return { ...v };-}--const FIELDS = ['x', 'y', 'z', 'w', 'r', 'g', 'b', 'a', 'width', 'height'];--function addValues(a: unknown, b: unknown): unknown {- if (typeof a === 'number' && typeof b === 'number') return a + b;- if (isObject(a) && isObject(b)) {- const out = snapshot(a) as Record<string, number>;- for (const f of FIELDS) if (typeof a[f] === 'number' && typeof b[f] === 'number') out[f] = a[f]! + b[f]!;- return out;- }- return b;-}--function interpolate(start: unknown, end: unknown, current: unknown, ratio: number, progress?: TweenOptions['progress']): unknown {- if (typeof start === 'number' && typeof end === 'number') {- return progress ? progress(start, end, typeof current === 'number' ? current : start, ratio) : start + (end - start) * ratio;- }- if (isObject(start) && isObject(end)) {- if (start instanceof Quat && end instanceof Quat) return Quat.slerp(new Quat(), start, end, ratio);- const out = (isObject(current) ? snapshot(current) : snapshot(start)) as Record<string, number>;- for (const f of FIELDS) {- const s = start[f], e = end[f];- if (typeof s === 'number' && typeof e === 'number') out[f] = progress ? progress(s, e, out[f] ?? s, ratio) : s + (e - s) * ratio;- }- return out;- }- return ratio >= 1 ? end : start;-}--// ----------------------------------------------------------------------------------------------------------------------// Actions: what a running tween is made of. `step(dt)` returns the time left over when it finished, or -1 while it runs.-// -----------------------------------------------------------------------------------------------------------------------interface Action { step(dt: number): number }--type Factory = (target: unknown) => Action;--class Sequence implements Action {- private i = 0;- constructor(private readonly actions: Action[]) {}- step(dt: number): number {- let left = dt;- while (this.i < this.actions.length) {- const rest = this.actions[this.i]!.step(left);- if (rest < 0) return -1;- left = rest;- this.i++;- }- return left;- }-}--class Parallel implements Action {- private readonly done: number[];- constructor(private readonly actions: Action[]) { this.done = actions.map(() => -1); }- step(dt: number): number {- let finished = true;- for (let i = 0; i < this.actions.length; i++) {- if (this.done[i]! >= 0) continue;- this.done[i] = this.actions[i]!.step(dt);- if (this.done[i]! < 0) finished = false;- }- return finished ? Math.min(...this.done) : -1;- }-}--class Repeat implements Action {- private n = 0;- private current: Action;- constructor(private readonly make: () => Action, private readonly times: number) { this.current = make(); }- step(dt: number): number {- let left = dt;- for (let guard = 0; guard < 10_000; guard++) {- const rest = this.current.step(left);- if (rest < 0) return -1;- left = rest;- if (++this.n >= this.times) return left;- this.current = this.make();- // an iteration that takes no time must not spin- if (left <= 0 && this.times === Infinity) return -1;- }- return -1;- }-}--/** Frames add up in floating point: ten steps of 0.1 are 0.9999999999999999, and a tween must not wait an extra frame for that. */-const EPS = 1e-9;--class Delay implements Action {- private t = 0;- constructor(private readonly duration: number) {}- step(dt: number): number {- this.t += dt;- return this.t >= this.duration - EPS ? Math.max(0, this.t - this.duration) : -1;- }-}--class Instant implements Action {- constructor(private readonly run: () => void) {}- step(dt: number): number { this.run(); return dt; }-}--class Interval implements Action {- private t = 0;- private from: Props | null = null;- private to: Props = {};- private started = false;- constructor(- private readonly target: Record<string, unknown>,- private readonly duration: number,- private readonly props: Props,- private readonly relative: boolean,- private readonly opts: TweenOptions,- ) {}-- private begin(): void {- this.started = true;- this.from = {};- for (const key of Object.keys(this.props)) {- const raw = this.props[key];- const value = isObject(raw) && 'value' in raw && !('x' in raw) ? (raw as { value: unknown }).value : raw;- this.from[key] = snapshot(this.target[key]);- this.to[key] = this.relative ? addValues(this.target[key], value) : value;- }- this.opts.onStart?.(this.target);- }-- step(dt: number): number {- if (!this.started) this.begin();- this.t += dt;- const k = this.duration <= 0 || this.t >= this.duration - EPS ? 1 : this.t / this.duration;- const eased = resolveEasing(this.opts.easing)(k);- for (const key of Object.keys(this.props)) {- const raw = this.props[key];- const own = isObject(raw) && 'value' in raw && !('x' in raw) ? (raw as { easing?: TweenOptions['easing']; progress?: TweenOptions['progress'] }) : null;- const ratio = own?.easing ? resolveEasing(own.easing)(k) : eased;- this.target[key] = interpolate(this.from![key], this.to[key], this.target[key], ratio, own?.progress ?? this.opts.progress);- }- this.opts.onUpdate?.(this.target, k);- if (k < 1) return -1;- this.opts.onComplete?.(this.target);- return Math.max(0, this.t - this.duration);- }-}--// ----------------------------------------------------------------------------------------------------------------------// The tween.-// -----------------------------------------------------------------------------------------------------------------------interface Running {- tween: Tween<unknown>;- root: Action;- paused: boolean;-}-const running = new Set<Running>();-let nextId = 1;--export class Tween<T = unknown> {- /** @internal */ _steps: Factory[] = [];- /** @internal */ _target: unknown;- private tag_ = -1;- private run_: Running | null = null;- readonly id = nextId++;-- constructor(target?: T) { this._target = target; }-- get tag(): number { return this.tag_; }- set tag(v: number) { this.tag_ = v; }-- /** The object being animated. */- getTarget(): T { return this._target as T; }-- target(t: unknown): Tween<T> { this._target = t; return this; }-- to<P extends Props>(duration: number, props: P, opts?: TweenOptions<T>): Tween<T> {- this._steps.push((t) => new Interval(t as Record<string, unknown>, duration, props, false, (opts ?? {}) as TweenOptions));- return this;- }-- by<P extends Props>(duration: number, props: P, opts?: TweenOptions<T>): Tween<T> {- this._steps.push((t) => new Interval(t as Record<string, unknown>, duration, props, true, (opts ?? {}) as TweenOptions));- return this;- }-- set<P extends Props>(props: P): Tween<T> {- this._steps.push((t) => new Instant(() => { for (const [k, v] of Object.entries(props)) (t as Record<string, unknown>)[k] = snapshot(v); }));- return this;- }-- delay(duration: number): Tween<T> {- this._steps.push(() => new Delay(duration));- return this;- }-- call(callback: (target?: T) => void): Tween<T> {- this._steps.push((t) => new Instant(() => callback(t as T)));- return this;- }-- /** Run another tween's steps here, on this tween's target. */- then(other: Tween<unknown>): Tween<T> {- const steps = other._steps.slice();- this._steps.push((t) => new Sequence(steps.map((f) => f(t))));- return this;- }-- /** Fold everything so far into one step, so a following `repeat` repeats all of it. */- union(): Tween<T> {- const steps = this._steps;- this._steps = [(t) => new Sequence(steps.map((f) => f(t)))];- return this;- }-- sequence(...tweens: Tween<unknown>[]): Tween<T> {- const parts = tweens.map((x) => x._steps.slice());- this._steps.push((t) => new Sequence(parts.flatMap((steps) => steps.map((f) => f(t)))));- return this;- }-- parallel(...tweens: Tween<unknown>[]): Tween<T> {- const parts = tweens.map((x) => x._steps.slice());- this._steps.push((t) => new Parallel(parts.map((steps) => new Sequence(steps.map((f) => f(t))))));- return this;- }-- /** Repeat @p embed, or everything so far when none is given. */- repeat(times: number, embed?: Tween<unknown>): Tween<T> {- return this.repeat_(times, embed);- }- repeatForever(embed?: Tween<unknown>): Tween<T> {- return this.repeat_(Infinity, embed);- }- private repeat_(times: number, embed?: Tween<unknown>): Tween<T> {- const steps = embed ? embed._steps.slice() : this._steps;- const make = (t: unknown) => (): Action => new Sequence(steps.map((f) => f(t)));- const factory: Factory = (t) => new Repeat(make(t), times);- if (embed) this._steps.push(factory); else this._steps = [factory];- return this;- }-- /** A copy with the same recipe, optionally on another target. */- clone(target?: unknown): Tween<T> {- const copy = new Tween<T>((target ?? this._target) as T);- copy._steps = this._steps.slice();- copy.tag_ = this.tag_;- return copy;- }-- // ---- Node conveniences, as Cocos has them --------------------------------------------------------------------------- hide(): Tween<T> { return this.call((t) => { if (t instanceof Node) t.active = false; }); }- show(): Tween<T> { return this.call((t) => { if (t instanceof Node) t.active = true; }); }- removeSelf(): Tween<T> { return this.call((t) => { if (t instanceof Node) t.removeFromParent(); }); }- destroySelf(): Tween<T> { return this.call((t) => { if (t instanceof Node) t.destroy(); }); }-- // ---- running --------------------------------------------------------------------------------------------------------- start(): Tween<T> {- this.stop();- const target = this._target ?? {};- const run: Running = { tween: this as Tween<unknown>, root: new Sequence(this._steps.map((f) => f(target))), paused: false };- this.run_ = run;- running.add(run);- return this;- }-- stop(): Tween<T> {- if (this.run_) { running.delete(this.run_); this.run_ = null; }- return this;- }-- pause(): Tween<T> { if (this.run_) this.run_.paused = true; return this; }- resume(): Tween<T> { if (this.run_) this.run_.paused = false; return this; }-- get isRunning(): boolean { return this.run_ !== null; }-- static stopAll(): void { for (const r of [...running]) r.tween.stop(); }- static stopAllByTag(tag: number, target?: unknown): void {- for (const r of [...running]) if (r.tween.tag === tag && (target === undefined || r.tween._target === target)) r.tween.stop();- }- static stopAllByTarget(target: unknown): void {- for (const r of [...running]) if (r.tween._target === target) r.tween.stop();- }-}--/** Start building a tween on @p target. */-export function tween<T>(target?: T): Tween<T> { return new Tween<T>(target); }-export const tweenUtil = tween;--/** Advance every running tween by @p dt seconds. Exported for a host with its own loop, and for tests. */-export function updateTweens(dt: number): void {- for (const run of [...running]) {- if (!running.has(run) || run.paused) continue;- const target = run.tween._target;- if (target instanceof Node) {- if (!target.isValid) { run.tween.stop(); continue; }- if (!target.activeInHierarchy) continue;- }- let rest: number;- try {- rest = run.root.step(dt);- } catch (err) {- log.error('cocos', 'a tween threw and was stopped', err);- run.tween.stop();- continue;- }- if (rest >= 0) run.tween.stop();- }-}--/** Register the system that advances tweens with the frame loop. */-export function declareTweenSystem(): void {- const system = defineSystem(- [Res(Time), GetWorld()],- (time) => { updateTweens(time.delta); },- { name: 'Cocos:Tween', touches: { opaque: true } },- );- addSystemToSchedule(Schedule.Update, system);-}--export { easing };diff --git a/sdk/src/cocos/ui/button.ts b/sdk/src/cocos/ui/button.tsdeleted file mode 100644index 5109fc8c9..000000000--- a/sdk/src/cocos/ui/button.ts+++ /dev/null@@ -1,187 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/button.ts- * @brief `Button` and `EventHandler`.- *- * Unlike `Label` or `Sprite`, a button is behaviour: it listens for the touches on its node and, when one ends inside, says "click"- * — to the handlers authored in the editor (`clickEvents`) and to whoever did `node.on(Button.EventType.CLICK, ...)`. So it is a- * real script class, declared through the same path as a game's (host.ts), with its settings as stored data.- *- * The one thing an editor-authored handler holds that the engine's data model cannot carry is a node reference inside a list of- * records. The records are therefore stored as two parallel lists — the targets, which are entity references the scene loader- * remaps, and the rest of each handler — and joined here when the button loads.- */-import { Component } from '../component';-import { Color } from '../math';-import { Node } from '../node';-import { declareClass } from '../host';-import { classInfoNamed } from '../registry';-import { Sprite } from './sprite';-import { UITransform } from './uiTransform';-import type { EventTouch } from '../input';--/** An editor-authored callback: call `handler` on the `component` of `target`, with the event and `customEventData`. */-export class EventHandler {- target: Node | null = null;- /** The class name of the component on `target`. */- component = '';- handler = '';- customEventData = '';-- emit(args: unknown[] = []): void {- const target = this.target;- if (!target || !target.isValid || !this.handler) return;- const comp = this.component ? target.getComponent(this.component) : null;- const fn = (comp as unknown as Record<string, unknown> | null)?.[this.handler];- if (typeof fn === 'function') fn.apply(comp, [...args, this.customEventData]);- }-- static emitEvents(handlers: EventHandler[], ...args: unknown[]): void {- for (const h of handlers) h.emit(args);- }-}--/** Editor-authored handlers are stored as a list of target nodes beside a list of the rest; join them. */-export function joinHandlers(- targets: Array<Node | null>,- records: Array<{ component: string; handler: string; customEventData: string }>,-): EventHandler[] {- return records.map((r, i) => {- const e = new EventHandler();- e.target = targets[i] ?? null;- e.component = r.component;- e.handler = r.handler;- e.customEventData = r.customEventData;- return e;- });-}--const Transition = Object.freeze({ NONE: 0, COLOR: 1, SPRITE: 2, SCALE: 3 });-const EventType = Object.freeze({ CLICK: 'click' });--export class Button extends Component {- static readonly Transition = Transition;- static readonly EventType = EventType;-- interactable = true;- transition: number = Transition.NONE;- zoomScale = 1.2;- duration = 0.1;- normalColor = new Color(255, 255, 255, 255);- hoverColor = new Color(211, 211, 211, 255);- pressedColor = new Color(255, 255, 255, 255);- disabledColor = new Color(124, 124, 124, 255);- /** The node the transition acts on; this node when none is set. */- target: Node | null = null;- clickTargets: Array<Node | null> = [];- clickHandlers: Array<{ component: string; handler: string; customEventData: string }> = [];- clickEvents: EventHandler[] = [];-- private pressed_ = false;- private restScale_: { x: number; y: number; z: number } | null = null;-- onLoad(): void {- if (this.clickEvents.length === 0) this.clickEvents = joinHandlers(this.clickTargets, this.clickHandlers);- }-- onEnable(): void {- this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);- this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);- this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);- this.applyTransition_();- }-- onDisable(): void {- this.node.off(Node.EventType.TOUCH_START, this.onTouchStart, this);- this.node.off(Node.EventType.TOUCH_END, this.onTouchEnd, this);- this.node.off(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);- this.pressed_ = false;- this.restore_();- }-- private onTouchStart(event: EventTouch): void {- if (!this.interactable || !this.enabledInHierarchy) return;- this.pressed_ = true;- this.applyTransition_();- event.stopPropagation();- }-- private onTouchEnd(event: EventTouch): void {- if (!this.pressed_) return;- this.pressed_ = false;- this.applyTransition_();- const inside = this.node.getComponent(UITransform)?.isHit(event.getUILocation()) ?? true;- if (this.interactable && this.enabledInHierarchy && inside) {- EventHandler.emitEvents(this.clickEvents, event);- this.node.emit(EventType.CLICK, this);- this.onClicked_(event);- }- event.stopPropagation();- }-- /** A click has been delivered. A button has nothing more to do; a toggle flips here. */- protected onClicked_(_event: EventTouch): void { /* nothing */ }-- private onTouchCancel(): void {- this.pressed_ = false;- this.applyTransition_();- }-- /** The node the transition acts on. */- private transitionTarget_(): Node { return this.target ?? this.node; }-- private restore_(): void {- if (this.restScale_) {- const s = this.restScale_;- this.transitionTarget_().setScale(s.x, s.y, s.z);- this.restScale_ = null;- }- }-- /** Instant: the press is shown or not. Cocos eases these over `duration`; a transition that lasts a tenth of a second is not what a script reads. */- private applyTransition_(): void {- const node = this.transitionTarget_();- if (this.transition === Transition.SCALE) {- if (this.pressed_) {- if (!this.restScale_) { const s = node.scale; this.restScale_ = { x: s.x, y: s.y, z: s.z }; }- const r = this.restScale_;- node.setScale(r.x * this.zoomScale, r.y * this.zoomScale, r.z);- } else {- this.restore_();- }- } else if (this.transition === Transition.COLOR) {- const sprite = node.getComponent(Sprite);- if (sprite) sprite.color = !this.interactable ? this.disabledColor : this.pressed_ ? this.pressedColor : this.normalColor;- }- }-}--/** Declare the button's component, so a scene that holds one finds it. */-export const BUTTON_PROPS: Array<{ name: string; kind: 'number' | 'boolean' | 'color' | 'node' | 'json'; array?: boolean }> = [- { name: 'interactable', kind: 'boolean' },- { name: 'transition', kind: 'number' },- { name: 'zoomScale', kind: 'number' },- { name: 'duration', kind: 'number' },- { name: 'normalColor', kind: 'color' },- { name: 'hoverColor', kind: 'color' },- { name: 'pressedColor', kind: 'color' },- { name: 'disabledColor', kind: 'color' },- { name: 'target', kind: 'node' },- { name: 'clickTargets', kind: 'node', array: true },- { name: 'clickHandlers', kind: 'json' },-];--export function declareButton(): void {- declareClass(Button as never, 'Button', BUTTON_PROPS);-}--export const isButtonDeclared = (): boolean => classInfoNamed('Button') !== undefined;--declare module '../component' {- namespace Component {- /** `Component.EventHandler`, as scripts name the class. */- let EventHandler: typeof import('./button').EventHandler;- }-}-(Component as unknown as { EventHandler: typeof EventHandler }).EventHandler = EventHandler;diff --git a/sdk/src/cocos/ui/camera.ts b/sdk/src/cocos/ui/camera.tsdeleted file mode 100644index c5bbe1c5e..000000000--- a/sdk/src/cocos/ui/camera.ts+++ /dev/null@@ -1,144 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/camera.ts- * @brief `Camera`: a view on the engine's `Camera`, with Cocos's names and the conversions scripts use it for.- *- * Every setting is the engine camera's, renamed (`orthoHeight` is its `orthoSize`, `visibility` its `cullingMask`, `rect` its- * `viewport`) and `projection` translated, since the two number the kinds the other way round. The conversions go through the- * UI camera — the one that draws the scene's UI and world content — so `screenToWorld(touch.getLocation())` lands where the- * finger is, which is what a script that has a camera in hand wants.- *- * `clearFlags` is carried (colour and depth, as the engine has them; a camera drawn over another clears depth only). `clearColor` is held so a- * script can read back what it set, but the engine's clear colour belongs to its renderer settings, not to the camera.- */-import { Camera as EngineCamera, type CameraData } from '../../ecs/component';-import type { World } from '../../ecs/world';-import type { Entity } from '../../types';-import { isProjectable, projectWorldPoint } from '../../ui/util/math';-import { screenToUiWorld } from '../../ui/util/ui-pick';-import { Color, Rect, Vec3 } from '../math';-import { Ray } from '../geometry';-import { Component } from '../component';-import { registerBuiltinComponent } from '../builtins';-import type { Node } from '../node';-import { viewAdapter } from './view';-import { UITransform } from './uiTransform';-import { getWindowPixels, uiCameraData } from './screen';--const ProjectionType = Object.freeze({ ORTHO: 0, PERSPECTIVE: 1 });-const FOVAxis = Object.freeze({ VERTICAL: 0, HORIZONTAL: 1 });-const ClearFlag = Object.freeze({ DONT_CLEAR: 0, DEPTH_ONLY: 6, SOLID_COLOR: 7, SKYBOX: 14 });--/** The engine's camera types: 0 perspective, 1 orthographic. */-const ENGINE_ORTHO = 1;--export class Camera extends Component {- static readonly ProjectionType = ProjectionType;- static readonly FOVAxis = FOVAxis;- static readonly ClearFlag = ClearFlag;-- private data_(): CameraData { return this._world.get(this._entity, EngineCamera); }- private patch_(patch: Partial<CameraData>): void { this._world.set(this._entity, EngineCamera, { ...this.data_(), ...patch }); }-- private clearColor_ = new Color(0, 0, 0, 255);-- get projection(): number { return this.data_().projectionType === ENGINE_ORTHO ? ProjectionType.ORTHO : ProjectionType.PERSPECTIVE; }- set projection(v: number) { this.patch_({ projectionType: v === ProjectionType.ORTHO ? ENGINE_ORTHO : 0 }); }-- /** Half the visible height in world units, as in Cocos. */- get orthoHeight(): number { return this.data_().orthoSize; }- set orthoHeight(v: number) { this.patch_({ orthoSize: v }); }-- get fov(): number { return this.data_().fov; }- set fov(v: number) { this.patch_({ fov: v }); }- get fovAxis(): number { return FOVAxis.VERTICAL; }-- get near(): number { return this.data_().nearPlane; }- set near(v: number) { this.patch_({ nearPlane: v }); }- get far(): number { return this.data_().farPlane; }- set far(v: number) { this.patch_({ farPlane: v }); }-- get priority(): number { return this.data_().priority; }- set priority(v: number) { this.patch_({ priority: v }); }-- /** The layers this camera draws, as a bitmask. */- get visibility(): number { return this.data_().cullingMask >>> 0; }- set visibility(v: number) { this.patch_({ cullingMask: v >>> 0 }); }-- /** The part of the window it draws into, 0..1. */- get rect(): Rect { const v = this.data_().viewport; return new Rect(v.x, v.y, v.z, v.w); }- set rect(r: Rect) { this.patch_({ viewport: { x: r.x, y: r.y, z: r.width, w: r.height } }); }-- get clearFlags(): number {- const engine = this.data_().clearFlags;- return engine === 3 ? ClearFlag.SOLID_COLOR : engine === 2 ? ClearFlag.DEPTH_ONLY : engine === 1 ? ClearFlag.SOLID_COLOR : ClearFlag.DONT_CLEAR;- }- set clearFlags(v: number) { this.patch_({ clearFlags: v === ClearFlag.SKYBOX ? 3 : (v & 1 ? 1 : 0) | (v & 2 ? 2 : 0) }); }- get clearColor(): Color { return this.clearColor_.clone(); }- set clearColor(v: Color) { this.clearColor_ = v.clone(); }-- get enabled(): boolean { return this.data_().isActive; }- set enabled(v: boolean) { this.patch_({ isActive: v }); }-- /**- * The world point under a screen point (pixels of the drawing surface, origin bottom-left — what `EventTouch.getLocation`- * gives). @p screenPos.z is the depth along the view ray; for a flat scene it does not change x and y.- */- screenToWorld(screenPos: Vec3, out: Vec3 = new Vec3()): Vec3 {- const cam = uiCameraData();- if (!cam?.valid) return out.set(0, 0, 0);- const w = screenToUiWorld(cam, screenPos.x, screenPos.y);- return out.set(w.x, w.y, 0);- }-- /**- * The ray from the camera through a screen point (pixels of the drawing surface, origin bottom-left): from the camera's own pose and lens,- * so a perspective camera's rays fan out from its position and an orthographic one's run parallel.- */- screenPointToRay(x: number, y: number, out: Ray = new Ray()): Ray {- const surface = getWindowPixels();- const width = surface.width > 0 ? surface.width : 1;- const height = surface.height > 0 ? surface.height : 1;- const lens = this.data_();- const nx = (x / width) * 2 - 1;- const ny = (y / height) * 2 - 1;- const aspect = width / height;- const rotation = this.node.getWorldRotation();- const position = this.node.getWorldPosition();- const turn = (v: Vec3): Vec3 => Vec3.transformQuat(new Vec3(), v, rotation);- if (lens.projectionType === ENGINE_ORTHO) {- const half = lens.orthoSize;- const origin = turn(new Vec3(nx * half * aspect, ny * half, 0));- const dir = turn(new Vec3(0, 0, -1));- out.o.set(position.x + origin.x, position.y + origin.y, position.z + origin.z);- out.d.set(dir.x, dir.y, dir.z);- return out;- }- const reach = Math.tan((lens.fov * Math.PI) / 360);- const dir = turn(new Vec3(nx * reach * aspect, ny * reach, -1)).normalize();- out.o.set(position.x, position.y, position.z);- out.d.set(dir.x, dir.y, dir.z);- return out;- }-- /** The screen point (surface pixels, origin bottom-left) a world point lands on. */- worldToScreen(worldPos: Vec3, out: Vec3 = new Vec3()): Vec3 {- const cam = uiCameraData();- if (!cam?.valid) return out.set(0, 0, 0);- const p = projectWorldPoint(worldPos.x, worldPos.y, worldPos.z, cam.viewProjection, cam.vpX, cam.vpY, cam.vpW, cam.vpH);- return isProjectable(p) ? out.set(p.x, p.y, 0) : out.set(0, 0, 0);- }-- /** A world point as a point in @p uiNode's space (relative to its anchor): where to put something there that is at @p worldPos. */- convertToUINode(worldPos: Vec3, uiNode: Node, out: Vec3 = new Vec3()): Vec3 {- const t = uiNode.getComponent(UITransform);- if (!t) return out.set(worldPos.x, worldPos.y, worldPos.z);- return t.convertToNodeSpaceAR(worldPos, out);- }-}--const hasCamera = (world: World, entity: Entity): boolean => world.has(entity, EngineCamera);-const addCamera = (world: World, entity: Entity): void => { world.insert(entity, EngineCamera, {}); };--registerBuiltinComponent(Camera, ['cc.Camera', 'Camera'], viewAdapter(Camera, hasCamera, addCamera));diff --git a/sdk/src/cocos/ui/controls.ts b/sdk/src/cocos/ui/controls.tsdeleted file mode 100644index 89fe0834a..000000000--- a/sdk/src/cocos/ui/controls.ts+++ /dev/null@@ -1,297 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/controls.ts- * @brief `Toggle`, `ToggleContainer`, `ProgressBar`, `Slider` and `BlockInputEvents`.- *- * The engine has its own toggles and sliders, but they are built on its flex-laid-out UI nodes; an imported scene is world-space- * nodes with a rectangle each, so these are the Cocos components as small script classes over that, with Cocos's rules:- * a toggle flips on a click that ends inside it, a group keeps one checked unless it allows none, a bar's fill is its length- * times its progress, a slider reads progress from where the finger is along its rectangle.- *- * Like `Button`, they are declared script classes with stored settings, so a scene that holds one loads it.- */-import { Component } from '../component';-import { Node } from '../node';-import { Vec3 } from '../math';-import { declareClass } from '../host';-import { Button, BUTTON_PROPS, EventHandler, joinHandlers } from './button';-import { Sprite } from './sprite';-import { UITransform } from './uiTransform';-import type { EventTouch } from '../input';--type Handlers = { component: string; handler: string; customEventData: string }[];--// ----------------------------------------------------------------------------------------------------------------------// ToggleContainer / Toggle-// -----------------------------------------------------------------------------------------------------------------------export class ToggleContainer extends Component {- allowSwitchOff = false;- checkTargets: Array<Node | null> = [];- checkHandlers: Handlers = [];- checkEvents: EventHandler[] = [];-- onLoad(): void {- if (this.checkEvents.length === 0) this.checkEvents = joinHandlers(this.checkTargets, this.checkHandlers);- }-- onEnable(): void { this.ensureValidState(); }-- /** The toggles under this container that are switched on. */- get toggleItems(): Toggle[] {- const out: Toggle[] = [];- for (const child of this.node.children) {- const t = child.getComponent(Toggle);- if (t && t.enabled && child.active) out.push(t);- }- return out;- }-- /** At least one on unless switching off is allowed, and never more than one. */- ensureValidState(): void {- const items = this.toggleItems;- const checked = items.filter((t) => t.isChecked);- if (!this.allowSwitchOff && checked.length === 0 && items.length > 0) items[0]!.isChecked = true;- else if (checked.length > 1) for (const t of checked.slice(1)) t.isChecked = false;- }-- anyTogglesChecked(): boolean { return this.toggleItems.some((t) => t.isChecked); }- setAllTogglesOff(): void { for (const t of this.toggleItems) t.isChecked = false; }-- /** @internal A toggle in the group switched on: the others go off. */- notifyToggleCheck(toggle: Toggle, emit = true): void {- for (const t of this.toggleItems) if (t !== toggle && t.isChecked) t.setChecked_(false, emit);- if (emit) {- EventHandler.emitEvents(this.checkEvents, toggle);- this.node.emit('toggle', this);- }- }-}--export class Toggle extends Button {- static readonly EventType = Object.freeze({ TOGGLE: 'toggle', CLICK: 'click' });-- private checked_ = false;- /** Whether it is on. Assigning to it switches the others of its group off, as checking it does (without the events). */- get isChecked(): boolean { return this.checked_; }- set isChecked(value: boolean) { this.setChecked_(!!value, false); }- /** The graphic shown while checked. */- checkMark: Sprite | null = null;- toggleGroup: ToggleContainer | null = null;- /** The group it belongs to: the one named, else the container its parent node holds, as in Cocos. */- private group_(): ToggleContainer | null {- return this.toggleGroup ?? this.node.parent?.getComponent(ToggleContainer) ?? null;- }- checkTargets: Array<Node | null> = [];- checkHandlers: Handlers = [];- checkEvents: EventHandler[] = [];-- onLoad(): void {- super.onLoad();- if (this.checkEvents.length === 0) this.checkEvents = joinHandlers(this.checkTargets, this.checkHandlers);- }-- onEnable(): void {- super.onEnable();- this.updateMark_();- }-- /** Check it, as a script's `toggle.check()`: events fire, and its group's others go off. */- check(): void { this.setChecked_(true, true); }- uncheck(): void { this.setChecked_(false, true); }- /** Set without any event. */- setIsCheckedWithoutNotify(value: boolean): void { this.isChecked = value; this.updateMark_(); }-- protected onClicked_(_event: EventTouch): void {- if (!this.interactable) return;- const group = this.group_();- // in a group that needs one on, clicking the one that is on does nothing- if (group && group.enabled && this.isChecked && !group.allowSwitchOff) return;- this.setChecked_(!this.isChecked, true);- }-- /** @internal */- setChecked_(value: boolean, emit: boolean): void {- if (this.checked_ === value) return;- this.checked_ = value;- this.updateMark_();- const group = this.group_();- if (value && group && group.enabled) group.notifyToggleCheck(this, emit);- if (emit) {- EventHandler.emitEvents(this.checkEvents, this);- this.node.emit(Toggle.EventType.TOGGLE, this);- }- }-- private updateMark_(): void {- if (this.checkMark) this.checkMark.node.active = this.isChecked;- }-}--// ----------------------------------------------------------------------------------------------------------------------// ProgressBar-// -----------------------------------------------------------------------------------------------------------------------const BarMode = Object.freeze({ HORIZONTAL: 0, VERTICAL: 1, FILLED: 2 });--export class ProgressBar extends Component {- static readonly Mode = BarMode;-- mode: number = BarMode.HORIZONTAL;- totalLength = 100;- progress_ = 0.5;- reverse = false;- barSprite: Sprite | null = null;-- get progress(): number { return this.progress_; }- set progress(v: number) {- this.progress_ = Math.min(1, Math.max(0, Number.isFinite(v) ? v : 0));- this.update_();- }-- onEnable(): void { this.update_(); }-- private update_(): void {- const bar = this.barSprite;- if (!bar) return;- const length = this.totalLength * this.progress_;- if (this.mode === BarMode.FILLED) {- bar.fillRange = this.reverse ? -this.progress_ : this.progress_;- return;- }- const t = bar.node.getComponent(UITransform);- if (!t) return;- if (this.mode === BarMode.HORIZONTAL) t.width = length; else t.height = length;- }-}--// ----------------------------------------------------------------------------------------------------------------------// Slider-// -----------------------------------------------------------------------------------------------------------------------const SliderDirection = Object.freeze({ HORIZONTAL: 0, VERTICAL: 1 });--export class Slider extends Component {- static readonly Direction = SliderDirection;- static readonly EventType = Object.freeze({ SLIDE: 'slide' });-- direction: number = SliderDirection.HORIZONTAL;- progress_ = 0.5;- handle: Button | null = null;- slideTargets: Array<Node | null> = [];- slideHandlers: Handlers = [];- slideEvents: EventHandler[] = [];-- get progress(): number { return this.progress_; }- set progress(v: number) {- const next = Math.min(1, Math.max(0, Number.isFinite(v) ? v : 0));- if (next === this.progress_) return;- this.progress_ = next;- this.placeHandle_();- EventHandler.emitEvents(this.slideEvents, this);- this.node.emit(Slider.EventType.SLIDE, this);- }-- onLoad(): void {- if (this.slideEvents.length === 0) this.slideEvents = joinHandlers(this.slideTargets, this.slideHandlers);- }-- onEnable(): void {- this.node.on(Node.EventType.TOUCH_START, this.onTouch_, this);- this.node.on(Node.EventType.TOUCH_MOVE, this.onTouch_, this);- const handle = this.handle?.node;- if (handle) {- handle.on(Node.EventType.TOUCH_START, this.onHandleTouch_, this);- handle.on(Node.EventType.TOUCH_MOVE, this.onHandleTouch_, this);- }- this.placeHandle_();- }-- onDisable(): void {- this.node.off(Node.EventType.TOUCH_START, this.onTouch_, this);- this.node.off(Node.EventType.TOUCH_MOVE, this.onTouch_, this);- const handle = this.handle?.node;- if (handle) {- handle.off(Node.EventType.TOUCH_START, this.onHandleTouch_, this);- handle.off(Node.EventType.TOUCH_MOVE, this.onHandleTouch_, this);- }- }-- private onTouch_(event: EventTouch): void {- if (this.handle && !this.handle.interactable) return;- this.slideTo_(event);- event.stopPropagation();- }-- private onHandleTouch_(event: EventTouch): void {- this.slideTo_(event);- event.stopPropagation();- }-- /** Progress from where the finger is along the slider's rectangle. */- private slideTo_(event: EventTouch): void {- const t = this.node.getComponent(UITransform);- if (!t) return;- const loc = event.getUILocation();- const local = t.convertToNodeSpaceAR(new Vec3(loc.x, loc.y, 0));- this.progress = this.direction === SliderDirection.HORIZONTAL- ? (local.x + t.anchorX * t.width) / (t.width || 1)- : (local.y + t.anchorY * t.height) / (t.height || 1);- }-- private placeHandle_(): void {- const handle = this.handle?.node;- const t = this.node.getComponent(UITransform);- if (!handle || !t) return;- const p = handle.getPosition();- if (this.direction === SliderDirection.HORIZONTAL) handle.setPosition(new Vec3(this.progress_ * t.width - t.anchorX * t.width, p.y, p.z));- else handle.setPosition(new Vec3(p.x, this.progress_ * t.height - t.anchorY * t.height, p.z));- }-}--// ----------------------------------------------------------------------------------------------------------------------// BlockInputEvents-// -----------------------------------------------------------------------------------------------------------------------/** A node that takes every touch that lands on it, so nothing behind it hears it. */-export class BlockInputEvents extends Component {- private readonly stop_ = (event: { stopPropagation(): void }): void => { event.stopPropagation(); };- private static readonly TYPES = [Node.EventType.TOUCH_START, Node.EventType.TOUCH_MOVE, Node.EventType.TOUCH_END, Node.EventType.TOUCH_CANCEL];-- onEnable(): void { for (const t of BlockInputEvents.TYPES) this.node.on(t, this.stop_, this); }- onDisable(): void { for (const t of BlockInputEvents.TYPES) this.node.off(t, this.stop_, this); }-}--// -----------------------------------------------------------------------------------------------------------------------export function declareControls(): void {- declareClass(ToggleContainer as never, 'ToggleContainer', [- { name: 'allowSwitchOff', kind: 'boolean' },- { name: 'checkTargets', kind: 'node', array: true },- { name: 'checkHandlers', kind: 'json' },- ]);- declareClass(Toggle as never, 'Toggle', [- ...BUTTON_PROPS,- { name: 'isChecked', kind: 'boolean' },- { name: 'checkMark', kind: 'component', type: Sprite },- { name: 'toggleGroup', kind: 'component', type: ToggleContainer },- { name: 'checkTargets', kind: 'node', array: true },- { name: 'checkHandlers', kind: 'json' },- ]);- declareClass(ProgressBar as never, 'ProgressBar', [- { name: 'mode', kind: 'number' },- { name: 'totalLength', kind: 'number' },- { name: 'progress_', kind: 'number' },- { name: 'reverse', kind: 'boolean' },- { name: 'barSprite', kind: 'component', type: Sprite },- ]);- declareClass(Slider as never, 'Slider', [- { name: 'direction', kind: 'number' },- { name: 'progress_', kind: 'number' },- { name: 'handle', kind: 'component', type: Button },- { name: 'slideTargets', kind: 'node', array: true },- { name: 'slideHandlers', kind: 'json' },- ]);- declareClass(BlockInputEvents as never, 'BlockInputEvents', []);-}diff --git a/sdk/src/cocos/ui/editBox.ts b/sdk/src/cocos/ui/editBox.tsdeleted file mode 100644index eff4cfa7b..000000000--- a/sdk/src/cocos/ui/editBox.ts+++ /dev/null@@ -1,201 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/editBox.ts- * @brief `EditBox`: a view on the engine's `TextInput`, as `Label` is a view on `Text`.- *- * The engine's field does everything an edit box does — it takes focus on a press, holds the value and the selection on the platform's own- * text surface (a hidden textarea on the web, the soft keyboard and its IME on a device), draws the text, the hint, the caret and the- * selection, and scrolls to keep the caret in view. An imported scene's edit box is that field on the node that was the box, with the- * style its two labels carried; nothing here holds a second copy of any of it. What a script reaches through `textLabel` and- * `placeholderLabel` — a colour, a size, a string — is the field's own style, handed back as a label-shaped object.- */-import { Component } from '../component';-import { Node } from '../node';-import type { World } from '../../ecs/world';-import type { Entity } from '../../types';-import { TextInput, TextInputFilter, type TextInputData } from '../../ui/text/text-input';-import { TextAlign } from '../../ui/core/text';-import { FocusManager, Focusable, type FocusManagerState } from '../../ui/input/focusable';-import { UIEventType } from '../../ui/core/events';-import { EntityEvents, type EntityEventQueue } from '../../ecs/entityEvents';-import { Schedule, defineSystem, addSystemToSchedule, GetWorld } from '../../ecs/system';-import { Res } from '../../ecs/resource';-import { SystemLabel } from '../../ecs/systemLabels';-import { Color } from '../math';-import { registerBuiltinComponent } from '../builtins';-import { toCocosColor, toEngineColor, viewAdapter } from './view';--const InputMode = Object.freeze({ ANY: 0, EMAIL: 1, NUMERIC: 2, PHONE_NUMBER: 3, URL: 4, DECIMAL: 5, SINGLE_LINE: 6 });-const InputFlag = Object.freeze({ PASSWORD: 0, SENSITIVE: 1, INITIAL_CAPS_WORD: 2, INITIAL_CAPS_SENTENCE: 3, INITIAL_CAPS_ALL_CHARACTERS: 4, DEFAULT: 5 });-const KeyboardReturnType = Object.freeze({ DEFAULT: 0, DONE: 1, SEND: 2, SEARCH: 3, GO: 4, NEXT: 5 });-const EventType = Object.freeze({- EDITING_DID_BEGAN: 'editing-did-began', EDITING_DID_ENDED: 'editing-did-ended', TEXT_CHANGED: 'text-changed', EDITING_RETURN: 'editing-return',-});--/** The filter and the line mode the engine's field has for a Cocos input mode. */-function fieldMode(mode: number): { inputFilter: TextInputFilter; multiline: boolean } {- switch (mode) {- case InputMode.NUMERIC: return { inputFilter: TextInputFilter.Digits, multiline: false };- case InputMode.DECIMAL: return { inputFilter: TextInputFilter.Decimal, multiline: false };- case InputMode.PHONE_NUMBER: return { inputFilter: TextInputFilter.Phone, multiline: false };- case InputMode.EMAIL:- case InputMode.URL:- case InputMode.SINGLE_LINE: return { inputFilter: TextInputFilter.None, multiline: false };- default: return { inputFilter: TextInputFilter.None, multiline: true };- }-}--/** The Cocos input mode a field's settings say, as far as they can: the filter decides, then the line mode. */-function modeOf(data: TextInputData): number {- if (data.inputFilter === TextInputFilter.Digits) return InputMode.NUMERIC;- if (data.inputFilter === TextInputFilter.Decimal) return InputMode.DECIMAL;- if (data.inputFilter === TextInputFilter.Phone) return InputMode.PHONE_NUMBER;- return data.multiline ? InputMode.ANY : InputMode.SINGLE_LINE;-}--/**- * What a script holds as an edit box's `textLabel` or `placeholderLabel`: the style of the field's text or of its hint, with a label's- * names. There is no node behind it — the engine draws the field's text itself — so the properties read and write the field.- */-class FieldLabel {- constructor(private readonly box: EditBox, private readonly hint: boolean) {}-- get node(): Node { return this.box.node; }- get enabled(): boolean { return true; }- set enabled(_v: boolean) {}-- get string(): string { return this.hint ? this.box.placeholder : this.box.string; }- set string(v: string) { if (this.hint) this.box.placeholder = v; else this.box.string = v; }-- get color(): Color { const d = this.box._data(); return toCocosColor(this.hint ? d.placeholderColor : d.color); }- set color(v: Color) { this.box._patch(this.hint ? { placeholderColor: toEngineColor(v) } : { color: toEngineColor(v) }); }-- get fontSize(): number { return this.box._data().fontSize; }- set fontSize(v: number) { this.box._patch({ fontSize: v }); }- get actualFontSize(): number { return this.fontSize; }- get fontFamily(): string { return this.box._data().fontFamily; }- set fontFamily(v: string) { this.box._patch({ fontFamily: v }); }-- /** The field lays its lines out at a fixed ratio of the size; a script that reads the pixel height gets that one back. */- lineHeight = 0;- horizontalAlign = 0;- verticalAlign = 1;- overflow = 0;- enableWrapText = false;- isBold = false;- isItalic = false;- isUnderline = false;- useSystemFont = true;- cacheMode = 0;- updateRenderData(_force = false): void {}- markForUpdateRenderData(_enable = true): void {}-}--export class EditBox extends Component {- static readonly EventType = EventType;- static readonly InputMode = InputMode;- static readonly InputFlag = InputFlag;- static readonly KeyboardReturnType = KeyboardReturnType;-- /** @internal */- _data(): TextInputData { return this._world.get(this._entity, TextInput); }- /** @internal */- _patch(patch: Partial<TextInputData>): void { this._world.set(this._entity, TextInput, { ...this._data(), ...patch }); }-- returnType: number = KeyboardReturnType.DEFAULT;- private readonly textLabel_ = new FieldLabel(this, false);- private readonly placeholderLabel_ = new FieldLabel(this, true);-- get textLabel(): FieldLabel { return this.textLabel_; }- set textLabel(_v: unknown) {}- get placeholderLabel(): FieldLabel { return this.placeholderLabel_; }- set placeholderLabel(_v: unknown) {}-- get string(): string { return this._data().value; }- set string(value: string) {- const text = value === null || value === undefined ? '' : String(value);- // the field's own rules apply to what a script puts in as to what is typed: the caret follows to the end of it- this._patch({ value: text, cursorPos: text.length });- }-- /** The hint shown while the field is empty. */- get placeholder(): string { return this._data().placeholder; }- set placeholder(value: string) { this._patch({ placeholder: value }); }-- get maxLength(): number { return this._data().maxLength || -1; }- set maxLength(value: number) { this._patch({ maxLength: value > 0 ? value : 0 }); }-- get inputMode(): number { return modeOf(this._data()); }- set inputMode(value: number) { this._patch(fieldMode(value)); }-- get inputFlag(): number { return this._data().password ? InputFlag.PASSWORD : InputFlag.DEFAULT; }- set inputFlag(value: number) { this._patch({ password: value === InputFlag.PASSWORD }); }-- get tabIndex(): number { return this._world.tryGet(this._entity, Focusable)?.tabIndex ?? 0; }- set tabIndex(value: number) {- const focusable = this._world.tryGet(this._entity, Focusable);- if (focusable) this._world.set(this._entity, Focusable, { ...focusable, tabIndex: value });- }-- get enabled(): boolean { return !this._data().readOnly; }- set enabled(value: boolean) { this._patch({ readOnly: !value }); }-- isFocused(): boolean { return this._data().focused; }-- /** Take the keyboard, as a press on the box does. */- focus(): void {- focusOf.get(this._world)?.focus(this._entity, false);- }-- /** Give the keyboard back. */- blur(): void {- const manager = focusOf.get(this._world);- if (manager?.focusedEntity === this._entity) manager.blur();- }-}--/** The focus manager of each world, learned from the frame loop that runs the systems below. */-const focusOf = new WeakMap<World, FocusManagerState>();--const hasField = (world: World, entity: Entity): boolean => world.has(entity, TextInput);-const addField = (world: World, entity: Entity): void => {- // a text surface that holds one line unless the script says otherwise, as a Cocos box's default mode is any text with a line limit of its own- world.insert(entity, TextInput, { ...fieldMode(InputMode.ANY), maxLength: 20 });-};--registerBuiltinComponent(EditBox, ['cc.EditBox', 'EditBox'], viewAdapter(EditBox, hasField, addField));--/** What the engine's field says happened, as the events a Cocos edit box emits on its node. */-const ToCocos: Record<string, string> = {- [UIEventType.Focus]: EventType.EDITING_DID_BEGAN,- [UIEventType.Blur]: EventType.EDITING_DID_ENDED,- [UIEventType.Change]: EventType.TEXT_CHANGED,- [UIEventType.Submit]: EventType.EDITING_RETURN,-};-const subscribed = new WeakMap<object, WeakSet<object>>();--/** Register the system that turns the field's events into the edit box's, for a script that listens on the node. */-export function declareEditBox(): void {- addSystemToSchedule(Schedule.PreUpdate, defineSystem(- [Res(EntityEvents), Res(FocusManager), GetWorld()],- (events, focus, world) => {- if (focus) focusOf.set(world, focus as FocusManagerState);- if (!events) return;- const queue = events as EntityEventQueue;- let seen = subscribed.get(world);- if (!seen) subscribed.set(world, (seen = new WeakSet()));- if (seen.has(queue)) return;- seen.add(queue);- for (const [engineType, cocosType] of Object.entries(ToCocos)) {- queue.on(engineType, (e) => {- // an event bubbles to interactable ancestors as copies; the node tree does its own, from the original only- if (e.currentTarget !== e.target || !world.valid(e.target) || !world.has(e.target, TextInput)) return;- const node = Node.for(world, e.target);- node.emit(cocosType, node.getComponent(EditBox));- });- }- },- { name: 'Cocos:EditBoxEvents', touches: { opaque: true }, runAfter: [SystemLabel.UIInteraction] },- ));-}diff --git a/sdk/src/cocos/ui/graphics.ts b/sdk/src/cocos/ui/graphics.tsdeleted file mode 100644index dd9933278..000000000--- a/sdk/src/cocos/ui/graphics.ts+++ /dev/null@@ -1,315 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/graphics.ts- * @brief `Graphics` and `Line`: path-drawing components, over the engine's vector paths.- *- * A scene stores only a Graphics' style (line width, colours); its picture is what scripts draw with `moveTo`, `lineTo`, `rect`, `circle`,- * `stroke` and `fill`, and Cocos keeps that picture until `clear()`. So this records the drawing and turns it into the geometry of the node's own- * `MeshRenderer` (the engine's `buildPathGeometry`: ear-clipped fills, strokes with the line join and cap Cocos names), which is retained,- * sorted and batched like any mesh and moves with the node. Nothing is redrawn per frame; the geometry is rebuilt on the frame after a change.- */-import { Component } from '../component';-import { UIRenderer } from './renderer';-import { Color, Vec2 } from '../math';-import { declareClass } from '../host';-import { Schedule, defineSystem, addSystemToSchedule } from '../../ecs/system';-import { Res } from '../../ecs/resource';-import { MeshRenderer } from '../../ecs/component';-import { MeshRenderers, type MeshRendererAPI } from '../../render/meshRenderer';-import { buildPathGeometry, mergeGeometry, type LineCap, type LineJoin, type PathColor } from '../../render/vectorPath';-import type { MeshRendererGeometry } from '../../ecs/component';--interface Subpath {- points: Vec2[];- closed: boolean;-}--interface Op {- kind: 'stroke' | 'fill';- paths: Subpath[];- color: PathColor;- width: number;- join: LineJoin;- cap: LineCap;- miterLimit: number;-}--const SEGMENTS_PER_CURVE = 16;-const JOINS: LineJoin[] = ['bevel', 'round', 'miter'];-const CAPS: LineCap[] = ['butt', 'round', 'square'];--const toColor = (c: Color): PathColor => [c.r / 255, c.g / 255, c.b / 255, c.a / 255];--/** The engine's geometry API, handed over by the frame (a component has no app to ask). */-let meshApi: MeshRendererAPI | null = null;--export class Graphics extends UIRenderer {- static readonly LineJoin = Object.freeze({ BEVEL: 0, ROUND: 1, MITER: 2 });- static readonly LineCap = Object.freeze({ BUTT: 0, ROUND: 1, SQUARE: 2 });-- lineWidth = 1;- lineJoin = 2;- lineCap = 0;- miterLimit = 10;- strokeColor: Color = new Color(0, 0, 0, 255);- fillColor: Color = new Color(255, 255, 255, 255);-- private path_: Subpath[] = [];- private cursor_: Vec2 | null = null;- private drawn_ = false;- private ops_: Op[] = [];- private dirty_ = false;-- // ---- building a path ----------------------------------------------------------------------------------------------- /** A path begun after something was drawn is a new one: the earlier shapes are on the canvas, not in the path. */- private fresh_(): void {- if (this.drawn_) { this.path_ = []; this.drawn_ = false; }- }-- private current_(): Subpath {- this.fresh_();- let sub = this.path_[this.path_.length - 1];- if (!sub || sub.closed) {- sub = { points: this.cursor_ ? [this.cursor_] : [], closed: false };- this.path_.push(sub);- }- return sub;- }-- moveTo(x: number, y: number): void {- this.fresh_();- this.cursor_ = new Vec2(x, y);- this.path_.push({ points: [this.cursor_], closed: false });- }-- lineTo(x: number, y: number): void {- const sub = this.current_();- this.cursor_ = new Vec2(x, y);- sub.points.push(this.cursor_);- }-- bezierCurveTo(c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number): void {- const sub = this.current_();- const from = sub.points[sub.points.length - 1] ?? new Vec2(c1x, c1y);- for (let i = 1; i <= SEGMENTS_PER_CURVE; i++) {- const t = i / SEGMENTS_PER_CURVE, u = 1 - t;- sub.points.push(new Vec2(- u * u * u * from.x + 3 * u * u * t * c1x + 3 * u * t * t * c2x + t * t * t * x,- u * u * u * from.y + 3 * u * u * t * c1y + 3 * u * t * t * c2y + t * t * t * y));- }- this.cursor_ = new Vec2(x, y);- }-- quadraticCurveTo(cx: number, cy: number, x: number, y: number): void {- const sub = this.current_();- const from = sub.points[sub.points.length - 1] ?? new Vec2(cx, cy);- for (let i = 1; i <= SEGMENTS_PER_CURVE; i++) {- const t = i / SEGMENTS_PER_CURVE, u = 1 - t;- sub.points.push(new Vec2(u * u * from.x + 2 * u * t * cx + t * t * x, u * u * from.y + 2 * u * t * cy + t * t * y));- }- this.cursor_ = new Vec2(x, y);- }-- arc(cx: number, cy: number, r: number, startAngle: number, endAngle: number, counterclockwise: boolean): void {- const sub = this.current_();- let sweep = endAngle - startAngle;- if (counterclockwise && sweep > 0) sweep -= Math.PI * 2;- if (!counterclockwise && sweep < 0) sweep += Math.PI * 2;- const steps = Math.max(4, Math.ceil((Math.abs(sweep) / (Math.PI * 2)) * 48));- for (let i = 0; i <= steps; i++) {- const a = startAngle + (sweep * i) / steps;- sub.points.push(new Vec2(cx + Math.cos(a) * r, cy + Math.sin(a) * r));- }- this.cursor_ = sub.points[sub.points.length - 1]!;- }-- private closedShape_(points: Vec2[]): void {- this.fresh_();- this.path_.push({ points, closed: true });- this.cursor_ = points[0] ?? null;- }-- rect(x: number, y: number, w: number, h: number): void {- this.closedShape_([new Vec2(x, y), new Vec2(x + w, y), new Vec2(x + w, y + h), new Vec2(x, y + h)]);- }-- roundRect(x: number, y: number, w: number, h: number, r: number): void {- const radius = Math.min(Math.abs(r), Math.abs(w) / 2, Math.abs(h) / 2);- if (radius === 0) { this.rect(x, y, w, h); return; }- const pts: Vec2[] = [];- const corner = (cx: number, cy: number, from: number): void => {- for (let i = 0; i <= 8; i++) {- const a = from + (Math.PI / 2) * (i / 8);- pts.push(new Vec2(cx + Math.cos(a) * radius, cy + Math.sin(a) * radius));- }- };- corner(x + w - radius, y + radius, -Math.PI / 2);- corner(x + w - radius, y + h - radius, 0);- corner(x + radius, y + h - radius, Math.PI / 2);- corner(x + radius, y + radius, Math.PI);- this.closedShape_(pts);- }-- fillRect(x: number, y: number, w: number, h: number): void {- this.rect(x, y, w, h);- this.fill();- }-- circle(cx: number, cy: number, r: number): void { this.ellipse(cx, cy, r, r); }-- ellipse(cx: number, cy: number, rx: number, ry: number): void {- const n = Math.max(24, Math.min(96, Math.ceil(Math.max(Math.abs(rx), Math.abs(ry)) / 2)));- const pts: Vec2[] = [];- for (let i = 0; i < n; i++) pts.push(new Vec2(cx + Math.cos((i / n) * Math.PI * 2) * rx, cy + Math.sin((i / n) * Math.PI * 2) * ry));- this.closedShape_(pts);- }-- close(): void {- const sub = this.path_[this.path_.length - 1];- if (sub) { sub.closed = true; this.cursor_ = sub.points[0] ?? null; }- }-- // ---- painting it ----------------------------------------------------------------------------------------------------- private snapshot_(): Subpath[] {- return this.path_.filter((p) => p.points.length > 0).map((p) => ({ closed: p.closed, points: p.points.map((v) => v.clone()) }));- }-- stroke(): void {- this.ops_.push({- kind: 'stroke', paths: this.snapshot_(), color: toColor(this.strokeColor), width: this.lineWidth,- join: JOINS[this.lineJoin] ?? 'miter', cap: CAPS[this.lineCap] ?? 'butt', miterLimit: this.miterLimit,- });- this.drawn_ = true;- this.dirty_ = true;- }-- fill(): void {- this.ops_.push({ kind: 'fill', paths: this.snapshot_(), color: toColor(this.fillColor), width: 0, join: 'miter', cap: 'butt', miterLimit: 4 });- this.drawn_ = true;- this.dirty_ = true;- }-- clear(): void {- this.ops_ = [];- this.path_ = [];- this.cursor_ = null;- this.drawn_ = false;- this.dirty_ = true;- }-- // ---- into the engine --------------------------------------------------------------------------------------------------- update(): void {- if (this.dirty_ && meshApi) this.upload_(meshApi);- }-- onDisable(): void {- // a Graphics that is off draws nothing; its picture is kept and comes back when it is on- meshApi?.clearGeometry(this.node._entity);- this.dirty_ = true;- }-- private upload_(api: MeshRendererAPI): void {- this.dirty_ = false;- putGeometry(this, api, this.geometry());- }-- /** What the recorded drawing is as geometry, in this node's own space. */- geometry(): MeshRendererGeometry {- const parts: MeshRendererGeometry[] = [];- for (const op of this.ops_) {- for (const sub of op.paths) {- const points = sub.points;- if (op.kind === 'fill') {- if (points.length >= 3) parts.push(buildPathGeometry(points, { fill: { color: op.color }, closed: true }));- } else if (points.length >= 2) {- parts.push(buildPathGeometry(points, {- stroke: { color: op.color, width: op.width, join: op.join, cap: op.cap, miterLimit: op.miterLimit }, closed: sub.closed,- }));- }- }- }- return mergeGeometry(parts);- }-}--/** Give a component's node the geometry as its mesh, or take its mesh away when there is none. */-function putGeometry(component: Component, api: MeshRendererAPI, geometry: MeshRendererGeometry): void {- const entity = component.node._entity;- if (geometry.indices.length === 0) { api.clearGeometry(entity); return; }- if (!component._world.has(entity, MeshRenderer)) component._world.insert(entity, MeshRenderer, { enabled: true });- api.setGeometry(entity, geometry);-}--// ----------------------------------------------------------------------------------------------------------------------// Line-// -----------------------------------------------------------------------------------------------------------------------/** `Line`: a polyline of a width and a colour. Its points are the world's (`worldSpace`) or the node's own. */-export class Line extends Component {- private positions_: Array<{ x: number; y: number; z: number }> = [];- worldSpace = true;- width = 1;- color: Color = new Color(255, 255, 255, 255);- private dirty_ = true;-- get positions(): Array<{ x: number; y: number; z: number }> { return this.positions_; }- set positions(value: Array<{ x: number; y: number; z: number }>) { this.positions_ = value; this.dirty_ = true; }-- update(): void {- if (!this.dirty_ || !meshApi) return;- this.dirty_ = false;- putGeometry(this, meshApi, this.geometry());- }-- onDisable(): void {- meshApi?.clearGeometry(this.node._entity);- this.dirty_ = true;- }-- /** The polyline as geometry in the node's space: a world-space line is carried back through the node's place. */- geometry(): MeshRendererGeometry {- if (this.positions_.length < 2) return { positions: [], colors: [], indices: [] };- let points: Vec2[] = this.positions_.map((p) => new Vec2(p.x, p.y));- if (this.worldSpace) {- const node = this.node;- const p = node.worldPosition, s = node.worldScale, q = node.worldRotation;- const angle = 2 * Math.atan2(q.z, q.w);- const cos = Math.cos(-angle), sin = Math.sin(-angle);- points = points.map((v) => {- const x = v.x - p.x, y = v.y - p.y;- return new Vec2((x * cos - y * sin) / (s.x || 1), (x * sin + y * cos) / (s.y || 1));- });- }- return buildPathGeometry(points, { stroke: { color: toColor(this.color), width: this.width, join: 'round', cap: 'butt' } });- }-}--/** Test seam: the geometry API the frame would hand over. */-export function setGraphicsMeshApi(api: MeshRendererAPI | null): void { meshApi = api; }--export function declareGraphics(): void {- declareClass(Graphics as never, 'Graphics', [- { name: 'lineWidth', kind: 'number' },- { name: 'lineJoin', kind: 'number' },- { name: 'lineCap', kind: 'number' },- { name: 'miterLimit', kind: 'number' },- { name: 'strokeColor', kind: 'color' },- { name: 'fillColor', kind: 'color' },- ]);- declareClass(Line as never, 'Line', [- { name: 'worldSpace', kind: 'boolean' },- { name: 'width', kind: 'number' },- { name: 'color', kind: 'color' },- { name: 'positions', kind: 'json' },- ]);- // The geometry API lives on the app; a component has no way to ask for it, so a system hands it over each frame.- addSystemToSchedule(Schedule.PreUpdate, defineSystem(- [Res(MeshRenderers)],- (api) => { if (api) meshApi = api; },- { name: 'Cocos:GraphicsApi', touches: { opaque: true } },- ));-}diff --git a/sdk/src/cocos/ui/index.ts b/sdk/src/cocos/ui/index.tsdeleted file mode 100644index 09e784162..000000000--- a/sdk/src/cocos/ui/index.ts+++ /dev/null@@ -1,22 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/index.ts- * @brief Cocos's built-in UI components, as views on the engine's. Importing this registers their adapters.- */-export { UITransform, ensureUITransform } from './uiTransform';-export { Label, LabelOutline, LabelShadow } from './label';-export { Sprite, UIOpacity } from './sprite';-export { Button, EventHandler, declareButton } from './button';-export { Toggle, ToggleContainer, ProgressBar, Slider, BlockInputEvents } from './controls';-export { ScrollView } from './scrollView';-export { Widget, alignWidget } from './widget';-export { Layout } from './layout';-export { getVisibleSize, setVisibleSize } from './screen';-export { Camera } from './camera';-export { RichText } from './richText';-export { Mask } from './mask';-export { Graphics, Line } from './graphics';-export { EditBox } from './editBox';-export { PageView, PageViewIndicator, ScrollBar } from './pages';-export { SafeArea, WebView } from './misc';diff --git a/sdk/src/cocos/ui/label.ts b/sdk/src/cocos/ui/label.tsdeleted file mode 100644index 1d46da274..000000000--- a/sdk/src/cocos/ui/label.ts+++ /dev/null@@ -1,137 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/label.ts- * @brief `Label`, `LabelOutline` and `LabelShadow`: views on the engine's `Text`.- *- * Every field a script sets maps to a `Text` field, converted at the boundary: colours between Cocos's 0..255 and the engine's- * 0..1, line height between pixels and a ratio of the font size, and the three enums, whose numbers agree for alignment and differ- * for overflow (Cocos's `SHRINK` is 2, the engine's is 3). Nothing is held here: a `Label` is the `Text` on its node.- */-import { Text, TextOverflow, type TextData } from '../../ui/core/text';-import type { World } from '../../ecs/world';-import type { Entity } from '../../types';-import { Color } from '../math';-import { Component } from '../component';-import { UIRenderer } from './renderer';-import { registerBuiltinComponent } from '../builtins';-import { toCocosColor, toEngineColor, viewAdapter } from './view';--/** Cocos's `Label.Overflow`: NONE, CLAMP, SHRINK, RESIZE_HEIGHT. */-const Overflow = Object.freeze({ NONE: 0, CLAMP: 1, SHRINK: 2, RESIZE_HEIGHT: 3 });-const HorizontalAlign = Object.freeze({ LEFT: 0, CENTER: 1, RIGHT: 2 });-const VerticalAlign = Object.freeze({ TOP: 0, CENTER: 1, BOTTOM: 2 });-const CacheMode = Object.freeze({ NONE: 0, BITMAP: 1, CHAR: 2 });--function toEngineOverflow(cocos: number): number {- if (cocos === Overflow.CLAMP) return TextOverflow.Clip;- if (cocos === Overflow.SHRINK) return TextOverflow.Shrink;- if (cocos === Overflow.RESIZE_HEIGHT) return TextOverflow.ResizeHeight;- return TextOverflow.Visible;-}--function toCocosOverflow(engine: number): number {- if (engine === TextOverflow.Clip || engine === TextOverflow.Ellipsis) return Overflow.CLAMP;- if (engine === TextOverflow.Shrink) return Overflow.SHRINK;- if (engine === TextOverflow.ResizeHeight) return Overflow.RESIZE_HEIGHT;- return Overflow.NONE;-}--/** The `Text` data of an entity: the thing every property below reads and writes. */-export class TextView extends UIRenderer {- protected text_(): TextData { return this._world.get(this._entity, Text); }- protected patch_(patch: Partial<TextData>): void { this._world.set(this._entity, Text, { ...this.text_(), ...patch }); }-}--export class Label extends TextView {- static readonly Overflow = Overflow;- static readonly HorizontalAlign = HorizontalAlign;- static readonly VerticalAlign = VerticalAlign;- static readonly CacheMode = CacheMode;-- /** The text shown. A script writes `label.string = ...` more than anything else it does. */- get string(): string { return this.text_().content; }- set string(v: string) { this.patch_({ content: v === undefined || v === null ? '' : String(v) }); }-- get color(): Color { return toCocosColor(this.text_().color); }- set color(v: Color) { this.patch_({ color: toEngineColor(v) }); }-- get fontSize(): number { return this.text_().fontSize; }- set fontSize(v: number) {- // Cocos keeps lineHeight in pixels, the engine as a ratio of the size: keep the pixel value across a size change.- const t = this.text_();- const px = t.lineHeight * t.fontSize;- this.patch_({ fontSize: v, lineHeight: v > 0 ? px / v : t.lineHeight });- }- get actualFontSize(): number { return this.text_().fontSize; }-- get lineHeight(): number { const t = this.text_(); return t.lineHeight * t.fontSize; }- set lineHeight(px: number) { const t = this.text_(); this.patch_({ lineHeight: t.fontSize > 0 ? px / t.fontSize : t.lineHeight }); }-- get horizontalAlign(): number { return this.text_().align; }- set horizontalAlign(v: number) { this.patch_({ align: v as TextData['align'] }); }- get verticalAlign(): number { return this.text_().verticalAlign; }- set verticalAlign(v: number) { this.patch_({ verticalAlign: v as TextData['verticalAlign'] }); }-- get overflow(): number { return toCocosOverflow(this.text_().overflow); }- set overflow(v: number) { this.patch_({ overflow: toEngineOverflow(v) as TextData['overflow'] }); }-- get enableWrapText(): boolean { return this.text_().wordWrap; }- set enableWrapText(v: boolean) { this.patch_({ wordWrap: v }); }-- get isUnderline(): boolean { return this.text_().underline === true; }- set isUnderline(v: boolean) { this.patch_({ underline: v }); }-- get isBold(): boolean { return this.text_().bold; }- set isBold(v: boolean) { this.patch_({ bold: v }); }- get isItalic(): boolean { return this.text_().italic; }- set isItalic(v: boolean) { this.patch_({ italic: v }); }-- get fontFamily(): string { return this.text_().fontFamily; }- set fontFamily(v: string) { this.patch_({ fontFamily: v }); }- /** Whether a font file is not in use. Reading only: which font is drawn is `Text.font`. */- get useSystemFont(): boolean { return !this.text_().font; }- set useSystemFont(_v: boolean) {}-- // What a game that patches the engine's `Label` (a replaced `string` setter, a replaced `onEnable`) reads and writes of its internals: the- // same data as the properties above, so the patch lands on the `Text` instead of on a field nothing draws from.- get _string(): string { return this.text_().content; }- set _string(v: string) { this.patch_({ content: v }); }- get _fontFamily(): string { return this.text_().fontFamily; }- set _fontFamily(v: string) { this.patch_({ fontFamily: v }); }- get _isSystemFontUsed(): boolean { return !this.text_().font; }- set _isSystemFontUsed(_v: boolean) {}- _font: unknown = null;- _applyFontTexture(): void {}-- /** The measured size of the text is the engine's layout to know; a no-op here, as a script calls it to force a refresh. */- updateRenderData(_force = false): void {}-- get enabled(): boolean { return this.text_().enabled; }- set enabled(v: boolean) { this.patch_({ enabled: v }); }-}--export class LabelOutline extends TextView {- get color(): Color { return toCocosColor(this.text_().strokeColor); }- set color(v: Color) { this.patch_({ strokeColor: toEngineColor(v) }); }- get width(): number { return this.text_().strokeWidth; }- set width(v: number) { this.patch_({ strokeWidth: v }); }-}--export class LabelShadow extends TextView {- get color(): Color { return toCocosColor(this.text_().shadowColor); }- set color(v: Color) { this.patch_({ shadowColor: toEngineColor(v) }); }- get offset(): { x: number; y: number } { const t = this.text_(); return { x: t.shadowOffsetX, y: -t.shadowOffsetY }; }- set offset(v: { x: number; y: number }) { this.patch_({ shadowOffsetX: v.x, shadowOffsetY: -v.y }); }- get blur(): number { return this.text_().shadowBlur; }- set blur(v: number) { this.patch_({ shadowBlur: v }); }-}--const hasText = (world: World, entity: Entity): boolean => world.has(entity, Text);-const addText = (world: World, entity: Entity): void => { world.insert(entity, Text, {}); };--registerBuiltinComponent(Label, ['cc.Label', 'Label'], viewAdapter(Label, hasText, addText));-// Outline and shadow are properties of the same Text: present when it has any, and adding one does not give it a visible effect until-// the script sets a width or an offset.-registerBuiltinComponent(LabelOutline, ['cc.LabelOutline', 'LabelOutline'], viewAdapter(LabelOutline, hasText, addText));-registerBuiltinComponent(LabelShadow, ['cc.LabelShadow', 'LabelShadow'], viewAdapter(LabelShadow, hasText, addText));diff --git a/sdk/src/cocos/ui/layout.ts b/sdk/src/cocos/ui/layout.tsdeleted file mode 100644index 8faf555bc..000000000--- a/sdk/src/cocos/ui/layout.ts+++ /dev/null@@ -1,327 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/layout.ts- * @brief `Layout`: a container that arranges its children in a row, a column or a grid.- *- * The arithmetic is Cocos's, ported rather than re-derived, so a list lands where it landed there: positions come from the layout's- * anchor and padding, each child contributes its size (times its scale only if `affectedByScale`), and a row or column breaks when- * the next child would cross the far edge, or at a fixed count. `resizeMode` lets the container grow to fit (CONTAINER) or the- * children stretch to fill it (CHILDREN).- *- * Cocos relayouts when something it listens to changes. Here the pass compares what the layout depends on — its settings and the- * active children with their sizes — against what it saw last, and relayouts on a difference, which is the same trigger without a- * listener on every child. `updateLayout()` forces it now.- */-import { Component } from '../component';-import { Node } from '../node';-import { Size, Vec3 } from '../math';-import { declareClass } from '../host';-import { instancesOfClass } from '../registry';-import type { World } from '../../ecs/world';-import type { Entity } from '../../types';-import { UITransform } from './uiTransform';-import { depthOf } from './widget';--const Type = Object.freeze({ NONE: 0, HORIZONTAL: 1, VERTICAL: 2, GRID: 3 });-const ResizeMode = Object.freeze({ NONE: 0, CONTAINER: 1, CHILDREN: 2 });-const AxisDirection = Object.freeze({ HORIZONTAL: 0, VERTICAL: 1 });-const VerticalDirection = Object.freeze({ BOTTOM_TO_TOP: 0, TOP_TO_BOTTOM: 1 });-const HorizontalDirection = Object.freeze({ LEFT_TO_RIGHT: 0, RIGHT_TO_LEFT: 1 });-const Constraint = Object.freeze({ NONE: 0, FIXED_ROW: 1, FIXED_COL: 2 });--const SETTINGS = [- 'type', 'resizeMode', 'paddingLeft', 'paddingRight', 'paddingTop', 'paddingBottom', 'spacingX', 'spacingY',- 'verticalDirection', 'horizontalDirection', 'affectedByScale', 'cellWidth', 'cellHeight', 'startAxis', 'constraint', 'constraintNum', 'isAlign',-] as const;--export class Layout extends Component {- static readonly Type = Type;- static readonly ResizeMode = ResizeMode;- static readonly AxisDirection = AxisDirection;- static readonly VerticalDirection = VerticalDirection;- static readonly HorizontalDirection = HorizontalDirection;- static readonly Constraint = Constraint;-- type: number = Type.NONE;- resizeMode: number = ResizeMode.NONE;- paddingLeft = 0;- paddingRight = 0;- paddingTop = 0;- paddingBottom = 0;- spacingX = 0;- spacingY = 0;- verticalDirection: number = VerticalDirection.TOP_TO_BOTTOM;- horizontalDirection: number = HorizontalDirection.LEFT_TO_RIGHT;- affectedByScale = false;- cellWidth = 40;- cellHeight = 40;- startAxis: number = AxisDirection.HORIZONTAL;- constraint: number = Constraint.NONE;- constraintNum = 2;- isAlign = false;-- /** @internal */- _seen = '';-- get cellSize(): Size { return new Size(this.cellWidth, this.cellHeight); }- set cellSize(v: Size) { this.cellWidth = v.width; this.cellHeight = v.height; }- get alignHorizontal(): boolean { return this.isAlign; }- set alignHorizontal(v: boolean) { this.isAlign = v; }- get alignVertical(): boolean { return this.isAlign; }- set alignVertical(v: boolean) { this.isAlign = v; }- get padding(): number { return this.paddingLeft; }- set padding(v: number) { this.paddingLeft = this.paddingRight = this.paddingTop = this.paddingBottom = v; }-- /** Arrange the children now, rather than at the end of the frame. */- updateLayout(force = false): void {- if (force) this._seen = '';- layoutNode(this);- this._seen = this.signature_();- }-- /** @internal What the layout depends on: its settings, and the useful children with their sizes. */- signature_(): string {- let s = '';- for (const k of SETTINGS) s += `${this[k]},`;- const own = this.node.getComponent(UITransform);- if (own) s += `${own.width},${own.height},${own.anchorX},${own.anchorY}`;- const scaled = this.affectedByScale;- for (const t of usefulChildren(this)) {- const sc = scaled ? t.node.getScale() : null;- s += `|${t.node._entity},${t.width},${t.height}${sc ? `,${sc.x},${sc.y}` : ''}`;- }- return s;- }-}--/** Active children that have a rectangle, in sibling order. */-function usefulChildren(layout: Layout): UITransform[] {- const out: UITransform[] = [];- for (const child of layout.node.children) {- if (!child.active) continue;- const t = child.getComponent(UITransform);- if (t) out.push(t);- }- return out;-}--const used = (layout: Layout, scale: number): number => (layout.affectedByScale ? Math.abs(scale) : 1);-const paddingH = (l: Layout): number => l.paddingLeft + l.paddingRight;-const paddingV = (l: Layout): number => l.paddingTop + l.paddingBottom;--/** How many children a row (or column) holds under a fixed constraint, 0 when it is free. */-function fixedBreakingNum(l: Layout, count: number): number {- if (l.type !== Type.GRID || l.constraint === Constraint.NONE || l.constraintNum <= 0) return 0;- let num = l.constraint === Constraint.FIXED_ROW ? Math.ceil(count / l.constraintNum) : l.constraintNum;- if (l.startAxis === AxisDirection.VERTICAL) num = l.constraint === Constraint.FIXED_COL ? Math.ceil(count / l.constraintNum) : l.constraintNum;- return num;-}--type Position = (child: Node, t: UITransform, offset: number) => number;--function layoutHorizontally(l: Layout, children: UITransform[], self: UITransform, baseWidth: number, rowBreak: boolean, positionY: Position, apply: boolean): number {- const limit = fixedBreakingNum(l, children.length);- let sign = 1;- let padX = l.paddingLeft;- if (l.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { sign = -1; padX = l.paddingRight; }-- const startPos = (l.horizontalDirection - self.anchorX) * baseWidth + sign * padX;- let nextX = startPos - sign * l.spacingX;- let totalHeight = 0, rowMaxHeight = 0, tempMaxHeight = 0, maxHeight = 0;- let isBreak = false;- let newChildWidth = l.cellWidth;- if (l.type !== Type.GRID && l.resizeMode === ResizeMode.CHILDREN) {- newChildWidth = (baseWidth - paddingH(l) - (children.length - 1) * l.spacingX) / children.length;- }-- for (let i = 0; i < children.length; i++) {- const t = children[i]!;- const child = t.node;- const scale = child.getScale();- const sx = used(l, scale.x), sy = used(l, scale.y);- if (l.resizeMode === ResizeMode.CHILDREN) {- t.width = newChildWidth / sx;- if (l.type === Type.GRID) t.height = l.cellHeight / sy;- }- const anchorX = Math.abs(l.horizontalDirection - t.anchorX);- const w = t.width * sx;- const h = t.height * sy;-- if (h > tempMaxHeight) {- maxHeight = Math.max(tempMaxHeight, maxHeight);- rowMaxHeight = tempMaxHeight || h;- tempMaxHeight = h;- }- nextX += sign * (anchorX * w + l.spacingX);- const rightBoundary = sign * (1 - anchorX) * w;-- if (rowBreak) {- if (limit > 0) {- isBreak = i / limit > 0 && i % limit === 0;- if (isBreak) rowMaxHeight = tempMaxHeight > h ? tempMaxHeight : rowMaxHeight;- } else if (w > baseWidth - paddingH(l)) {- if (nextX > startPos + sign * (anchorX * w)) isBreak = true;- } else {- const boundary = (1 - l.horizontalDirection - self.anchorX) * baseWidth;- const breakBoundary = nextX + rightBoundary + sign * (sign > 0 ? l.paddingRight : l.paddingLeft);- isBreak = Math.abs(breakBoundary) > Math.abs(boundary);- }- if (isBreak) {- nextX = startPos + sign * (anchorX * w);- if (h !== tempMaxHeight) rowMaxHeight = tempMaxHeight;- totalHeight += rowMaxHeight + l.spacingY;- rowMaxHeight = tempMaxHeight = h;- }- }- const y = positionY(child, t, totalHeight);- if (apply) child.setPosition(nextX, y);- nextX += rightBoundary;- }- rowMaxHeight = Math.max(rowMaxHeight, tempMaxHeight);- return Math.max(maxHeight, totalHeight + rowMaxHeight) + paddingV(l);-}--function layoutVertically(l: Layout, children: UITransform[], self: UITransform, baseHeight: number, columnBreak: boolean, positionX: Position, apply: boolean): number {- const limit = fixedBreakingNum(l, children.length);- let sign = 1;- let padY = l.paddingBottom;- if (l.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { sign = -1; padY = l.paddingTop; }-- const startPos = (l.verticalDirection - self.anchorY) * baseHeight + sign * padY;- let nextY = startPos - sign * l.spacingY;- let tempMaxWidth = 0, maxWidth = 0, colMaxWidth = 0, totalWidth = 0;- let isBreak = false;- let newChildHeight = l.cellHeight;- if (l.type !== Type.GRID && l.resizeMode === ResizeMode.CHILDREN) {- newChildHeight = (baseHeight - paddingV(l) - (children.length - 1) * l.spacingY) / children.length;- }-- for (let i = 0; i < children.length; i++) {- const t = children[i]!;- const child = t.node;- const scale = child.getScale();- const sx = used(l, scale.x), sy = used(l, scale.y);- if (l.resizeMode === ResizeMode.CHILDREN) {- t.height = newChildHeight / sy;- if (l.type === Type.GRID) t.width = l.cellWidth / sx;- }- const anchorY = Math.abs(l.verticalDirection - t.anchorY);- const w = t.width * sx;- const h = t.height * sy;-- if (w > tempMaxWidth) {- maxWidth = Math.max(tempMaxWidth, maxWidth);- colMaxWidth = tempMaxWidth || w;- tempMaxWidth = w;- }- nextY += sign * (anchorY * h + l.spacingY);- const topBoundary = sign * (1 - anchorY) * h;-- if (columnBreak) {- if (limit > 0) {- isBreak = i / limit > 0 && i % limit === 0;- if (isBreak) colMaxWidth = tempMaxWidth > h ? tempMaxWidth : colMaxWidth;- } else if (h > baseHeight - paddingV(l)) {- if (nextY > startPos + sign * (anchorY * h)) isBreak = true;- } else {- const boundary = (1 - l.verticalDirection - self.anchorY) * baseHeight;- const breakBoundary = nextY + topBoundary + sign * (sign > 0 ? l.paddingTop : l.paddingBottom);- isBreak = Math.abs(breakBoundary) > Math.abs(boundary);- }- if (isBreak) {- nextY = startPos + sign * (anchorY * h);- if (w !== tempMaxWidth) colMaxWidth = tempMaxWidth;- totalWidth += colMaxWidth + l.spacingX;- colMaxWidth = tempMaxWidth = w;- }- }- const x = positionX(child, t, totalWidth);- if (apply) child.setPosition(new Vec3(x, nextY, child.getPosition().z));- nextY += topBoundary;- }- colMaxWidth = Math.max(colMaxWidth, tempMaxWidth);- return Math.max(maxWidth, totalWidth + colMaxWidth) + paddingH(l);-}--/** Arrange one layout's children. */-export function layoutNode(l: Layout): void {- const self = l.node.getComponent(UITransform);- if (!self) return;- const children = usefulChildren(l);-- if (l.type === Type.HORIZONTAL) {- let baseWidth = self.width;- if (l.resizeMode === ResizeMode.CONTAINER) {- baseWidth = children.reduce((s, t) => s + t.width * used(l, t.node.getScale().x), 0) + (children.length - 1) * l.spacingX + paddingH(l);- }- layoutHorizontally(l, children, self, baseWidth, false, (c) => (l.isAlign ? 0 : c.getPosition().y), true);- self.width = baseWidth;- } else if (l.type === Type.VERTICAL) {- let baseHeight = self.height;- if (l.resizeMode === ResizeMode.CONTAINER) {- baseHeight = children.reduce((s, t) => s + t.height * used(l, t.node.getScale().y), 0) + (children.length - 1) * l.spacingY + paddingV(l);- }- layoutVertically(l, children, self, baseHeight, false, (c) => (l.isAlign ? 0 : c.getPosition().x), true);- self.height = baseHeight;- } else if (l.type === Type.GRID) {- const anchor = { x: self.anchorX, y: self.anchorY };- const size = { width: self.width, height: self.height };- if (l.startAxis === AxisDirection.HORIZONTAL) {- let sign = 1;- let bottom = -anchor.y * size.height;- let padY = l.paddingBottom;- if (l.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { sign = -1; bottom = (1 - anchor.y) * size.height; padY = l.paddingTop; }- const fn: Position = (c, t, off) => bottom + sign * (off + (1 - t.anchorY) * t.height * used(l, c.getScale().y) + padY);- let newHeight = 0;- if (l.resizeMode === ResizeMode.CONTAINER) {- newHeight = layoutHorizontally(l, children, self, size.width, true, fn, false);- bottom = -anchor.y * newHeight;- if (l.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) bottom = (1 - anchor.y) * newHeight;- }- layoutHorizontally(l, children, self, size.width, true, fn, true);- if (l.resizeMode === ResizeMode.CONTAINER) self.setContentSize(size.width, newHeight);- } else {- let sign = 1;- let left = -anchor.x * size.width;- let padX = l.paddingLeft;- if (l.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { sign = -1; left = (1 - anchor.x) * size.width; padX = l.paddingRight; }- const fn: Position = (c, t, off) => left + sign * (off + (1 - t.anchorX) * t.width * used(l, c.getScale().x) + padX);- let newWidth = 0;- if (l.resizeMode === ResizeMode.CONTAINER) {- newWidth = layoutVertically(l, children, self, size.height, true, fn, false);- left = -anchor.x * newWidth;- if (l.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) left = (1 - anchor.x) * newWidth;- }- layoutVertically(l, children, self, size.height, true, fn, true);- if (l.resizeMode === ResizeMode.CONTAINER) self.setContentSize(newWidth, size.height);- }- }-}--/** Arrange every layout whose inputs changed, innermost first (an outer container may be sized by an inner one). */-export function layoutAll(world: World): void {- const due: Array<{ layout: Layout; depth: number }> = [];- for (const [entity, inst] of instancesOfClass(world, Layout) as Array<[Entity, Layout]>) {- if (!inst.enabled || !world.isEntityActive(entity) || inst.type === Type.NONE) continue;- const sig = inst.signature_();- if (sig === inst._seen) continue;- due.push({ layout: inst, depth: depthOf(inst.node) });- }- due.sort((a, b) => b.depth - a.depth);- for (const { layout } of due) {- layoutNode(layout);- // Laying out can resize the container or the children, which changes what the layout depends on; record the result so it settles.- layout._seen = layout.signature_();- }-}--export function declareLayout(): void {- declareClass(Layout as never, 'Layout', [- ...['type', 'resizeMode', 'paddingLeft', 'paddingRight', 'paddingTop', 'paddingBottom', 'spacingX', 'spacingY',- 'verticalDirection', 'horizontalDirection', 'cellWidth', 'cellHeight', 'startAxis', 'constraint', 'constraintNum']- .map((name) => ({ name, kind: 'number' as const })),- { name: 'affectedByScale', kind: 'boolean' as const },- { name: 'isAlign', kind: 'boolean' as const },- ]);-}diff --git a/sdk/src/cocos/ui/mask.ts b/sdk/src/cocos/ui/mask.tsdeleted file mode 100644index 41535de38..000000000--- a/sdk/src/cocos/ui/mask.ts+++ /dev/null@@ -1,40 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/mask.ts- * @brief `Mask`: a view on the engine's `UIMask`, clipping the node's children to its rectangle.- *- * The clip box is the node's `ContentRect` (what `UITransform` reads and writes), so a mask is an engine `UIMask` on a node that- * has a size, and the renderer's scissor does the work. A rectangle mask is exact. The shaped types — ellipse, graphics, image — clip- * to the same rectangle: the engine cuts a shape from a sprite on the node, which a Cocos mask does not carry. `inverted` is not- * carried either. Both are held so a script can read back what it set.- */-import { UIMask, MaskMode } from '../../ui/core/ui-mask';-import type { World } from '../../ecs/world';-import type { Entity } from '../../types';-import { Component } from '../component';-import { registerBuiltinComponent } from '../builtins';-import { ensureUITransform } from './uiTransform';-import { viewAdapter } from './view';--const Type = Object.freeze({ RECT: 0, ELLIPSE: 1, GRAPHICS_STENCIL: 2, IMAGE_STENCIL: 3 });--export class Mask extends Component {- static readonly Type = Type;-- type: number = Type.RECT;- inverted = false;- segments = 64;- alphaThreshold = 0.1;-- get enabled(): boolean { return this._world.get(this._entity, UIMask).enabled; }- set enabled(v: boolean) { this._world.set(this._entity, UIMask, { ...this._world.get(this._entity, UIMask), enabled: v }); }-}--const hasMask = (world: World, entity: Entity): boolean => world.has(entity, UIMask);-const addMask = (world: World, entity: Entity): void => {- ensureUITransform(world, entity);- world.insert(entity, UIMask, { enabled: true, mode: MaskMode.Scissor, alphaCutoff: 0 });-};--registerBuiltinComponent(Mask, ['cc.Mask', 'Mask'], viewAdapter(Mask, hasMask, addMask));diff --git a/sdk/src/cocos/ui/misc.ts b/sdk/src/cocos/ui/misc.tsdeleted file mode 100644index 7c53acabb..000000000--- a/sdk/src/cocos/ui/misc.ts+++ /dev/null@@ -1,78 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/misc.ts- * @brief `SafeArea` and `WebView`.- *- * A safe area keeps a node inside the part of the screen a notch or a home bar leaves free: it is a widget whose margins are the screen's safe- * insets. A web view needs a surface the host provides; none is wired in, so the component keeps its address and events and says once that- * nothing is shown.- */-import { Component } from '../component';-import { Node } from '../node';-import { declareClass } from '../host';-import { log } from '../../util/logger';-import { Widget } from './widget';-import { getSafeInsets } from './screen';-import { EventHandler, joinHandlers } from './button';--type Handlers = Array<{ component: string; handler: string; customEventData: string }>;--export class SafeArea extends Component {- private seen_ = '';-- onEnable(): void { this.seen_ = ''; }-- update(): void {- const { left, right, top, bottom } = getSafeInsets();- const key = `${left},${right},${top},${bottom}`;- if (key === this.seen_) return;- this.seen_ = key;- const widget = this.node.getComponent(Widget) ?? this.node.addComponent(Widget)!;- const flags = Widget.AlignFlags;- widget.alignFlags |= flags.LEFT | flags.RIGHT | flags.TOP | flags.BOT;- widget.isAbsLeft = widget.isAbsRight = widget.isAbsTop = widget.isAbsBottom = true;- widget.left = left;- widget.right = right;- widget.top = top;- widget.bottom = bottom;- }-}--const WebViewEvent = Object.freeze({ LOADING: 0, LOADED: 1, ERROR: 2 });--export class WebView extends Component {- static readonly EventType = WebViewEvent;- url = '';- webviewTargets: Array<Node | null> = [];- webviewHandlers: Handlers = [];- webviewEvents: EventHandler[] = [];- private warned_ = false;-- onLoad(): void {- if (this.webviewEvents.length === 0) this.webviewEvents = joinHandlers(this.webviewTargets, this.webviewHandlers);- }-- onEnable(): void { this.explain_(); }-- /** Ask for an address. There is no web surface to show it on, so it is only kept. */- loadURL(url: string): void { this.url = url; this.explain_(); }- setJavascriptInterfaceScheme(_scheme: string): void { /* no page to talk to */ }- setOnJSCallback(_callback: (view: WebView, url: string) => void): void { /* no page to talk to */ }- evaluateJS(_code: string): void { /* no page to run it in */ }-- private explain_(): void {- if (this.warned_ || !this.url) return;- this.warned_ = true;- log.warn('cocos', `WebView (${this.node.name}) shows nothing here: this host has no web surface for ${this.url}`);- }-}--export function declareMisc(): void {- declareClass(SafeArea as never, 'SafeArea', []);- declareClass(WebView as never, 'WebView', [- { name: 'url', kind: 'string' },- { name: 'webviewTargets', kind: 'node', array: true },- { name: 'webviewHandlers', kind: 'json' },- ]);-}diff --git a/sdk/src/cocos/ui/pages.ts b/sdk/src/cocos/ui/pages.tsdeleted file mode 100644index f670a0d77..000000000--- a/sdk/src/cocos/ui/pages.ts+++ /dev/null@@ -1,208 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/pages.ts- * @brief `PageView`, `PageViewIndicator` and `ScrollBar`: what sits on top of a `ScrollView`.- *- * A page view is a scroll view whose content is a row (or column) of pages, which settles on one when the finger lifts. A scroll bar is a handle- * that shows where the view is along its content. Both read the scroll view's own offset, so they follow whatever moved it.- */-import { Component } from '../component';-import { Node } from '../node';-import { Vec2 } from '../math';-import { declareClass } from '../host';-import { ScrollView } from './scrollView';-import { UITransform } from './uiTransform';-import { EventHandler, joinHandlers } from './button';--type Handlers = Array<{ component: string; handler: string; customEventData: string }>;--const PageViewEvent = Object.freeze({ PAGE_TURNING: 'page-turning' });--export class PageView extends ScrollView {- static readonly SizeMode = Object.freeze({ Unified: 0, Free: 1 });- static readonly Direction = Object.freeze({ Horizontal: 0, Vertical: 1 });- static readonly EventType = Object.freeze({ ...ScrollView.EventType, ...PageViewEvent });-- sizeMode = 1;- direction = 0;- /** The distance a drag must cover to turn the page, in canvas units. */- autoPageTurningThreshold = 100;- /** Seconds a settle takes. */- pageTurningSpeed = 0.3;- indicator: PageViewIndicator | null = null;- pageTargets: Array<Node | null> = [];- pageHandlers: Handlers = [];- pageEvents: EventHandler[] = [];-- private page_ = 0;- private from_ = 0;-- onLoad(): void {- super.onLoad();- if (this.pageEvents.length === 0) this.pageEvents = joinHandlers(this.pageTargets, this.pageHandlers);- this.horizontal = this.direction === 0;- this.vertical = this.direction === 1;- }-- onEnable(): void {- super.onEnable();- this.node.on(ScrollView.EventType.SCROLL_BEGAN, this.onBegan_, this);- this.node.on(ScrollView.EventType.TOUCH_UP, this.onLifted_, this);- this.indicator?.setPageView(this);- }-- onDisable(): void {- this.node.off(ScrollView.EventType.SCROLL_BEGAN, this.onBegan_, this);- this.node.off(ScrollView.EventType.TOUCH_UP, this.onLifted_, this);- super.onDisable();- }-- getPages(): Node[] { return this.content?.children ?? []; }- getCurrentPageIndex(): number { return this.page_; }- setCurrentPageIndex(index: number): void { this.scrollToPage(index, 0); }-- addPage(page: Node): void { this.content?.addChild(page); this.indicator?.refresh(); }- insertPage(page: Node, index: number): void { this.content?.addChild(page); page.setSiblingIndex(index); this.indicator?.refresh(); }- removePage(page: Node): void { if (page.parent === this.content) page.removeFromParent(); this.indicator?.refresh(); }- removePageAtIndex(index: number): void { const page = this.getPages()[index]; if (page) this.removePage(page); }- removeAllPages(): void { this.content?.removeAllChildren(); this.indicator?.refresh(); }-- /** Settle on page @p index over @p timeInSecond. */- scrollToPage(index: number, timeInSecond = this.pageTurningSpeed): void {- const pages = this.getPages();- if (pages.length === 0) return;- const target = Math.min(pages.length - 1, Math.max(0, Math.trunc(index)));- const offset = this.offsetOf_(pages[target]!);- if (!offset) return;- const turned = target !== this.page_;- this.page_ = target;- this.scrollToOffset(offset, timeInSecond);- if (turned) {- EventHandler.emitEvents(this.pageEvents, this, PageViewEvent.PAGE_TURNING);- this.node.emit(PageViewEvent.PAGE_TURNING, this);- this.indicator?.refresh();- }- }-- /** The scroll offset that brings @p page to the middle of the view. */- private offsetOf_(page: Node): Vec2 | null {- const content = this.content;- const view = content?.parent?.getComponent(UITransform);- const size = content?.getComponent(UITransform);- if (!content || !view || !size) return null;- const max = this.getMaxScrollOffset();- const p = page.position;- const x = p.x + size.width * size.anchorX - view.width / 2;- const y = size.height * (1 - size.anchorY) - p.y - view.height / 2;- return new Vec2(Math.min(max.x, Math.max(0, x)), Math.min(max.y, Math.max(0, y)));- }-- private axis_(offset: Vec2): number { return this.direction === 0 ? offset.x : offset.y; }-- private onBegan_(): void { this.from_ = this.axis_(this.getScrollOffset()); }-- /** On lifting the finger: a drag longer than the threshold turns the page in its direction; a shorter one settles on the nearest. */- private onLifted_(): void {- const pages = this.getPages();- if (pages.length === 0) return;- const now = this.axis_(this.getScrollOffset());- const moved = now - this.from_;- const offsets = pages.map((p) => this.offsetOf_(p)).map((o) => (o ? this.axis_(o) : 0));- let nearest = 0;- for (let i = 1; i < offsets.length; i++) if (Math.abs(offsets[i]! - now) < Math.abs(offsets[nearest]! - now)) nearest = i;- let target = nearest;- if (Math.abs(moved) >= this.autoPageTurningThreshold && nearest === this.page_) target = this.page_ + (moved > 0 ? 1 : -1);- this.stopAutoScroll();- this.scrollToPage(target);- }-}--/** The dots under a page view. Their number follows the pages and the lit one the current page; drawing them is the scene's own sprites. */-export class PageViewIndicator extends Component {- static readonly Direction = Object.freeze({ HORIZONTAL: 0, VERTICAL: 1 });- spacing = 0;- direction = 0;- cellSize: { width: number; height: number } = { width: 20, height: 20 };- private view_: PageView | null = null;-- setPageView(view: PageView | null): void { this.view_ = view; this.refresh(); }- /** How many pages there are and which one is current. */- get pageCount(): number { return this.view_?.getPages().length ?? 0; }- get currentPage(): number { return this.view_?.getCurrentPageIndex() ?? 0; }- refresh(): void { /* the dots are the scene's own nodes: the count and the lit one are read from pageCount and currentPage */ }-}--export class ScrollBar extends Component {- static readonly Direction = Object.freeze({ HORIZONTAL: 0, VERTICAL: 1 });- scrollView: ScrollView | null = null;- /** The node that slides along the bar. */- handle: Node | null = null;- direction = 1;- enableAutoHide = false;- autoHideTime = 1;- private idle_ = 0;-- update(dt: number): void {- const view = this.scrollView, handle = this.handle;- if (!view || !handle) return;- const track = this.node.getComponent(UITransform);- const content = view.content?.getComponent(UITransform);- const port = view.content?.parent?.getComponent(UITransform);- const knob = handle.getComponent(UITransform);- if (!track || !content || !port || !knob) return;- const horizontal = this.direction === 0;- const trackLength = horizontal ? track.width : track.height;- const contentLength = horizontal ? content.width : content.height;- const viewLength = horizontal ? port.width : port.height;- const offset = view.getScrollOffset();- const max = view.getMaxScrollOffset();- const travel = horizontal ? max.x : max.y;- const ratio = travel > 0 ? (horizontal ? offset.x : offset.y) / travel : 0;- const length = Math.min(trackLength, Math.max(10, contentLength > 0 ? (trackLength * viewLength) / contentLength : trackLength));- if (horizontal) knob.width = length; else knob.height = length;- const along = Math.min(1, Math.max(0, ratio)) * (trackLength - length);- const p = handle.position;- if (horizontal) handle.setPosition(-trackLength / 2 + length / 2 + along, p.y, p.z);- else handle.setPosition(p.x, trackLength / 2 - length / 2 - along, p.z);- // a bar that hides itself shows only while its view moves- if (this.enableAutoHide) {- this.idle_ = view.isScrolling() ? 0 : this.idle_ + dt;- this.node.active = this.idle_ < this.autoHideTime || travel <= 0 ? this.idle_ < this.autoHideTime : false;- }- }-}--export function declarePages(): void {- declareClass(PageView as never, 'PageView', [- { name: 'content', kind: 'node' },- { name: 'horizontal', kind: 'boolean' },- { name: 'vertical', kind: 'boolean' },- { name: 'inertia', kind: 'boolean' },- { name: 'brake', kind: 'number' },- { name: 'elastic', kind: 'boolean' },- { name: 'bounceDuration', kind: 'number' },- { name: 'cancelInnerEvents', kind: 'boolean' },- { name: 'scrollTargets', kind: 'node', array: true },- { name: 'scrollHandlers', kind: 'json' },- { name: 'sizeMode', kind: 'number' },- { name: 'direction', kind: 'number' },- { name: 'autoPageTurningThreshold', kind: 'number' },- { name: 'pageTurningSpeed', kind: 'number' },- { name: 'indicator', kind: 'component', type: PageViewIndicator },- { name: 'pageTargets', kind: 'node', array: true },- { name: 'pageHandlers', kind: 'json' },- ]);- declareClass(PageViewIndicator as never, 'PageViewIndicator', [- { name: 'spacing', kind: 'number' },- { name: 'direction', kind: 'number' },- { name: 'cellSize', kind: 'json' },- ]);- declareClass(ScrollBar as never, 'ScrollBar', [- { name: 'scrollView', kind: 'component', type: ScrollView },- { name: 'handle', kind: 'node' },- { name: 'direction', kind: 'number' },- { name: 'enableAutoHide', kind: 'boolean' },- { name: 'autoHideTime', kind: 'number' },- ]);-}diff --git a/sdk/src/cocos/ui/pass.ts b/sdk/src/cocos/ui/pass.tsdeleted file mode 100644index e9488b5aa..000000000--- a/sdk/src/cocos/ui/pass.ts+++ /dev/null@@ -1,83 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/pass.ts- * @brief Registers the Cocos UI components and the systems that arrange layouts and publish the screen to scripts.- *- * Alignment is the engine's (RectAnchors); the Layout arithmetic is Cocos's, and runs between the engine's two anchor passes.- */-import { Schedule, defineSystem, addSystemToSchedule, GetWorld } from '../../ecs/system';-import { Res } from '../../ecs/resource';-import { UICameraInfo } from '../../ui/core/ui-camera-info';-import { ScreenLayout, type ScreenLayoutData } from '../../ui/core/screen-layout';-import { ScreenScaling, type ScreenScalingData } from '../../camera/ScreenScaling';-import { setCurrentWorld } from '../node';-import { declareWidget } from './widget';-import { rectAnchorsPlugin, setRectAnchorsScreenFallback } from '../../ui/layout/rect-anchors';-import { SystemLabel } from '../../ecs/systemLabels';-import { Renderer } from '../../render/renderer';-import { getDefaultContext } from '../../ecs/context';-import { layoutAll, declareLayout } from './layout';-import { declareControls } from './controls';-import { declareGraphics } from './graphics';-import { declareEditBox } from './editBox';-import { declareScrollView } from './scrollView';-import { getVisibleSize, setProjectDesign, setSafeInsets, setScreenLayout, setUiCameraData, setVisibleSize, setWindowPixels } from './screen';-import { declarePages } from './pages';-import { declareMisc } from './misc';--/** The screen the pass aligns to: the engine's, or — where there is none yet (a test, a host before its first frame) — the visible size it was told. */-function screenOrVisible(screen: ScreenLayoutData | undefined): ScreenLayoutData {- if (screen?.valid) return screen;- const v = getVisibleSize();- const halfW = v.width / 2, halfH = v.height / 2;- return { valid: true, left: -halfW, right: halfW, bottom: -halfH, top: halfH, safeLeft: -halfW, safeRight: halfW, safeBottom: -halfH, safeTop: halfH, scale: 1, viewportW: v.width, viewportH: v.height };-}--/** Cocos's UI_2D layer, as a bit of the engine's layer mask. */-const TREE_ORDERED_LAYERS = (1 << 25) >>> 0;--export function declareUiPass(): void {- declareWidget();- declareLayout();- declareControls();- declareGraphics();- declareEditBox();- declarePages();- declareMisc();- declareScrollView();- // The engine's anchor system places what is pinned; a Cocos Layout then arranges and resizes, and the engine's second anchor pass- // follows the sizes the layouts set (the nodes set to align every frame). Cocos does both after the frame's scripts have run, so a- // script that moves or resizes something this frame is answered in the same frame.- getDefaultContext().pendingPlugins.push(rectAnchorsPlugin);- setRectAnchorsScreenFallback(() => screenOrVisible(undefined));- addSystemToSchedule(Schedule.PostUpdate, defineSystem(- [GetWorld()],- (world) => {- const previous = setCurrentWorld(world);- try { layoutAll(world); } finally { setCurrentWorld(previous); }- },- { name: 'Cocos:Layout', touches: { opaque: true }, runAfter: [SystemLabel.RectAnchors], runBefore: [SystemLabel.RectAnchorsLate] },- ));- // What scripts read about the screen, before they run: the project design, the visible size and the framebuffer, the safe insets,- // the camera for the conversions a Cocos `Camera` offers.- addSystemToSchedule(Schedule.PreUpdate, defineSystem(- [Res(UICameraInfo), Res(ScreenLayout), Res(ScreenScaling)],- (camera, screen: ScreenLayoutData | undefined, scaling: ScreenScalingData | undefined) => {- // Cocos paints a layer's nodes in hierarchy order, a label no different from an image: a popup covers the text of the view under- // it. The UI layer is therefore painted in tree order, which is a setting of the renderer and so is stated where the pass is.- Renderer.setTreeSortLayers(TREE_ORDERED_LAYERS);- if (scaling) setProjectDesign(scaling.designWidth, scaling.designHeight, scaling.scaleMode);- setUiCameraData(camera ?? null);- setScreenLayout(screenOrVisible(screen));- if (screen?.valid) {- setVisibleSize(screen.right - screen.left, screen.top - screen.bottom);- setWindowPixels(screen.viewportW, screen.viewportH);- setSafeInsets(- Math.max(0, screen.safeLeft - screen.left), Math.max(0, screen.right - screen.safeRight),- Math.max(0, screen.top - screen.safeTop), Math.max(0, screen.safeBottom - screen.bottom));- }- },- { name: 'Cocos:Screen', touches: { opaque: true } },- ));-}diff --git a/sdk/src/cocos/ui/renderer.ts b/sdk/src/cocos/ui/renderer.tsdeleted file mode 100644index d1091e26e..000000000--- a/sdk/src/cocos/ui/renderer.ts+++ /dev/null@@ -1,23 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/renderer.ts- * @brief `UIRenderer`: what every component that draws a 2D UI element is, in Cocos.- *- * Cocos builds each element's vertices on the CPU and asks to have them rebuilt when something changed; a script that changes how a- * label or a sprite is built says so with `markForUpdateRenderData` or `setVertsDirty`. The engine draws from the component's data- * as it stands, every frame, so there is nothing to rebuild, and these are accepted and do nothing. They are here so the scripts- * that ask are not stopped by the question.- */-import { Component } from '../component';--export class UIRenderer extends Component {- /** Ask for the element's vertices to be rebuilt. The engine draws from current data, so there is nothing to rebuild. */- markForUpdateRenderData(_enable = true): void { /* drawn from the component's data every frame */ }- setVertsDirty(): void { /* see markForUpdateRenderData */ }- updateRenderer(): void { /* see markForUpdateRenderData */ }- /** A script that replaces `onEnable` on the engine's class calls the base one first; there is nothing to set up here. */- onEnable(): void { /* the engine draws from the component's data */ }- /** Whether the element is waiting for a rebuild: never, here. */- get renderEntity(): undefined { return undefined; }-}diff --git a/sdk/src/cocos/ui/richText.ts b/sdk/src/cocos/ui/richText.tsdeleted file mode 100644index 138135c37..000000000--- a/sdk/src/cocos/ui/richText.ts+++ /dev/null@@ -1,56 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/richText.ts- * @brief `RichText`: a view on the engine's `Text` with markup on.- *- * Nothing here parses markup. A `RichText` is a `Text` whose `richText` flag is set, and the string a script writes —- * `<color=#ff0000>hit</color> <b>crit</b><br/>` — is handed to the engine's own rich-text parser, which reads the tags Cocos's- * rich text uses. Tags the renderer cannot draw (underline, outline, click) keep their text and lose their style.- */-import { Text, type TextData } from '../../ui/core/text';-import type { World } from '../../ecs/world';-import type { Entity } from '../../types';-import { Color } from '../math';-import { registerBuiltinComponent } from '../builtins';-import { TextView } from './label';-import { toCocosColor, toEngineColor, viewAdapter } from './view';--export class RichText extends TextView {- /** Kept so a script can read back what it set; the engine draws text, not touch handlers. */- handleTouchEvent = true;-- get string(): string { return this.text_().content; }- set string(v: string) { this.patch_({ content: v === undefined || v === null ? '' : String(v) }); }-- get fontSize(): number { return this.text_().fontSize; }- set fontSize(v: number) {- const t = this.text_();- const px = t.lineHeight * t.fontSize;- this.patch_({ fontSize: v, lineHeight: v > 0 ? px / v : t.lineHeight });- }-- get lineHeight(): number { const t = this.text_(); return t.lineHeight * t.fontSize; }- set lineHeight(px: number) { const t = this.text_(); this.patch_({ lineHeight: t.fontSize > 0 ? px / t.fontSize : t.lineHeight }); }-- get fontColor(): Color { return toCocosColor(this.text_().color); }- set fontColor(v: Color) { this.patch_({ color: toEngineColor(v) }); }-- get horizontalAlign(): number { return this.text_().align; }- set horizontalAlign(v: number) { this.patch_({ align: v as TextData['align'] }); }-- /** The width at which lines wrap; 0 means they do not. */- get maxWidth(): number { const t = this.text_(); return t.wordWrap ? (t.boxWidth ?? 0) : 0; }- set maxWidth(v: number) { this.patch_(v > 0 ? { wordWrap: true, boxWidth: v } : { wordWrap: false }); }-- get enabled(): boolean { return this.text_().enabled; }- set enabled(v: boolean) { this.patch_({ enabled: v }); }-}--const isRich = (world: World, entity: Entity): boolean => world.has(entity, Text) && world.get(entity, Text).richText;-const addRich = (world: World, entity: Entity): void => {- if (world.has(entity, Text)) world.set(entity, Text, { ...world.get(entity, Text), richText: true });- else world.insert(entity, Text, { richText: true });-};--registerBuiltinComponent(RichText, ['cc.RichText', 'RichText'], viewAdapter(RichText, isRich, addRich));diff --git a/sdk/src/cocos/ui/screen.ts b/sdk/src/cocos/ui/screen.tsdeleted file mode 100644index 7ecddd5fe..000000000--- a/sdk/src/cocos/ui/screen.ts+++ /dev/null@@ -1,79 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/screen.ts- * @brief The rectangle a root UI node aligns to (Cocos's "visible rect"), and the window it sits in.- *- * A widget on a node whose parent has no rectangle of its own (the canvas, or anything straight under the scene) aligns to the- * visible area of the screen, which in the engine is centred on the world origin, so the rectangle is a width and a height about it. The frame loop sets it from the UI camera every frame- * (see pass.ts); until it does, it is the size of a typical design resolution so a scene still lays out.- */--import type { UICameraData } from '../../ui/core/ui-camera-info';-import type { ScreenLayoutData } from '../../ui/core/screen-layout';-import type { World } from '../../ecs/world';--let uiCamera: UICameraData | null = null;-let width = 960;-let height = 640;-let safeLeft = 0;-let safeRight = 0;-let safeTop = 0;-let safeBottom = 0;-let windowW = 960;-let windowH = 640;-const listeners: Array<(kind: 'visible' | 'window') => void> = [];--let projectDesign: { width: number; height: number; scaleMode: number } | null = null;-/** @internal The project's own design resolution and fit (the engine's screen scaling), which a script that never set one reads. */-export function setProjectDesign(width: number, height: number, scaleMode: number): void { projectDesign = scaleMode >= 0 ? { width, height, scaleMode } : null; }-/** @internal */-export function getProjectDesign(): { width: number; height: number; scaleMode: number } | null { return projectDesign; }--let screenLayout: ScreenLayoutData | null = null;-/** @internal The layout the pass last saw, for an alignment a script asks for now. */-export function setScreenLayout(layout: ScreenLayoutData | null): void { screenLayout = layout; }-/** @internal */-export function getScreenLayoutOf(_world: World): ScreenLayoutData | null { return screenLayout; }--/** The visible area's size, in the canvas units scripts see. */-export function getVisibleSize(): { width: number; height: number } { return { width, height }; }--/** How far in from each edge of the visible area the safe area starts (a notch, a rounded corner, a home bar), in canvas units. */-export function getSafeInsets(): { left: number; right: number; top: number; bottom: number } {- return { left: safeLeft, right: safeRight, top: safeTop, bottom: safeBottom };-}--export function setSafeInsets(left: number, right: number, top: number, bottom: number): void {- if (left === safeLeft && right === safeRight && top === safeTop && bottom === safeBottom) return;- safeLeft = left; safeRight = right; safeTop = top; safeBottom = bottom;- for (const l of [...listeners]) l('visible');-}--/** Tell the layer the visible area changed; widgets set to follow the window re-align. */-export function setVisibleSize(w: number, h: number): void {- if (w === width && h === height) return;- width = w;- height = h;- for (const l of [...listeners]) l('visible');-}--/** The window (the drawing surface) in physical pixels. */-export function getWindowPixels(): { width: number; height: number } { return { width: windowW, height: windowH }; }--export function setWindowPixels(w: number, h: number): void {- if (w === windowW && h === windowH) return;- windowW = w;- windowH = h;- for (const l of [...listeners]) l('window');-}--/** Hear about a change to either size. Returns the way to stop hearing. */-export function onScreenChange(listener: (kind: 'visible' | 'window') => void): () => void {- listeners.push(listener);- return () => { const i = listeners.indexOf(listener); if (i >= 0) listeners.splice(i, 1); };-}--/** The UI camera's data as of the last frame (the live object the frame loop keeps current), for the conversions a camera offers. */-export function setUiCameraData(data: UICameraData | null): void { uiCamera = data; }-export function uiCameraData(): UICameraData | null { return uiCamera; }diff --git a/sdk/src/cocos/ui/scrollView.ts b/sdk/src/cocos/ui/scrollView.tsdeleted file mode 100644index 2a698a25c..000000000--- a/sdk/src/cocos/ui/scrollView.ts+++ /dev/null@@ -1,317 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/scrollView.ts- * @brief `ScrollView`: a content node moved inside a view by dragging, with inertia and an elastic edge.- *- * The motion is the engine's own scroll model (ui/collection: ScrollContainer, KineticScroll, ScrollMotion) — the same one the- * engine's UI scroll areas use — and this adds Cocos's shape around it: the view is the content's parent, the content is a child- * that is bigger, and the offsets scripts read are Cocos's (`getScrollOffset()` is how far the content has moved toward its end;- * positive x is scrolled right, positive y scrolled down). The settings map onto the model: `elastic` and `bounceDuration` are the- * container's, `inertia` and `brake` set how long a flick coasts.- *- * Touches are heard in the CAPTURE phase, so a drag that starts on a button inside the content still scrolls; once the finger has- * moved far enough to be a drag, the button is cancelled (`cancelInnerEvents`) and does not click on release.- */-import { Component } from '../component';-import { Node } from '../node';-import { Vec2, Vec3 } from '../math';-import { declareClass } from '../host';-import { ScrollContainer } from '../../ui/collection/scroll-container';-import { ScrollMotion } from '../../ui/collection/scroll-motion';-import { KineticScroll } from '../../ui/collection/kinetic-scroll';-import { EventHandler, joinHandlers } from './button';-import { UITransform } from './uiTransform';-import type { EventTouch } from '../input';--const EventType = Object.freeze({- SCROLL_TO_TOP: 'scroll-to-top',- SCROLL_TO_BOTTOM: 'scroll-to-bottom',- SCROLL_TO_LEFT: 'scroll-to-left',- SCROLL_TO_RIGHT: 'scroll-to-right',- SCROLLING: 'scrolling',- BOUNCE_TOP: 'bounce-top',- BOUNCE_BOTTOM: 'bounce-bottom',- BOUNCE_LEFT: 'bounce-left',- BOUNCE_RIGHT: 'bounce-right',- SCROLL_ENDED: 'scroll-ended',- TOUCH_UP: 'touch-up',- AUTOSCROLL_ENDED_WITH_THRESHOLD: 'autoscroll-ended-with-threshold',- SCROLL_BEGAN: 'scroll-began',-});--/** How far a finger must travel before the touch is a drag and the node under it is cancelled. */-const DRAG_THRESHOLD = 7;--/** Cocos's `brake` (0 = coast long, 1 = stop at once) as the fraction of speed the engine's coast keeps after a second. */-const decelerationOf = (brake: number): number => 0.5 * 0.04 ** Math.min(1, Math.max(0, brake));--export class ScrollView extends Component {- static readonly EventType = EventType;-- content: Node | null = null;- horizontal = false;- vertical = true;- inertia = true;- brake = 0.5;- elastic = true;- bounceDuration = 1;- cancelInnerEvents = true;- scrollTargets: Array<Node | null> = [];- scrollHandlers: { component: string; handler: string; customEventData: string }[] = [];- scrollEvents: EventHandler[] = [];-- private motion_: ScrollMotion | null = null;- private settings_ = '';- private dragging_ = false;- private began_ = false;- private travelled_ = 0;- private anchor_: Vec3 | null = null;- private last_: Vec3 | null = null;- private resting_ = true;- private edge_ = { top: false, bottom: false, left: false, right: false };-- onLoad(): void {- if (this.scrollEvents.length === 0) this.scrollEvents = joinHandlers(this.scrollTargets, this.scrollHandlers);- }-- onEnable(): void {- this.node.on(Node.EventType.TOUCH_START, this.onStart_, this, true);- this.node.on(Node.EventType.TOUCH_MOVE, this.onMove_, this, true);- this.node.on(Node.EventType.TOUCH_END, this.onEnd_, this, true);- this.node.on(Node.EventType.TOUCH_CANCEL, this.onCancel_, this, true);- // listening in capture alone leaves the node itself unclaimed when nothing under the finger listens- this.node.on(Node.EventType.TOUCH_START, noop, this);- this.sync_();- this.place_();- }-- onDisable(): void {- this.node.off(Node.EventType.TOUCH_START, this.onStart_, this, true);- this.node.off(Node.EventType.TOUCH_MOVE, this.onMove_, this, true);- this.node.off(Node.EventType.TOUCH_END, this.onEnd_, this, true);- this.node.off(Node.EventType.TOUCH_CANCEL, this.onCancel_, this, true);- this.node.off(Node.EventType.TOUCH_START, noop, this);- this.dragging_ = false;- }-- update(dt: number): void {- if (this.dragging_) return;- const motion = this.sync_();- if (!motion) return;- if (motion.tick(dt)) { this.place_(); this.notify_(EventType.SCROLLING); }- const idle = !motion.isMoving;- if (idle && !this.resting_) {- this.resting_ = true;- this.notify_(EventType.SCROLL_ENDED);- } else if (!idle) {- this.resting_ = false;- }- }-- // ---- the Cocos API -------------------------------------------------------------------------------------------------- /** How far the content has moved toward its end on each axis (right and down are positive). */- getScrollOffset(): Vec2 { const o = this.sync_()?.container.getOffset(); return new Vec2(o?.x ?? 0, o?.y ?? 0); }- getMaxScrollOffset(): Vec2 { const m = this.sync_()?.container.getMaxOffset(); return new Vec2(m?.x ?? 0, m?.y ?? 0); }- isScrolling(): boolean { return this.dragging_ || (this.motion_?.isMoving ?? false); }- isAutoScrolling(): boolean { return !this.dragging_ && (this.motion_?.isMoving ?? false); }- stopAutoScroll(): void { this.motion_?.stop(); }-- scrollToOffset(offset: Vec2, timeInSecond = 0, _attenuated = true): void {- const motion = this.sync_();- if (!motion) return;- const o = motion.container.getOffset();- motion.animateTo({ x: this.horizontal ? offset.x : o.x, y: this.vertical ? offset.y : o.y }, timeInSecond);- if (timeInSecond <= 0) { this.place_(); this.notify_(EventType.SCROLLING); }- }-- /** Scroll so the content's position along each axis is @p anchor, 0..1, where (0, 1) is the top-left. */- scrollTo(anchor: Vec2, timeInSecond = 0, attenuated = true): void {- const max = this.getMaxScrollOffset();- this.scrollToOffset(new Vec2(anchor.x * max.x, (1 - anchor.y) * max.y), timeInSecond, attenuated);- }- scrollToTop(t = 0, a = true): void { this.scrollToOffset(new Vec2(this.getScrollOffset().x, 0), t, a); }- scrollToBottom(t = 0, a = true): void { this.scrollToOffset(new Vec2(this.getScrollOffset().x, this.getMaxScrollOffset().y), t, a); }- scrollToLeft(t = 0, a = true): void { this.scrollToOffset(new Vec2(0, this.getScrollOffset().y), t, a); }- scrollToRight(t = 0, a = true): void { this.scrollToOffset(new Vec2(this.getMaxScrollOffset().x, this.getScrollOffset().y), t, a); }- scrollToTopLeft(t = 0, a = true): void { this.scrollToOffset(new Vec2(0, 0), t, a); }- scrollToTopRight(t = 0, a = true): void { this.scrollToOffset(new Vec2(this.getMaxScrollOffset().x, 0), t, a); }- scrollToBottomLeft(t = 0, a = true): void { this.scrollToOffset(new Vec2(0, this.getMaxScrollOffset().y), t, a); }- scrollToBottomRight(t = 0, a = true): void { const m = this.getMaxScrollOffset(); this.scrollToOffset(new Vec2(m.x, m.y), t, a); }-- getContentPosition(): Vec3 { return this.content?.getPosition() ?? new Vec3(); }- setContentPosition(p: Vec3): void { this.content?.setPosition(p); this.readBack_(); }-- // ---- geometry -------------------------------------------------------------------------------------------------------- private view_(): UITransform | null { return this.content?.parent?.getComponent(UITransform) ?? null; }- private contentSize_(): { w: number; h: number; ax: number; ay: number } | null {- const c = this.content;- const t = c?.getComponent(UITransform);- if (!c || !t) return null;- const s = c.getScale();- return { w: t.width * Math.abs(s.x), h: t.height * Math.abs(s.y), ax: t.anchorX, ay: t.anchorY };- }-- /** The engine's scroll model for this view, made when the settings are first known and again when they change; its extents kept current. */- private sync_(): ScrollMotion | null {- const view = this.view_();- const c = this.contentSize_();- if (!view || !c) return this.motion_;- const key = [this.horizontal, this.vertical, this.inertia, this.brake, this.elastic, this.bounceDuration].join(',');- if (!this.motion_ || key !== this.settings_) {- const previous = this.motion_?.container.getOffset();- const container = new ScrollContainer({- viewportSize: { x: view.width, y: view.height },- contentSize: { x: c.w, y: c.h },- direction: this.horizontal && this.vertical ? 'both' : this.horizontal ? 'horizontal' : 'vertical',- elastic: this.elastic,- bounceTime: this.bounceDuration,- initialOffset: previous,- showScrollbar: false,- });- // no inertia is a coast that stops at once- this.motion_ = new ScrollMotion(container, new KineticScroll({ decelerationRate: this.inertia ? decelerationOf(this.brake) : 0 }));- this.settings_ = key;- this.readBack_();- }- this.motion_.container.setSizes({ x: view.width, y: view.height }, { x: c.w, y: c.h });- return this.motion_;- }-- /** Put the content where the model says, pulled past an end by the overscroll. */- private place_(): void {- const view = this.view_();- const c = this.contentSize_();- const content = this.content;- const container = this.motion_?.container;- if (!view || !c || !content || !container) return;- const o = container.getOffset();- const over = container.getOverscroll();- const p = content.getPosition();- const viewLeft = -view.anchorX * view.width;- const viewTop = (1 - view.anchorY) * view.height;- // when the content is narrower than the view it sits at the start edge, as Cocos's does- const x = this.horizontal ? viewLeft - (o.x + over.x) + c.ax * c.w : p.x;- const y = this.vertical ? viewTop + (o.y + over.y) - (1 - c.ay) * c.h : p.y;- content.setPosition(new Vec3(x, y, p.z));- }-- /** Take the offsets from where the content is now (a script may have moved it). */- private readBack_(): void {- const view = this.view_();- const c = this.contentSize_();- const content = this.content;- const container = this.motion_?.container;- if (!view || !c || !content || !container) return;- const p = content.getPosition();- container.setOffset({- x: -view.anchorX * view.width - (p.x - c.ax * c.w),- y: p.y + (1 - c.ay) * c.h - (1 - view.anchorY) * view.height,- });- }-- // ---- touches --------------------------------------------------------------------------------------------------------- private local_(event: EventTouch): Vec3 | null {- const view = this.view_();- if (!view) return null;- const loc = event.getUILocation();- return view.convertToNodeSpaceAR(new Vec3(loc.x, loc.y, 0));- }-- private onStart_(event: EventTouch): void {- const motion = this.sync_();- if (!this.content || !motion) return;- this.readBack_();- motion.grab();- this.dragging_ = true;- this.began_ = false;- this.travelled_ = 0;- this.anchor_ = null;- this.last_ = this.local_(event);- }-- private onMove_(event: EventTouch): void {- const motion = this.motion_;- if (!this.dragging_ || !this.last_ || !motion) return;- const now = this.local_(event);- if (!now) return;- this.travelled_ += Math.hypot(now.x - this.last_.x, now.y - this.last_.y);- this.last_ = now;- if (this.travelled_ < DRAG_THRESHOLD && !this.began_) return;- if (!this.began_) {- this.began_ = true;- this.resting_ = false;- // the drag counts from where it became one, so the content does not jump by the threshold- this.anchor_ = now;- if (this.cancelInnerEvents) event.cancelInner();- this.notify_(EventType.SCROLL_BEGAN);- return;- }- const a = this.anchor_!;- motion.dragBy({ x: this.horizontal ? -(now.x - a.x) : 0, y: this.vertical ? now.y - a.y : 0 }, 1 / 60);- this.place_();- this.notify_(EventType.SCROLLING);- // a drag the scroll view owns is not the business of anything above it- event.stopPropagation();- }-- private onEnd_(event: EventTouch): void {- if (!this.dragging_) return;- this.dragging_ = false;- this.notify_(EventType.TOUCH_UP);- if (this.began_) {- this.motion_?.release();- event.stopPropagation();- }- this.began_ = false;- }-- private onCancel_(): void {- // a cancel the scroll view itself caused must not end its own drag; one from above does- if (this.began_) return;- this.dragging_ = false;- }-- // ---- events ---------------------------------------------------------------------------------------------------------- private notify_(type: string): void {- EventHandler.emitEvents(this.scrollEvents, this, type);- this.node.emit(type, this);- if (type !== EventType.SCROLLING) return;- const o = this.motion_?.container.getOffset() ?? { x: 0, y: 0 };- const m = this.motion_?.container.getMaxOffset() ?? { x: 0, y: 0 };- const e = this.edge_;- const atTop = o.y <= 0, atBottom = o.y >= m.y && m.y > 0;- const atLeft = o.x <= 0, atRight = o.x >= m.x && m.x > 0;- if (atTop && !e.top) this.notifyEdge_(EventType.SCROLL_TO_TOP);- if (atBottom && !e.bottom) this.notifyEdge_(EventType.SCROLL_TO_BOTTOM);- if (atLeft && !e.left) this.notifyEdge_(EventType.SCROLL_TO_LEFT);- if (atRight && !e.right) this.notifyEdge_(EventType.SCROLL_TO_RIGHT);- e.top = atTop; e.bottom = atBottom; e.left = atLeft; e.right = atRight;- }-- private notifyEdge_(type: string): void {- EventHandler.emitEvents(this.scrollEvents, this, type);- this.node.emit(type, this);- }-}--function noop(): void { /* claims the node for touches; the capture handlers do the work */ }--export function declareScrollView(): void {- declareClass(ScrollView as never, 'ScrollView', [- { name: 'content', kind: 'node' },- { name: 'horizontal', kind: 'boolean' },- { name: 'vertical', kind: 'boolean' },- { name: 'inertia', kind: 'boolean' },- { name: 'brake', kind: 'number' },- { name: 'elastic', kind: 'boolean' },- { name: 'bounceDuration', kind: 'number' },- { name: 'cancelInnerEvents', kind: 'boolean' },- { name: 'scrollTargets', kind: 'node', array: true },- { name: 'scrollHandlers', kind: 'json' },- ]);-}diff --git a/sdk/src/cocos/ui/sprite.ts b/sdk/src/cocos/ui/sprite.tsdeleted file mode 100644index 063fb2d43..000000000--- a/sdk/src/cocos/ui/sprite.ts+++ /dev/null@@ -1,96 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/sprite.ts- * @brief `Sprite` and `UIOpacity`: views on the engine's `Sprite` and `GroupOpacity`.- *- * Colour, the draw type and the enable flag map directly. The frame (`spriteFrame`) is a texture, which the engine addresses by a- * handle that an asset load produces; assigning one is the asset layer's job, so here the frame is the path the `Sprite` was made- * with and assigning a path is carried to the engine's `texture` only where the project's assets have already loaded it.- */-import { GroupOpacity, Sprite as EngineSprite } from '../../ecs/component';-import { SpriteDrawMode } from '../../wasm/wasm.generated';-import type { World } from '../../ecs/world';-import type { Entity } from '../../types';-import { Color } from '../math';-import { SpriteFrame } from '../assets';-import { Component } from '../component';-import { UIRenderer } from './renderer';-import { registerBuiltinComponent } from '../builtins';-import { toCocosColor, toEngineColor, viewAdapter } from './view';--/** Cocos's `Sprite.Type`: SIMPLE, SLICED, TILED, FILLED. */-const SpriteType = Object.freeze({ SIMPLE: 0, SLICED: 1, TILED: 2, FILLED: 3 });-const SizeMode = Object.freeze({ CUSTOM: 0, TRIMMED: 1, RAW: 2 });--function toEngineDrawMode(type: number): SpriteDrawMode {- if (type === SpriteType.SLICED) return SpriteDrawMode.NineSlice;- if (type === SpriteType.TILED) return SpriteDrawMode.Tiled;- return SpriteDrawMode.Simple; // SIMPLE, and FILLED, which the engine draws whole-}--function toCocosType(mode: SpriteDrawMode | undefined): number {- if (mode === SpriteDrawMode.NineSlice) return SpriteType.SLICED;- if (mode === SpriteDrawMode.Tiled) return SpriteType.TILED;- return SpriteType.SIMPLE;-}--export class Sprite extends UIRenderer {- static readonly Type = SpriteType;- static readonly SizeMode = SizeMode;-- private data_() { return this._world.get(this._entity, EngineSprite); }- private patch_(patch: Partial<ReturnType<Sprite['data_']>>): void { this._world.set(this._entity, EngineSprite, { ...this.data_(), ...patch }); }-- get color(): Color { return toCocosColor(this.data_().color); }- set color(v: Color) { this.patch_({ color: toEngineColor(v) }); }-- get type(): number { return toCocosType(this.data_().drawMode); }- set type(v: number) { this.patch_({ drawMode: toEngineDrawMode(v) }); }-- private frame_: SpriteFrame | null = null;- /**- * The frame the sprite draws. Its texture is the engine sprite's texture; a frame that has not bound one is not drawn, and the sprite- * keeps its size unless the size mode asks for the image's own.- */- get spriteFrame(): SpriteFrame | null { return this.frame_; }- set spriteFrame(v: SpriteFrame | null) {- this.frame_ = v;- const texture = v?.texture;- const patch: Partial<ReturnType<Sprite['data_']>> = { texture: texture?._handle ?? 0 };- if (texture && this.sizeMode !== SizeMode.CUSTOM) patch.size = { x: texture.width, y: texture.height };- this.patch_(patch);- }-- /** The size mode decides whether the node takes the image's size. */- sizeMode = SizeMode.CUSTOM;- /** Not carried: the engine has no grayscale draw for a sprite. */- grayscale = false;- fillType = 0;- fillRange = 0;-- get enabled(): boolean { return this.data_().enabled; }- set enabled(v: boolean) { this.patch_({ enabled: v }); }-}--/** `UIOpacity`: the alpha of a node and everything under it, which is the engine's `GroupOpacity` (0..1) in Cocos's 0..255. */-export class UIOpacity extends Component {- get opacity(): number { return Math.round(this._world.get(this._entity, GroupOpacity).opacity * 255); }- set opacity(v: number) {- const opacity = Math.min(255, Math.max(0, v)) / 255;- this._world.set(this._entity, GroupOpacity, { ...this._world.get(this._entity, GroupOpacity), opacity });- }-- get enabled(): boolean { return this._world.get(this._entity, GroupOpacity).enabled; }- set enabled(v: boolean) { this._world.set(this._entity, GroupOpacity, { ...this._world.get(this._entity, GroupOpacity), enabled: v }); }-}--const hasSprite = (world: World, entity: Entity): boolean => world.has(entity, EngineSprite);-const addSprite = (world: World, entity: Entity): void => { world.insert(entity, EngineSprite, {}); };--registerBuiltinComponent(Sprite, ['cc.Sprite', 'Sprite'], viewAdapter(Sprite, hasSprite, addSprite));-registerBuiltinComponent(UIOpacity, ['cc.UIOpacity', 'UIOpacity'], viewAdapter(- UIOpacity,- (world, entity) => world.has(entity, GroupOpacity),- (world, entity) => { world.insert(entity, GroupOpacity, {}); },-));diff --git a/sdk/src/cocos/ui/uiTransform.ts b/sdk/src/cocos/ui/uiTransform.tsdeleted file mode 100644index cac893a4b..000000000--- a/sdk/src/cocos/ui/uiTransform.ts+++ /dev/null@@ -1,133 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/uiTransform.ts- * @brief `UITransform`: a node's content size and anchor point, as a view on the engine's `ContentRect`.- *- * In Cocos the rectangle belongs to the node and the renderers draw into it; the engine's `ContentRect` is the same idea (a size and- * the pivot the transform sits on), and the `Sprite`, `Text` and clip mask on the entity follow it. So `UITransform` has no- * storage and no copying of its own: it reads and writes `ContentRect`, and the rectangle's consumers are the engine's.- *- * Importing a scene writes a `ContentRect` for every node that had a `UITransform`; a node that never had one gets it when a- * script first asks, filled in from the renderer it has.- */-import { Sprite, Transform } from '../../ecs/component';-import { ContentRect, applyContentRect, contentRectContains, type ContentRectData } from '../../ui/core/content-rect';-import { Text } from '../../ui/core/text';-import type { World } from '../../ecs/world';-import type { Entity } from '../../types';-import { Rect, Size, Vec2, Vec3 } from '../math';-import { Component } from '../component';-import { registerBuiltinComponent } from '../builtins';-import { viewAdapter } from './view';--/** The rectangle a node's renderers say it has, for a node that was never given one. */-function derive(world: World, entity: Entity): ContentRectData {- const sprite = world.has(entity, Sprite) ? world.get(entity, Sprite) : null;- if (sprite) return { size: { x: sprite.size.x, y: sprite.size.y }, pivot: { x: sprite.pivot.x, y: sprite.pivot.y } };- const text = world.has(entity, Text) ? world.get(entity, Text) : null;- const w = text?.boxWidth ?? 0, h = text?.boxHeight ?? 0;- if (text && (w > 0 || h > 0)) {- const pivot = text.boxPivot ?? { x: 0.5, y: 0.5 };- return { size: { x: w, y: h }, pivot: { x: pivot.x, y: pivot.y } };- }- return { size: { x: 100, y: 100 }, pivot: { x: 0.5, y: 0.5 } };-}--/** The rectangle of a node, made if it has none. */-export function ensureUITransform(world: World, entity: Entity): ContentRectData {- if (!world.has(entity, ContentRect)) world.insert(entity, ContentRect, derive(world, entity));- return world.get(entity, ContentRect);-}--export class UITransform extends Component {- private rect_(): ContentRectData { return ensureUITransform(this._world, this._entity); }- /** Write the rectangle, and let the sprite and text on the node follow it now rather than at the end of the frame. */- private write_(size: { x: number; y: number }, pivot: { x: number; y: number }): void {- this._world.set(this._entity, ContentRect, { size, pivot });- applyContentRect(this._world, this._entity);- }-- get contentSize(): Size { const r = this.rect_(); return new Size(r.size.x, r.size.y); }- set contentSize(v: Size) { this.write_({ x: v.width, y: v.height }, this.rect_().pivot); }- setContentSize(w: number | Size, h?: number): void {- if (typeof w === 'object') this.contentSize = w; else this.write_({ x: w, y: h ?? this.rect_().size.y }, this.rect_().pivot);- }-- get width(): number { return this.rect_().size.x; }- set width(v: number) { const r = this.rect_(); this.write_({ x: v, y: r.size.y }, r.pivot); }- get height(): number { return this.rect_().size.y; }- set height(v: number) { const r = this.rect_(); this.write_({ x: r.size.x, y: v }, r.pivot); }-- get anchorPoint(): Vec2 { const r = this.rect_(); return new Vec2(r.pivot.x, r.pivot.y); }- set anchorPoint(v: Vec2) { this.write_(this.rect_().size, { x: v.x, y: v.y }); }- setAnchorPoint(x: number | Vec2, y?: number): void {- if (typeof x === 'object') this.anchorPoint = x; else this.write_(this.rect_().size, { x, y: y ?? this.rect_().pivot.y });- }- get anchorX(): number { return this.rect_().pivot.x; }- set anchorX(v: number) { const r = this.rect_(); this.write_(r.size, { x: v, y: r.pivot.y }); }- get anchorY(): number { return this.rect_().pivot.y; }- set anchorY(v: number) { const r = this.rect_(); this.write_(r.size, { x: r.pivot.x, y: v }); }-- /** The rectangle in the node's own space: its left/bottom corner is minus the anchor times the size. */- private local_(): Rect {- const r = this.rect_();- return new Rect(-r.pivot.x * r.size.x, -r.pivot.y * r.size.y, r.size.x, r.size.y);- }-- /** A point in the node's space (relative to its anchor) as a point in world space, scale and rotation applied. */- convertToWorldSpaceAR(point: Vec3, out?: Vec3): Vec3 {- const world = this._world;- world.ensureTransformsComposed();- const t = world.get(this._entity, Transform);- const { x: qx, y: qy, z: qz, w: qw } = t.worldRotation;- const sx = point.x * t.worldScale.x, sy = point.y * t.worldScale.y, sz = point.z * t.worldScale.z;- const tx = 2 * (qy * sz - qz * sy), ty = 2 * (qz * sx - qx * sz), tz = 2 * (qx * sy - qy * sx);- const result = out ?? new Vec3();- result.x = t.worldPosition.x + sx + qw * tx + (qy * tz - qz * ty);- result.y = t.worldPosition.y + sy + qw * ty + (qz * tx - qx * tz);- result.z = t.worldPosition.z + sz + qw * tz + (qx * ty - qy * tx);- return result;- }-- /** The reverse: a world point as a point relative to this node's anchor. */- convertToNodeSpaceAR(point: Vec3, out?: Vec3): Vec3 {- const world = this._world;- world.ensureTransformsComposed();- const t = world.get(this._entity, Transform);- const dx = point.x - t.worldPosition.x, dy = point.y - t.worldPosition.y, dz = point.z - t.worldPosition.z;- const { x: qx, y: qy, z: qz, w: qw } = t.worldRotation;- const ix = -qx, iy = -qy, iz = -qz;- const tx = 2 * (iy * dz - iz * dy), ty = 2 * (iz * dx - ix * dz), tz = 2 * (ix * dy - iy * dx);- const rx = dx + qw * tx + (iy * tz - iz * ty);- const ry = dy + qw * ty + (iz * tx - ix * tz);- const rz = dz + qw * tz + (ix * ty - iy * tx);- const result = out ?? new Vec3();- result.x = rx / (t.worldScale.x || 1);- result.y = ry / (t.worldScale.y || 1);- result.z = rz / (t.worldScale.z || 1);- return result;- }-- /** Whether a world-space point is inside the rectangle. */- isHit(worldPoint: Vec2): boolean {- this.rect_();- return contentRectContains(this._world, this._entity, worldPoint.x, worldPoint.y);- }-- /** The axis-aligned box of the rectangle in world space. */- getBoundingBoxToWorld(): Rect {- const r = this.local_();- const corners = [new Vec3(r.x, r.y, 0), new Vec3(r.x + r.width, r.y, 0), new Vec3(r.x + r.width, r.y + r.height, 0), new Vec3(r.x, r.y + r.height, 0)]- .map((c) => this.convertToWorldSpaceAR(c));- const xs = corners.map((c) => c.x), ys = corners.map((c) => c.y);- const x = Math.min(...xs), y = Math.min(...ys);- return new Rect(x, y, Math.max(...xs) - x, Math.max(...ys) - y);- }-}--registerBuiltinComponent(UITransform, ['cc.UITransform', 'UITransform'], viewAdapter(- UITransform,- (world, entity) => world.has(entity, ContentRect) || world.has(entity, Sprite) || world.has(entity, Text),- (world, entity) => { ensureUITransform(world, entity); },-));diff --git a/sdk/src/cocos/ui/view.ts b/sdk/src/cocos/ui/view.tsdeleted file mode 100644index a5354af0a..000000000--- a/sdk/src/cocos/ui/view.ts+++ /dev/null@@ -1,64 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/view.ts- * @brief The shared shape of a Cocos built-in component that is a view on engine data.- *- * `Label`, `Sprite`, `UITransform` and the rest have no storage of their own: each reads and writes a component the engine- * already has (`Text`, `Sprite`), or a small compat data component where the engine has no counterpart. What they share is how a- * view is found and made — one instance per (world, entity, class), created on demand, never driven by the host's lifecycle- * system, because there is nothing for it to run — and that is here.- */-import type { World } from '../../ecs/world';-import type { Entity } from '../../types';-import { Component } from '../component';-import type { BuiltinAdapter } from '../builtins';-import { instancesOn, nodeOf, storeInstance } from '../registry';-import { Color } from '../math';--/** A view on engine data. `enabled` is read from and written to the underlying component where it has one. */-export abstract class ViewComponent extends Component {- /** The enable flag of whatever stands behind this view: the engine's `enabled` field, or the view's own. */- protected abstract readEnabled(): boolean;- protected abstract writeEnabled(value: boolean): void;-}--/**- * The adapter for a view class: @p present says whether the entity has what stands behind it, @p create gives it that.- * The view instance is made once and kept, so `node.getComponent(Label) === node.getComponent(Label)`.- */-export function viewAdapter<T extends Component>(- ctor: new () => T,- present: (world: World, entity: Entity) => boolean,- create: (world: World, entity: Entity) => void,-): BuiltinAdapter {- const view = (world: World, entity: Entity): T => {- let inst = instancesOn(world, entity)?.get(ctor) as T | undefined;- if (!inst) {- inst = new ctor();- inst._world = world;- inst._entity = entity;- inst.node = nodeOf(world, entity);- inst._loaded = true;- storeInstance(world, entity, ctor, inst);- }- return inst;- };- return {- get: (world, entity) => (present(world, entity) ? view(world, entity) : null),- add: (world, entity) => {- if (!present(world, entity)) create(world, entity);- return view(world, entity);- },- };-}--/** An engine colour (channels 0..1) as Cocos's (0..255). */-export function toCocosColor(c: { r: number; g: number; b: number; a: number }): Color {- return new Color(Math.round(c.r * 255), Math.round(c.g * 255), Math.round(c.b * 255), Math.round(c.a * 255));-}--/** Cocos's colour (0..255) as the engine's (0..1). */-export function toEngineColor(c: Color): { r: number; g: number; b: number; a: number } {- return { r: c.r / 255, g: c.g / 255, b: c.b / 255, a: c.a / 255 };-}diff --git a/sdk/src/cocos/ui/widget.ts b/sdk/src/cocos/ui/widget.tsdeleted file mode 100644index 919e5836d..000000000--- a/sdk/src/cocos/ui/widget.ts+++ /dev/null@@ -1,140 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/ui/widget.ts- * @brief `Widget`: a view on the engine's `RectAnchors`.- *- * The alignment itself (stretch, pin to an edge, centre, margins in units or as a fraction) is the engine's: `RectAnchors` is a component of- * its own, aligned by an engine system in the editor's edit mode as well as in play. A Cocos `Widget` is that component under Cocos's names.- * A node whose parent has no rectangle aligns to the screen, the centred layout box of the UI camera's domain.- *- * Only the parent as target is supported; a widget that names another node as its target aligns to the parent and says so once.- */-import { registerComponent } from '../../ecs/component';-import { RectAnchors, AnchorFlag, AnchorMode, alignRectAnchorsNow, type RectAnchorsData } from '../../ui/layout/rect-anchors';-import { ScreenLayout } from '../../ui/core/screen-layout';-import { Component } from '../component';-import { Node } from '../node';-import { registerBuiltinComponent } from '../builtins';-import { log } from '../../util/logger';-import { getScreenLayoutOf } from './screen';-import { viewAdapter } from './view';--const AlignFlags = Object.freeze({ TOP: AnchorFlag.TOP, MID: AnchorFlag.MID, BOT: AnchorFlag.BOTTOM, LEFT: AnchorFlag.LEFT, CENTER: AnchorFlag.CENTER, RIGHT: AnchorFlag.RIGHT, HORIZONTAL: AnchorFlag.HORIZONTAL, VERTICAL: AnchorFlag.VERTICAL });-const AlignMode = Object.freeze({ ONCE: AnchorMode.ONCE, ON_WINDOW_RESIZE: AnchorMode.ON_RESIZE, ALWAYS: AnchorMode.ALWAYS });--type NumberKey = 'alignFlags' | 'left' | 'right' | 'top' | 'bottom' | 'horizontalCenter' | 'verticalCenter' | 'alignMode';-type FlagKey = 'isAbsLeft' | 'isAbsRight' | 'isAbsTop' | 'isAbsBottom' | 'isAbsHorizontalCenter' | 'isAbsVerticalCenter';--export class Widget extends Component {- static readonly AlignMode = AlignMode;- static readonly AlignFlags = AlignFlags;-- /** The node another widget setting names as its target; only the parent is honoured. */- target: Node | null = null;- private warnedTarget_ = false;-- private data_(): RectAnchorsData { return this._world.get(this._entity, RectAnchors); }- private patch_(fields: Partial<RectAnchorsData>): void {- if (this.target && this.target !== this.node.parent && !this.warnedTarget_) {- this.warnedTarget_ = true;- log.warn('cocos', `${this.node.name}: Widget.target other than the parent is not supported; aligning to the parent`);- }- this._world.set(this._entity, RectAnchors, { ...this.data_(), ...fields });- }- private num_(key: NumberKey): number { return this.data_()[key]; }- private flag_(key: FlagKey): boolean { return this.data_()[key]; }- private bit_(bit: number): boolean { return (this.data_().alignFlags & bit) > 0; }- private setBit_(bit: number, on: boolean, clears = 0): void {- const flags = this.data_().alignFlags;- this.patch_({ alignFlags: on ? (flags | bit) & ~clears : flags & ~bit });- }-- get enabled(): boolean { return this.data_().enabled; }- set enabled(v: boolean) { this.patch_({ enabled: v }); }-- get alignFlags(): number { return this.num_('alignFlags'); }- set alignFlags(v: number) { this.patch_({ alignFlags: v }); }- get alignMode(): number { return this.num_('alignMode'); }- set alignMode(v: number) { this.patch_({ alignMode: v }); }- get left(): number { return this.num_('left'); }- set left(v: number) { this.patch_({ left: v }); }- get right(): number { return this.num_('right'); }- set right(v: number) { this.patch_({ right: v }); }- get top(): number { return this.num_('top'); }- set top(v: number) { this.patch_({ top: v }); }- get bottom(): number { return this.num_('bottom'); }- set bottom(v: number) { this.patch_({ bottom: v }); }- get horizontalCenter(): number { return this.num_('horizontalCenter'); }- set horizontalCenter(v: number) { this.patch_({ horizontalCenter: v }); }- get verticalCenter(): number { return this.num_('verticalCenter'); }- set verticalCenter(v: number) { this.patch_({ verticalCenter: v }); }-- get isAbsLeft(): boolean { return this.flag_('isAbsLeft'); }- set isAbsLeft(v: boolean) { this.patch_({ isAbsLeft: v }); }- get isAbsRight(): boolean { return this.flag_('isAbsRight'); }- set isAbsRight(v: boolean) { this.patch_({ isAbsRight: v }); }- get isAbsTop(): boolean { return this.flag_('isAbsTop'); }- set isAbsTop(v: boolean) { this.patch_({ isAbsTop: v }); }- get isAbsBottom(): boolean { return this.flag_('isAbsBottom'); }- set isAbsBottom(v: boolean) { this.patch_({ isAbsBottom: v }); }- get isAbsHorizontalCenter(): boolean { return this.flag_('isAbsHorizontalCenter'); }- set isAbsHorizontalCenter(v: boolean) { this.patch_({ isAbsHorizontalCenter: v }); }- get isAbsVerticalCenter(): boolean { return this.flag_('isAbsVerticalCenter'); }- set isAbsVerticalCenter(v: boolean) { this.patch_({ isAbsVerticalCenter: v }); }-- get isAlignLeft(): boolean { return this.bit_(AlignFlags.LEFT); }- set isAlignLeft(v: boolean) { this.setBit_(AlignFlags.LEFT, v, AlignFlags.CENTER); }- get isAlignRight(): boolean { return this.bit_(AlignFlags.RIGHT); }- set isAlignRight(v: boolean) { this.setBit_(AlignFlags.RIGHT, v, AlignFlags.CENTER); }- get isAlignTop(): boolean { return this.bit_(AlignFlags.TOP); }- set isAlignTop(v: boolean) { this.setBit_(AlignFlags.TOP, v, AlignFlags.MID); }- get isAlignBottom(): boolean { return this.bit_(AlignFlags.BOT); }- set isAlignBottom(v: boolean) { this.setBit_(AlignFlags.BOT, v, AlignFlags.MID); }- get isAlignHorizontalCenter(): boolean { return this.bit_(AlignFlags.CENTER); }- set isAlignHorizontalCenter(v: boolean) { this.setBit_(AlignFlags.CENTER, v, AlignFlags.LEFT | AlignFlags.RIGHT); }- get isAlignVerticalCenter(): boolean { return this.bit_(AlignFlags.MID); }- set isAlignVerticalCenter(v: boolean) { this.setBit_(AlignFlags.MID, v, AlignFlags.TOP | AlignFlags.BOT); }- get isStretchWidth(): boolean { return (this.alignFlags & (AlignFlags.LEFT | AlignFlags.RIGHT)) === (AlignFlags.LEFT | AlignFlags.RIGHT); }- get isStretchHeight(): boolean { return (this.alignFlags & (AlignFlags.TOP | AlignFlags.BOT)) === (AlignFlags.TOP | AlignFlags.BOT); }-- get isAbsoluteLeft(): boolean { return this.isAbsLeft; }- set isAbsoluteLeft(v: boolean) { this.isAbsLeft = v; }- get isAbsoluteRight(): boolean { return this.isAbsRight; }- set isAbsoluteRight(v: boolean) { this.isAbsRight = v; }- get isAbsoluteTop(): boolean { return this.isAbsTop; }- set isAbsoluteTop(v: boolean) { this.isAbsTop = v; }- get isAbsoluteBottom(): boolean { return this.isAbsBottom; }- set isAbsoluteBottom(v: boolean) { this.isAbsBottom = v; }- get isAbsoluteHorizontalCenter(): boolean { return this.isAbsHorizontalCenter; }- set isAbsoluteHorizontalCenter(v: boolean) { this.isAbsHorizontalCenter = v; }- get isAbsoluteVerticalCenter(): boolean { return this.isAbsVerticalCenter; }- set isAbsoluteVerticalCenter(v: boolean) { this.isAbsVerticalCenter = v; }-- /** Align now, rather than at the end of the frame. */- updateAlignment(): void { alignRectAnchorsNow(this._world, this._entity, getScreenLayoutOf(this._world)); }-- /** Ask for alignment at the end of the frame, whatever the mode: a write of the settings is what the engine watches for. */- setDirty(): void { this.patch_({ alignFlags: this.alignFlags }); this.updateAlignment(); }-}--/** Align one widget to its parent now (rotation ignored). */-export function alignWidget(widget: Widget): void { widget.updateAlignment(); }--/** How deep a node is: parents align before the children that depend on their size. */-export function depthOf(node: Node): number {- let d = 0;- for (let p = node.parent; p; p = p.parent) d++;- return d;-}--registerBuiltinComponent(Widget, ['cc.Widget', 'Widget'], viewAdapter(- Widget,- (world, entity) => world.has(entity, RectAnchors),- (world, entity) => { world.insert(entity, RectAnchors, {}); },-));--/** The component is the engine's; a host without the engine's UI plugin (a test, a bare app) still needs it registered for a scene to load. */-export function declareWidget(): void { registerComponent('RectAnchors', RectAnchors); }--export { ScreenLayout };diff --git a/sdk/src/cocos/unsupported.ts b/sdk/src/cocos/unsupported.tsdeleted file mode 100644index d3b8dbb43..000000000--- a/sdk/src/cocos/unsupported.ts+++ /dev/null@@ -1,45 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/unsupported.ts- * @brief What a script gets for a part of Cocos the layer does not provide, so one missing name does not take the whole project down.- *- * Cocos hands a script `undefined` for a name it does not export, and a project's scripts are evaluated together: the first one that- * reaches into such a name while its module loads (`new gfx.Attribute(...)` to build a vertex format, say) throws, and every script- * after it never registers. This is a stand-in that survives being read, called and constructed, answers with more of itself, and says- * once, by name, that the part is not there. It does nothing: a script that really needs what it stands for will not work, but the- * rest of the project still starts.- */-import { log } from '../util/logger';--const told = new Set<string>();--function tell(name: string): void {- const top = name.split(/[.(]/).slice(0, 2).join('.');- if (told.has(top)) return;- told.add(top);- log.warn('cocos', `${top} is not provided by the compatibility layer; scripts that use it will not behave as they do in Cocos`);-}--/** A stand-in for `cc.<name>`, which the layer does not have. */-export function unsupported(name: string): any {- const children = new Map<string, unknown>();- const make = (path: string): unknown => {- const target = function () { /* a stand-in */ } as unknown as Record<PropertyKey, unknown>;- return new Proxy(target, {- get(self, key) {- if (key === 'prototype') return self.prototype;- if (key === Symbol.toPrimitive) return () => '';- if (typeof key === 'symbol' || key === 'then') return undefined;- const child = `${path}.${key}`;- let found = children.get(child);- if (found === undefined) { found = make(child); children.set(child, found); }- return found;- },- set: () => true,- apply: () => { tell(path); return make(`${path}()`); },- construct: () => { tell(path); return make(`${path}()`) as object; },- });- };- return make(`cc.${name}`);-}diff --git a/sdk/src/cocos/view.ts b/sdk/src/cocos/view.tsdeleted file mode 100644index 7343630b6..000000000--- a/sdk/src/cocos/view.ts+++ /dev/null@@ -1,109 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file cocos/view.ts- * @brief `view` / `View` and `screen`: the size of what the player sees and of the window it is in.- *- * Both are read-mostly. The visible size is whatever the UI camera shows (the frame loop feeds it in; see ui/screen.ts), which in- * an imported scene is the canvas the script sees. The design resolution is what the project asked for; a script that never set- * one gets the visible size. Fitting design to window is the engine's screen layout, so the policy setters record the choice and- * leave the fitting to it.- *- * `screen.windowSize` is in physical pixels, as in Cocos, and `view.getFrameSize()` is the same in CSS pixels.- */-import { platformDevicePixelRatio } from '../platform';-import { Emitter } from './emitter';-import { Rect, Size, Vec2 } from './math';-import { getProjectDesign, getVisibleSize, getWindowPixels, onScreenChange } from './ui/screen';--const ResolutionPolicy = Object.freeze({ EXACT_FIT: 0, NO_BORDER: 1, SHOW_ALL: 2, FIXED_HEIGHT: 3, FIXED_WIDTH: 4, UNKNOWN: 5 });--const dpr = (): number => platformDevicePixelRatio() || 1;--export class View extends Emitter {- static readonly instance: View = new View();- static readonly ResolutionPolicy = ResolutionPolicy;-- private design_: Size | null = null;- private policy_: number = ResolutionPolicy.UNKNOWN;- private autoFullScreen_ = false;- private orientation_ = 3;-- constructor() {- super();- // The two sizes change in one place; the events Cocos scripts listen for are named here.- onScreenChange((kind) => {- if (kind === 'visible') this.emit('canvas-resize');- else this.emit('canvas-resize');- });- }-- /** The area the player sees, in canvas units. */- getVisibleSize(): Size { const v = getVisibleSize(); return new Size(v.width, v.height); }- getVisibleSizeInPixel(): Size { const v = getVisibleSize(); const s = this.getScaleX(); return new Size(v.width * s, v.height * s); }- /** The visible area is centred on the world origin, as the engine's screen is. */- getVisibleOrigin(): Vec2 { const v = getVisibleSize(); return new Vec2(-v.width / 2, -v.height / 2); }- getVisibleOriginInPixel(): Vec2 { const v = this.getVisibleSizeInPixel(); return new Vec2(-v.width / 2, -v.height / 2); }- getViewportRect(): Rect { const w = getWindowPixels(); return new Rect(0, 0, w.width, w.height); }-- /** What the script set; else the project's own design resolution (the engine's screen scaling); else the visible size. */- getDesignResolutionSize(): Size {- if (this.design_) return this.design_.clone();- const project = getProjectDesign();- return project ? new Size(project.width, project.height) : this.getVisibleSize();- }- setDesignResolutionSize(width: number, height: number, policy: number = this.policy_): void {- this.design_ = new Size(width, height);- this.policy_ = policy;- this.emit('design-resolution-changed');- }- getResolutionPolicy(): number {- if (this.policy_ !== ResolutionPolicy.UNKNOWN) return this.policy_;- const project = getProjectDesign();- // the engine's camera scale mode: fixed width (0) and fixed height (1) are Cocos's FIXED_WIDTH and FIXED_HEIGHT- return project?.scaleMode === 0 ? ResolutionPolicy.FIXED_WIDTH : project?.scaleMode === 1 ? ResolutionPolicy.FIXED_HEIGHT : this.policy_;- }- setResolutionPolicy(policy: number): void { this.policy_ = policy; }-- /** The window in CSS pixels. */- getFrameSize(): Size { const w = getWindowPixels(); return new Size(w.width / dpr(), w.height / dpr()); }- setFrameSize(_w: number, _h: number): void { /* the host's window */ }- getCanvasSize(): Size { const w = getWindowPixels(); return new Size(w.width, w.height); }- setCanvasSize(_w: number, _h: number): void { /* the host's canvas */ }-- /** Window pixels per canvas unit. */- getScaleX(): number { const v = getVisibleSize(); return v.width > 0 ? getWindowPixels().width / v.width : 1; }- getScaleY(): number { const v = getVisibleSize(); return v.height > 0 ? getWindowPixels().height / v.height : 1; }- getDevicePixelRatio(): number { return dpr(); }-- isAutoFullScreenEnabled(): boolean { return this.autoFullScreen_; }- enableAutoFullScreen(enabled: boolean): void { this.autoFullScreen_ = enabled; }- isAntiAliasEnabled(): boolean { return true; }- enableAntiAlias(_enabled: boolean): void { /* a configuration of the engine */ }- resizeWithBrowserSize(_enabled: boolean): void { /* the host decides */ }- adjustViewportMeta(_enabled: boolean): void { /* the page's */ }- setOrientation(orientation: number): void { this.orientation_ = orientation; }- get orientation(): number { return this.orientation_; }-}--export const view = View.instance;--class Screen extends Emitter {- /** The window in physical pixels. */- get windowSize(): Size { const w = getWindowPixels(); return new Size(w.width, w.height); }- get devicePixelRatio(): number { return dpr(); }- get supportsFullScreen(): boolean { return false; }- isFullScreen(): boolean { return false; }- requestFullScreen(): Promise<void> { return Promise.resolve(); }- exitFullScreen(): Promise<void> { return Promise.resolve(); }- autoFullScreen(): Promise<void> { return Promise.resolve(); }- get resolution(): Size { return this.windowSize; }-- constructor() {- super();- onScreenChange((kind) => { if (kind === 'window') this.emit('window-resize', this.windowSize.width, this.windowSize.height); });- }-}--export const screen = new Screen();-export { ResolutionPolicy };diff --git a/sdk/tests/builtin-meshes.test.ts b/sdk/tests/builtin-meshes.test.tsindex d2f109c7a..7eceb18fb 100644--- a/sdk/tests/builtin-meshes.test.ts+++ b/sdk/tests/builtin-meshes.test.ts@@ -38,7 +38,7 @@ const cross = (a: Vec, b: Vec): Vec => ({describe('built-in meshes', () => {it('offers every primitive under a builtin: ref', () => {expect(BUILTIN_MESH_TEMPLATES.map((t) => t.id).sort())- .toEqual(['capsule', 'cocos-plane', 'cone', 'cube', 'cylinder', 'plane', 'quad', 'sphere']);+ .toEqual(['capsule', 'cone', 'cube', 'cylinder', 'plane', 'quad', 'sphere']);for (const t of BUILTIN_MESH_TEMPLATES) {expect(t.ref).toBe(`builtin:${t.id}`);expect(isBuiltinMeshRef(t.ref)).toBe(true);@@ -46,25 +46,6 @@ describe('built-in meshes', () => {}});- // A texture over the plane of Cocos reads as a map seen from above, v running towards +z; the engine's own plane runs it the other way.- it('runs the v of the Cocos plane along +z and the v of the plane the other way', () => {- const vOf = (id: string, z: number): number => {- const mesh = builtinMeshTemplate(`builtin:${id}`)!.build();- const view = new DataView(mesh.vertices.buffer, mesh.vertices.byteOffset, mesh.vertices.byteLength);- const pos = mesh.channels.find((c) => c.semantic === MeshChannel.Position)!;- const uv = mesh.channels.find((c) => c.semantic === MeshChannel.TexCoord0)!;- for (let i = 0; i < mesh.vertexCount; i++) {- const at = i * mesh.vertexStride;- if (Math.abs(view.getFloat32(at + pos.offset + 8, true) - z) < 1e-3) return view.getFloat32(at + uv.offset + 4, true);- }- throw new Error('no vertex there');- };- expect(vOf('cocos-plane', -5)).toBeCloseTo(0, 5);- expect(vOf('cocos-plane', 5)).toBeCloseTo(1, 5);- expect(vOf('plane', -50)).toBeCloseTo(1, 5);- expect(vOf('plane', 50)).toBeCloseTo(0, 5);- });-// A misspelled built-in must stay a path, so the loader 404s it by name rather// than the ref quietly resolving to nothing at all.it('does not claim a ref it cannot build', () => {@@ -116,17 +97,15 @@ describe('built-in meshes', () => {}});- // The plane of Cocos is the one exception: it stands for what a Cocos effect reads in the mesh's own space, and that plane is 10 across.- it('builds each primitive 100 units across, centred on the origin, and the Cocos plane 10', () => {+ it('builds each primitive 100 units across, centred on the origin', () => {for (const t of BUILTIN_MESH_TEMPLATES) {const mesh = t.build();- const across = t.id === 'cocos-plane' ? 10 : 100;for (let k = 0; k < 3; k++) {expect(mesh.aabbMin[k]).toBeCloseTo(-mesh.aabbMax[k]!, 4);- expect(mesh.aabbMax[k]).toBeLessThanOrEqual(across / 2 + 0.0001);+ expect(mesh.aabbMax[k]).toBeLessThanOrEqual(50.0001);}const size = Math.max(...mesh.aabbMax.map((v, k) => v - mesh.aabbMin[k]!));- expect(size).toBeCloseTo(across, 4);+ expect(size).toBeCloseTo(100, 4);}});});diff --git a/sdk/tests/cocos/camera-richtext-wasm.test.ts b/sdk/tests/cocos/camera-richtext-wasm.test.tsdeleted file mode 100644index b62b22e10..000000000--- a/sdk/tests/cocos/camera-richtext-wasm.test.ts+++ /dev/null@@ -1,200 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file `Camera` and `RichText`, and the two kinds of place a touch has, against the real engine.- *- * A camera's settings are the engine camera's under Cocos's names; its conversions go through the UI camera, so a touch's SCREEN- * point (`getLocation`) converts to the world point under the finger and back. A `RichText` is a `Text` with markup on, and the- * markup is the engine's parser's to read.- */-import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';-import type { ESEngineModule } from '../../src/wasm';-import { App, flushPendingRegistrations } from '../../src/app/app';-import { Camera as EngineCamera, Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';-import { AppContext, setDefaultContext } from '../../src/ecs/context';-import { Text } from '../../src/ui/core/text';-import { UIMask, MaskMode } from '../../src/ui/core/ui-mask';-import { ContentRect } from '../../src/ui/core/content-rect';-import { parseRichText } from '../../src/ui/text/rich-text-parser';-import { resetClassRegistry } from '../../src/cocos/registry';-import { declareBuiltinScripts } from '../../src/cocos/builtinScripts';-import { Camera, Color, Mask, Node, RichText, UITransform, Vec3, setCurrentWorld } from '../../src/cocos';-import { setUiCameraData } from '../../src/cocos/ui/screen';-import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';--// An orthographic view 800 x 600 pixels showing world x in -400..400, y in -300..300: the screen point (400, 300) is the world origin.-const toWorld = (glX: number, glY: number) => ({ x: glX - 400, y: glY - 300 });-vi.mock('../../src/ui/util/ui-pick', () => ({ screenToUiWorld: (_cam: unknown, glX: number, glY: number) => toWorld(glX, glY) }));-vi.mock('../../src/ui/util/math', async (orig) => {- const real = await orig<typeof import('../../src/ui/util/math')>();- return { ...real, projectWorldPoint: (wx: number, wy: number) => ({ x: wx + 400, y: wy + 300, clipW: 1 }) };-});--describe.skipIf(!HAS_WASM)('Camera, RichText and touch locations', () => {- let module: ESEngineModule;- let registry: InstanceType<ESEngineModule['Registry']> | undefined;- let app: App | undefined;-- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- afterEach(() => {- setUiCameraData(null);- setCurrentWorld(null);- app?.world.disconnectCpp();- registry?.delete();- app = undefined;- registry = undefined;- });-- function boot(): void {- setDefaultContext(new AppContext());- ensureBuiltinComponentsRegistered();- resetClassRegistry();- declareBuiltinScripts();- registry = new module.Registry();- app = App.new();- app.connectCpp(registry as never, module);- flushPendingRegistrations(app);- setCurrentWorld(app.world);- setUiCameraData({ valid: true, screenH: 600, viewProjection: new Float32Array(16), vpX: 0, vpY: 0, vpW: 800, vpH: 600 } as never);- }- const node = (name: string): Node => { const n = new Node(name); app!.world.insert(n._entity, Transform); return n; };-- describe('Camera', () => {- it('is the engine camera under Cocos\'s names', () => {- boot();- const n = node('cam');- const cam = n.addComponent(Camera)!;- expect(app!.world.has(n._entity, EngineCamera)).toBe(true);- cam.orthoHeight = 320;- cam.fov = 50;- cam.near = 2;- cam.far = 500;- cam.priority = 3;- cam.visibility = 0b1010;- const d = app!.world.get(n._entity, EngineCamera);- expect([d.orthoSize, d.fov, d.nearPlane, d.farPlane, d.priority, d.cullingMask]).toEqual([320, 50, 2, 500, 3, 10]);- expect([cam.orthoHeight, cam.visibility]).toEqual([320, 10]);- });-- it('numbers the projection kinds the way Cocos does, the other way round from the engine', () => {- boot();- const n = node('cam');- const cam = n.addComponent(Camera)!;- cam.projection = Camera.ProjectionType.ORTHO;- expect(app!.world.get(n._entity, EngineCamera).projectionType).toBe(1);- expect(cam.projection).toBe(Camera.ProjectionType.ORTHO);- cam.projection = Camera.ProjectionType.PERSPECTIVE;- expect(app!.world.get(n._entity, EngineCamera).projectionType).toBe(0);- expect(cam.projection).toBe(Camera.ProjectionType.PERSPECTIVE);- });-- it('clears what Cocos says it clears: a camera drawn over another clears depth only', () => {- boot();- const n = node('cam');- const cam = n.addComponent(Camera)!;- cam.clearFlags = Camera.ClearFlag.DEPTH_ONLY;- expect(app!.world.get(n._entity, EngineCamera).clearFlags).toBe(2);- expect(cam.clearFlags).toBe(Camera.ClearFlag.DEPTH_ONLY);- cam.clearFlags = Camera.ClearFlag.SOLID_COLOR;- expect(app!.world.get(n._entity, EngineCamera).clearFlags).toBe(3);- cam.clearFlags = Camera.ClearFlag.DONT_CLEAR;- expect(app!.world.get(n._entity, EngineCamera).clearFlags).toBe(0);- });-- it('maps the viewport to rect and the active flag to enabled', () => {- boot();- const n = node('cam');- const cam = n.addComponent(Camera)!;- cam.rect = { x: 0.25, y: 0, width: 0.5, height: 1 } as never;- const v = app!.world.get(n._entity, EngineCamera).viewport;- expect([v.x, v.y, v.z, v.w]).toEqual([0.25, 0, 0.5, 1]);- cam.enabled = false;- expect(app!.world.get(n._entity, EngineCamera).isActive).toBe(false);- });-- it('converts a screen point to the world under it, and back', () => {- boot();- const cam = node('cam').addComponent(Camera)!;- const world = cam.screenToWorld(new Vec3(500, 350, 0));- expect([world.x, world.y]).toEqual([100, 50]);- const screen = cam.worldToScreen(new Vec3(100, 50, 0));- expect([screen.x, screen.y]).toEqual([500, 350]);- });-- it('keeps a clear colour a script set, without applying it', () => {- boot();- const cam = node('cam').addComponent(Camera)!;- cam.clearColor = new Color(10, 20, 30, 255);- expect([cam.clearColor.r, cam.clearColor.g, cam.clearColor.b]).toEqual([10, 20, 30]);- });-- it('converts a world point into a node\'s own space', () => {- boot();- const cam = node('cam').addComponent(Camera)!;- const panel = node('panel');- panel.addComponent(UITransform)!.setContentSize(100, 100);- panel.setPosition(200, 100, 0);- const local = cam.convertToUINode(new Vec3(230, 90, 0), panel);- expect([local.x, local.y]).toEqual([30, -10]);- });- });-- describe('RichText', () => {- it('is a Text with markup on, found as a RichText and writes its string through', () => {- boot();- const n = node('rich');- const rt = n.addComponent(RichText)!;- expect(app!.world.get(n._entity, Text).richText).toBe(true);- rt.string = '<color=red>hit</color><br/><size=40>big</size>';- expect(app!.world.get(n._entity, Text).content).toBe('<color=red>hit</color><br/><size=40>big</size>');- expect(n.getComponent(RichText)).toBe(rt);- });-- it('hands the engine\'s parser the markup it writes, and the parser reads it', () => {- const runs = parseRichText('<color=red>hit</color><br/><size=40>big</size>');- const text = runs.map((r) => (r.type === 'text' ? r.text : '')).join('');- expect(text).toBe('hit\nbig');- });-- it('keeps line height in pixels across a size change, and wraps at maxWidth when it is set', () => {- boot();- const n = node('rich');- const rt = n.addComponent(RichText)!;- rt.fontSize = 20;- rt.lineHeight = 30;- rt.fontSize = 40;- expect(rt.lineHeight).toBeCloseTo(30, 5);- expect(rt.maxWidth).toBe(0);- rt.maxWidth = 300;- const t = app!.world.get(n._entity, Text);- expect([t.wordWrap, t.boxWidth]).toEqual([true, 300]);- expect(rt.maxWidth).toBe(300);- rt.maxWidth = 0;- expect(app!.world.get(n._entity, Text).wordWrap).toBe(false);- });-- it('reads a plain Text that is not rich as no RichText', () => {- boot();- const n = node('plain');- app!.world.insert(n._entity, Text, {});- expect(n.getComponent(RichText)).toBeNull();- });- });-- describe('Mask', () => {- it('is the engine UIMask on a node with a rectangle, so the clip box is the size of the node', () => {- boot();- const n = node('clip');- const m = n.addComponent(Mask)!;- expect(app!.world.has(n._entity, UIMask)).toBe(true);- expect(app!.world.get(n._entity, UIMask).mode).toBe(MaskMode.Scissor);- expect(app!.world.has(n._entity, ContentRect)).toBe(true);- n.getComponent(UITransform)!.setContentSize(300, 200);- const r = app!.world.get(n._entity, ContentRect);- expect([r.size.x, r.size.y]).toEqual([300, 200]);- m.enabled = false;- expect(app!.world.get(n._entity, UIMask).enabled).toBe(false);- expect(n.getComponent(Mask)).toBe(m);- });- });-});diff --git a/sdk/tests/cocos/ccclass-plain.test.ts b/sdk/tests/cocos/ccclass-plain.test.tsdeleted file mode 100644index cb4debc4a..000000000--- a/sdk/tests/cocos/ccclass-plain.test.ts+++ /dev/null@@ -1,19 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file `@ccclass` on a class that is not a component: Cocos allows it for serializable data, and the layer must not drive it as a script.- */-import { describe, expect, it } from 'vitest';-import { ccclass, classInfoOf, Component } from '../../src/cocos';--describe('ccclass on a plain class', () => {- it('declares nothing for a class that does not derive from Component', () => {- @ccclass('PlainData')- class PlainData { value = 1; }- @ccclass('RealScript')- class RealScript extends Component {}- expect(classInfoOf(PlainData)).toBeUndefined();- expect(classInfoOf(RealScript)).toBeDefined();- expect(new PlainData().value).toBe(1);- });-});diff --git a/sdk/tests/cocos/collider-wasm.test.ts b/sdk/tests/cocos/collider-wasm.test.tsdeleted file mode 100644index 874ba920e..000000000--- a/sdk/tests/cocos/collider-wasm.test.ts+++ /dev/null@@ -1,113 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file `BoxCollider` against the real engine: a script adds one, sets its size and centre in the node's units, and the engine's box holds- * them scaled by the node, with a static body beside it.- */-import { afterEach, beforeAll, describe, expect, it } from 'vitest';-import type { ESEngineModule } from '../../src/wasm';-import { World } from '../../src/ecs/world';-import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';-import { AppContext, setDefaultContext } from '../../src/ecs/context';-import { BoxCollider3D, RigidBody3D } from '../../src/physics3d/Physics3DComponents';-import { BoxCollider, Node, PhysicsSystem, Vec3, geometry, setCurrentWorld } from '../../src/cocos';-import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';--describe.skipIf(!HAS_WASM)('BoxCollider on the engine', () => {- let module: ESEngineModule;- let registry: InstanceType<ESEngineModule['Registry']> | undefined;- let world: World | undefined;-- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- afterEach(() => {- setCurrentWorld(null);- world?.disconnectCpp();- registry?.delete();- registry = undefined;- world = undefined;- });-- function node(): Node {- setDefaultContext(new AppContext());- registry = new module.Registry();- world = new World();- world.connectCpp(registry, module);- setCurrentWorld(world);- const n = new Node('building');- world.insert(n._entity, Transform);- return n;- }-- it('is made by addComponent with a unit box and a static body', () => {- const n = node();- const c = n.addComponent(BoxCollider)!;- expect(c).toBeInstanceOf(BoxCollider);- expect(n.getComponent(BoxCollider)).toBe(c);- expect(world!.get(n._entity, RigidBody3D).bodyType).toBe(0);- const s = c.size;- expect([s.x, s.y, s.z]).toEqual([1, 1, 1]);- });-- it('reads back the size and centre it was given, whatever the node scale', () => {- const n = node();- n.setScale(new Vec3(2, 4, 1));- const c = n.addComponent(BoxCollider)!;- c.size = new Vec3(1, 1.5, 1);- c.center = new Vec3(0, 0.75, 0);- c.isTrigger = true;- const half = world!.get(n._entity, BoxCollider3D).halfExtents;- expect([half.x, half.y, half.z]).toEqual([1, 3, 0.5]);- expect(world!.get(n._entity, BoxCollider3D).center.y).toBe(3);- expect(world!.get(n._entity, BoxCollider3D).isSensor).toBe(true);- expect([c.size.x, c.size.y, c.size.z]).toEqual([1, 1.5, 1]);- expect(c.center.y).toBeCloseTo(0.75, 6);- expect(c.isTrigger).toBe(true);- });-});--describe.skipIf(!HAS_WASM)('PhysicsSystem on the engine', () => {- let module: ESEngineModule;- let registry: InstanceType<ESEngineModule['Registry']> | undefined;- let world: World | undefined;- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- afterEach(() => { setCurrentWorld(null); world?.disconnectCpp(); registry?.delete(); registry = undefined; world = undefined; });-- function box(name: string, at: Vec3, size: Vec3, trigger = false): Node {- const n = new Node(name);- world!.insert(n._entity, Transform);- n.setPosition(at);- const c = n.addComponent(BoxCollider)!;- c.size = size;- c.isTrigger = trigger;- return n;- }-- it('lists the boxes a ray crosses nearest first and names the face it met', () => {- setDefaultContext(new AppContext());- registry = new module.Registry(); world = new World(); world.connectCpp(registry, module); setCurrentWorld(world);- const far = box('far', new Vec3(0, 0, -10), new Vec3(2, 2, 2));- const near = box('near', new Vec3(0, 0, -4), new Vec3(2, 2, 2));- box('aside', new Vec3(8, 0, -4), new Vec3(2, 2, 2));- const ray = new geometry.Ray(0, 0, 0, 0, 0, -1);- expect(PhysicsSystem.instance.raycast(ray)).toBe(true);- const hits = PhysicsSystem.instance.raycastResults;- expect(hits.map((h) => h.collider.node.name)).toEqual(['near', 'far']);- expect(hits[0]!.distance).toBeCloseTo(3, 6);- expect(hits[0]!.hitPoint.z).toBeCloseTo(-3, 6);- expect(hits[0]!.hitNormal.z).toBeCloseTo(1, 6);- expect(PhysicsSystem.instance.raycastClosest(ray)).toBe(true);- expect(PhysicsSystem.instance.raycastClosestResult.collider.node).toBe(near);- expect(far).toBeTruthy();- });-- it('skips triggers when asked not to, and boxes behind the origin or past the range', () => {- setDefaultContext(new AppContext());- registry = new module.Registry(); world = new World(); world.connectCpp(registry, module); setCurrentWorld(world);- box('trigger', new Vec3(0, 0, -4), new Vec3(2, 2, 2), true);- box('behind', new Vec3(0, 0, 6), new Vec3(2, 2, 2));- const ray = new geometry.Ray(0, 0, 0, 0, 0, -1);- expect(PhysicsSystem.instance.raycast(ray, 0xffffffff, 100, false)).toBe(false);- expect(PhysicsSystem.instance.raycast(ray, 0xffffffff, 2, true)).toBe(false);- expect(PhysicsSystem.instance.raycast(ray, 0xffffffff, 100, true)).toBe(true);- });-});diff --git a/sdk/tests/cocos/controls-wasm.test.ts b/sdk/tests/cocos/controls-wasm.test.tsdeleted file mode 100644index deea2c095..000000000--- a/sdk/tests/cocos/controls-wasm.test.ts+++ /dev/null@@ -1,290 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file Toggle, ToggleContainer, ProgressBar, Slider, BlockInputEvents and ScrollView, driven by touches against the real engine.- *- * The camera is faked as the identity, as in the touch tests, so a screen pixel is a world unit with y flipped.- */-import { afterEach, beforeAll, describe, expect, it } from 'vitest';-import type { ESEngineModule } from '../../src/wasm';-import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';-import {- BlockInputEvents, Button, Node, ProgressBar, ScrollView, Slider, Sprite, Toggle, ToggleContainer, UITransform, Vec2,-} from '../../src/cocos';-import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';-import { pointerApp, type PointerApp } from './helpers/pointerApp';--describe.skipIf(!HAS_WASM)('toggles, bars, sliders and scroll views', () => {- let module: ESEngineModule;- let P: PointerApp | undefined;-- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- afterEach(() => { P?.dispose(); P = undefined; });-- function boot(): void { P = pointerApp(module); }- const W = () => P!.app.world;- const frame = (n = 2): Promise<void> => P!.frame(n);-- function box(name: string, x: number, y: number, w = 100, h = 100, parent?: Node): Node {- const n = new Node(name);- W().insert(n._entity, Transform);- n.addComponent(UITransform)!.setContentSize(w, h);- n.setPosition(x, y, 0);- parent?.addChild(n);- return n;- }-- const press = (x: number, y: number, id = 1): Promise<void> => P!.press(x, y, id);- const move = (x: number, y: number, id = 1): Promise<void> => P!.move(x, y, id);- const release = (x: number, y: number, id = 1): Promise<void> => P!.release(x, y, id);- const tap = (x: number, y: number): Promise<void> => P!.tap(x, y);-- // ---- Toggle ------------------------------------------------------------------------------------------------------- async function toggle(name: string, x: number, y: number, parent?: Node): Promise<{ node: Node; t: Toggle; mark: Node }> {- const node = box(name, x, y, 60, 60, parent);- const mark = box(`${name}-mark`, 0, 0, 30, 30, node);- const markSprite = mark.addComponent(Sprite)!;- const t = node.addComponent<Toggle>('Toggle')!;- t.checkMark = markSprite;- await frame(1);- return { node, t, mark };- }-- it('flips on a click, shows its check mark only while on, and says so', async () => {- boot();- const { node, t, mark } = await toggle('t', 200, 200);- const seen: boolean[] = [];- node.on(Toggle.EventType.TOGGLE, (x: Toggle) => seen.push(x.isChecked));- expect(mark.active).toBe(false);- await tap(200, 200);- expect(t.isChecked).toBe(true);- expect(mark.active).toBe(true);- await tap(200, 200);- expect(t.isChecked).toBe(false);- expect(mark.active).toBe(false);- expect(seen).toEqual([true, false]);- });-- it('does not flip when it is not interactable, or when set without notify', async () => {- boot();- const { t, mark } = await toggle('t', 200, 200);- t.interactable = false;- await tap(200, 200);- expect(t.isChecked).toBe(false);- t.interactable = true;- t.setIsCheckedWithoutNotify(true);- expect(mark.active).toBe(true);- });-- it('keeps one on in a group, and leaves the one that is on alone when switching off is not allowed', async () => {- boot();- const holder = box('group', 400, 400, 400, 100);- const group = holder.addComponent<ToggleContainer>('ToggleContainer')!;- const a = await toggle('a', 300, 400, holder);- const b = await toggle('b', 500, 400, holder);- a.t.toggleGroup = group;- b.t.toggleGroup = group;- await frame(1);- expect(a.t.isChecked || b.t.isChecked).toBe(true); // the container made one on when it enabled- const firstOn = a.t.isChecked ? a : b;- const other = a.t.isChecked ? b : a;- await tap(other.node.getWorldPosition().x, other.node.getWorldPosition().y);- expect(other.t.isChecked).toBe(true);- expect(firstOn.t.isChecked).toBe(false);- // clicking the one that is on does nothing- await tap(other.node.getWorldPosition().x, other.node.getWorldPosition().y);- expect(other.t.isChecked).toBe(true);- // …unless the group allows none- group.allowSwitchOff = true;- await tap(other.node.getWorldPosition().x, other.node.getWorldPosition().y);- expect(other.t.isChecked).toBe(false);- expect(group.anyTogglesChecked()).toBe(false);- });-- it('is found when its base class is asked for, as a Toggle is a Button, and a click on it reaches a handler bound through the Button', async () => {- boot();- const { t, node } = await toggle('t', 200, 200);- expect(node.getComponent(Button)).toBe(t);- expect(node.getComponents(Button)).toEqual([t]);- const clicked: number[] = [];- node.on(Button.EventType.CLICK, () => clicked.push(1));- await tap(200, 200);- expect(clicked).toEqual([1]);- expect(t.isChecked).toBe(true);- });-- it('belongs to the container its parent holds, and switching one on by assignment switches the others off', async () => {- boot();- const holder = box('group', 400, 400, 400, 100);- holder.addComponent<ToggleContainer>('ToggleContainer')!;- const a = await toggle('a', 300, 400, holder);- const b = await toggle('b', 500, 400, holder); // no toggleGroup named: the parent's container is the group- await frame(1);- a.t.isChecked = true;- b.t.isChecked = true;- expect(b.t.isChecked).toBe(true);- expect(a.t.isChecked).toBe(false);- });-- // ---- ProgressBar ------------------------------------------------------------------------------------------------- it('sizes its bar to total length times progress, clamped', async () => {- boot();- const holder = box('holder', 0, 0, 200, 20);- const barNode = box('bar', 0, 0, 10, 20, holder);- const bar = barNode.addComponent(Sprite)!;- const p = holder.addComponent<ProgressBar>('ProgressBar')!;- p.barSprite = bar;- p.totalLength = 200;- p.progress = 0.25;- expect(barNode.getComponent(UITransform)!.width).toBe(50);- p.progress = 2;- expect(p.progress).toBe(1);- expect(barNode.getComponent(UITransform)!.width).toBe(200);- p.progress = -1;- expect(barNode.getComponent(UITransform)!.width).toBe(0);- p.mode = ProgressBar.Mode.VERTICAL;- p.progress = 0.5;- expect(barNode.getComponent(UITransform)!.height).toBe(100);- });-- // ---- Slider ------------------------------------------------------------------------------------------------------ it('reads progress from where the finger is along it, moves its handle, and says it slid', async () => {- boot();- const track = box('track', 300, 300, 200, 20);- const knobNode = box('knob', 0, 0, 20, 20, track);- const knob = knobNode.addComponent<Button>('Button')!;- const s = track.addComponent<Slider>('Slider')!;- s.handle = knob;- await frame(1);- let slid = 0;- track.on(Slider.EventType.SLIDE, () => slid++);- await press(250, 300); // a quarter of the way: the track spans 200..400- expect(s.progress).toBeCloseTo(0.25, 5);- await move(350, 300);- expect(s.progress).toBeCloseTo(0.75, 5);- await release(350, 300);- expect(knobNode.position.x).toBeCloseTo(50, 3); // 0.75 * 200 - 100- expect(slid).toBe(2);- });-- // ---- BlockInputEvents -------------------------------------------------------------------------------------------- it('takes a touch so the node behind it does not hear it', async () => {- boot();- const root = box('root', 0, 0, 1000, 1000);- const behind = box('behind', 200, 200, 300, 300, root);- const front = box('front', 200, 200, 100, 100, root);- front.addComponent(BlockInputEvents);- await frame(1);- let heard = 0;- behind.on(Node.EventType.TOUCH_START, () => heard++);- await tap(200, 200);- expect(heard).toBe(0);- await tap(320, 200); // beside the blocker (it spans 150..250), still on the node behind (50..350)- expect(heard).toBe(1);- });-- // ---- ScrollView -------------------------------------------------------------------------------------------------- async function scroller(horizontal = false): Promise<{ view: Node; content: Node; sv: ScrollView; button: Node; clicks: () => number }> {- const view = box('view', 300, 300, 200, 200);- const content = box('content', 0, 0, horizontal ? 800 : 200, horizontal ? 200 : 800, view);- content.getComponent(UITransform)!.setAnchorPoint(horizontal ? 0 : 0.5, horizontal ? 0.5 : 1);- const button = box('button', horizontal ? 100 : 0, horizontal ? 0 : -100, 80, 60, content);- const b = button.addComponent<Button>('Button')!;- void b;- let clicked = 0;- button.on(Button.EventType.CLICK, () => clicked++);- const sv = view.addComponent<ScrollView>('ScrollView')!;- sv.content = content;- sv.vertical = !horizontal;- sv.horizontal = horizontal;- await frame(1);- return { view, content, sv, button, clicks: () => clicked };- }-- it('reports how far the content can go, and starts at the top', async () => {- boot();- const { sv } = await scroller();- expect(sv.getMaxScrollOffset().y).toBe(600);- expect(sv.getScrollOffset().y).toBe(0);- });-- it('moves the content with the finger, a screen pixel for a world unit, and stops where it is without inertia', async () => {- boot();- const { content, sv } = await scroller();- sv.inertia = false;- const top = content.position.y;- await press(300, 350);- await move(300, 340); // 10 px: past the drag threshold- await move(300, 300); // 50 more, upward on screen = toward the content's end- await release(300, 300);- // the finger went DOWN the screen (y decreases) by 50 after the threshold, which pulls the content down: offset shrinks, but- // it was at the start, so it is an overscroll that springs back; check the direction through the offset sign mid-drag instead- expect(sv.getScrollOffset().y).toBeLessThanOrEqual(0);- await frame(90);- expect(sv.getScrollOffset().y).toBeCloseTo(0, 1);- expect(content.position.y).toBeCloseTo(top, 1);- });-- it('scrolls toward the end when the finger moves up the screen, and glides on after a flick', async () => {- boot();- const { sv } = await scroller();- await press(300, 250);- for (let i = 1; i <= 8; i++) { await move(300, 250 + i * 10); } // up the screen: world y grows- const held = sv.getScrollOffset().y;- expect(held).toBeGreaterThan(40);- await release(300, 330);- await frame(1);- await frame(60);- expect(sv.getScrollOffset().y).toBeGreaterThan(held);- expect(sv.getScrollOffset().y).toBeLessThanOrEqual(600 + 1e-6);- });-- it('does not click a button the drag began on, but clicks it on a plain tap', async () => {- boot();- const { button, sv, clicks } = await scroller();- // the button is 100 below the content's top edge; the content's top is at the view's top (y 400)- const bx = 300, by = 300; // view centre: content top 400, button centre at 400 - 100 = 300- void button;- await press(bx, by);- await move(bx, by + 30);- await move(bx, by + 60);- await release(bx, by + 60);- expect(clicks()).toBe(0);- expect(sv.getScrollOffset().y).toBeGreaterThan(0);-- sv.scrollToTop(0);- await frame(2);- await tap(bx, by);- expect(clicks()).toBe(1);- });-- it('scrolls to the end, to a place over a time, and says it got there', async () => {- boot();- const { sv, view } = await scroller();- const seen: string[] = [];- for (const t of [ScrollView.EventType.SCROLL_TO_BOTTOM, ScrollView.EventType.SCROLL_ENDED]) view.on(t, () => seen.push(t));- sv.scrollToBottom(0);- expect(sv.getScrollOffset().y).toBe(600);- sv.scrollToTop(0);- sv.scrollToOffset(new Vec2(0, 300), 0.5);- await frame(40);- expect(sv.getScrollOffset().y).toBe(300);- expect(seen).toContain(ScrollView.EventType.SCROLL_TO_BOTTOM);- expect(seen).toContain(ScrollView.EventType.SCROLL_ENDED);- });-- it('scrolls sideways when horizontal', async () => {- boot();- const { sv } = await scroller(true);- expect(sv.getMaxScrollOffset().x).toBe(600);- sv.scrollToRight(0);- expect(sv.getScrollOffset().x).toBe(600);- sv.scrollToLeft(0);- expect(sv.getScrollOffset().x).toBe(0);- });-});diff --git a/sdk/tests/cocos/editbox-wasm.test.ts b/sdk/tests/cocos/editbox-wasm.test.tsdeleted file mode 100644index fa45cb1a8..000000000--- a/sdk/tests/cocos/editbox-wasm.test.ts+++ /dev/null@@ -1,177 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file EditBox is a view on the engine's TextInput: a press takes the platform's text editor, what is typed lands in the field, and the- * field's rules (mode, length, password, hint) hold. The field draws its own text and hint, so what is read back is the field's.- */-import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';-import type { ESEngineModule } from '../../src/wasm';-import { Children, Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';-import { Text } from '../../src/ui/core/text';-import { TextInput } from '../../src/ui/text/text-input';-import { Color, EditBox, Node, UITransform } from '../../src/cocos';-import type { PlatformTextEditor, TextEditorEvent, TextEditorState } from '../../src/platform/types';-import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';-import { pointerApp, type PointerApp } from './helpers/pointerApp';--/** A text surface the test types into. */-class FakeEditor implements PlatformTextEditor {- state: TextEditorState = { value: '', selectionStart: 0, selectionEnd: 0, backward: false };- options: unknown = null;- focused = false;- disposed = false;- private handlers: Array<(e: TextEditorEvent) => void> = [];- focus(state: TextEditorState, options: unknown): void { this.state = { ...state }; this.options = options; this.focused = true; }- blur(): void { this.focused = false; }- read(): TextEditorState { return { ...this.state }; }- write(state: TextEditorState): void { this.state = { ...state }; }- subscribe(h: (e: TextEditorEvent) => void): () => void { this.handlers.push(h); return () => { this.handlers = this.handlers.filter((x) => x !== h); }; }- dispose(): void { this.disposed = true; }- type(value: string): void { this.state = { ...this.state, value, selectionStart: value.length, selectionEnd: value.length }; this.emit({ kind: 'change' }); }- emit(e: TextEditorEvent): void { for (const h of [...this.handlers]) h(e); }-}--// the field measures its text through a glyph atlas; a fixed advance stands in for the platform's rasterizer, which a test has none of-vi.mock('../../src/ui/text/text-renderer', () => ({- SdfTextRenderer: class {- atlas = { renderSize: 64, pixelSizeFor: () => 64, getGlyph: () => ({ advance: 16 }) };- dispose(): void {}- },-}));--let editor: FakeEditor | null;-vi.mock('../../src/platform', async (importOriginal) => ({- ...(await importOriginal<typeof import('../../src/platform')>()),- platformCreateTextEditor: () => editor,-}));--describe.skipIf(!HAS_WASM)('EditBox', () => {- let module: ESEngineModule;- let P: PointerApp | undefined;-- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- beforeEach(() => { editor = new FakeEditor(); });- afterEach(() => { P?.dispose(); P = undefined; });-- function box(name: string, x: number, y: number, w: number, h: number, parent?: Node): Node {- const n = new Node(name);- P!.app.world.insert(n._entity, Transform);- n.addComponent(UITransform)!.setContentSize(w, h);- n.setPosition(x, y, 0);- parent?.addChild(n);- return n;- }-- async function field(configure: (e: EditBox) => void = () => {}): Promise<{ node: Node; edit: EditBox }> {- P = pointerApp(module, { x: 0, y: 0 }, { fields: true });- const node = box('input', 200, 200, 160, 40);- const edit = node.addComponent<EditBox>('EditBox')!;- edit.placeholder = 'type here';- configure(edit);- await P.frame(2);- return { node, edit };- }-- /** What the field is showing now: its text part, which holds the hint while the value is empty. */- function shown(node: Node): string {- const parts = P!.app.world.get(node._entity, Children).entities;- return P!.app.world.get(parts[1]!, Text).content;- }-- it('is the engine field on its node: added if there is none, the same view each time', async () => {- const { node, edit } = await field();- expect(P!.app.world.has(node._entity, TextInput)).toBe(true);- expect(node.getComponent(EditBox)).toBe(edit);- expect(node.getComponent('cc.EditBox')).toBe(edit);- });-- it("takes the text editor on a press, and tells the field's listeners", async () => {- const { node, edit } = await field();- const seen: string[] = [];- node.on(EditBox.EventType.EDITING_DID_BEGAN, () => seen.push('began'));- await P!.tap(200, 200);- await P!.frame(1);- expect(editor!.focused).toBe(true);- expect(edit.isFocused()).toBe(true);- expect(seen).toEqual(['began']);- });-- it('shows the hint while empty, and what is typed after, with the field text-changed event', async () => {- const { node, edit } = await field();- const changed: string[] = [];- node.on(EditBox.EventType.TEXT_CHANGED, (e: EditBox) => changed.push(e.string));- expect(shown(node)).toBe('type here');- await P!.tap(200, 200);- editor!.type('hello');- await P!.frame(2);- expect(edit.string).toBe('hello');- expect(shown(node)).toBe('hello');- editor!.type('');- await P!.frame(2);- expect(shown(node)).toBe('type here');- expect(changed).toEqual(['hello', '']);- });-- it('holds to the length and the characters its mode takes, writing the fit text back to the surface', async () => {- const { edit } = await field((e) => { e.maxLength = 4; e.inputMode = EditBox.InputMode.NUMERIC; });- await P!.tap(200, 200);- editor!.type('12ab3456');- await P!.frame(1);- expect(edit.string).toBe('1234');- expect(editor!.state.value).toBe('1234');- });-- it('shows bullets for a password and keeps the real text', async () => {- const { node, edit } = await field((e) => { e.inputFlag = EditBox.InputFlag.PASSWORD; });- await P!.tap(200, 200);- editor!.type('secret');- await P!.frame(2);- expect(edit.string).toBe('secret');- expect(shown(node)).toBe('●●●●●●');- expect((editor!.options as { password: boolean }).password).toBe(true);- });-- it('ends on submit with a return event and then an end event, giving the surface back', async () => {- const { node, edit } = await field();- const seen: string[] = [];- node.on(EditBox.EventType.EDITING_RETURN, () => seen.push('return'));- node.on(EditBox.EventType.EDITING_DID_ENDED, () => seen.push('ended'));- await P!.tap(200, 200);- await P!.frame(1);- editor!.emit({ kind: 'submit' });- await P!.frame(2);- expect(seen).toEqual(['return', 'ended']);- expect(edit.isFocused()).toBe(false);- expect(editor!.focused).toBe(false);- });-- it('can be set from a script, and shows it', async () => {- const { node, edit } = await field();- edit.string = 'preset';- await P!.frame(2);- expect(shown(node)).toBe('preset');- expect(P!.app.world.get(node._entity, TextInput).value).toBe('preset');- });-- it("hands a script the field's style as its text and hint labels", async () => {- const { node, edit } = await field();- edit.textLabel.color = new Color(255, 0, 0, 255);- edit.placeholderLabel.color = new Color(0, 255, 0, 255);- edit.textLabel.fontSize = 28;- const data = P!.app.world.get(node._entity, TextInput);- expect(data.color).toMatchObject({ r: 1, g: 0, b: 0 });- expect(data.placeholderColor).toMatchObject({ r: 0, g: 1, b: 0 });- expect(data.fontSize).toBe(28);- expect(edit.placeholderLabel.string).toBe('type here');- });-- it('does nothing on a host with no text editor', async () => {- editor = null;- const { node, edit } = await field();- const seen: string[] = [];- node.on(EditBox.EventType.EDITING_DID_BEGAN, () => seen.push('began'));- await P!.tap(200, 200);- expect(seen).toEqual([]);- expect(edit.string).toBe('');- });-});diff --git a/sdk/tests/cocos/geometry.test.ts b/sdk/tests/cocos/geometry.test.tsdeleted file mode 100644index 39574bf0b..000000000--- a/sdk/tests/cocos/geometry.test.ts+++ /dev/null@@ -1,57 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import { describe, expect, it } from 'vitest';-import { Vec3 } from '../../src/cocos/math';-import { geometry } from '../../src/cocos/geometry';--const { AABB, Ray, Plane, intersect } = geometry;--describe('geometry.AABB', () => {- it('is a centre and half sizes, from corners or by itself', () => {- const box = AABB.fromPoints(new Vec3(0, 0, 0), new Vec3(4, 2, 6));- expect([box.center.x, box.center.y, box.center.z]).toEqual([2, 1, 3]);- expect([box.halfExtents.x, box.halfExtents.y, box.halfExtents.z]).toEqual([2, 1, 3]);- expect(new AABB().halfExtents.x).toBe(1);- const min = new Vec3(), max = new Vec3();- box.getBoundary(min, max);- expect([min.x, max.z]).toEqual([0, 6]);- });-- it('merges into the box that holds both', () => {- const merged = AABB.merge(new AABB(), new AABB(0, 0, 0, 1, 1, 1), new AABB(10, 0, 0, 1, 1, 1));- expect(merged.center.x).toBe(5);- expect(merged.halfExtents.x).toBe(6);- });-});--describe('geometry.intersect', () => {- it('tells boxes that overlap (touching counts) from ones that do not', () => {- expect(intersect.aabbWithAABB(new AABB(0, 0, 0, 1, 1, 1), new AABB(1.5, 0, 0, 1, 1, 1))).toBe(true);- expect(intersect.aabbWithAABB(new AABB(0, 0, 0, 1, 1, 1), new AABB(2, 0, 0, 1, 1, 1))).toBe(true);- expect(intersect.aabbWithAABB(new AABB(0, 0, 0, 1, 1, 1), new AABB(2.1, 0, 0, 1, 1, 1))).toBe(false);- });-- it('answers how far along a ray a plane is, and 0 for a miss', () => {- const plane = Plane.fromNormalAndPoint(new Plane(), new Vec3(0, 1, 0), new Vec3(0, 5, 0));- expect(intersect.rayPlane(new Ray(0, 0, 0, 0, 1, 0), plane)).toBe(5);- expect(intersect.rayPlane(new Ray(0, 0, 0, 1, 0, 0), plane)).toBe(0); // parallel- expect(intersect.rayPlane(new Ray(0, 0, 0, 0, -1, 0), plane)).toBe(0); // behind- });-- it('answers how far along a ray a box is, from outside and from inside', () => {- const box = new AABB(0, 0, -10, 1, 1, 1);- expect(intersect.rayAABB(new Ray(0, 0, 0, 0, 0, -1), box)).toBe(9);- expect(intersect.rayAABB(new Ray(5, 0, 0, 0, 0, -1), box)).toBe(0);- expect(intersect.rayAABB(new Ray(0, 0, -10, 0, 0, -1), box)).toBe(1); // starts inside: where it leaves- });-});--describe('geometry.Ray', () => {- it('points from one place to another, and finds a point along itself', () => {- const ray = Ray.fromPoints(new Ray(), new Vec3(0, 0, 0), new Vec3(0, 0, -4));- expect([ray.d.x, ray.d.y, ray.d.z]).toEqual([0, 0, -1]);- const hit = new Vec3();- ray.computeHit(hit, 3);- expect(hit.z).toBe(-3);- });-});diff --git a/sdk/tests/cocos/globals-wasm.test.ts b/sdk/tests/cocos/globals-wasm.test.tsdeleted file mode 100644index 60dd9bc7d..000000000--- a/sdk/tests/cocos/globals-wasm.test.ts+++ /dev/null@@ -1,133 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file The global `input`, the game clock, and the visible size, fed by the real frame loop.- *- * A listener on `input` hears every touch, key and mouse event whether or not anything is under the pointer; keys arrive as Cocos- * key codes; the wheel is reported with Cocos's sign; the game clock advances with the engine's; and the visible size scripts read- * is what the UI camera shows.- */-import { afterEach, beforeAll, describe, expect, it } from 'vitest';-import type { ESEngineModule } from '../../src/wasm';-import { App, flushPendingRegistrations } from '../../src/app/app';-import { ensureBuiltinComponentsRegistered } from '../../src/ecs/component';-import { AppContext, setDefaultContext } from '../../src/ecs/context';-import { InputState } from '../../src/input/input';-import { ScreenLayout } from '../../src/ui/core/screen-layout';-import { resetClassRegistry } from '../../src/cocos/registry';-import { declareBuiltinScripts } from '../../src/cocos/builtinScripts';-import { pumpKeysAndMouse } from '../../src/cocos/input';-import type { ControlPointer } from '../../src/ui/input/control-pointers';-import { pointerApp, type PointerApp } from './helpers/pointerApp';-import {- EventKeyboard, EventMouse, EventTouch, Input, KeyCode, game, input, screen, setCurrentWorld, view,-} from '../../src/cocos';-import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';--/** The mouse as the engine reports it: the world point and the surface point are the same here. */-const mouseAt = (x: number, y: number): ControlPointer => ({ worldX: x, worldY: y, screenX: x, screenY: y }) as never;--describe.skipIf(!HAS_WASM)('input, game and view from the frame loop', () => {- let module: ESEngineModule;- let registry: InstanceType<ESEngineModule['Registry']> | undefined;- let app: App | undefined;- let P: PointerApp | undefined;-- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- afterEach(() => {- input.targetOff(undefined);- for (const t of Object.values(Input.EventType)) input.off(t);- P?.dispose();- P = undefined;- setCurrentWorld(null);- app?.world.disconnectCpp();- registry?.delete();- app = undefined;- registry = undefined;- });-- function boot(): void {- setDefaultContext(new AppContext());- ensureBuiltinComponentsRegistered();- resetClassRegistry();- declareBuiltinScripts();- registry = new module.Registry();- app = App.new();- app.connectCpp(registry as never, module);- flushPendingRegistrations(app);- setCurrentWorld(app.world);- }-- it('tells a listener on input about every touch, wherever it lands', async () => {- P = pointerApp(module);- const log: string[] = [];- for (const t of [Input.EventType.TOUCH_START, Input.EventType.TOUCH_MOVE, Input.EventType.TOUCH_END]) {- input.on(t, (e: EventTouch) => log.push(`${t}@${Math.round(e.getUILocationX())},${Math.round(e.getUILocationY())}`));- }- await P.press(300, 200);- await P.move(320, 200);- await P.release(320, 200);- expect(log).toEqual(['touch-start@300,200', 'touch-move@320,200', 'touch-end@320,200']);- });-- it('turns key state into KEY_DOWN, KEY_PRESSING and KEY_UP with Cocos key codes', () => {- boot();- const state = new InputState();- const log: string[] = [];- for (const t of [Input.EventType.KEY_DOWN, Input.EventType.KEY_PRESSING, Input.EventType.KEY_UP]) {- input.on(t, (e: EventKeyboard) => log.push(`${t}:${e.keyCode}:${e.isPressed}`));- }- state.noteKeyDown('KeyA');- pumpKeysAndMouse(state, null);- state.keysPressed.clear();- pumpKeysAndMouse(state, null); // held- state.noteKeyUp('KeyA');- pumpKeysAndMouse(state, null);- expect(log).toEqual([- `keydown:${KeyCode.KEY_A}:true`,- `key-pressing:${KeyCode.KEY_A}:true`,- `keyup:${KeyCode.KEY_A}:false`,- ]);- });-- it('turns the mouse into MOUSE_DOWN / MOVE / UP / WHEEL, with the wheel signed as Cocos signs it', () => {- boot();- const state = new InputState();- const log: string[] = [];- input.on(Input.EventType.MOUSE_DOWN, (e: EventMouse) => log.push(`down:${e.getButton()}@${e.getUILocationX()},${e.getUILocationY()}`));- input.on(Input.EventType.MOUSE_MOVE, (e: EventMouse) => log.push(`move:${e.getDeltaX()}`));- input.on(Input.EventType.MOUSE_UP, (e: EventMouse) => log.push(`up:${e.getButton()}`));- input.on(Input.EventType.MOUSE_WHEEL, (e: EventMouse) => log.push(`wheel:${e.getScrollY()}`));- pumpKeysAndMouse(state, mouseAt(100, 100)); // the first frame only learns where the mouse is- state.noteMouseDown(0);- pumpKeysAndMouse(state, mouseAt(100, 100));- state.mouseButtonsPressed.clear();- pumpKeysAndMouse(state, mouseAt(130, 100));- state.noteMouseUp(0);- state.scrollDeltaY = 120; // the DOM's "down"- pumpKeysAndMouse(state, mouseAt(130, 100));- expect(log).toEqual(['down:0@100,100', 'move:30', 'up:0', 'wheel:-120']);- });-- it('advances the game clock with the engine\'s, and lets a script read it', async () => {- boot();- await app!.tick(1 / 60);- const before = game.totalTime;- await app!.tick(1 / 60);- await app!.tick(1 / 60);- expect(game.deltaTime).toBeCloseTo(1 / 60, 4);- expect(game.totalTime).toBeGreaterThan(before);- expect(game.frameStartTime).toBeGreaterThan(0);- });-- it('takes the visible size and the window from the screen layout', async () => {- boot();- app!.insertResource(ScreenLayout, {- valid: true, left: -640, right: 640, bottom: -360, top: 360, safeLeft: -640, safeRight: 640, safeBottom: -360, safeTop: 360,- scale: 2, viewportW: 2560, viewportH: 1440,- } as never);- await app!.tick(1 / 60);- expect([view.getVisibleSize().width, view.getVisibleSize().height]).toEqual([1280, 720]);- expect([screen.windowSize.width, screen.windowSize.height]).toEqual([2560, 1440]);- });-});diff --git a/sdk/tests/cocos/globals.test.ts b/sdk/tests/cocos/globals.test.tsdeleted file mode 100644index db47f3b3e..000000000--- a/sdk/tests/cocos/globals.test.ts+++ /dev/null@@ -1,328 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file The globals a Cocos script reads at startup: `sys`, `macro`, `Layers`, `view`, `screen`, `game`, `KeyCode`, and- * `resources` / `assetManager`. No engine: what is checked is the values scripts compare against and the shapes they iterate.- */-import { beforeEach, describe, expect, it } from 'vitest';-import {- Component, EventHandler, Game, KeyCode, Scheduler, Asset, director, reportFrame, Layers, Prefab, Size, View, assetManager, game, macro, resources, screen, setCurrentWorld, setResourceManifest, setVisibleSize, sys, view,- providePrefab,-} from '../../src/cocos';-import { keyCodeOf } from '../../src/cocos/inputApi';-import { AppContext, setDefaultContext } from '../../src/ecs/context';-import { declareBuiltinScripts } from '../../src/cocos/builtinScripts';-import { resetClassRegistry } from '../../src/cocos/registry';-import { setWindowPixels } from '../../src/cocos/ui/screen';--describe('sys', () => {- it('answers in the names scripts compare against', () => {- expect(Object.values(sys.OS)).toContain(sys.os);- expect(Object.values(sys.Platform)).toContain(sys.platform);- expect(sys.OS.IOS).toBe('iOS');- expect(sys.OS.ANDROID).toBe('Android');- expect(sys.Platform.WECHAT_GAME).not.toBe(sys.Platform.IOS);- expect(typeof sys.isNative).toBe('boolean');- expect(typeof sys.isBrowser).toBe('boolean');- });-- it('keeps values in localStorage, as strings, and forgets what was removed', () => {- sys.localStorage.setItem('k', 42 as never);- expect(sys.localStorage.getItem('k')).toBe('42');- sys.localStorage.removeItem('k');- expect(sys.localStorage.getItem('k')).toBeNull();- sys.localStorage.setItem('a', '1');- sys.localStorage.clear();- expect(sys.localStorage.getItem('a')).toBeNull();- });-});--describe('macro and Layers', () => {- it('has the constants scripts use', () => {- expect(macro.REPEAT_FOREVER).toBe(Number.MAX_VALUE - 1);- expect(macro.TextAlignment.CENTER).toBe(1);- expect(macro.INVALID_INDEX).toBe(-1);- });-- it('has Cocos\'s layer numbers, and names layers both ways', () => {- expect(Layers.Enum.UI_2D).toBe(1 << 25);- expect(Layers.Enum.DEFAULT).toBe(1 << 30);- expect(Layers.nameToLayer('UI_2D')).toBe(1 << 25);- expect(Layers.layerToName(1 << 25)).toBe('UI_2D');- Layers.addLayer('Boss', 3);- expect(Layers.nameToLayer('Boss')).toBe(8);- expect(Layers.check(8 | 1, Layers.makeMaskInclude([8]))).toBe(true);- expect(Layers.check(1, Layers.makeMaskExclude([1]))).toBe(false);- Layers.deleteLayer(3);- expect(Layers.nameToLayer('Boss')).toBeUndefined();- });-});--describe('view and screen', () => {- beforeEach(() => { setVisibleSize(960, 640); setWindowPixels(1920, 1280); });-- it('is one View', () => {- expect(View.instance).toBe(view);- });-- it('reports the visible size, and the design size as the visible size until one is set', () => {- expect([view.getVisibleSize().width, view.getVisibleSize().height]).toEqual([960, 640]);- expect(view.getDesignResolutionSize()).toEqual(new Size(960, 640));- view.setDesignResolutionSize(750, 1334, View.ResolutionPolicy.FIXED_WIDTH);- expect(view.getDesignResolutionSize()).toEqual(new Size(750, 1334));- expect(view.getResolutionPolicy()).toBe(View.ResolutionPolicy.FIXED_WIDTH);- });-- it('tells a listener when the canvas resizes, once per change', () => {- let n = 0;- const cb = (): void => { n++; };- view.on('canvas-resize', cb);- setVisibleSize(960, 640); // unchanged- setVisibleSize(1280, 720);- view.off('canvas-resize', cb);- setVisibleSize(1000, 700);- expect(n).toBe(1);- });-- it('gives the window in physical pixels, and the frame in CSS pixels', () => {- expect([screen.windowSize.width, screen.windowSize.height]).toEqual([1920, 1280]);- expect(view.getFrameSize().width).toBe(1920 / screen.devicePixelRatio);- expect(view.getScaleX()).toBe(2);- let seen: number[] = [];- screen.on('window-resize', (w: number, h: number) => { seen = [w, h]; });- setWindowPixels(800, 600);- expect(seen).toEqual([800, 600]);- });-});--describe('game', () => {- it('has the event names scripts register for', () => {- expect(Game.EVENT_HIDE).toBe('game_on_hide');- expect(Game.EVENT_SHOW).toBe('game_on_show');- expect(game.isInited).toBe(true);- });-- it('emits and removes listeners like any event target', () => {- const seen: unknown[] = [];- const cb = (x: unknown): void => { seen.push(x); };- game.on('custom', cb);- game.emit('custom', 1);- game.off('custom', cb);- game.emit('custom', 2);- expect(seen).toEqual([1]);- });-- it('keeps persistent roots', () => {- const node = {} as never;- game.addPersistRootNode(node);- expect(game.isPersistRootNode(node)).toBe(true);- game.removePersistRootNode(node);- expect(game.isPersistRootNode(node)).toBe(false);- });-});--describe('KeyCode', () => {- it('has the numbers of Cocos and finds them from the engine\'s key names', () => {- expect(KeyCode.KEY_A).toBe(65);- expect(KeyCode.SPACE).toBe(32);- expect(KeyCode.ARROW_UP).toBe(38);- expect(keyCodeOf('KeyW')).toBe(KeyCode.KEY_W);- expect(keyCodeOf('ArrowLeft')).toBe(KeyCode.ARROW_LEFT);- expect(keyCodeOf('Digit5')).toBe(KeyCode.DIGIT_5);- expect(keyCodeOf('MediaPlay')).toBe(KeyCode.NONE);- });-- it('gives every key its own number', () => {- const values = Object.values(KeyCode);- expect(new Set(values).size).toBe(values.length);- });-});--describe('resources and assetManager', () => {- const prepared = { ref: 'bullet.esprefab', scene: { version: 4, name: 'bullet', entities: [] } as never, rootId: 0, missing: [], release() {} };- beforeEach(() => {- setResourceManifest({- resources: { 'prefab/bullet': { path: 'bullet.esprefab', kind: 'prefab' }, 'icon/gold': { path: 'gold.png', kind: 'texture' }, 'model/ship': { path: '', kind: 'fbx' } },- hero: { 'skin/red': { path: 'red.esprefab', kind: 'prefab' } },- });- providePrefab('bullet.esprefab', prepared);- providePrefab('red.esprefab', prepared);- });-- const load = <T>(fn: (cb: (e: Error | null, r: T) => void) => void): Promise<{ err: Error | null; result: T }> =>- new Promise((resolve) => fn((err, result) => resolve({ err, result })));-- it('loads a prefab by its resources path, in any argument order', async () => {- const a = await load<Prefab>((cb) => resources.load('prefab/bullet', Prefab, cb));- expect(a.err).toBeNull();- expect(a.result).toBeInstanceOf(Prefab);- expect(a.result.path).toBe('bullet.esprefab');- const b = await load<Prefab>((cb) => resources.load('prefab/bullet', (() => {}) as never, cb));- expect(b.err).toBeNull();- const c = await load<Prefab>((cb) => resources.load('prefab/bullet.prefab', cb)); // an extension is ignored- expect(c.err).toBeNull();- });-- it('loads a list of paths into a list, and a directory into everything under it that loads', async () => {- const many = await load<Prefab[]>((cb) => resources.load(['prefab/bullet'], Prefab, cb));- expect(Array.isArray(many.result)).toBe(true);- const dir = await load<Prefab[]>((cb) => resources.loadDir('prefab', Prefab, cb));- expect(dir.result.map((p) => p.path)).toEqual(['bullet.esprefab']);- });-- it('says what is missing or not supported, instead of answering an empty asset', async () => {- const missing = await load<unknown>((cb) => resources.load('nope', cb));- expect(missing.err?.message).toMatch(/no asset "nope"/);- const model = await load<unknown>((cb) => resources.load('model/ship', cb));- expect(model.err?.message).toMatch(/not supported/);- // an image needs the engine's loader to become a texture, and says so when there is none- const texture = await load<unknown>((cb) => resources.load('icon/gold', cb));- expect(texture.err?.message).toMatch(/asset loader/);- // the sprite frame and the texture of an image are named by a suffix on its path, and are found as the image is- const frame = await load<unknown>((cb) => resources.load('icon/gold/spriteFrame', cb));- expect(frame.err?.message).toMatch(/asset loader/);- const asTexture = await load<unknown>((cb) => resources.load('icon/gold/texture', cb));- expect(asTexture.err?.message).toMatch(/asset loader/);- });-- it('has bundles by name, from the manifest', async () => {- const bundle = await load<{ name: string; load: Function }>((cb) => assetManager.loadBundle('hero', cb));- expect(bundle.err).toBeNull();- expect(bundle.result.name).toBe('hero');- expect(assetManager.getBundle('hero')).toBe(bundle.result);- const prefab = await load<Prefab>((cb) => (bundle.result as never as { load: Function }).load('skin/red', Prefab, cb));- expect(prefab.result.path).toBe('red.esprefab');- const unknown = await load<unknown>((cb) => assetManager.loadBundle('ghost', cb));- expect(unknown.err?.message).toMatch(/no bundle "ghost"/);- });-- it('has the caches scripts iterate', async () => {- await load<Prefab>((cb) => resources.load('prefab/bullet', Prefab, cb));- expect(assetManager.assets.count).toBeGreaterThan(0);- let seen = 0;- assetManager.assets.forEach(() => seen++);- expect(seen).toBe(assetManager.assets.count);- expect(assetManager.bundles.find((b) => b.name === 'resources')).toBe(resources);- expect(assetManager.cacheManager.cachedFiles.count).toBe(0);- });-});--describe('director', () => {- it('hands out a scheduler that runs timers by target, with a delay, an interval and a repeat count', () => {- const scheduler = director.getScheduler();- const target = {};- const calls: number[] = [];- scheduler.schedule(function (this: unknown, dt) { expect(this).toBe(target); calls.push(dt); }, target, 0.5, 1, 0.25);- reportFrame(0.2); expect(calls).toHaveLength(0); // inside the delay- reportFrame(0.1); expect(calls).toHaveLength(1); // the delay ended: the first fire- reportFrame(0.5); expect(calls).toHaveLength(2); // one interval later: the one repeat- reportFrame(0.5); expect(calls).toHaveLength(2); // and no more- expect(scheduler.isScheduled(() => {}, target)).toBe(false);- });-- it('stops what was unscheduled, pauses by target, and scales time', () => {- const scheduler = new Scheduler();- const target = {};- let n = 0;- const tick = (): void => { n++; };- scheduler.schedule(tick, target);- scheduler.update(0.1); expect(n).toBe(1);- scheduler.pauseTarget(target); scheduler.update(0.1); expect(n).toBe(1);- scheduler.resumeTarget(target); scheduler.setTimeScale(0.5);- let seen = 0; scheduler.unscheduleAllForTarget(target);- scheduler.schedule((dt) => { seen = dt; }, target);- scheduler.update(0.2); expect(seen).toBeCloseTo(0.1);- scheduler.unscheduleAllForTarget(target); scheduler.update(0.2); expect(n).toBe(1);- });-- it('calls update on a scheduled target, lowest priority first', () => {- const scheduler = new Scheduler();- const order: string[] = [];- scheduler.scheduleUpdate({ update: () => order.push('late') }, 5);- scheduler.scheduleUpdate({ update: () => order.push('early') }, -5);- scheduler.update(0.016);- expect(order).toEqual(['early', 'late']);- });-- it('reports the frame delta to scripts', () => {- reportFrame(0.033);- expect(director.getDeltaTime()).toBeCloseTo(0.033);- });-});--describe('Asset', () => {- it('keeps a count of its holders', () => {- const a = new Asset('x');- expect(a.addRef()).toBe(a);- a.addRef();- expect(a.refCount).toBe(2);- a.decRef();- expect(a.refCount).toBe(1);- a.decRef(); a.decRef();- expect(a.refCount).toBe(0);- });-- it('is loaded by uuid, from the manifest listing', async () => {- setResourceManifest({ resources: { 'prefab/bullet': { path: 'bullet.esprefab', kind: 'prefab', uuid: 'abc-123' } } });- providePrefab('bullet.esprefab', { ref: 'bullet.esprefab', scene: { version: 4, name: 'bullet', entities: [] } as never, rootId: 0, missing: [], release() {} });- const loaded = await new Promise<{ err: Error | null; result: unknown }>((resolve) =>- assetManager.loadAny({ uuid: 'abc-123' }, (err: Error | null, result: unknown) => resolve({ err, result })));- expect(loaded.err).toBeNull();- expect(loaded.result).toBeInstanceOf(Prefab);- const missing = await new Promise<Error | null>((resolve) => assetManager.loadAny('nope', (err: Error | null) => resolve(err)));- expect(missing?.message).toMatch(/uuid nope/);- });-});--describe('a session that follows another in the same script runtime', () => {- it("queues the layer's own systems again for the App that follows, once", () => {- const context = new AppContext();- setDefaultContext(context);- resetClassRegistry();- declareBuiltinScripts();- const first = context.drainPendingSystems().length;- expect(first).toBeGreaterThan(0);- // the next App takes the queues from a context that declared the layer once and does not import it again- declareBuiltinScripts();- expect(context.pendingSystems.length).toBe(first);- declareBuiltinScripts();- expect(context.pendingSystems.length).toBe(first);- });-- it('is not handed what the last one loaded, from the moment scripts run in its world', () => {- const first = {} as never, second = {} as never;- setCurrentWorld(first);- providePrefab('kept.esprefab', { ref: 'kept.esprefab', scene: { version: 4, name: 'kept', entities: [] } as never, rootId: 0, missing: [], release() {} });- expect(new Prefab('kept.esprefab')._prepared).toBeDefined();- setCurrentWorld(second);- expect(new Prefab('kept.esprefab')._prepared).toBeUndefined();- setCurrentWorld(null);- });-});--describe('a directory with a file the layer cannot load', () => {- it('loads the rest: a directory of configs holds a readme too', async () => {- setResourceManifest({- resources: {- 'cfg/rules': { path: 'rules.esprefab', kind: 'prefab' },- 'cfg/README': { path: '', kind: 'md' },- },- });- providePrefab('rules.esprefab', { ref: 'rules.esprefab', scene: { version: 4, name: 'rules', entities: [] } as never, rootId: 0, missing: [], release() {} });- const result = await new Promise<{ err: Error | null; assets: unknown[] }>((resolve) =>- resources.loadDir('cfg', (err: Error | null, assets: unknown[]) => resolve({ err, assets })));- expect(result.err).toBeNull();- expect(result.assets).toHaveLength(1);- // named for its file, as a script keys what it loads- expect((result.assets[0] as { name: string }).name).toBe('rules');- });-});--describe('Component.EventHandler', () => {- it('is the class scripts construct handlers with', () => {- const handler = new Component.EventHandler();- handler.handler = 'onTap';- expect(handler).toBeInstanceOf(EventHandler);- expect(handler.handler).toBe('onTap');- });-});diff --git a/sdk/tests/cocos/graphics-wasm.test.ts b/sdk/tests/cocos/graphics-wasm.test.tsdeleted file mode 100644index bf7fc581c..000000000--- a/sdk/tests/cocos/graphics-wasm.test.ts+++ /dev/null@@ -1,160 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file Graphics: a script draws a path and keeps it until `clear()`; it becomes the geometry of the node's own mesh renderer, in the node's space.- */-import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';-import type { ESEngineModule } from '../../src/wasm';-import { MeshRenderer, Transform, ensureBuiltinComponentsRegistered, type MeshRendererGeometry } from '../../src/ecs/component';-import type { MeshRendererAPI } from '../../src/render/meshRenderer';-import { Color, Graphics, Line, Node, Vec3 } from '../../src/cocos';-import { setGraphicsMeshApi } from '../../src/cocos/ui/graphics';-import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';-import { pointerApp, type PointerApp } from './helpers/pointerApp';--/** The geometry API, recording what a Graphics hands it. */-class FakeMeshApi {- geometry = new Map<number, MeshRendererGeometry>();- setGeometry(entity: number, g: MeshRendererGeometry): void { this.geometry.set(entity, g); }- clearGeometry(entity: number): void { this.geometry.delete(entity); }-}--describe.skipIf(!HAS_WASM)('Graphics', () => {- let module: ESEngineModule;- let P: PointerApp | undefined;- let api: FakeMeshApi;-- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- beforeEach(() => { api = new FakeMeshApi(); setGraphicsMeshApi(api as unknown as MeshRendererAPI); });- afterEach(() => { setGraphicsMeshApi(null); P?.dispose(); P = undefined; });-- async function graphics(): Promise<{ node: Node; g: Graphics }> {- P = pointerApp(module);- const node = new Node('g');- P.app.world.insert(node._entity, Transform);- const g = node.addComponent<Graphics>('Graphics')!;- await P.frame(1);- return { node, g };- }-- const shown = (node: Node): MeshRendererGeometry | undefined => api.geometry.get(node._entity as number);- const bounds = (g: MeshRendererGeometry) => {- const xs = g.positions.filter((_, i) => i % 2 === 0), ys = g.positions.filter((_, i) => i % 2 === 1);- return { minX: Math.min(...xs), maxX: Math.max(...xs), minY: Math.min(...ys), maxY: Math.max(...ys) };- };-- it('fills a rectangle as the triangles of its corners, in the fill colour, on the node\'s own mesh', async () => {- const { node, g } = await graphics();- g.fillColor = new Color(255, 0, 0, 255);- g.rect(10, 20, 30, 40);- g.fill();- await P!.frame(1);- const geometry = shown(node)!;- expect(geometry.indices).toHaveLength(6);- expect(bounds(geometry)).toEqual({ minX: 10, maxX: 40, minY: 20, maxY: 60 });- expect(geometry.colors!.slice(0, 4)).toEqual([1, 0, 0, 1]);- expect(P!.app.world.has(node._entity, MeshRenderer)).toBe(true);- });-- it('fills a path that is not a rectangle: a triangle, a rounded rectangle, a circle', async () => {- const { node, g } = await graphics();- g.moveTo(0, 0);- g.lineTo(10, 0);- g.lineTo(5, 8);- g.close();- g.fill();- await P!.frame(1);- expect(shown(node)!.indices).toHaveLength(3);-- g.clear();- g.roundRect(0, 0, 40, 20, 6);- g.fill();- await P!.frame(1);- expect(shown(node)!.indices.length).toBeGreaterThan(30);-- g.clear();- g.circle(0, 0, 10);- g.fill();- await P!.frame(1);- const b = bounds(shown(node)!);- expect(b.maxX).toBeCloseTo(10, 4);- expect(b.minY).toBeCloseTo(-10, 0);- });-- it('strokes a path at the line width, in the stroke colour', async () => {- const { node, g } = await graphics();- g.lineWidth = 4;- g.strokeColor = new Color(0, 255, 0, 255);- g.moveTo(0, 0);- g.lineTo(100, 0);- g.stroke();- await P!.frame(1);- const geometry = shown(node)!;- const b = bounds(geometry);- expect(b.maxX - b.minX).toBeGreaterThanOrEqual(100);- expect(b.maxY - b.minY).toBeCloseTo(4, 4); // butt caps: as wide as the line- expect(geometry.colors!.slice(0, 4)).toEqual([0, 1, 0, 1]);- });-- it('rounds the ends of a stroke when the cap is round', async () => {- const { node, g } = await graphics();- g.lineWidth = 10;- g.lineCap = Graphics.LineCap.ROUND;- g.moveTo(0, 0);- g.lineTo(100, 0);- g.stroke();- await P!.frame(1);- const b = bounds(shown(node)!);- expect(b.minX).toBeCloseTo(-5, 1); // the cap is a round of short flat pieces- expect(b.maxX).toBeCloseTo(105, 1);- });-- it('keeps what was drawn until it is cleared, and a path begun after a draw starts afresh', async () => {- const { node, g } = await graphics();- g.rect(0, 0, 5, 5);- g.fill();- g.rect(20, 0, 5, 5);- g.fill();- await P!.frame(1);- expect(shown(node)!.indices).toHaveLength(12); // two rectangles, the first not drawn a second time- g.clear();- await P!.frame(1);- expect(shown(node)).toBeUndefined();- });-- it('draws nothing while it is disabled and comes back when it is enabled', async () => {- const { node, g } = await graphics();- g.rect(0, 0, 5, 5);- g.fill();- await P!.frame(1);- g.enabled = false;- await P!.frame(1);- expect(shown(node)).toBeUndefined();- g.enabled = true;- await P!.frame(2);- expect(shown(node)).toBeDefined();- });-- it('draws a Line as a stroked polyline, carrying a world-space line back through its node', async () => {- P = pointerApp(module);- const node = new Node('line');- P.app.world.insert(node._entity, Transform);- node.setPosition(100, 50, 0);- node.setScale(new Vec3(2, 2, 1));- const line = node.addComponent<Line>('Line')!;- line.width = 4;- line.color = new Color(0, 0, 255, 255);- line.worldSpace = true;- line.positions = [{ x: 100, y: 50, z: 0 }, { x: 140, y: 50, z: 0 }]; // 40 along in the world: 20 in the node's own scaled space- await P.frame(2);- const geometry = api.geometry.get(node._entity as number)!;- const b = bounds(geometry);- expect(b.minX).toBeCloseTo(0, 3);- expect(b.maxX).toBeCloseTo(20, 3);- expect(geometry.colors!.slice(0, 4)).toEqual([0, 0, 1, 1]);- line.worldSpace = false;- line.positions = [{ x: 0, y: 0, z: 0 }, { x: 10, y: 0, z: 0 }];- await P.frame(2);- expect(bounds(api.geometry.get(node._entity as number)!).maxX).toBeCloseTo(10, 3);- });-});diff --git a/sdk/tests/cocos/helpers/pointerApp.ts b/sdk/tests/cocos/helpers/pointerApp.tsdeleted file mode 100644index 57cbac144..000000000--- a/sdk/tests/cocos/helpers/pointerApp.ts+++ /dev/null@@ -1,108 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file An app with the engine's real pointer pipeline, for tests that touch Cocos nodes.- *- * The camera maps the world square 0..800 x 0..800 onto an 800 x 800 surface, so a world point (x, y) is the surface pixel (x, y)- * counted from the bottom-left, and the pointer for it is at CSS (x, 800 - y). Every press, move and release is a real frame:- * the input state is set, the app ticks, and the engine's interaction system picks, holds and reports as it does in a game.- */-import { App, flushPendingRegistrations } from '../../../src/app/app';-import { registerComponent } from '../../../src/ecs/component';-import { AppContext, setDefaultContext } from '../../../src/ecs/context';-import { Input, InputState } from '../../../src/input/input';-import { UICameraInfo } from '../../../src/ui/core/ui-camera-info';-import { UILayoutGeneration } from '../../../src/ui/layout/ui-layout-generation';-import { uiInteractionPlugin } from '../../../src/ui/input/interaction';-import { focusPlugin } from '../../../src/ui/input/focus';-import { textInputPlugin } from '../../../src/ui/text/text-input-plugin';-import { ensureBuiltinComponentsRegistered } from '../../../src/ecs/component';-import { resetClassRegistry } from '../../../src/cocos/registry';-import { declareBuiltinScripts } from '../../../src/cocos/builtinScripts';-import { setCurrentWorld } from '../../../src/cocos';-import type { ESEngineModule } from '../../../src/wasm';--export const SURFACE = 800;--export interface PointerApp {- app: App;- input: InputState;- /** One frame. */- frame(n?: number): Promise<void>;- /** A finger lands on the world point (x, y). */- press(x: number, y: number, id?: number): Promise<void>;- move(x: number, y: number, id?: number): Promise<void>;- release(x: number, y: number, id?: number): Promise<void>;- tap(x: number, y: number): Promise<void>;- dispose(): void;-}--/** @p origin: how far the world's origin sits from the surface's bottom-left corner, in pixels: a surface point is the world point plus it. */-export function pointerApp(module: ESEngineModule, origin: { x: number; y: number } = { x: 0, y: 0 }, options: { fields?: boolean } = {}): PointerApp {- setDefaultContext(new AppContext());- ensureBuiltinComponentsRegistered();- resetClassRegistry();- declareBuiltinScripts();- const registry = new module.Registry();- const app = App.new();- app.connectCpp(registry as never, module);- const input = new InputState();- app.insertResource(Input, input);- const s = 2 / SURFACE;- const projection = new Float32Array([s, 0, 0, 0, 0, s, 0, 0, 0, 0, -0.001, 0, -1 + s * origin.x, -1 + s * origin.y, 0, 1]);- app.insertResource(UICameraInfo, {- ...UICameraInfo._default, viewProjection: projection, vpX: 0, vpY: 0, vpW: SURFACE, vpH: SURFACE, screenW: SURFACE, screenH: SURFACE, valid: true,- });- app.insertResource(UILayoutGeneration, { generation: 0 });- uiInteractionPlugin.build(app);- // text fields: focus follows a press, and the field's plugin takes the text surface- if (options.fields) {- focusPlugin.build(app);- textInputPlugin.build(app);- }- flushPendingRegistrations(app);- setCurrentWorld(app.world);-- // a world point is the surface point minus the origin; CSS y counts from the top- const css = (x: number, y: number, id: number) => ({ id, x: x + origin.x, y: SURFACE - (y + origin.y) });- const frame = async (n = 1): Promise<void> => {- for (let i = 0; i < n; i++) {- app.world.ensureTransformsComposed();- await app.tick(1 / 60);- }- };- return {- app, input, frame,- async press(x, y, id = 1) {- const p = css(x, y, id);- input.touches.set(id, p);- input.touchesStarted.set(id, p);- await frame();- input.touchesStarted.clear();- },- async move(x, y, id = 1) {- input.touches.set(id, css(x, y, id));- await frame();- },- async release(x, y, id = 1) {- const p = css(x, y, id);- input.touches.delete(id);- input.touchesEnded.set(id, p);- await frame();- input.touchesEnded.clear();- },- async tap(x, y) {- await this.press(x, y);- await this.release(x, y);- },- dispose() {- uiInteractionPlugin.cleanup(app);- textInputPlugin.cleanup(app);- setCurrentWorld(null);- app.world.disconnectCpp();- registry.delete();- },- };-}--export { registerComponent };diff --git a/sdk/tests/cocos/import-contract-wasm.test.ts b/sdk/tests/cocos/import-contract-wasm.test.tsdeleted file mode 100644index 477526bfe..000000000--- a/sdk/tests/cocos/import-contract-wasm.test.ts+++ /dev/null@@ -1,109 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A scene as the importer writes it, loaded into the real engine with the compatibility layer.- *- * The importer (pipeline/src/import/cocos) and the layer agree on a contract by name only: `ContentRect` (the engine's), `RectAnchors`,- * `Cocos.Button`, `Cocos.<ScriptClass>`, with a node reference as the entity id the loader maps. This is the one place that agreement- * is exercised end to end, so a rename on either side fails here and not on a user's project.- */-import { afterEach, beforeAll, describe, expect, it } from 'vitest';-import type { ESEngineModule } from '../../src/wasm';-import { App, flushPendingRegistrations } from '../../src/app/app';-import { ensureBuiltinComponentsRegistered } from '../../src/ecs/component';-import { AppContext, setDefaultContext } from '../../src/ecs/context';-import { loadSceneData } from '../../src/scene/scene';-import type { SceneData } from '../../src/scene/scene';-import { resetClassRegistry } from '../../src/cocos/registry';-import { declareBuiltinScripts } from '../../src/cocos/builtinScripts';-import { Button, Component, Node, UITransform, Widget, _decorator, setCurrentWorld, setVisibleSize } from '../../src/cocos';-import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';--const transform = { type: 'Transform', data: { position: { x: 0, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 1, y: 1, z: 1 } } };--describe.skipIf(!HAS_WASM)('the importer\'s scene in the compatibility layer', () => {- let module: ESEngineModule;- let registry: InstanceType<ESEngineModule['Registry']> | undefined;- let app: App | undefined;-- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- afterEach(() => {- setCurrentWorld(null);- app?.world.disconnectCpp();- registry?.delete();- app = undefined;- registry = undefined;- });-- it('loads UI geometry, alignment, a button with a handler on a later node, and a script with node references', async () => {- setDefaultContext(new AppContext());- ensureBuiltinComponentsRegistered();- resetClassRegistry();- declareBuiltinScripts();-- // The project's own script, as the layer's decorators declare it.- const seen: string[] = [];- @_decorator.ccclass('Hud')- class Hud extends Component {- @_decorator.property(Node) label: Node | null = null;- @_decorator.property([Node]) all: Node[] = [];- @_decorator.property speed = 1;- onBuy(_event: unknown, data: string): void { seen.push(data); }- }- // the decorator ran before the registry was reset above in some orders; declare is idempotent per name- void Hud;-- registry = new module.Registry();- app = App.new();- app.connectCpp(registry as never, module);- flushPendingRegistrations(app);- setCurrentWorld(app.world);- setVisibleSize(960, 640);-- const scene: SceneData = {- version: 4,- name: 'main',- entities: [- { id: 0, name: 'Canvas', parent: null, children: [1, 2], visible: true, components: [- transform,- { type: 'ContentRect', data: { size: { x: 10, y: 10 }, pivot: { x: 0.5, y: 0.5 } } },- { type: 'RectAnchors', data: { enabled: true, alignFlags: 45, left: 0, right: 0, top: 0, bottom: 0, alignMode: 1 } },- ] },- { id: 1, name: 'Buy', parent: 0, children: [], visible: true, components: [- transform,- { type: 'ContentRect', data: { size: { x: 120, y: 48 }, pivot: { x: 0.5, y: 0.5 } } },- { type: 'Cocos.Button', data: { enabled: true, interactable: true, transition: 3, zoomScale: 1.1, clickTargets: [2], clickHandlers: [{ component: 'Hud', handler: 'onBuy', customEventData: 'gold' }] } },- ] },- { id: 2, name: 'Hud', parent: 0, children: [], visible: true, components: [- transform,- { type: 'Cocos.Hud', data: { enabled: true, speed: 3, label: 1, all: [1, 2] } },- ] },- ],- } as never;- const map = loadSceneData(app.world, scene);- await app.tick(1 / 60);- await app.tick(1 / 60);-- const canvas = Node.for(app.world, map.get(0)!);- const buy = Node.for(app.world, map.get(1)!);- const hud = Node.for(app.world, map.get(2)!);-- // geometry and alignment: the canvas was authored 10x10 and stretches to the visible area- const t = canvas.getComponent(UITransform)!;- expect([t.width, t.height]).toEqual([960, 640]);- expect(canvas.position.x).toBe(0); // the screen is centred on the origin-- // a script with its fields, node references mapped to the entities the loader made- const script = hud.getComponent('Hud') as unknown as Hud;- expect(script.speed).toBe(3);- expect(script.label).toBe(buy);- expect(script.all).toEqual([buy, hud]);-- // the button's handler finds the script on a node that was later in the file, by its class name- const button = buy.getComponent(Button)!;- expect(button.clickEvents).toHaveLength(1);- button.clickEvents[0]!.emit([{}]);- expect(seen).toEqual(['gold']);- void Widget;- });-});diff --git a/sdk/tests/cocos/instantiate-wasm.test.ts b/sdk/tests/cocos/instantiate-wasm.test.tsdeleted file mode 100644index 086bf6f70..000000000--- a/sdk/tests/cocos/instantiate-wasm.test.ts+++ /dev/null@@ -1,219 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file `instantiate` and `tween` on nodes, against the real engine.- *- * A prefab is given in its prepared form (what the engine's loader makes), so what is exercised is the layer's side: that a held- * `Prefab` is a handle on a path, that instantiating spawns a whole subtree whose scripts then run, that the result is outside the- * scene until it has a parent, and that a copied node is independent of its original but keeps references to nodes outside it.- */-import { afterEach, beforeAll, describe, expect, it } from 'vitest';-import type { ESEngineModule } from '../../src/wasm';-import { App, flushPendingRegistrations } from '../../src/app/app';-import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';-import { AppContext, setDefaultContext } from '../../src/ecs/context';-import { loadSceneData, SCENE_FORMAT_VERSION } from '../../src/scene/scene';-import type { SceneData } from '../../src/scene/scene';-import type { PreparedPrefab } from '../../src/prefab/preparedPrefab';-import { resetClassRegistry } from '../../src/cocos/registry';-import { declareBuiltinScripts } from '../../src/cocos/builtinScripts';-import { Component, Node, Prefab, Vec3, _decorator, instantiate, providePrefab, setCurrentWorld, tween } from '../../src/cocos';-import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';--const transform = (x = 0, y = 0) => ({ type: 'Transform', data: { position: { x, y, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 1, y: 1, z: 1 } } });--describe.skipIf(!HAS_WASM)('instantiate and tween on the engine', () => {- let module: ESEngineModule;- let registry: InstanceType<ESEngineModule['Registry']> | undefined;- let app: App | undefined;-- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- afterEach(() => {- setCurrentWorld(null);- app?.world.disconnectCpp();- registry?.delete();- app = undefined;- registry = undefined;- });-- function connect(): void {- setDefaultContext(new AppContext());- ensureBuiltinComponentsRegistered();- resetClassRegistry();- declareBuiltinScripts();- }- function boot(): void {- registry = new module.Registry();- app = App.new();- app.connectCpp(registry as never, module);- flushPendingRegistrations(app);- setCurrentWorld(app.world);- }- const frame = async (n = 2): Promise<void> => { for (let i = 0; i < n; i++) await app!.tick(1 / 60); };-- /** A prefab of a root with one child, the root carrying the script. */- function bullet(): PreparedPrefab {- const scene = {- version: SCENE_FORMAT_VERSION, name: 'bullet',- entities: [- { id: 0, name: 'Bullet', parent: null, children: [1], visible: true, components: [transform(5, 6), { type: 'Cocos.Bullet', data: { enabled: true, damage: 7 } }] },- { id: 1, name: 'Trail', parent: 0, children: [], visible: true, components: [transform(1, 0)] },- ],- } as unknown as SceneData;- return { ref: 'bullet.esprefab', scene, rootId: 0, missing: [], release() {} };- }-- it('holds a prefab property as a handle on its path, and spawns the prepared prefab whole', async () => {- connect();- const started: number[] = [];- @_decorator.ccclass('Bullet')- class Bullet extends Component {- @_decorator.property damage = 1;- start() { started.push(this.damage); }- }- @_decorator.ccclass('Gun')- class Gun extends Component {- @_decorator.property(Prefab) round: Prefab | null = null;- }- void Bullet;- providePrefab('bullet.esprefab', bullet());- boot();-- const map = loadSceneData(app!.world, {- version: SCENE_FORMAT_VERSION, name: 'main',- entities: [{ id: 0, name: 'Gun', parent: null, children: [], visible: true, components: [transform(), { type: 'Cocos.Gun', data: { enabled: true, round: 'bullet.esprefab' } }] }],- } as unknown as SceneData);- await frame();- const gun = Node.for(app!.world, map.get(0)!);- const script = gun.getComponent(Gun)!;- expect(script.round).toBeInstanceOf(Prefab);- expect(script.round!.path).toBe('bullet.esprefab');-- const made = instantiate(script.round!);- expect(made.name).toBe('Bullet');- expect(made.children.map((c) => c.name)).toEqual(['Trail']);- expect([made.position.x, made.position.y]).toEqual([5, 6]);-- // out of the scene until it has a parent: nothing runs, but the node itself says it is active- expect(made.active).toBe(true);- expect(made.activeInHierarchy).toBe(false);- await frame();- expect(started).toEqual([]);-- gun.addChild(made);- expect(made.activeInHierarchy).toBe(true);- await frame();- expect(started).toEqual([7]);- });-- it('says what is wrong when the prefab has not loaded, rather than answering half a node', () => {- connect();- boot();- expect(() => instantiate(new Prefab('never-loaded.esprefab'))).toThrow(/not loaded yet/);- });-- it('keeps a switched-off instance switched off after it is parented', async () => {- connect();- boot();- // provided once the session's world is the current one: a prefab provided before it belongs to the session before- providePrefab('p.esprefab', bullet());- const made = instantiate(new Prefab('p.esprefab'));- made.active = false;- expect(made.active).toBe(false);- const parent = new Node('holder');- app!.world.insert(parent._entity, Transform);- parent.addChild(made);- expect(made.active).toBe(false);- expect(made.activeInHierarchy).toBe(false);- });-- it('copies a node with its children and scripts, independent of the original', async () => {- connect();- const ticks: string[] = [];- @_decorator.ccclass('Counter')- class Counter extends Component {- @_decorator.property n = 0;- update() { this.n++; ticks.push(this.node.name); }- }- void Counter;- boot();- const map = loadSceneData(app!.world, {- version: SCENE_FORMAT_VERSION, name: 'main',- entities: [- { id: 0, name: 'Root', parent: null, children: [1], visible: true, components: [transform(), { type: 'Cocos.Counter', data: { enabled: true, n: 10 } }] },- { id: 1, name: 'Child', parent: 0, children: [], visible: true, components: [transform(3, 0)] },- ],- } as unknown as SceneData);- const original = Node.for(app!.world, map.get(0)!);- const copy = instantiate(original);- expect(copy).not.toBe(original);- expect(copy.children.map((c) => c.name)).toEqual(['Child']);- expect(copy.children[0]).not.toBe(original.children[0]);- original.setPosition(100, 0, 0);- expect(copy.position.x).toBe(0);-- const holder = new Node('holder');- app!.world.insert(holder._entity, Transform);- holder.addChild(copy);- await frame(1);- expect(ticks.filter((n) => n === 'Root')).toHaveLength(2); // the original's and the copy's- });-- it('keeps a copy\'s reference to a node outside it pointed at that node', async () => {- connect();- @_decorator.ccclass('Follower')- class Follower extends Component {- @_decorator.property(Node) leader: Node | null = null;- }- boot();- const map = loadSceneData(app!.world, {- version: SCENE_FORMAT_VERSION, name: 'main',- entities: [- { id: 1, name: 'Leader', parent: null, children: [], visible: true, components: [transform()] },- { id: 2, name: 'Fan', parent: null, children: [], visible: true, components: [transform(), { type: 'Cocos.Follower', data: { enabled: true, leader: 1 } }] },- ],- } as unknown as SceneData);- await frame();- const leader = Node.for(app!.world, map.get(1)!);- const copy = instantiate(Node.for(app!.world, map.get(2)!));- const holder = new Node('holder');- app!.world.insert(holder._entity, Transform);- holder.addChild(copy);- await frame();- // `===`, not toBe: a failing toBe walks both nodes' worlds to print a diff, and the wasm heap is in there- expect(copy.getComponent(Follower)!.leader === leader).toBe(true);- });-- it('tweens a node\'s position by its accessor, and stops when the node is destroyed', async () => {- connect();- boot();- const n = new Node('mover');- app!.world.insert(n._entity, Transform);- tween(n).to(0.5, { position: new Vec3(60, 0, 0) }).start();- await frame(15); // 0.25s at 60 fps- expect(n.position.x).toBeCloseTo(30, 0);- await frame(30);- expect(n.position.x).toBe(60);-- const doomed = new Node('doomed');- app!.world.insert(doomed._entity, Transform);- const t = tween(doomed).to(10, { position: new Vec3(1, 0, 0) }).start();- doomed.destroy();- await frame(2);- expect(t.isRunning).toBe(false);- });-- it('waits while the node is switched off', async () => {- connect();- boot();- const n = new Node('sleeper');- app!.world.insert(n._entity, Transform);- tween(n).to(1, { position: new Vec3(10, 0, 0) }).start();- n.active = false;- await frame(30);- expect(n.position.x).toBe(0);- n.active = true;- await frame(70);- expect(n.position.x).toBe(10);- });-});diff --git a/sdk/tests/cocos/lifecycle.test.ts b/sdk/tests/cocos/lifecycle.test.tsdeleted file mode 100644index 8b1aba321..000000000--- a/sdk/tests/cocos/lifecycle.test.ts+++ /dev/null@@ -1,335 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file The Cocos compatibility layer: a script written against `cc` runs on the engine's own frame loop.- *- * The scripts here use real legacy decorators (this folder's tsconfig turns them on, as a Cocos project's does), and run through- * `App` and a `World` exactly as a game's would. What is pinned is what a Cocos script relies on and nothing else could tell it- * is wrong: the ORDER of the lifecycle, that `this.node` is the entity's node and the same object each time, that a property's- * stored value becomes the instance's value, and that switching a node off is not destroying it.- */-import { beforeEach, describe, expect, it } from 'vitest';-import { App, flushPendingRegistrations } from '../../src/app/app';-import { AppContext, setDefaultContext } from '../../src/ecs/context';-import { SceneOwner, getUserComponents } from '../../src/ecs/component';-import { resetClassRegistry } from '../../src/cocos/registry';-import { Component, Node, Vec3, _decorator, director, find, isValid, setCurrentWorld } from '../../src/cocos';--const { ccclass, property } = _decorator;--beforeEach(() => {- setDefaultContext(new AppContext());- resetClassRegistry();-});--async function boot(): Promise<App> {- const app = App.new();- flushPendingRegistrations(app);- return app;-}--const comp = (name: string) => getUserComponents().get(`Cocos.${name}`)!;--describe('declaring a script class', () => {- it('makes an Estella component of it, carrying its property defaults and the enabled flag', () => {- @ccclass('Patrol')- class Patrol extends Component {- @property speed = 60;- @property label = 'hi';- @property loop = true;- @property(Node) target: Node | null = null;- @property tint = new Vec3(1, 2, 3);- }- void Patrol;- const def = comp('Patrol') as unknown as { _default: Record<string, unknown> } | undefined;- expect(def).toBeDefined();- expect(def!._default).toEqual({ enabled: true, speed: 60, label: 'hi', loop: true, target: 0, tint: { x: 1, y: 2, z: 3 } });- });-- it('is named under a prefix, so a class named like an engine component cannot collide with it', () => {- @ccclass('Health')- class Health extends Component {}- void Health;- expect(getUserComponents().has('Cocos.Health')).toBe(true);- });-- it('takes the class name when @ccclass is given none, and when it is applied bare', () => {- @ccclass- class Bare extends Component {}- @ccclass()- class Called extends Component {}- void Bare; void Called;- expect(getUserComponents().has('Cocos.Bare')).toBe(true);- expect(getUserComponents().has('Cocos.Called')).toBe(true);- });-});--describe('the lifecycle', () => {- function lifecycle(events: string[]) {- @ccclass('Life')- class Life extends Component {- onLoad() { events.push('onLoad'); }- onEnable() { events.push('onEnable'); }- start() { events.push('start'); }- update(dt: number) { events.push(`update:${dt > 0 ? 'dt' : '0'}`); }- lateUpdate() { events.push('lateUpdate'); }- onDisable() { events.push('onDisable'); }- onDestroy() { events.push('onDestroy'); }- }- return Life;- }-- it('runs in the order Cocos does: onLoad, onEnable, start, then update and lateUpdate each frame', async () => {- const events: string[] = [];- lifecycle(events);- const app = await boot();- const e = app.world.spawn('life');- app.world.insert(e, comp('Life'), { enabled: true });- await app.tick(1 / 60);- await app.tick(1 / 60);- expect(events).toEqual(['onLoad', 'onEnable', 'start', 'update:dt', 'lateUpdate', 'update:dt', 'lateUpdate']);- });-- it('ends with onDisable then onDestroy when the entity is despawned', async () => {- const events: string[] = [];- lifecycle(events);- const app = await boot();- const e = app.world.spawn('life');- app.world.insert(e, comp('Life'), { enabled: true });- await app.tick(1 / 60);- events.length = 0;- app.world.despawn(e);- await app.tick(1 / 60);- expect(events).toEqual(['onDisable', 'onDestroy']);- });-- it('treats switching a node off as disabling it, not destroying it, and back on as enabling it again', async () => {- const events: string[] = [];- lifecycle(events);- const app = await boot();- const e = app.world.spawn('life');- app.world.insert(e, comp('Life'), { enabled: true });- await app.tick(1 / 60);- events.length = 0;-- Node.for(app.world, e).active = false;- await app.tick(1 / 60);- expect(events).toEqual(['onDisable']); // no update while off, and no onDestroy-- events.length = 0;- Node.for(app.world, e).active = true;- await app.tick(1 / 60);- expect(events).toEqual(['onEnable', 'update:dt', 'lateUpdate']); // start does not run a second time- });-- it('does not let one script throwing stop the rest', async () => {- const events: string[] = [];- @ccclass('Bad')- class Bad extends Component { update() { throw new Error('boom'); } }- @ccclass('Good')- class Good extends Component { update() { events.push('good'); } }- void Bad; void Good;- const app = await boot();- const a = app.world.spawn('a'), b = app.world.spawn('b');- app.world.insert(a, comp('Bad'), { enabled: true });- app.world.insert(b, comp('Good'), { enabled: true });- await app.tick(1 / 60);- await app.tick(1 / 60);- expect(events).toEqual(['good', 'good']);- });-});--describe('this.node', () => {- it('is the entity node, and the same object every time', async () => {- let seen: Node | null = null;- let again: Node | null = null;- @ccclass('Who')- class Who extends Component {- onLoad() { seen = this.node; again = Node.for(this._world, this._entity); }- }- void Who;- const app = await boot();- const e = app.world.spawn('hero');- app.world.insert(e, comp('Who'), { enabled: true });- await app.tick(1 / 60);- expect(seen).not.toBeNull();- expect(seen!.name).toBe('hero');- expect(seen).toBe(again);- });-- it('finds a sibling component through getComponent, the same instance each time', async () => {- const found: unknown[] = [];- @ccclass('Other')- class Other extends Component { @property hp = 5; }- @ccclass('Seeker')- class Seeker extends Component {- start() { found.push(this.getComponent(Other), this.node.getComponent(Other), this.getComponent('Other')); }- }- void Seeker;- const app = await boot();- const e = app.world.spawn('both');- app.world.insert(e, comp('Other'), { enabled: true, hp: 9 });- app.world.insert(e, comp('Seeker'), { enabled: true });- await app.tick(1 / 60);- expect(found).toHaveLength(3);- expect(found[0]).toBeInstanceOf(Other);- expect((found[0] as { hp: number }).hp).toBe(9); // the stored value, not the initializer- expect(found[1]).toBe(found[0]);- expect(found[2]).toBe(found[0]);- });-- it('answers null for a component the node does not have', async () => {- let got: unknown = 'unset';- @ccclass('Lone')- class Lone extends Component {- @property x = 0;- onLoad() { got = this.node.getComponent('Nope'); }- }- void Lone;- const app = await boot();- const e = app.world.spawn('x');- app.world.insert(e, comp('Lone'), { enabled: true, x: 0 });- await app.tick(1 / 60);- expect(got).toBeNull();- });-});--describe('properties', () => {- it('hand the instance the stored value in the Cocos type: a Vec3 for a vector, a Node for a node reference', async () => {- let seen: { speed?: number; dir?: unknown; target?: unknown } = {};- @ccclass('Props')- class Props extends Component {- @property speed = 1;- @property dir = new Vec3();- @property(Node) target: Node | null = null;- onLoad() { seen = { speed: this.speed, dir: this.dir, target: this.target }; }- }- void Props;- const app = await boot();- const other = app.world.spawn('other');- const e = app.world.spawn('holder');- app.world.insert(e, comp('Props'), { enabled: true, speed: 42, dir: { x: 1, y: 2, z: 3 }, target: other });- await app.tick(1 / 60);- expect(seen.speed).toBe(42);- expect(seen.dir).toBeInstanceOf(Vec3);- expect((seen.dir as Vec3).y).toBe(2);- expect(seen.target).toBeInstanceOf(Node);- expect((seen.target as Node).name).toBe('other');- });-- it('declare the node-typed ones as entity references, so a scene remaps them on load', () => {- @ccclass('Refs')- class Refs extends Component {- @property(Node) a: Node | null = null;- @property([Node]) list: Node[] = [];- @property n = 0;- }- void Refs;- const def = comp('Refs') as unknown as { entityFields: string[] };- expect([...def.entityFields].sort()).toEqual(['a', 'list']);- });-});--describe('scheduling', () => {- it('scheduleOnce fires once after its delay, and schedule repeats at its interval until unscheduled', async () => {- const log: string[] = [];- @ccclass('Timers')- class Timers extends Component {- start() {- this.scheduleOnce(() => log.push('once'), 0.05);- const tick = (): void => { log.push('tick'); if (log.filter((l) => l === 'tick').length === 3) this.unschedule(tick); };- this.schedule(tick, 0.02);- }- }- void Timers;- const app = await boot();- const e = app.world.spawn('t');- app.world.insert(e, comp('Timers'), { enabled: true });- for (let i = 0; i < 12; i++) await app.tick(0.01);- expect(log.filter((l) => l === 'once')).toHaveLength(1);- expect(log.filter((l) => l === 'tick')).toHaveLength(3);- });-});--describe('director, find, isValid', () => {- // Hierarchy and transforms live in the C++ registry, so what needs a parent is tested against the real engine (node-wasm.test.ts).- it('find a root node by name, and report a despawned one as invalid', async () => {- let canvas: Node | null = null;- @ccclass('Finder')- class Finder extends Component {- onLoad() {- canvas = find('Canvas');- expect(director.getScene()!.getChildByName('Canvas')).toBe(canvas);- }- }- void Finder;- const app = await boot();- const c = app.world.spawn('Canvas');- const h = app.world.spawn('host');- app.world.insert(h, comp('Finder'), { enabled: true });- await app.tick(1 / 60);- expect(canvas).toBe(Node.for(app.world, c));- expect(isValid(canvas)).toBe(true);- app.world.despawn(c);- expect(isValid(canvas)).toBe(false);- expect(isValid(null)).toBe(false);- });-});--describe('the start phase', () => {- it("gives every enabled component its start before any update of the frame, whichever was declared first", async () => {- const seen: unknown[] = [];-- @ccclass('Bar')- class Bar extends Component {- state = '';- percent: number | undefined;- update(dt: number) { if (this.state === 'start') this.percent = dt; }- }-- @ccclass('Screen')- class Screen extends Component {- bar: Bar | null = null;- start() { this.bar!.state = 'start'; }- update() { seen.push(this.bar!.percent); }- }- void Screen;-- const app = await boot();- const world = app.world;- const barEntity = world.spawn('bar');- world.insert(barEntity, comp('Bar'), { enabled: true });- const screenEntity = world.spawn('screen');- world.insert(screenEntity, comp('Screen'), { enabled: true });- // both exist before the frame, as a view and its child do when a script has been asking for them- const bar = Node.for(world, barEntity).getComponent(Bar)!;- const screen = Node.for(world, screenEntity).getComponent(Screen)!;- screen.bar = bar;- await app.tick(1 / 60);- // Bar is declared before Screen, so its update runs first in the frame: it must already see what Screen's start set- expect(seen).toEqual([1 / 60]);- });-});--describe('keeping a node through scene changes', () => {- it("marks the node persistent, and lists the new scene's own roots before the kept ones", async () => {- const app = await boot();- const world = app.world;- const kept = world.spawn('ui_layer');- world.insert(kept, SceneOwner, { scene: 'main', persistent: false });- const own = world.spawn('ui_layer');- world.insert(own, SceneOwner, { scene: 'level', persistent: false });-- setCurrentWorld(world);- director.addPersistRootNode(Node.for(world, kept));- expect(world.get(kept, SceneOwner).persistent).toBe(true);- expect(world.get(own, SceneOwner).persistent).toBe(false);- expect(director.isPersistRootNode(Node.for(world, kept))).toBe(true);-- // the new scene's own root answers a lookup by name, as in Cocos, where the kept nodes are put under the scene after it- const scene = director.getScene()!;- expect(scene.getChildByName('ui_layer')!._entity).toBe(own);- director.removePersistRootNode(Node.for(world, kept));- setCurrentWorld(null);- });-});diff --git a/sdk/tests/cocos/math.test.ts b/sdk/tests/cocos/math.test.tsdeleted file mode 100644index f8d3f6e0b..000000000--- a/sdk/tests/cocos/math.test.ts+++ /dev/null@@ -1,141 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file The value types a script reaches for, in the forms Cocos has them: what a game's own code calls (`tempVec3.lerp`, `Vec3.scaleAndAdd`,- * `Quat.fromViewUp`, `Mat4.fromRTS`, `Color.toArray`) must exist and give the numbers Cocos gives.- */-import { describe, expect, it } from 'vitest';-import { Color, Mat4, Quat, Vec2, Vec3, Vec4 } from '../../src/cocos';--describe('Vec3', () => {- it('lerps itself toward another by a ratio', () => {- const v = new Vec3(0, 10, -4).lerp(new Vec3(10, 20, 4), 0.5);- expect([v.x, v.y, v.z]).toEqual([5, 15, 0]);- });-- it('multiplies, divides and clamps in place', () => {- const v = new Vec3(2, 4, 6).multiply(new Vec3(2, 2, 2)).divide(new Vec3(4, 4, 4)).clampf(new Vec3(0, 0, 0), new Vec3(1, 1, 1));- expect([v.x, v.y, v.z]).toEqual([1, 1, 1]);- });-- it('has the static forms a script writes with an out parameter', () => {- const out = new Vec3();- expect(Vec3.scaleAndAdd(out, new Vec3(1, 1, 1), new Vec3(0, 2, 0), 3)).toBe(out);- expect([out.x, out.y, out.z]).toEqual([1, 7, 1]);- expect(Vec3.cross(new Vec3(), Vec3.RIGHT, Vec3.UP).z).toBe(1);- expect(Vec3.dot(new Vec3(1, 2, 3), new Vec3(4, 5, 6))).toBe(32);- expect(Vec3.squaredDistance(new Vec3(), new Vec3(1, 2, 2))).toBe(9);- expect(Vec3.angle(Vec3.RIGHT, Vec3.UP)).toBeCloseTo(Math.PI / 2, 6);- expect(Vec3.angle(Vec3.ZERO, Vec3.UP)).toBe(0);- expect(Vec3.min(new Vec3(), new Vec3(1, 5, 3), new Vec3(2, 4, 3)).y).toBe(4);- expect(Vec3.max(new Vec3(), new Vec3(1, 5, 3), new Vec3(2, 4, 3)).x).toBe(2);- expect(Vec3.toArray([], new Vec3(1, 2, 3))).toEqual([1, 2, 3]);- expect(Vec3.clone(new Vec3(1, 2, 3)).equals(new Vec3(1, 2, 3))).toBe(true);- expect(Vec3.equals(new Vec3(1, 2, 3), new Vec3(1, 2, 3.0000001))).toBe(true);- });-});--describe('Vec2', () => {- it('sets, measures and takes the angle between', () => {- const v = Vec2.set(new Vec2(), 3, 4);- expect(Vec2.len(v)).toBe(5);- expect(Vec2.angle(new Vec2(1, 0), new Vec2(0, 1))).toBeCloseTo(Math.PI / 2, 6);- expect(new Vec2(0, 0).lerp(new Vec2(10, 20), 0.25).y).toBe(5);- });-});--describe('Quat', () => {- it('inverts, conjugates and normalizes as Cocos does', () => {- const q = Quat.fromEuler(new Quat(), 10, 20, 30);- const inv = Quat.invert(new Quat(), q);- const id = Quat.multiply(new Quat(), q, inv);- expect(id.w).toBeCloseTo(1, 6);- expect(Math.abs(id.x) + Math.abs(id.y) + Math.abs(id.z)).toBeLessThan(1e-6);- const c = Quat.conjugate(new Quat(), q);- expect([c.x, c.w]).toEqual([-q.x, q.w]);- expect(Quat.dot(q, q)).toBeCloseTo(1, 6);- expect(Quat.normalize(new Quat(), new Quat(0, 0, 0, 2)).w).toBe(1);- });-- it('makes a rotation from an axis and an angle', () => {- const q = Quat.fromAxisAngle(new Quat(), Vec3.UP, Math.PI / 2);- const v = Vec3.transformQuat(new Vec3(), Vec3.RIGHT, q);- expect(v.z).toBeCloseTo(-1, 6);- });-- it('turns +z to the view direction with up kept upright (fromViewUp)', () => {- const view = new Vec3(1, 0, 0);- const q = Quat.fromViewUp(new Quat(), view);- const z = Vec3.transformQuat(new Vec3(), new Vec3(0, 0, 1), q);- expect(z.x).toBeCloseTo(1, 6);- const up = Vec3.transformQuat(new Vec3(), Vec3.UP, q);- expect(up.y).toBeCloseTo(1, 6);- expect(Quat.fromViewUp(new Quat(), Vec3.ZERO).w).toBe(1);- });-- it('is the shortest rotation between two directions (rotationTo)', () => {- const q = Quat.rotationTo(new Quat(), Vec3.RIGHT, Vec3.UP);- const v = Vec3.transformQuat(new Vec3(), Vec3.RIGHT, q);- expect(v.y).toBeCloseTo(1, 6);- const opposite = Quat.rotationTo(new Quat(), Vec3.RIGHT, new Vec3(-1, 0, 0));- expect(Vec3.transformQuat(new Vec3(), Vec3.RIGHT, opposite).x).toBeCloseTo(-1, 6);- expect(Quat.rotationTo(new Quat(), Vec3.UP, Vec3.UP).w).toBe(1);- });-- it('reads from and writes to arrays', () => {- expect(Quat.toArray([], new Quat(1, 2, 3, 4))).toEqual([1, 2, 3, 4]);- expect(Quat.fromArray(new Quat(), [0, 0, 0, 0, 5, 6, 7, 8], 4).w).toBe(8);- });-});--describe('Mat4', () => {- it('composes rotation, translation and scale (fromRTS) and takes them apart again (toRTS)', () => {- const q = Quat.fromEuler(new Quat(), 0, 90, 0);- const m = Mat4.fromRTS(new Mat4(), q, new Vec3(1, 2, 3), new Vec3(2, 2, 2));- const rq = new Quat(), rv = new Vec3(), rs = new Vec3();- Mat4.toRTS(m, rq, rv, rs);- expect([rv.x, rv.y, rv.z]).toEqual([1, 2, 3]);- expect(rs.x).toBeCloseTo(2, 6);- expect(Math.abs(Quat.dot(q, rq))).toBeCloseTo(1, 6);- expect(Mat4.getTranslation(new Vec3(), m).z).toBe(3);- });-- it('turns about Y after the matrix it is given (rotateY)', () => {- const m = Mat4.rotateY(new Mat4(), new Mat4(), Math.PI / 2);- const p = Vec3.transformMat4(new Vec3(), Vec3.RIGHT, m);- expect(p.z).toBeCloseTo(-1, 6);- });-- it('is a GL perspective projection', () => {- const m = Mat4.perspective(new Mat4(), Math.PI / 2, 2, 1, 11);- expect(m.m00).toBeCloseTo(0.5, 6);- expect(m.m05).toBeCloseTo(1, 6);- expect(m.m10).toBeCloseTo(-1.2, 6);- expect(m.m11).toBe(-1);- expect(m.m14).toBeCloseTo(-2.2, 6);- });-- it('copies, compares and moves through arrays', () => {- const a = Mat4.fromTranslation(new Mat4(), new Vec3(1, 2, 3));- const b = Mat4.copy(new Mat4(), a);- expect(Mat4.strictEquals(a, b)).toBe(true);- const arr = Mat4.toArray([], a);- expect(arr.length).toBe(16);- expect(Mat4.fromArray(new Mat4(), arr).m13).toBe(2);- });-});--describe('Vec4 and Color', () => {- it('writes a Vec4 into an array', () => {- expect(Vec4.toArray([], new Vec4(1, 2, 3, 4))).toEqual([1, 2, 3, 4]);- expect(Vec4.copy(new Vec4(), new Vec4(1, 2, 3, 4)).w).toBe(4);- });-- it('writes a Color as 0..1 floats, lerps, and reads hex statically', () => {- expect(Color.toArray([], new Color(255, 0, 51, 255))).toEqual([1, 0, 0.2, 1]);- const mid = Color.lerp(new Color(), new Color(0, 0, 0, 0), new Color(200, 100, 50, 255), 0.5);- expect([mid.r, mid.g, mid.b]).toEqual([100, 50, 25]);- const c = Color.fromHEX(new Color(), '#ff8000');- expect([c.r, c.g, c.b, c.a]).toEqual([255, 128, 0, 255]);- });-});diff --git a/sdk/tests/cocos/mesh-renderer-wasm.test.ts b/sdk/tests/cocos/mesh-renderer-wasm.test.tsdeleted file mode 100644index e610fbb86..000000000--- a/sdk/tests/cocos/mesh-renderer-wasm.test.ts+++ /dev/null@@ -1,126 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A script's MeshRenderer: its material is the engine's, a shared one is shared and an instance is this renderer's own, and a- * property set on either reaches the engine material.- */-import { afterEach, beforeAll, describe, expect, it } from 'vitest';-import type { ESEngineModule } from '../../src/wasm';-import { World } from '../../src/ecs/world';-import { MeshRenderer as EngineMeshRenderer, Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';-import { AppContext, setDefaultContext } from '../../src/ecs/context';-import { Material as EngineMaterial } from '../../src/render/material';-import { Color, MeshRenderer, Node, SpriteFrame, Texture2D, UIMeshRenderer, setCurrentWorld } from '../../src/cocos';-import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';--describe.skipIf(!HAS_WASM)('MeshRenderer on the engine', () => {- let module: ESEngineModule;- let registry: InstanceType<ESEngineModule['Registry']> | undefined;- let world: World | undefined;- const W = (): World => world!;-- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });-- function connect(): void {- setDefaultContext(new AppContext());- ensureBuiltinComponentsRegistered();- registry = new module.Registry();- world = new World();- world.connectCpp(registry, module);- setCurrentWorld(world);- }- afterEach(() => {- setCurrentWorld(null);- world?.disconnectCpp();- registry?.delete();- registry = undefined;- world = undefined;- });-- const node = (name: string): Node => { const n = new Node(name); W().insert(n._entity, Transform); return n; };-- it('is the engine renderer on its node, the same view each time', () => {- connect();- const n = node('m');- expect(n.getComponent(MeshRenderer)).toBeNull();- const r = n.addComponent(MeshRenderer)!;- expect(W().has(n._entity, EngineMeshRenderer)).toBe(true);- expect(n.getComponent(MeshRenderer)).toBe(r);- expect(n.getComponent('cc.MeshRenderer')).toBe(r);- r.enabled = false;- expect(W().get(n._entity, EngineMeshRenderer).enabled).toBe(false);- });-- it('shares a material until an instance is asked for, then has one of its own', () => {- connect();- const shared = EngineMaterial.create({ shader: 7, uniforms: { u_tint: { x: 1, y: 1, z: 1, w: 1 } } });- const a = node('a'), b = node('b');- for (const n of [a, b]) { n.addComponent(MeshRenderer); W().set(n._entity, EngineMeshRenderer, { ...W().get(n._entity, EngineMeshRenderer), material: shared }); }- const ra = a.getComponent(MeshRenderer)!, rb = b.getComponent(MeshRenderer)!;-- expect(ra.getSharedMaterial(0)).toBe(rb.getSharedMaterial(0));- expect(ra.material!._handle).toBe(shared);-- const mine = ra.getMaterialInstance(0)!;- expect(mine._handle).not.toBe(shared);- expect(W().get(a._entity, EngineMeshRenderer).material).toBe(mine._handle);- expect(ra.getMaterialInstance(0)).toBe(mine); // made once- expect(ra.getSharedMaterial(0)!._handle).toBe(shared); // the shared one is still the shared one- expect(rb.material!._handle).toBe(shared); // and the other renderer is untouched- });-- it('writes a property through to the engine material, colours in 0..1, and remembers it', () => {- connect();- const shared = EngineMaterial.create({ shader: 7, uniforms: { u_tint: { x: 1, y: 1, z: 1, w: 1 }, u_level: 0 } });- const n = node('p');- const r = n.addComponent(MeshRenderer)!;- W().set(n._entity, EngineMeshRenderer, { ...W().get(n._entity, EngineMeshRenderer), material: shared });- const m = r.getMaterialInstance(0)!;- m.setProperty('u_level', 0.5);- m.setProperty('u_tint', new Color(255, 0, 128, 255));- expect(EngineMaterial.getUniform(m._handle, 'u_level')).toBe(0.5);- const tint = EngineMaterial.getUniform(m._handle, 'u_tint') as { x: number; y: number; z: number; w: number };- expect([tint.x, tint.y, tint.z, tint.w].map((v) => Math.round(v * 100) / 100)).toEqual([1, 0, 0.5, 1]);- expect(m.getProperty('u_level')).toBe(0.5);- expect(EngineMaterial.getUniform(shared, 'u_level')).toBe(0); // the shared one did not change- });-- it('hands the engine material the texture a script sets by name, from an image or from the frame that holds one', () => {- connect();- const shared = EngineMaterial.create({ shader: 7, uniforms: {} });- const n = node('t');- const r = n.addComponent(MeshRenderer)!;- W().set(n._entity, EngineMeshRenderer, { ...W().get(n._entity, EngineMeshRenderer), material: shared });- const m = r.getMaterialInstance(0)!;- const image = new Texture2D('mask');- image._handle = 5;- m.setProperty('regionMask', image);- expect(EngineMaterial.getUniform(m._handle, 'regionMask')).toMatchObject({ __textureRef: true, textureId: 5 });- const other = new Texture2D('other');- other._handle = 6;- const frame = new SpriteFrame('frame');- frame.texture = other;- m.setProperty('regionMask', frame);- expect(EngineMaterial.getUniform(m._handle, 'regionMask')).toMatchObject({ textureId: 6 });- });-- it('makes the colour of an instance the renderer tint, and reads it back', () => {- connect();- const shared = EngineMaterial.create({ shader: 7 });- const n = node('t');- const r = n.addComponent(MeshRenderer)!;- W().set(n._entity, EngineMeshRenderer, { ...W().get(n._entity, EngineMeshRenderer), material: shared });- const m = r.getMaterialInstance(0)!;- m.setProperty('mainColor', new Color(255, 128, 0, 255));- const tint = W().get(n._entity, EngineMeshRenderer).color;- expect([tint.r, Math.round(tint.g * 255), tint.b, tint.a]).toEqual([1, 128, 0, 1]);- const back = m.getProperty('mainColor') as Color;- expect([back.r, back.g, back.b]).toEqual([255, 128, 0]);- });-- it('lets UIMeshRenderer be added without anything behind it', () => {- connect();- const n = node('ui');- expect(n.addComponent(UIMeshRenderer)).toBeInstanceOf(UIMeshRenderer);- });-});diff --git a/sdk/tests/cocos/misc.test.ts b/sdk/tests/cocos/misc.test.tsdeleted file mode 100644index d0d6b13cd..000000000--- a/sdk/tests/cocos/misc.test.ts+++ /dev/null@@ -1,106 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import { describe, expect, it } from 'vitest';-import { NodePool, ccenum, js, profiler } from '../../src/cocos/misc';-import type { Node } from '../../src/cocos/node';-import { Graphics, Label, Quat, Sprite, UIRenderer, Vec3 } from '../../src/cocos';--/** The parts of a node a pool touches. */-function fakeNode(handler?: { unuse(): void; reuse(args: unknown[]): void }) {- const log: string[] = [];- const node = {- removeFromParent: () => log.push('removed'),- destroy: () => { log.push('destroyed'); return true; },- getComponent: () => handler ?? null,- };- return { node: node as unknown as Node, log };-}--describe('NodePool', () => {- it('keeps what is put in, hands it back newest first, and says null when empty', () => {- const pool = new NodePool();- const a = fakeNode(), b = fakeNode();- pool.put(a.node);- pool.put(b.node);- pool.put(b.node); // the same node is not kept twice- expect(pool.size()).toBe(2);- expect(a.log).toEqual(['removed']);- expect(pool.get()).toBe(b.node);- expect(pool.get()).toBe(a.node);- expect(pool.get()).toBeNull();- });-- it('tells a handler component it is put away and brought back', () => {- const calls: string[] = [];- const handler = { unuse: () => calls.push('unuse'), reuse: (args: unknown[]) => calls.push(`reuse ${args.join(',')}`) };- const pool = new NodePool('Bullet');- pool.put(fakeNode(handler).node);- pool.get(1, 2);- expect(calls).toEqual(['unuse', 'reuse 1,2']);- });-- it('destroys what it holds when cleared', () => {- const pool = new NodePool();- const a = fakeNode();- pool.put(a.node);- pool.clear();- expect(pool.size()).toBe(0);- expect(a.log).toContain('destroyed');- });-});--describe('js and ccenum', () => {- it('names a class and its instances, and knows a subclass', () => {- class Base { }- class Child extends Base { }- expect(js.getClassName(Child)).toBe('Child');- expect(js.getClassName(new Child())).toBe('Child');- expect(js.getClassName(null)).toBe('');- expect(js.isChildClassOf(Child, Base)).toBe(true);- expect(js.isChildClassOf(Base, Child)).toBe(false);- expect(js.getSuper(Child)).toBe(Base);- });-- it('mixes in everything, or only what is missing', () => {- expect(js.mixin({ a: 1 }, { a: 2, b: 3 })).toEqual({ a: 2, b: 3 });- expect(js.addon({ a: 1 }, { a: 2, b: 3 })).toEqual({ a: 1, b: 3 });- });-- it('hands an enum back as it is', () => {- enum Mode { A, B }- expect(ccenum(Mode)).toBe(Mode);- });-});--describe('profiler', () => {- it('takes show and hide, and remembers which', () => {- expect(profiler.isShowingStats()).toBe(false);- profiler.showStats();- expect(profiler.isShowingStats()).toBe(true);- profiler.hideStats();- expect(profiler.isShowingStats()).toBe(false);- });-});--describe('UIRenderer', () => {- it('is the base of what draws a 2D element, and takes the rebuild requests that scripts send', () => {- for (const type of [Sprite, Label, Graphics]) {- expect(type.prototype).toBeInstanceOf(UIRenderer);- expect(typeof type.prototype.markForUpdateRenderData).toBe('function');- }- const probe = Object.create(Sprite.prototype) as Sprite;- expect(() => { probe.markForUpdateRenderData(); probe.markForUpdateRenderData(false); probe.setVertsDirty(); }).not.toThrow();- });-});--describe('Vec3.transformQuat', () => {- it('keeps a vector under the identity and turns it by a quarter about Y', () => {- const forward = new Vec3(0, 0, -1);- expect(Vec3.transformQuat(new Vec3(), forward, new Quat(0, 0, 0, 1))).toMatchObject({ x: 0, y: 0, z: -1 });- const s = Math.SQRT1_2;- const turned = Vec3.transformQuat(new Vec3(), forward, new Quat(0, s, 0, s));- expect(turned.x).toBeCloseTo(-1, 6);- expect(turned.y).toBeCloseTo(0, 6);- expect(turned.z).toBeCloseTo(0, 6);- });-});diff --git a/sdk/tests/cocos/node-components-wasm.test.ts b/sdk/tests/cocos/node-components-wasm.test.tsdeleted file mode 100644index 2a4c6f505..000000000--- a/sdk/tests/cocos/node-components-wasm.test.ts+++ /dev/null@@ -1,74 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file `node._components`: a project prepares the scripts of a node it just made (reads their `_components`) before the node is given a parent, so- * a script on a node that is not active has what it needs when something calls it before it loads.- */-import { afterEach, beforeAll, describe, expect, it } from 'vitest';-import type { ESEngineModule } from '../../src/wasm';-import { App, flushPendingRegistrations } from '../../src/app/app';-import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';-import { AppContext, setDefaultContext } from '../../src/ecs/context';-import { loadSceneData, SCENE_FORMAT_VERSION } from '../../src/scene/scene';-import type { SceneData } from '../../src/scene/scene';-import { resetClassRegistry } from '../../src/cocos/registry';-import { declareBuiltinScripts } from '../../src/cocos/builtinScripts';-import { Component, Node, _decorator, setCurrentWorld } from '../../src/cocos';-import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';--void Transform;-const transform = { type: 'Transform', data: { position: { x: 0, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 1, y: 1, z: 1 } } };--describe.skipIf(!HAS_WASM)('the components a node holds', () => {- let module: ESEngineModule;- let registry: InstanceType<ESEngineModule['Registry']> | undefined;- let app: App | undefined;-- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- afterEach(() => {- setCurrentWorld(null);- app?.world.disconnectCpp();- registry?.delete();- app = undefined;- registry = undefined;- });-- it('lists the scripts of a node under an inactive parent, ready to be prepared before they load', () => {- setDefaultContext(new AppContext());- ensureBuiltinComponentsRegistered();- resetClassRegistry();- declareBuiltinScripts();- const log: string[] = [];-- @_decorator.ccclass('Prepared')- class Prepared extends Component {- ready = false;- parseNode() { this.ready = true; log.push('parse'); }- onLoad() { log.push('load'); }- }- void Prepared;-- registry = new module.Registry();- app = App.new();- app.connectCpp(registry as never, module);- flushPendingRegistrations(app);- setCurrentWorld(app.world);- const map = loadSceneData(app.world, {- version: SCENE_FORMAT_VERSION, name: 'main',- entities: [- { id: 0, name: 'Parent', parent: null, children: [1], visible: true, components: [transform] },- { id: 1, name: 'Child', parent: 0, children: [], visible: true, components: [transform, { type: 'Disabled', data: {} }, { type: 'Cocos.Prepared', data: { enabled: true } }] },- ],- } as unknown as SceneData);- const child = Node.for(app.world, map.get(1)!);-- const held = child._components;- expect(held).toHaveLength(1);- expect(held[0]).toBeInstanceOf(Prepared);- (held[0] as unknown as { parseNode(): void }).parseNode();- expect((child.getComponent(Prepared) as Prepared).ready).toBe(true);- // the instance the node answers with, not a second one- expect(child.getComponent(Prepared)).toBe(held[0]);- expect(log).toContain('parse');- });-});diff --git a/sdk/tests/cocos/node-wasm.test.ts b/sdk/tests/cocos/node-wasm.test.tsdeleted file mode 100644index 251abbf87..000000000--- a/sdk/tests/cocos/node-wasm.test.ts+++ /dev/null@@ -1,324 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file `Node` against the real engine: hierarchy, transform and activity live in the C++ registry, so these run on the built- * wasm core and skip where there is none.- *- * What is pinned is what a Cocos script cannot be told is wrong: that a handle is the entity (`===`), that a position set is a- * position got, that `setWorldPosition` under a rotated, scaled parent lands where it was asked to, and that a tree walks the- * way `getChildByPath` and `find` say.- */-import { afterEach, beforeAll, describe, expect, it } from 'vitest';-import type { ESEngineModule } from '../../src/wasm';-import { World } from '../../src/ecs/world';-import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';-import { AppContext, setDefaultContext } from '../../src/ecs/context';-import { Button, Label, Node, Quat, UIRenderer, Vec3, director, find, setCurrentWorld } from '../../src/cocos';-import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';--describe.skipIf(!HAS_WASM)('Node on the engine', () => {- // After connect() both are set; the tests read them through these.- const W = (): World => world!;- let module: ESEngineModule;- let registry: InstanceType<ESEngineModule['Registry']> | undefined;- let world: World | undefined;-- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });-- function connect(): void {- setDefaultContext(new AppContext());- registry = new module.Registry();- world = new World();- world.connectCpp(registry, module);- setCurrentWorld(world);- }- afterEach(() => {- setCurrentWorld(null);- world?.disconnectCpp();- registry?.delete();- registry = undefined;- world = undefined;- });-- /** The names of nodes: comparing Node objects deeply would walk the whole world they hold. */- const names = (nodes: Node[]): string[] => nodes.map((n) => n.name);-- /** Canvas > Panel > Button, with Canvas also holding Label. */- function tree(): Record<'canvas' | 'panel' | 'button' | 'label', Node> {- const mk = (name: string): Node => { const n = new Node(name); W().insert(n._entity, Transform); return n; };- const canvas = mk('Canvas'), panel = mk('Panel'), button = mk('Button'), label = mk('Label');- canvas.addChild(panel); canvas.addChild(label); panel.addChild(button);- return { canvas, panel, button, label };- }-- it('walks a hierarchy the way a script reads it', () => {- connect();- const { canvas, panel, button, label } = tree();- expect(button.parent).toBe(panel);- expect(panel.parent).toBe(canvas);- expect(canvas.parent).toBeNull();- expect(names(canvas.children)).toEqual(['Panel', 'Label']);- expect(canvas.getChildByName('Panel')).toBe(panel);- expect(canvas.getChildByName('Nope')).toBeNull();- expect(canvas.getChildByPath('Panel/Button')).toBe(button);- expect(button.isChildOf(canvas)).toBe(true);- expect(canvas.isChildOf(button)).toBe(false);- });-- it('moves a node among its siblings, and the child order follows', () => {- connect();- const { canvas, panel, label } = tree();- const extra = new Node('Extra'); W().insert(extra._entity, Transform); canvas.addChild(extra);- expect(names(canvas.children)).toEqual(['Panel', 'Label', 'Extra']);- extra.setSiblingIndex(0);- expect(names(canvas.children)).toEqual(['Extra', 'Panel', 'Label']);- expect(extra.getSiblingIndex()).toBe(0);- panel.setSiblingIndex(-1);- expect(names(canvas.children)).toEqual(['Extra', 'Label', 'Panel']);- label.setSiblingIndex(99); // past the end is the end- expect(names(canvas.children)).toEqual(['Extra', 'Panel', 'Label']);- });-- it('finds a layer component by the name a scene and a script give it, `cc.Button`, as well as `Button`', () => {- connect();- const { panel } = tree();- const button = panel.addComponent(Button)!;- expect(panel.getComponent('Button')).toBe(button);- expect(panel.getComponent('cc.Button')).toBe(button);- expect(panel.getComponent('cc.NoSuchThing')).toBeNull();- });-- it('lets a script name its component', () => {- connect();- const { panel } = tree();- const button = panel.addComponent(Button)!;- expect(button.name).toBe('Panel<Button>');- button.name = 'MyButton';- expect(button.name).toBe('MyButton');- });-- it('detaches with removeFromParent, and moves with setParent', () => {- connect();- const { canvas, panel, button, label } = tree();- button.removeFromParent();- expect(button.parent).toBeNull();- expect(panel.children).toHaveLength(0);- button.setParent(label);- expect(names(label.children)).toEqual(['Button']);- expect(names(canvas.children)).toEqual(['Panel', 'Label']);- });-- it('holds a position, a scale and a rotation as the values that were set', () => {- connect();- const { panel } = tree();- panel.setPosition(10, 20, 30);- expect(panel.position.x).toBe(10);- expect(panel.position.y).toBe(20);- expect(panel.position.z).toBe(30);- panel.setPosition(new Vec3(1, 2, 3));- expect(panel.getPosition().equals(new Vec3(1, 2, 3))).toBe(true);- // x and y only: z stays- panel.setPosition(7, 8);- expect(panel.position.z).toBe(3);- panel.setScale(2, 3);- expect(panel.scale.x).toBe(2);- expect(panel.scale.y).toBe(3);- panel.setRotationFromEuler(0, 0, 90);- expect(panel.angle).toBeCloseTo(90, 4);- panel.angle = 45;- expect(panel.eulerAngles.z).toBeCloseTo(45, 4);- });-- it('reads the world directions of its axes: forward is -z, turned by the rotation', () => {- connect();- const { panel } = tree();- expect(panel.forward.z).toBeCloseTo(-1, 5);- expect(panel.up.y).toBeCloseTo(1, 5);- panel.setRotationFromEuler(0, 90, 0);- expect(panel.forward.x).toBeCloseTo(-1, 5);- expect(panel.right.z).toBeCloseTo(-1, 5);- });-- it('gives its world transform as a matrix: the position in the translation column, the scale on the diagonal', () => {- connect();- const { panel } = tree();- panel.setPosition(4, 5, 6);- panel.setScale(2, 2, 2);- const m = panel.worldMatrix;- expect(m.m12).toBeCloseTo(panel.worldPosition.x, 5);- expect(m.m13).toBeCloseTo(panel.worldPosition.y, 5);- expect(m.m00).toBeCloseTo(panel.worldScale.x, 5);- });-- it('reads a changed position back as a new object, so mutating it does not move the node', () => {- connect();- const { panel } = tree();- panel.setPosition(5, 5, 0);- const p = panel.position;- p.x = 99;- expect(panel.position.x).toBe(5);- panel.position = p;- expect(panel.position.x).toBe(99);- });-- it('places a node in world space under a parent that is moved, rotated and scaled', async () => {- connect();- const { canvas, panel } = tree();- canvas.setPosition(100, 50, 0);- canvas.setRotationFromEuler(0, 0, 90);- canvas.setScale(2, 2, 1);- panel.setWorldPosition(new Vec3(100, 150, 0));- const got = panel.worldPosition;- expect(got.x).toBeCloseTo(100, 3);- expect(got.y).toBeCloseTo(150, 3);- });-- it('switches off with its subtree and reports it per node', () => {- connect();- const { canvas, panel, button } = tree();- panel.active = false;- expect(panel.active).toBe(false);- expect(panel.activeInHierarchy).toBe(false);- expect(button.active).toBe(true); // its own switch is untouched- expect(button.activeInHierarchy).toBe(false); // an ancestor's takes it out- expect(canvas.activeInHierarchy).toBe(true);- panel.active = true;- expect(button.activeInHierarchy).toBe(true);- });-- it('destroys a node and reports it invalid', () => {- connect();- const { panel } = tree();- expect(panel.isValid).toBe(true);- panel.destroy();- expect(panel.isValid).toBe(false);- expect(panel.destroy()).toBe(false);- });-- it('finds nodes by path from the scene roots, with find and the scene', () => {- connect();- const { canvas, panel, button } = tree();- expect(find('Canvas')).toBe(canvas);- expect(find('Canvas/Panel')).toBe(panel);- expect(find('Canvas/Panel/Button')).toBe(button);- expect(find('Canvas/Nope')).toBeNull();- expect(find('Button')).toBe(button); // a bare name searches everything- expect(names(director.getScene()!.children)).toEqual(['Canvas']);- expect(find('Panel/Button', canvas)).toBe(button); // relative to a node- });-- it('delivers an event to its listeners with the target as this, once for once, and not after off', () => {- connect();- const { panel } = tree();- const log: string[] = [];- const target = { id: 't' };- const handler = function (this: { id: string }, arg: number): void { log.push(`${this.id}:${arg}`); };- panel.on('custom', handler, target);- panel.once('custom', () => log.push('once'));- panel.emit('custom', 1);- panel.emit('custom', 2);- panel.off('custom', handler, target);- panel.emit('custom', 3);- expect(log).toEqual(['t:1', 'once', 't:2']);- });-});--describe('Euler angles', () => {- it('round-trip through a quaternion, using Cocos own formulas', () => {- for (const [x, y, z] of [[0, 0, 90], [0, 0, 45], [30, 0, 0], [0, 60, 0], [20, 40, 70], [0, 0, -135]] as const) {- const e = Quat.toEuler(new Vec3(), Quat.fromEuler(new Quat(), x, y, z));- const back = Quat.fromEuler(new Quat(), e.x, e.y, e.z);- const q = Quat.fromEuler(new Quat(), x, y, z);- // the same rotation, whichever of the two equal quaternions (q and -q) came back- const dot = Math.abs(q.x * back.x + q.y * back.y + q.z * back.z + q.w * back.w);- expect(dot).toBeCloseTo(1, 5);- }- });-- it('a rotation about z alone reads back as that angle', () => {- const e = Quat.toEuler(new Vec3(), Quat.fromEuler(new Quat(), 0, 0, 45));- expect(e.z).toBeCloseTo(45, 4);- expect(e.x).toBeCloseTo(0, 4);- expect(e.y).toBeCloseTo(0, 4);- });-});--describe.skipIf(!HAS_WASM)('Node world-space setters', () => {- let module: ESEngineModule;- let registry: InstanceType<ESEngineModule['Registry']> | undefined;- let world: World | undefined;- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- afterEach(() => { setCurrentWorld(null); world?.disconnectCpp(); registry?.delete(); registry = undefined; world = undefined; });-- function pair(): { parent: Node; child: Node } {- setDefaultContext(new AppContext());- registry = new module.Registry(); world = new World(); world.connectCpp(registry, module); setCurrentWorld(world);- const parent = new Node('p'), child = new Node('c');- world.insert(parent._entity, Transform); world.insert(child._entity, Transform);- parent.addChild(child);- parent.setScale(2, 2, 2);- parent.setRotationFromEuler(0, 90, 0);- return { parent, child };- }-- it('sets a world rotation and scale that read back, under a turned and scaled parent', () => {- const { child } = pair();- child.setWorldRotationFromEuler(0, 30, 0);- child.setWorldScale(new Vec3(4, 4, 4));- expect(child.worldEulerAngles.y).toBeCloseTo(30, 4);- expect(child.worldScale.x).toBeCloseTo(4, 5);- expect(child.scale.x).toBeCloseTo(2, 5);- });-- it('looks at a point with -Z, walks the tree, and puts a world point in the node\'s space', () => {- const { parent, child } = pair();- child.setWorldPosition(new Vec3(0, 0, 0));- child.lookAt(new Vec3(10, 0, 0));- expect(child.forward.x).toBeCloseTo(1, 5);- const seen: string[] = [];- parent.walk((n) => seen.push(`in:${n.name}`), (n) => seen.push(`out:${n.name}`));- expect(seen).toEqual(['in:p', 'in:c', 'out:c', 'out:p']);- child.setWorldRotation(new Quat(0, 0, 0, 1));- child.setWorldPosition(new Vec3(1, 0, 0));- expect(child.inverseTransformPoint(new Vec3(), new Vec3(3, 0, 0)).x).toBeCloseTo(1, 5);- child.translate(new Vec3(0, 0, 1), Node.NodeSpace.WORLD);- expect(child.worldPosition.z).toBeCloseTo(1, 5);- });-});--describe.skipIf(!HAS_WASM)('Node.insertChild', () => {- let module: ESEngineModule;- let registry: InstanceType<ESEngineModule['Registry']> | undefined;- let world: World | undefined;- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- afterEach(() => { setCurrentWorld(null); world?.disconnectCpp(); registry?.delete(); registry = undefined; world = undefined; });-- it('puts a child at the place asked among the others', () => {- setDefaultContext(new AppContext());- registry = new module.Registry(); world = new World(); world.connectCpp(registry, module); setCurrentWorld(world);- const mk = (name: string): Node => { const n = new Node(name); world!.insert(n._entity, Transform); return n; };- const parent = mk('p'), a = mk('a'), b = mk('b'), c = mk('c');- parent.addChild(a); parent.addChild(b);- parent.insertChild(c, 1);- expect(parent.children.map((n) => n.name)).toEqual(['a', 'c', 'b']);- });-});--describe.skipIf(!HAS_WASM)('a base of the built-in views', () => {- let module: ESEngineModule;- let registry: InstanceType<ESEngineModule['Registry']> | undefined;- let world: World | undefined;- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- afterEach(() => { setCurrentWorld(null); world?.disconnectCpp(); registry?.delete(); registry = undefined; world = undefined; });-- it('is found as the Label the node holds, and is nothing on a node with no drawn element', () => {- setDefaultContext(new AppContext());- registry = new module.Registry(); world = new World(); world.connectCpp(registry, module); setCurrentWorld(world);- const n = new Node('n'), bare = new Node('bare');- world.insert(n._entity, Transform); world.insert(bare._entity, Transform);- const label = n.addComponent(Label)!;- expect(n.getComponent(UIRenderer)).toBe(label);- expect(n.getComponents(UIRenderer)).toEqual([label]);- expect(bare.getComponent(UIRenderer)).toBeNull();- });-});diff --git a/sdk/tests/cocos/pages-wasm.test.ts b/sdk/tests/cocos/pages-wasm.test.tsdeleted file mode 100644index 1413cf4ff..000000000--- a/sdk/tests/cocos/pages-wasm.test.ts+++ /dev/null@@ -1,113 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file PageView, ScrollBar, SafeArea and WebView.- */-import { afterEach, beforeAll, describe, expect, it } from 'vitest';-import type { ESEngineModule } from '../../src/wasm';-import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';-import { Node, PageView, SafeArea, ScrollBar, UITransform, Vec2, WebView, Widget } from '../../src/cocos';-import { setSafeInsets } from '../../src/cocos/ui/screen';-import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';-import { pointerApp, type PointerApp } from './helpers/pointerApp';--describe.skipIf(!HAS_WASM)('pages, bars, safe area and web view', () => {- let module: ESEngineModule;- let P: PointerApp | undefined;-- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- afterEach(() => { setSafeInsets(0, 0, 0, 0); P?.dispose(); P = undefined; });-- function box(name: string, x: number, y: number, w: number, h: number, parent?: Node, anchor = new Vec2(0.5, 0.5)): Node {- const n = new Node(name);- P!.app.world.insert(n._entity, Transform);- const t = n.addComponent(UITransform)!;- t.setContentSize(w, h);- t.anchorX = anchor.x;- t.anchorY = anchor.y;- n.setPosition(x, y, 0);- parent?.addChild(n);- return n;- }-- /** A 200 x 100 view over a row of three 200 x 100 pages, content anchored at its left. */- async function pager(): Promise<{ view: PageView; pages: Node[] }> {- P = pointerApp(module);- const host = box('view', 300, 300, 200, 100);- const content = box('content', -100, 0, 600, 100, host, new Vec2(0, 0.5));- const pages = [0, 1, 2].map((i) => box(`page${i}`, 100 + i * 200, 0, 200, 100, content));- const view = host.addComponent<PageView>('PageView')!;- view.content = content;- view.direction = PageView.Direction.Horizontal;- await P.frame(2);- return { view, pages };- }-- it('settles on a page it is asked for, and says it turned', async () => {- const { view } = await pager();- const turned: number[] = [];- view.node.on(PageView.EventType.PAGE_TURNING, (v: PageView) => turned.push(v.getCurrentPageIndex()));- expect(view.getPages()).toHaveLength(3);- view.scrollToPage(2, 0);- await P!.frame(2);- expect(view.getCurrentPageIndex()).toBe(2);- expect(view.getScrollOffset().x).toBeCloseTo(400, 3);- view.setCurrentPageIndex(0);- await P!.frame(2);- expect(view.getScrollOffset().x).toBeCloseTo(0, 3);- expect(turned).toEqual([2, 0]);- });-- it('keeps the page inside the pages there are', async () => {- const { view } = await pager();- view.scrollToPage(9, 0);- expect(view.getCurrentPageIndex()).toBe(2);- view.scrollToPage(-4, 0);- expect(view.getCurrentPageIndex()).toBe(0);- });-- it('moves a scroll bar\'s handle along its track as the view scrolls, and sizes it to the share of the content in view', async () => {- P = pointerApp(module);- const host = box('scroll', 300, 300, 100, 100);- const content = box('content', 0, 50, 100, 400, host, new Vec2(0.5, 1));- const track = box('track', 60, 0, 10, 100, host);- const handle = box('handle', 0, 0, 10, 100, track);- const { ScrollView } = await import('../../src/cocos');- const view = host.addComponent<InstanceType<typeof ScrollView>>('ScrollView')!;- view.content = content;- const bar = track.addComponent<ScrollBar>('ScrollBar')!;- bar.scrollView = view;- bar.handle = handle;- bar.direction = ScrollBar.Direction.VERTICAL;- await P.frame(2);- const knob = handle.getComponent(UITransform)!;- expect(knob.height).toBeCloseTo(25, 3); // a quarter of the content is in view- expect(handle.position.y).toBeCloseTo(50 - 12.5, 3); // at the top of the track- view.scrollToBottom(0);- await P.frame(2);- expect(handle.position.y).toBeCloseTo(-50 + 12.5, 3); // at the bottom- });-- it('keeps a node inside the safe area: a widget whose margins are the insets', async () => {- P = pointerApp(module);- const node = box('hud', 480, 320, 100, 100);- node.addComponent<SafeArea>('SafeArea');- setSafeInsets(44, 0, 30, 20);- await P.frame(2);- const widget = node.getComponent(Widget)!;- expect([widget.left, widget.right, widget.top, widget.bottom]).toEqual([44, 0, 30, 20]);- expect(widget.isAlignLeft && widget.isAlignRight && widget.isAlignTop && widget.isAlignBottom).toBe(true);- setSafeInsets(0, 0, 0, 0);- await P.frame(2);- expect(widget.left).toBe(0);- });-- it('keeps a web view\'s address and answers its calls without a surface', async () => {- P = pointerApp(module);- const node = box('web', 100, 100, 100, 100);- const web = node.addComponent<WebView>('WebView')!;- web.loadURL('https://example.com');- expect(web.url).toBe('https://example.com');- expect(() => { web.evaluateJS('1'); web.setJavascriptInterfaceScheme('x'); }).not.toThrow();- });-});diff --git a/sdk/tests/cocos/prefab-held.test.ts b/sdk/tests/cocos/prefab-held.test.tsdeleted file mode 100644index a2dd0a3fd..000000000--- a/sdk/tests/cocos/prefab-held.test.ts+++ /dev/null@@ -1,33 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A prefab is handed over with the prefabs its scripts hold: a List in a screen holds its row's prefab, and the screen's own code builds rows- * the moment it is up.- */-import { describe, expect, it } from 'vitest';-import { Component, Prefab, _decorator } from '../../src/cocos';-import { prefabsHeldBy } from '../../src/cocos/prefabs';-import type { PreparedPrefab } from '../../src/prefab/preparedPrefab';--const { ccclass, property } = _decorator;--describe('prefabs a prefab holds', () => {- it('names the paths in Prefab fields of its script components, lists too, and nothing else', () => {- @ccclass('HeldList')- class HeldList extends Component {- @property(Prefab) row: Prefab | null = null;- @property([Prefab]) more: Prefab[] = [];- @property(String) label = '';- }- expect(HeldList).toBeDefined();- const prepared = {- scene: { entities: [- { id: 1, name: 'a', parent: null, children: [], components: [- { type: 'Cocos.HeldList', data: { row: 'ui/row', more: ['ui/a', 'ui/b'], label: 'ui/not-a-prefab' } },- { type: 'Transform', data: {} },- ] },- ] },- } as unknown as PreparedPrefab;- expect(prefabsHeldBy(prepared).sort()).toEqual(['ui/a', 'ui/b', 'ui/row']);- });-});diff --git a/sdk/tests/cocos/renderer-namespace.test.ts b/sdk/tests/cocos/renderer-namespace.test.tsdeleted file mode 100644index b6f204498..000000000--- a/sdk/tests/cocos/renderer-namespace.test.ts+++ /dev/null@@ -1,20 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file `renderer.scene.CameraProjection` has Cocos's numbers, and the same as `Camera.ProjectionType`, so a script that compares one with the other- * tells an orthographic camera from a perspective one.- */-import { describe, expect, it } from 'vitest';-import { Camera, renderer } from '../../src/cocos';--describe('renderer.scene.CameraProjection', () => {- it('is the numbering a Camera answers its projection in', () => {- expect(renderer.scene.CameraProjection.ORTHO).toBe(Camera.ProjectionType.ORTHO);- expect(renderer.scene.CameraProjection.PERSPECTIVE).toBe(Camera.ProjectionType.PERSPECTIVE);- expect(renderer.scene.CameraProjection.ORTHO).not.toBe(renderer.scene.CameraProjection.PERSPECTIVE);- });-- it('still answers a name it does not have, with a stand-in that does not throw', () => {- expect(() => new renderer.scene.Camera()).not.toThrow();- });-});diff --git a/sdk/tests/cocos/script-active-wasm.test.ts b/sdk/tests/cocos/script-active-wasm.test.tsdeleted file mode 100644index f020ceb00..000000000--- a/sdk/tests/cocos/script-active-wasm.test.ts+++ /dev/null@@ -1,189 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file A script may switch nodes on and off from `start`, which the host runs for every script in one pass: the pass must not be a query- * being walked, because switching a node off adds and removes components, which a walked query refuses.- */-import { afterEach, beforeAll, describe, expect, it } from 'vitest';-import type { ESEngineModule } from '../../src/wasm';-import { App, flushPendingRegistrations } from '../../src/app/app';-import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';-import { AppContext, setDefaultContext } from '../../src/ecs/context';-import { loadSceneData, SCENE_FORMAT_VERSION } from '../../src/scene/scene';-import type { SceneData } from '../../src/scene/scene';-import { resetClassRegistry, syncActivity } from '../../src/cocos/registry';-import { declareBuiltinScripts } from '../../src/cocos/builtinScripts';-import { Component, Node, _decorator, setCurrentWorld } from '../../src/cocos';-import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';--const transform = { type: 'Transform', data: { position: { x: 0, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 1, y: 1, z: 1 } } };--describe.skipIf(!HAS_WASM)('a script that switches nodes on and off', () => {- let module: ESEngineModule;- let registry: InstanceType<ESEngineModule['Registry']> | undefined;- let app: App | undefined;-- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- afterEach(() => {- setCurrentWorld(null);- app?.world.disconnectCpp();- registry?.delete();- app = undefined;- registry = undefined;- });-- it('can switch another node on in start, and the scripts that node carries still start', async () => {- setDefaultContext(new AppContext());- ensureBuiltinComponentsRegistered();- resetClassRegistry();- declareBuiltinScripts();- const started: string[] = [];-- @_decorator.ccclass('Switcher')- class Switcher extends Component {- @_decorator.property(Node) other: Node | null = null;- start() {- started.push('switcher');- this.other!.active = true; // takes the Disabled tag off, which a walked query refuses- this.node.active = false;- }- }- @_decorator.ccclass('Bystander')- class Bystander extends Component {- start() { started.push('bystander'); }- }- void Switcher; void Bystander;-- registry = new module.Registry();- app = App.new();- app.connectCpp(registry as never, module);- flushPendingRegistrations(app);- setCurrentWorld(app.world);- const map = loadSceneData(app.world, {- version: SCENE_FORMAT_VERSION, name: 'main',- entities: [- { id: 0, name: 'A', parent: null, children: [], visible: true, components: [transform, { type: 'Cocos.Switcher', data: { enabled: true, other: 1 } }] },- { id: 1, name: 'B', parent: null, children: [], visible: true, components: [transform, { type: 'Disabled', data: {} }, { type: 'Cocos.Bystander', data: { enabled: true } }] },- ],- } as unknown as SceneData);- for (let i = 0; i < 3; i++) await app.tick(1 / 60);-- expect(started).toContain('switcher');- expect(Node.for(app.world, map.get(0)!).active).toBe(false);- expect(Node.for(app.world, map.get(1)!).active).toBe(true);- expect(started).toContain('bystander');- });-- it('enables a script as soon as its node joins an active parent, so a value set right after addChild is not undone', async () => {- setDefaultContext(new AppContext());- ensureBuiltinComponentsRegistered();- resetClassRegistry();- declareBuiltinScripts();- const calls: string[] = [];-- @_decorator.ccclass('Resetter')- class Resetter extends Component {- opacity = 0;- onEnable() { calls.push('enable'); this.opacity = 255; }- onDisable() { calls.push('disable'); }- }- void Resetter;-- registry = new module.Registry();- app = App.new();- app.connectCpp(registry as never, module);- flushPendingRegistrations(app);- setCurrentWorld(app.world);- const map = loadSceneData(app.world, {- version: SCENE_FORMAT_VERSION, name: 'main',- entities: [- { id: 0, name: 'Parent', parent: null, children: [1], visible: true, components: [transform] },- { id: 1, name: 'Child', parent: 0, children: [], visible: true, components: [transform, { type: 'Cocos.Resetter', data: { enabled: true } }] },- ],- } as unknown as SceneData);- const child = Node.for(app.world, map.get(1)!);- child.setParent(null);- child.active = false;- calls.length = 0;- // an orphan that is switched on and given a parent: onEnable runs inside the call- child.active = true;- child.setParent(Node.for(app.world, map.get(0)!));- const resetter = child.getComponent(Resetter)!;- resetter.opacity = 120;- expect(calls).toContain('enable');- await app.tick(1 / 60);- expect(resetter.opacity).toBe(120);-- child.active = false;- expect(calls).toContain('disable');- });-- it('loads every script of a tree before it enables any, in node order, when the tree is activated at once', async () => {- setDefaultContext(new AppContext());- ensureBuiltinComponentsRegistered();- resetClassRegistry();- declareBuiltinScripts();- const calls: string[] = [];-- @_decorator.ccclass('First')- class First extends Component {- onLoad() { calls.push('first.load'); }- onEnable() { calls.push('first.enable'); }- }- @_decorator.ccclass('Second')- class Second extends Component {- onLoad() { calls.push('second.load'); }- onEnable() { calls.push('second.enable'); }- }- void First; void Second;-- registry = new module.Registry();- app = App.new();- app.connectCpp(registry as never, module);- flushPendingRegistrations(app);- setCurrentWorld(app.world);- const map = loadSceneData(app.world, {- version: SCENE_FORMAT_VERSION, name: 'main',- entities: [- { id: 0, name: 'Root', parent: null, children: [1], visible: true, components: [transform, { type: 'Cocos.First', data: { enabled: true } }] },- { id: 1, name: 'Child', parent: 0, children: [], visible: true, components: [transform, { type: 'Cocos.Second', data: { enabled: true } }] },- ],- } as unknown as SceneData);- syncActivity(app.world, map.get(0)!);- expect(calls).toEqual(['first.load', 'second.load', 'first.enable', 'second.enable']);- });-});--describe.skipIf(!HAS_WASM)('a component added to a node that is not active', () => {- let module: ESEngineModule;- let registry: InstanceType<ESEngineModule['Registry']> | undefined;- let app: App | undefined;- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- afterEach(() => { setCurrentWorld(null); app?.world.disconnectCpp(); registry?.delete(); app = undefined; registry = undefined; });-- it('loads when the node becomes active, not when it is added, so what its creator sets after addComponent is there for onLoad', () => {- setDefaultContext(new AppContext());- ensureBuiltinComponentsRegistered();- resetClassRegistry();- declareBuiltinScripts();- const seen: Array<string | null> = [];- @_decorator.ccclass('NeedsOwner')- class NeedsOwner extends Component {- owner: string | null = null;- onLoad() { seen.push(this.owner); }- }- registry = new module.Registry();- app = App.new();- app.connectCpp(registry as never, module);- flushPendingRegistrations(app);- setCurrentWorld(app.world);- const n = new Node('n');- app.world.insert(n._entity, Transform);- n.active = false;- const comp = n.addComponent(NeedsOwner)!;- expect(seen).toEqual([]);- comp.owner = 'view';- n.active = true;- expect(seen).toEqual(['view']);- });-});diff --git a/sdk/tests/cocos/touch-locations-wasm.test.ts b/sdk/tests/cocos/touch-locations-wasm.test.tsdeleted file mode 100644index b612a45b0..000000000--- a/sdk/tests/cocos/touch-locations-wasm.test.ts+++ /dev/null@@ -1,64 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file The two places a touch has: the screen point (`getLocation`) and the canvas point (`getUILocation`).- *- * Through the engine's real pointer pipeline, with a camera that puts the world origin 400 pixels right of and 300 above the surface's- * bottom-left corner, so the two are different numbers and a mix-up shows.- */-import { afterEach, beforeAll, describe, expect, it } from 'vitest';-import type { ESEngineModule } from '../../src/wasm';-import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';-import { Camera, EventTouch, Node, UITransform, Vec3 } from '../../src/cocos';-import { setUiCameraData } from '../../src/cocos/ui/screen';-import { UICameraInfo } from '../../src/ui/core/ui-camera-info';-import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';-import { pointerApp, type PointerApp } from './helpers/pointerApp';--describe.skipIf(!HAS_WASM)('touch locations', () => {- let module: ESEngineModule;- let P: PointerApp | undefined;-- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- afterEach(() => { P?.dispose(); P = undefined; setUiCameraData(null); });-- function boot(): void {- P = pointerApp(module, { x: 400, y: 300 });- // the frame loop hands a camera the live UI camera data; this app has no pass that does, so do it directly- setUiCameraData(P.app.getResource(UICameraInfo));- }- const node = (name: string): Node => { const n = new Node(name); P!.app.world.insert(n._entity, Transform); return n; };-- it('gives the screen point from getLocation and the canvas point from getUILocation', async () => {- boot();- const seen: Array<{ screen: number[]; ui: number[] }> = [];- const n = node('target');- n.addComponent(UITransform)!.setContentSize(2000, 2000);- n.on(Node.EventType.TOUCH_START, (e: EventTouch) => {- seen.push({ screen: [e.getLocationX(), e.getLocationY()], ui: [e.getUILocationX(), e.getUILocationY()] });- });- await P!.press(100, 50); // world (100, 50): the surface point (500, 350)- expect(seen).toHaveLength(1);- expect(seen[0]!.ui[0]).toBeCloseTo(100, 2);- expect(seen[0]!.ui[1]).toBeCloseTo(50, 2);- expect(seen[0]!.screen[0]).toBeCloseTo(500, 2);- expect(seen[0]!.screen[1]).toBeCloseTo(350, 2);- });-- it('hands a camera the screen point of the touch and gets the canvas point back', async () => {- boot();- const cam = node('cam').addComponent(Camera)!;- const n = node('target');- n.addComponent(UITransform)!.setContentSize(2000, 2000);- let checked = 0;- n.on(Node.EventType.TOUCH_START, (e: EventTouch) => {- const l = e.getLocation();- const world = cam.screenToWorld(new Vec3(l.x, l.y, 0));- expect(world.x).toBeCloseTo(e.getUILocationX(), 2);- expect(world.y).toBeCloseTo(e.getUILocationY(), 2);- checked++;- });- await P!.press(120, 80);- expect(checked).toBe(1);- });-});diff --git a/sdk/tests/cocos/touch-wasm.test.ts b/sdk/tests/cocos/touch-wasm.test.tsdeleted file mode 100644index 0e6c8d11d..000000000--- a/sdk/tests/cocos/touch-wasm.test.ts+++ /dev/null@@ -1,247 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file Touches on nodes, and `Button`, against the real engine.- *- * What a Cocos script cannot be told is wrong, and what is pinned: a touch is claimed at its start by the TOPMOST node that listens and- * holds the point; the rest of the gesture goes to that node wherever the finger goes; the event bubbles up the ancestors, nearest- * first, until one stops it; and a button clicks when a touch ends INSIDE it, and not otherwise.- *- * The camera is faked as the identity (a screen pixel is a world unit, y flipped), so the geometry in the tests is the geometry on screen.- */-import { afterEach, beforeAll, describe, expect, it } from 'vitest';-import type { ESEngineModule } from '../../src/wasm';-import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';-import { Button, Component, EventHandler, EventTouch, Node, NodeEventType, UITransform, _decorator } from '../../src/cocos';-import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';-import { pointerApp, type PointerApp } from './helpers/pointerApp';--describe.skipIf(!HAS_WASM)('touches and buttons on the engine', () => {- let module: ESEngineModule;- let P: PointerApp | undefined;-- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- afterEach(() => { P?.dispose(); P = undefined; });-- function connect(): void { P = pointerApp(module); }- const app = () => P!.app;- const W = () => P!.app.world;-- /** A node of @p w by @p h whose centre is at (x, y). */- function box(name: string, x: number, y: number, w = 100, h = 100, parent?: Node): Node {- const n = new Node(name);- W().insert(n._entity, Transform);- n.addComponent(UITransform)!.setContentSize(w, h);- n.setPosition(x, y, 0);- parent?.addChild(n);- return n;- }-- // ---- driving the pointers: real frames through the engine's own interaction system ----------------------------------------- const press = (id: number, x: number, y: number): Promise<void> => P!.press(x, y, id);- const move = (id: number, x: number, y: number): Promise<void> => P!.move(x, y, id);- const release = (id: number, x: number, y: number): Promise<void> => P!.release(x, y, id);-- function record(node: Node, log: string[], tag = node.name): void {- for (const type of [NodeEventType.TOUCH_START, NodeEventType.TOUCH_MOVE, NodeEventType.TOUCH_END]) {- node.on(type, (e: EventTouch) => log.push(`${tag}:${type.replace('touch-', '')}@${Math.round(e.getUILocationX())},${Math.round(e.getUILocationY())}`));- }- }-- it('tells a node about a touch that starts, moves and ends on it, with where each happened', async () => {- connect();- const a = box('a', 200, 200);- const log: string[] = [];- record(a, log);- await press(1, 210, 190);- await move(1, 230, 190);- await release(1, 230, 190);- expect(log).toEqual(['a:start@210,190', 'a:move@230,190', 'a:end@230,190']);- });-- it('says nothing to a node the touch missed', async () => {- connect();- const a = box('a', 200, 200);- const log: string[] = [];- record(a, log);- await press(1, 400, 400);- await release(1, 400, 400);- expect(log).toEqual([]);- });-- it('hands the touch to the topmost of two overlapping nodes: the later sibling', async () => {- connect();- const root = box('root', 0, 0, 1000, 1000);- const under = box('under', 200, 200, 100, 100, root);- const over = box('over', 220, 200, 100, 100, root);- const log: string[] = [];- record(under, log);- record(over, log);- await press(1, 210, 200); // inside both- await release(1, 210, 200);- expect(log.every((l) => l.startsWith('over:'))).toBe(true);- expect(log).toHaveLength(2);- });-- it('hands the touch to what is drawn last, not to what was made last: a node made later and placed first is underneath', async () => {- connect();- const root = box('root', 0, 0, 1000, 1000);- const content = box('content', 200, 200, 100, 100, root);- // a backdrop taken from a pool and put under the panel after the panel was built: made last, drawn first- const backdrop = box('backdrop', 200, 200, 400, 400, root);- backdrop.setSiblingIndex(0);- const log: string[] = [];- record(content, log);- record(backdrop, log);- await press(1, 210, 200);- await release(1, 210, 200);- expect(log).toHaveLength(2);- expect(log.every((l) => l.startsWith('content:'))).toBe(true);- });-- it('keeps sending the gesture to the node that claimed it, wherever the finger goes', async () => {- connect();- const a = box('a', 200, 200);- const b = box('b', 600, 200);- const log: string[] = [];- record(a, log);- record(b, log);- await press(1, 200, 200);- await move(1, 600, 200); // over b, but a has the touch- await release(1, 600, 200);- expect(log.map((l) => l.split('@')[0])).toEqual(['a:start', 'a:move', 'a:end']);- });-- it('bubbles to the ancestors nearest first, and stops where a listener says so', async () => {- connect();- const parent = box('parent', 300, 300, 400, 400);- const child = box('child', 0, 0, 100, 100, parent);- const grand = box('grand', 300, 300, 400, 400);- const order: string[] = [];- child.on(NodeEventType.TOUCH_START, () => order.push('child'));- parent.on(NodeEventType.TOUCH_START, () => order.push('parent'));- await press(1, 300, 300);- await release(1, 300, 300);- expect(order).toEqual(['child', 'parent']);-- order.length = 0;- child.targetOff(undefined);- child.on(NodeEventType.TOUCH_START, (e: EventTouch) => { order.push('child2'); e.stopPropagation(); });- await press(2, 300, 300);- await release(2, 300, 300);- expect(order).toContain('child2');- expect(order).not.toContain('parent');- void grand;- });-- it('does not tell a switched-off node, or one under a switched-off parent', async () => {- connect();- const parent = box('parent', 200, 200, 300, 300);- const child = box('child', 0, 0, 100, 100, parent);- const log: string[] = [];- record(child, log);- parent.active = false;- await press(1, 200, 200);- await release(1, 200, 200);- expect(log).toEqual([]);- });-- it('gives the event its target and current target, and reads back a delta', async () => {- connect();- const parent = box('parent', 200, 200, 300, 300);- const child = box('child', 0, 0, 100, 100, parent);- const seen: Array<{ target: string; current: string; dx?: number }> = [];- child.on(NodeEventType.TOUCH_START, () => {});- parent.on(NodeEventType.TOUCH_START, (e: EventTouch) => seen.push({ target: e.target!.name, current: e.currentTarget!.name }));- child.on(NodeEventType.TOUCH_MOVE, (e: EventTouch) => seen.push({ target: 'm', current: 'm', dx: e.getDelta().x }));- await press(1, 200, 200);- await move(1, 215, 200);- expect(seen[0]).toEqual({ target: 'child', current: 'parent' });- expect(seen[1]!.dx).toBe(15);- });-- // ---- Button ------------------------------------------------------------------------------------------------------ /** Defined per test: the registry is reset when the engine connects, which would forget a class decorated at load. */- function defineTarget() {- @_decorator.ccclass('Target')- class Target extends Component {- calls: unknown[][] = [];- onClicked(_event: unknown, data: string): void { this.calls.push([data]); }- }- return Target;- }-- async function button(x = 200, y = 200): Promise<{ node: Node; button: Button }> {- const node = box('btn', x, y);- const b = node.addComponent<Button>('Button')!;- await P!.frame(1); // onEnable registers the listeners- return { node, button: b };- }-- it('clicks when a touch ends inside it: the node event, and the authored handlers with their custom data', async () => {- connect();- const holder = box('holder', 0, 0);- const Target = defineTarget();- const t = holder.addComponent(Target)!;- const { node, button: b } = await button();- const handler = new EventHandler();- handler.target = holder; handler.component = 'Target'; handler.handler = 'onClicked'; handler.customEventData = 'buy';- b.clickEvents = [handler];- let clicked = 0;- node.on(Button.EventType.CLICK, () => clicked++);- await press(1, 205, 205);- await release(1, 195, 195);- expect(clicked).toBe(1);- expect(t.calls).toEqual([['buy']]);- });-- it('does not click when the touch ends outside, or when the button is not interactable', async () => {- connect();- const { node, button: b } = await button();- let clicked = 0;- node.on(Button.EventType.CLICK, () => clicked++);- await press(1, 200, 200);- await release(1, 500, 500); // dragged off and let go- expect(clicked).toBe(0);- b.interactable = false;- await press(2, 200, 200);- await release(2, 200, 200);- expect(clicked).toBe(0);- });-- it('swallows the touch, so a node behind it does not also hear it', async () => {- connect();- const behind = box('behind', 200, 200, 300, 300);- const log: string[] = [];- record(behind, log);- await button();- await press(1, 200, 200);- await release(1, 200, 200);- expect(log).toEqual([]);- });-- it('zooms its node while pressed, with the SCALE transition, and puts it back', async () => {- connect();- const { node, button: b } = await button();- b.transition = Button.Transition.SCALE;- b.zoomScale = 1.5;- node.setScale(2, 2, 1);- await press(1, 200, 200);- expect(node.scale.x).toBeCloseTo(3, 5);- await release(1, 200, 200);- expect(node.scale.x).toBeCloseTo(2, 5);- });-- it('stops listening when disabled', async () => {- connect();- const { node, button: b } = await button();- let clicked = 0;- node.on(Button.EventType.CLICK, () => clicked++);- b.enabled = false;- await P!.frame(1); // the host sees the change and calls onDisable- await press(1, 200, 200);- await release(1, 200, 200);- expect(clicked).toBe(0);- });-});diff --git a/sdk/tests/cocos/tsconfig.json b/sdk/tests/cocos/tsconfig.jsondeleted file mode 100644index ea397a74e..000000000--- a/sdk/tests/cocos/tsconfig.json+++ /dev/null@@ -1,7 +0,0 @@-{- "extends": "../../tsconfig.json",- "compilerOptions": {- "experimentalDecorators": true,- "useDefineForClassFields": false- }-}diff --git a/sdk/tests/cocos/tween.test.ts b/sdk/tests/cocos/tween.test.tsdeleted file mode 100644index 376b75be9..000000000--- a/sdk/tests/cocos/tween.test.ts+++ /dev/null@@ -1,191 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file `tween`: the chain a Cocos script writes, advanced by hand.- *- * Pure objects as targets, so the arithmetic is what is under test: `to` goes to a value and `by` goes by it, an easing reshapes- * progress, a chain runs its steps in order and hands the time left over from one to the next, `repeat` and `union` mean what Cocos- * means by them, and the value types are interpolated per component.- */-import { afterEach, describe, expect, it } from 'vitest';-import { Color, Vec3, Tween, easing, tween, updateTweens } from '../../src/cocos';--afterEach(() => Tween.stopAll());--/** Run for @p seconds in @p frames equal steps. */-function run(seconds: number, frames = 10): void { for (let i = 0; i < frames; i++) updateTweens(seconds / frames); }--describe('tween steps', () => {- it('goes to a value over its duration, and stops there', () => {- const o = { x: 0 };- tween(o).to(1, { x: 10 }).start();- run(0.5, 5);- expect(o.x).toBeCloseTo(5, 5);- run(1, 10);- expect(o.x).toBe(10);- });-- it('goes by a value from wherever the target is when the step begins', () => {- const o = { x: 3 };- tween(o).by(1, { x: 4 }).by(1, { x: 4 }).start();- run(2, 20);- expect(o.x).toBe(11);- });-- it('runs steps in order and carries the leftover time of one into the next', () => {- const o = { x: 0, y: 0 };- tween(o).to(1, { x: 1 }).to(1, { y: 1 }).start();- updateTweens(1.5); // one step's worth and half of the next in a single frame- expect(o.x).toBe(1);- expect(o.y).toBeCloseTo(0.5, 5);- });-- it('sets at once, waits, and calls back with the target', () => {- const o = { x: 0 };- const log: string[] = [];- tween(o).set({ x: 5 }).call((t) => log.push(`call:${(t as typeof o).x}`)).delay(1).call(() => log.push('after')).start();- updateTweens(0.1);- expect(log).toEqual(['call:5']);- updateTweens(1);- expect(log).toEqual(['call:5', 'after']);- });-- it('applies an easing by name or by function', () => {- const a = { x: 0 }, b = { x: 0 };- tween(a).to(1, { x: 100 }, { easing: 'quadIn' }).start();- tween(b).to(1, { x: 100 }, { easing: (k) => k * k * k }).start();- updateTweens(0.5);- expect(a.x).toBeCloseTo(25, 5);- expect(b.x).toBeCloseTo(12.5, 5);- });-- it('has curves that begin at 0 and end at 1', () => {- for (const [name, fn] of Object.entries(easing)) {- expect(fn(0), `${name}(0)`).toBeCloseTo(0, 6);- expect(fn(1), `${name}(1)`).toBeCloseTo(1, 6);- }- });-- it('reports its progress through onUpdate, and start and completion once each', () => {- const o = { x: 0 };- const seen: number[] = [];- let started = 0, completed = 0;- tween(o).to(1, { x: 1 }, { onStart: () => started++, onUpdate: (_t, r) => seen.push(r), onComplete: () => completed++ }).start();- run(1, 4);- expect(seen).toEqual([0.25, 0.5, 0.75, 1]);- expect([started, completed]).toEqual([1, 1]);- });-});--describe('tween composition', () => {- it('repeats a sub-tween a number of times', () => {- const o = { n: 0 };- tween(o).repeat(3, tween(o).by(0.1, { n: 1 })).start();- run(1, 20);- expect(o.n).toBe(3);- });-- it('repeats everything so far when no tween is given, and forever until stopped', () => {- const o = { x: 0 };- const t = tween(o).by(0.5, { x: 1 }).delay(0.5).repeatForever().start();- run(5, 50);- expect(o.x).toBe(5);- expect(t.isRunning).toBe(true);- t.stop();- run(2, 20);- expect(o.x).toBe(5);- });-- it('unions what came before so a repeat covers all of it', () => {- const o = { x: 0, y: 0 };- tween(o).by(0.1, { x: 1 }).by(0.1, { y: 1 }).union().repeat(2).start();- run(1, 20);- expect([o.x, o.y]).toEqual([2, 2]);- });-- it('runs tweens in parallel, finishing when the longest does', () => {- const o = { x: 0, y: 0 };- let done = false;- tween(o).parallel(tween(o).to(1, { x: 1 }), tween(o).to(2, { y: 1 })).call(() => { done = true; }).start();- run(1, 10);- expect(o.x).toBe(1);- expect(o.y).toBeCloseTo(0.5, 6);- expect(done).toBe(false);- run(1, 10);- expect([o.x, o.y, done]).toEqual([1, 1, true]);- });-- it('runs tweens in sequence, and another tween\'s steps with then', () => {- const o = { x: 0 };- tween(o).sequence(tween(o).to(1, { x: 1 }), tween(o).to(1, { x: 3 })).then(tween(o).to(1, { x: 0 })).start();- run(1, 10);- expect(o.x).toBe(1);- run(1, 10);- expect(o.x).toBe(3);- run(1, 10);- expect(o.x).toBe(0);- });-- it('stops by target and by tag, and not the others', () => {- const a = { x: 0 }, b = { x: 0 }, c = { x: 0 };- tween(a).to(1, { x: 1 }).start();- const tb = tween(b).to(1, { x: 1 }); tb.tag = 7; tb.start();- tween(c).to(1, { x: 1 }).start();- Tween.stopAllByTarget(a);- Tween.stopAllByTag(7);- run(1, 10);- expect([a.x, b.x, c.x]).toEqual([0, 0, 1]);- });-- it('restarts from the beginning when started again', () => {- const o = { x: 0 };- const t = tween(o).to(1, { x: 10 }).start();- run(0.5, 5);- t.start();- expect(t.isRunning).toBe(true);- run(0.5, 5);- // the second run began its own clock, from the value it found (5): half of the way from there to 10- expect(o.x).toBeCloseTo(7.5, 5);- });-- it('can be paused and resumed', () => {- const o = { x: 0 };- const t = tween(o).to(1, { x: 1 }).start();- run(0.5, 5);- t.pause();- run(5, 50);- expect(o.x).toBeCloseTo(0.5, 5);- t.resume();- run(0.5, 5);- expect(o.x).toBe(1);- });-- it('keeps one throwing callback from stopping the others', () => {- const a = { x: 0 }, b = { x: 0 };- tween(a).call(() => { throw new Error('boom'); }).start();- tween(b).to(1, { x: 1 }).start();- run(1, 10);- expect(b.x).toBe(1);- });-});--describe('tween values', () => {- it('interpolates vectors and colours per component, and assigns a new value back', () => {- const o = { position: new Vec3(0, 0, 0), color: new Color(0, 0, 0, 255) };- const before = o.position;- tween(o).to(1, { position: new Vec3(10, 20, 30), color: new Color(200, 100, 0, 255) }).start();- run(0.5, 5);- expect([o.position.x, o.position.y, o.position.z]).toEqual([5, 10, 15]);- expect(o.position).not.toBe(before); // an accessor on a Node sees every write- expect([o.color.r, o.color.g]).toEqual([100, 50]);- });-- it('lets the target\'s own start value be anything the property returns, without changing it as it moves', () => {- const start = new Vec3(1, 1, 1);- const o = { position: start };- tween(o).by(1, { position: new Vec3(1, 1, 1) }).start();- run(1, 10);- expect(start.x).toBe(1);- expect(o.position.x).toBe(2);- });-});diff --git a/sdk/tests/cocos/ui-adapters-wasm.test.ts b/sdk/tests/cocos/ui-adapters-wasm.test.tsdeleted file mode 100644index acb2a5c3e..000000000--- a/sdk/tests/cocos/ui-adapters-wasm.test.ts+++ /dev/null@@ -1,286 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file Cocos's built-in UI components as views on the engine's, against the real engine (Sprite is a C++ component).- *- * What a script relies on and cannot be told is wrong: that `label.string = ...` is the Text that is drawn, that a colour set in- * Cocos's 0..255 comes back as the same 0..255, that line height keeps its pixel value when the font size changes (the engine stores- * a ratio), that the overflow numbers translate (SHRINK is 2 in Cocos and 3 in the engine), and that a size set on UITransform- * reaches the Sprite and Text that draw into it.- */-import { afterEach, beforeAll, describe, expect, it } from 'vitest';-import type { ESEngineModule } from '../../src/wasm';-import { World } from '../../src/ecs/world';-import { Sprite as EngineSprite, Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';-import { AppContext, setDefaultContext } from '../../src/ecs/context';-import { Text } from '../../src/ui/core/text';-import { TextOverflow } from '../../src/ui/core/text';-import { GroupOpacity } from '../../src/ecs/component';-import { Color, Label, LabelOutline, LabelShadow, Node, Size, Sprite, SpriteFrame, Texture2D, UIOpacity, UITransform, Vec2, Vec3, setCurrentWorld } from '../../src/cocos';-import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';--describe.skipIf(!HAS_WASM)('built-in UI components on the engine', () => {- let module: ESEngineModule;- let registry: InstanceType<ESEngineModule['Registry']> | undefined;- let world: World | undefined;- const W = (): World => world!;-- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });-- function connect(): void {- setDefaultContext(new AppContext());- ensureBuiltinComponentsRegistered();- registry = new module.Registry();- world = new World();- world.connectCpp(registry, module);- setCurrentWorld(world);- }- afterEach(() => {- setCurrentWorld(null);- world?.disconnectCpp();- registry?.delete();- registry = undefined;- world = undefined;- });-- const node = (name: string): Node => { const n = new Node(name); W().insert(n._entity, Transform); return n; };-- describe('Label', () => {- it('is the Text on its node: added if there is none, the same view each time', () => {- connect();- const n = node('l');- expect(n.getComponent(Label)).toBeNull();- const label = n.addComponent(Label)!;- expect(label).toBeInstanceOf(Label);- expect(W().has(n._entity, Text)).toBe(true);- expect(n.getComponent(Label)).toBe(label);- expect(n.getComponent('cc.Label')).toBe(label);- });-- it('writes the string, size and flags through to the Text that is drawn', () => {- connect();- const n = node('l');- const label = n.addComponent(Label)!;- label.string = '胜利';- label.fontSize = 36;- label.isBold = true;- label.enableWrapText = false;- const t = W().get(n._entity, Text);- expect(t.content).toBe('胜利');- expect(t.fontSize).toBe(36);- expect(t.bold).toBe(true);- expect(t.wordWrap).toBe(false);- expect(label.string).toBe('胜利');- });-- it('takes a game that replaces the engine\'s string setter and writes its internal _string', () => {- connect();- const n = node('l');- const label = n.addComponent(Label)!;- const original = Object.getOwnPropertyDescriptor(Label.prototype, 'string')!;- // what a project patching the engine's Label does: it sets the engine's own field and marks the element for a rebuild- Object.defineProperty(Label.prototype, 'string', {- set(this: { _string: string; markForUpdateRenderData(): void }, value: string) {- if (this._string === value) return;- this._string = value;- this.markForUpdateRenderData();- },- });- try {- label.string = 'patched';- expect(W().get(n._entity, Text).content).toBe('patched');- expect(label.string).toBe('patched');- } finally {- Object.defineProperty(Label.prototype, 'string', original);- }- });-- it('turns a null or undefined string into empty text, as Cocos does', () => {- connect();- const label = node('l').addComponent(Label)!;- label.string = 'x';- label.string = undefined as never;- expect(label.string).toBe('');- });-- it('converts a colour between Cocos 0..255 and the engine 0..1, and reads back what was set', () => {- connect();- const n = node('l');- const label = n.addComponent(Label)!;- label.color = new Color(255, 128, 0, 64);- const t = W().get(n._entity, Text);- expect(t.color.r).toBeCloseTo(1, 5);- expect(t.color.g).toBeCloseTo(128 / 255, 5);- expect(t.color.b).toBe(0);- expect(t.color.a).toBeCloseTo(64 / 255, 5);- const back = label.color;- expect([back.r, back.g, back.b, back.a]).toEqual([255, 128, 0, 64]);- });-- it('keeps a line height in pixels when the font size changes, though the engine stores a ratio', () => {- connect();- const label = node('l').addComponent(Label)!;- label.fontSize = 20;- label.lineHeight = 30;- expect(label.lineHeight).toBeCloseTo(30, 5);- label.fontSize = 40;- expect(label.lineHeight).toBeCloseTo(30, 5); // still 30px, not 60- });-- it('translates the overflow numbers and the alignments', () => {- connect();- const n = node('l');- const label = n.addComponent(Label)!;- label.overflow = Label.Overflow.SHRINK;- expect(W().get(n._entity, Text).overflow).toBe(TextOverflow.Shrink);- expect(label.overflow).toBe(Label.Overflow.SHRINK);- label.overflow = Label.Overflow.CLAMP;- expect(W().get(n._entity, Text).overflow).toBe(TextOverflow.Clip);- label.overflow = Label.Overflow.RESIZE_HEIGHT;- expect(W().get(n._entity, Text).overflow).toBe(TextOverflow.ResizeHeight);- expect(label.overflow).toBe(Label.Overflow.RESIZE_HEIGHT);- label.isUnderline = true;- expect(W().get(n._entity, Text).underline).toBe(true);- expect(label.isUnderline).toBe(true);- label.horizontalAlign = Label.HorizontalAlign.RIGHT;- label.verticalAlign = Label.VerticalAlign.BOTTOM;- const t = W().get(n._entity, Text);- expect([t.align, t.verticalAlign]).toEqual([2, 2]);- });-- it('has its outline and shadow as properties of the same Text', () => {- connect();- const n = node('l');- n.addComponent(Label);- const outline = n.addComponent(LabelOutline)!;- outline.color = new Color(0, 0, 255, 255);- outline.width = 3;- const shadow = n.addComponent(LabelShadow)!;- shadow.offset = { x: 2, y: -4 };- shadow.blur = 5;- const t = W().get(n._entity, Text);- expect(t.strokeWidth).toBe(3);- expect(t.strokeColor.b).toBe(1);- // Cocos's y is up; the engine's shadow y is down- expect(t.shadowOffsetX).toBe(2);- expect(t.shadowOffsetY).toBe(4);- expect(t.shadowBlur).toBe(5);- expect(shadow.offset).toEqual({ x: 2, y: -4 });- });- });-- describe('Sprite and UIOpacity', () => {- it('is the engine Sprite on its node, with Cocos colour and type numbers', () => {- connect();- const n = node('s');- const sprite = n.addComponent(Sprite)!;- expect(W().has(n._entity, EngineSprite)).toBe(true);- sprite.color = new Color(10, 20, 30, 255);- expect(W().get(n._entity, EngineSprite).color.g).toBeCloseTo(20 / 255, 5);- sprite.type = Sprite.Type.SLICED;- expect(sprite.type).toBe(Sprite.Type.SLICED);- sprite.type = Sprite.Type.TILED;- expect(sprite.type).toBe(Sprite.Type.TILED);- sprite.enabled = false;- expect(W().get(n._entity, EngineSprite).enabled).toBe(false);- });-- it('draws the texture of the frame it is given, and lets go of it when given none', () => {- connect();- const n = node('f');- const sprite = n.addComponent(Sprite)!;- const texture = new Texture2D('gold.png');- texture._handle = 7;- texture.width = 64;- texture.height = 32;- const frame = new SpriteFrame('gold.png');- frame.texture = texture;- sprite.spriteFrame = frame;- expect(sprite.spriteFrame).toBe(frame);- expect(W().get(n._entity, EngineSprite).texture).toBe(7);- sprite.spriteFrame = null;- expect(W().get(n._entity, EngineSprite).texture).toBe(0);- });-- it('is the engine\'s GroupOpacity, in Cocos\'s 0..255', () => {- connect();- const n = node('p');- const opacity = n.addComponent(UIOpacity)!;- expect(opacity.opacity).toBe(255);- opacity.opacity = 128;- expect(W().get(n._entity, GroupOpacity).opacity).toBeCloseTo(128 / 255, 5);- expect(opacity.opacity).toBe(128);- opacity.opacity = 999;- expect(opacity.opacity).toBe(255);- });- });-- describe('UITransform', () => {- it('starts from the renderer the node has, and is there for a node that draws nothing', () => {- connect();- const withSprite = node('a');- withSprite.addComponent(Sprite);- W().set(withSprite._entity, EngineSprite, { ...W().get(withSprite._entity, EngineSprite), size: { x: 80, y: 40 }, pivot: { x: 0, y: 1 } });- const t = withSprite.getComponent(UITransform)!;- expect(t.contentSize.width).toBe(80);- expect(t.contentSize.height).toBe(40);- expect(t.anchorPoint.equals(new Vec2(0, 1))).toBe(true);-- const bare = node('b');- const bt = bare.addComponent(UITransform)!;- bt.setContentSize(300, 200);- expect(bare.getComponent(UITransform)).toBe(bt);- expect(bt.width).toBe(300);- expect(bt.height).toBe(200);- });-- it('carries a size and anchor to the Sprite and Text that draw into it', () => {- connect();- const n = node('both');- n.addComponent(Sprite);- n.addComponent(Label);- const t = n.addComponent(UITransform)!;- t.contentSize = new Size(120, 60);- t.anchorPoint = new Vec2(0.5, 1);- const s = W().get(n._entity, EngineSprite);- expect([s.size.x, s.size.y, s.pivot.x, s.pivot.y]).toEqual([120, 60, 0.5, 1]);- const x = W().get(n._entity, Text);- expect([x.boxWidth, x.boxHeight, x.boxPivot?.x, x.boxPivot?.y]).toEqual([120, 60, 0.5, 1]);- });-- it('tests a world point against its rectangle, anchor and position applied', () => {- connect();- const n = node('hit');- const t = n.addComponent(UITransform)!;- t.setContentSize(100, 50);- t.setAnchorPoint(0.5, 0.5);- n.setPosition(200, 100, 0);- expect(t.isHit(new Vec2(200, 100))).toBe(true);- expect(t.isHit(new Vec2(249, 124))).toBe(true);- expect(t.isHit(new Vec2(251, 100))).toBe(false);- expect(t.isHit(new Vec2(200, 126))).toBe(false);- // an anchor at the bottom-left moves the rectangle up and to the right of the node- t.setAnchorPoint(0, 0);- expect(t.isHit(new Vec2(250, 120))).toBe(true);- expect(t.isHit(new Vec2(199, 100))).toBe(false);- });-- it('converts between node space and world space under a scaled, moved parent', () => {- connect();- const parent = node('p'), child = node('c');- parent.addChild(child);- parent.setPosition(100, 0, 0);- parent.setScale(2, 2, 1);- child.setPosition(10, 5, 0);- const t = child.addComponent(UITransform)!;- const world = t.convertToWorldSpaceAR(new Vec3(0, 0, 0));- expect(world.x).toBeCloseTo(120, 3); // 100 + 10 * 2- expect(world.y).toBeCloseTo(10, 3);- const back = t.convertToNodeSpaceAR(world);- expect(back.x).toBeCloseTo(0, 3);- expect(back.y).toBeCloseTo(0, 3);- const box = t.getBoundingBoxToWorld();- expect(box.width).toBeCloseTo(200, 3); // the 100px default width, scaled by the parent- });- });-});diff --git a/sdk/tests/cocos/unsupported.test.ts b/sdk/tests/cocos/unsupported.test.tsdeleted file mode 100644index 765e51245..000000000--- a/sdk/tests/cocos/unsupported.test.ts+++ /dev/null@@ -1,22 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import { describe, expect, it } from 'vitest';-import { unsupported } from '../../src/cocos/unsupported';--describe('a part of Cocos the layer does not provide', () => {- it('survives what a script does with it while its module loads', () => {- const gfx = unsupported('gfx') as any;- const format = [new gfx.Attribute('a_position', gfx.Format.RGB32F), gfx.Format.RG32F];- expect(format).toHaveLength(2);- expect(`${gfx.Format.RGB32F}`).toBe('');- expect(gfx.Attribute).toBe(gfx.Attribute);- expect(() => { gfx.useless(1).deeper.still(); gfx.flag = 3; })- .not.toThrow();- class Derived extends (unsupported('Base') as any) { }- expect(() => new Derived()).not.toThrow();- });-- it('is not a promise, so awaiting it does not hang', async () => {- await expect(Promise.resolve(unsupported('x'))).resolves.toBeDefined();- });-});diff --git a/sdk/tests/cocos/widget-layout-wasm.test.ts b/sdk/tests/cocos/widget-layout-wasm.test.tsdeleted file mode 100644index 47e980eb9..000000000--- a/sdk/tests/cocos/widget-layout-wasm.test.ts+++ /dev/null@@ -1,207 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file `Widget` and `Layout` against the real engine.- *- * The numbers are the ones Cocos produces for the same settings: a stretched panel takes its parent's size minus its margins, a- * pinned one keeps its size and sits at the edge by its anchor, a centred one is offset from the middle; a row starts at the- * container's left edge plus padding and advances by each child's width plus spacing.- */-import { afterEach, beforeAll, describe, expect, it } from 'vitest';-import type { ESEngineModule } from '../../src/wasm';-import { App, flushPendingRegistrations } from '../../src/app/app';-import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';-import { AppContext, setDefaultContext } from '../../src/ecs/context';-import { resetClassRegistry } from '../../src/cocos/registry';-import { Layout, Node, UITransform, Widget, setCurrentWorld, setVisibleSize } from '../../src/cocos';-import { declareUiPass } from '../../src/cocos/ui/pass';-import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';--describe.skipIf(!HAS_WASM)('widgets and layouts on the engine', () => {- let module: ESEngineModule;- let registry: InstanceType<ESEngineModule['Registry']> | undefined;- let app: App | undefined;-- beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });-- function connect(): void {- setDefaultContext(new AppContext());- ensureBuiltinComponentsRegistered();- resetClassRegistry();- declareUiPass();- registry = new module.Registry();- app = App.new();- app.connectCpp(registry as never, module);- flushPendingRegistrations(app);- setCurrentWorld(app.world);- setVisibleSize(960, 640);- }- afterEach(() => {- setCurrentWorld(null);- app?.world.disconnectCpp();- registry?.delete();- app = undefined;- registry = undefined;- });-- function box(name: string, w: number, h: number, parent?: Node, ax = 0.5, ay = 0.5): Node {- const n = new Node(name);- app!.world.insert(n._entity, Transform);- const t = n.addComponent(UITransform)!;- t.setContentSize(w, h);- t.setAnchorPoint(ax, ay);- parent?.addChild(n);- return n;- }- const frame = async (n = 2): Promise<void> => { for (let i = 0; i < n; i++) await app!.tick(1 / 60); };- const widget = (n: Node, set: (w: Widget) => void): Widget => { const w = n.addComponent(Widget)!; set(w); return w; };- const size = (n: Node): number[] => { const t = n.getComponent(UITransform)!; return [t.width, t.height]; };-- it('stretches a panel to its parent minus the margins', async () => {- connect();- const parent = box('parent', 400, 300);- const panel = box('panel', 10, 10, parent);- widget(panel, (w) => { w.isAlignLeft = w.isAlignRight = w.isAlignTop = w.isAlignBottom = true; w.left = 20; w.right = 40; w.top = 10; w.bottom = 30; });- await frame();- expect(size(panel)).toEqual([340, 260]);- // the parent's space is anchor-relative: its left edge is -200, so the panel spans -180..160 and is centred at -10- expect(panel.position.x).toBeCloseTo(-10, 5);- expect(panel.position.y).toBeCloseTo(((-150 + 30) + (150 - 10)) / 2, 5);- });-- it('pins a node to one edge by its anchor and keeps its size', async () => {- connect();- const parent = box('parent', 400, 300);- const node = box('n', 50, 20, parent, 0, 1); // anchored top-left- widget(node, (w) => { w.isAlignRight = true; w.right = 10; w.isAlignTop = true; w.top = 5; });- await frame();- expect([node.position.x, node.position.y]).toEqual([200 - 10 - 50, 150 - 5]);- expect(size(node)).toEqual([50, 20]);- });-- it('centres with an offset, in pixels or as a fraction of the parent', async () => {- connect();- const parent = box('parent', 400, 300);- const a = box('a', 50, 50, parent);- widget(a, (w) => { w.isAlignHorizontalCenter = true; w.horizontalCenter = 30; w.isAlignVerticalCenter = true; w.verticalCenter = -10; });- const b = box('b', 50, 50, parent);- widget(b, (w) => { w.isAlignHorizontalCenter = true; w.isAbsHorizontalCenter = false; w.horizontalCenter = 0.25; });- await frame();- expect([a.position.x, a.position.y]).toEqual([30, -10]);- expect(b.position.x).toBe(100);- });-- it('aligns a node under no rectangle to the visible area, and follows it when it changes', async () => {- connect();- const canvas = box('canvas', 1, 1);- widget(canvas, (w) => { w.isAlignLeft = w.isAlignRight = w.isAlignTop = w.isAlignBottom = true; });- await frame();- expect(size(canvas)).toEqual([960, 640]);- expect([canvas.position.x, canvas.position.y]).toEqual([0, 0]); // the screen is centred on the origin- setVisibleSize(1280, 720);- await frame();- expect(size(canvas)).toEqual([1280, 720]);- expect(canvas.position.x).toBe(0);- });-- it('aligns once and leaves the node to the script after, in ONCE mode; every frame, in ALWAYS mode', async () => {- connect();- const parent = box('parent', 400, 300);- const once = box('once', 50, 50, parent);- widget(once, (w) => { w.alignMode = Widget.AlignMode.ONCE; w.isAlignLeft = true; });- const always = box('always', 50, 50, parent);- widget(always, (w) => { w.alignMode = Widget.AlignMode.ALWAYS; w.isAlignLeft = true; });- await frame();- once.setPosition(0, 0, 0);- always.setPosition(0, 0, 0);- await frame();- expect(once.position.x).toBe(0);- expect(always.position.x).toBe(-175);- });-- it('aligns again when a setting changes, whatever the mode', async () => {- connect();- const parent = box('parent', 400, 300);- const node = box('n', 50, 50, parent);- const w = widget(node, (x) => { x.alignMode = Widget.AlignMode.ONCE; x.isAlignLeft = true; });- await frame();- expect(node.position.x).toBe(-175);- w.left = 100;- await frame();- expect(node.position.x).toBe(-75);- });-- it('lays children out in a row from the left edge, with padding and spacing', async () => {- connect();- const row = box('row', 300, 50);- const layout = row.addComponent(Layout)!;- layout.type = Layout.Type.HORIZONTAL;- layout.paddingLeft = 10;- layout.spacingX = 5;- const kids = [box('a', 40, 20, row), box('b', 60, 20, row), box('c', 20, 20, row)];- await frame();- // the left edge is -150, plus 10 of padding; the centres follow at +20, +30 after a 5 gap, +10 after another- expect(kids.map((k) => k.position.x)).toEqual([-120, -65, -20]);- expect(size(row)).toEqual([300, 50]);- });-- it('grows the container to fit in CONTAINER mode, and fills it from the top', async () => {- connect();- const col = box('col', 100, 10);- const layout = col.addComponent(Layout)!;- layout.type = Layout.Type.VERTICAL;- layout.resizeMode = Layout.ResizeMode.CONTAINER;- layout.paddingTop = 4;- layout.paddingBottom = 6;- layout.spacingY = 10;- const a = box('a', 30, 40, col), b = box('b', 30, 20, col);- await frame();- const height = 4 + 6 + 40 + 20 + 10;- expect(size(col)[1]).toBe(height);- expect(a.position.y).toBe(height / 2 - 4 - 20);- expect(b.position.y).toBe(height / 2 - 4 - 40 - 10 - 10);- });-- it('stretches the children to share the container in CHILDREN mode', async () => {- connect();- const row = box('row', 220, 50);- const layout = row.addComponent(Layout)!;- layout.type = Layout.Type.HORIZONTAL;- layout.resizeMode = Layout.ResizeMode.CHILDREN;- layout.spacingX = 10;- const kids = [box('a', 5, 20, row), box('b', 5, 20, row)];- await frame();- expect(kids.map((k) => size(k)[0])).toEqual([105, 105]);- });-- it('wraps a grid at the container edge, and relayouts when a child is added', async () => {- connect();- const grid = box('grid', 100, 100);- const layout = grid.addComponent(Layout)!;- layout.type = Layout.Type.GRID;- layout.cellWidth = layout.cellHeight = 40;- box('a', 40, 40, grid); box('b', 40, 40, grid); box('c', 40, 40, grid);- await frame();- const [a, b, c] = grid.children;- expect(a!.position.y).toBe(b!.position.y); // two fit on the first row- expect(c!.position.y).toBeLessThan(a!.position.y); // the third wrapped below- expect(c!.position.x).toBe(a!.position.x);- const d = box('d', 40, 40, grid);- await frame();- expect(d.position.x).toBe(b!.position.x);- expect(d.position.y).toBe(c!.position.y);- });-- it('lets a widget-stretched container relayout its children in the same frame', async () => {- connect();- const parent = box('parent', 400, 100);- const row = box('row', 10, 100, parent);- widget(row, (w) => { w.isAlignLeft = w.isAlignRight = true; });- const layout = row.addComponent(Layout)!;- layout.type = Layout.Type.HORIZONTAL;- layout.resizeMode = Layout.ResizeMode.CHILDREN;- const kids = [box('a', 5, 20, row), box('b', 5, 20, row)];- await frame(1);- expect(kids.map((k) => size(k)[0])).toEqual([200, 200]);- });-});diff --git a/tools/apiSubsystems.mjs b/tools/apiSubsystems.mjsindex 6ae4c2959..7f7005142 100644--- a/tools/apiSubsystems.mjs+++ b/tools/apiSubsystems.mjs@@ -26,7 +26,6 @@* subsystem cannot be mistaken for adding plumbing.*/export const INFRASTRUCTURE = {- cocos: 'the Cocos Creator compatibility layer (`esengine/cocos`): scripts written for Cocos run on it; a game built for this engine does not import it','debug-channel': 'a development build\'s line back to the editor — tooling, never in a shipped game',diagnostics: 'the engine reporting on itself — a census and a stats overlay, read by tooling',document: 'document-model diagnostics shared with the editor, not part of a game',diff --git a/tools/goldenProjects.mjs b/tools/goldenProjects.mjsindex b15fcc928..a5ba834e3 100644--- a/tools/goldenProjects.mjs+++ b/tools/goldenProjects.mjs@@ -944,40 +944,16 @@ export const SHIPPED = {{ notCertifiable: "A UI behaviour, covered by its unit tests; no golden project uses it, and a packaged launch frame does not drive it." },"World content has a rectangle: `ContentRect`.":{ notCertifiable: "A rendering feature, covered by its unit tests and the render-scene pixel gates where it draws; no golden project places it, and one packaged frame cannot decide a result that depends on the device." },- "Edited Cocos documents move to RectAnchors.":- { notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },"RectAnchors: world content that follows its parent.":{ notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },- "A converted Cocos project fits the screen as the game does.":- { notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },- "A Cocos node layer is its renderers layer.":- { notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },- "A converted Cocos project starts as the game does.":- { notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },- "Cocos layer components survive a replay.":- { notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },- "A material colour is the renderer tint.":- { notCertifiable: "A rendering feature, covered by its unit tests and the render-scene pixel gates where it draws; no golden project places it, and one packaged frame cannot decide a result that depends on the device." },- "Mesh renderers and materials in the Cocos layer.":- { notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },- "More of `cc`.":- { notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },"The script bundle is not rebuilt for nothing.":{ notCertifiable: "Editor or tooling behaviour rather than a rendered game capability; its own suites check it." },- "Two Cocos classes with one name.":- { notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },"Large projects open faster.":{ notCertifiable: "Editor or tooling behaviour rather than a rendered game capability; its own suites check it." },"A model texture the project does not have is left off.":{ notCertifiable: "A rendering feature, covered by its unit tests and the render-scene pixel gates where it draws; no golden project places it, and one packaged frame cannot decide a result that depends on the device." },"An unlit mesh variant with tangents links.":{ notCertifiable: "A rendering feature, covered by its unit tests and the render-scene pixel gates where it draws; no golden project places it, and one packaged frame cannot decide a result that depends on the device." },- "Cocos scripts load one by one.":- { notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },- "A converted Cocos project links its images.":- { notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },- "A Cocos conversion shows its progress.":- { notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },"Bursts on a schedule.":{ notCertifiable: "A rendering feature, covered by its unit tests and the render-scene pixel gates where it draws; no golden project places it, and one packaged frame cannot decide a result that depends on the device." },"A 3D collider can sit off its entity.":@@ -996,10 +972,6 @@ export const SHIPPED = {{ notCertifiable: "A rendering feature, covered by its unit tests and the render-scene pixel gates where it draws; no golden project places it, and one packaged frame cannot decide a result that depends on the device." },"Fade a whole group of world content with one value: `GroupOpacity`.":{ notCertifiable: "A rendering feature, covered by its unit tests and the render-scene pixel gates where it draws; no golden project places it, and one packaged frame cannot decide a result that depends on the device." },- "Open a Cocos Creator project from the editor.":- { notCertifiable: "Editor or tooling behaviour rather than a rendered game capability; its own suites check it." },- "Re-import a Cocos project without losing your edits.":- { notCertifiable: "Editor or tooling behaviour rather than a rendered game capability; its own suites check it." },"A held pointer reports where it goes, and a hold can be given up.":{ notCertifiable: "A UI behaviour, covered by its unit tests; no golden project uses it, and a packaged launch frame does not drive it." },"The engine's runtime tuning is a project setting.":@@ -1046,18 +1018,8 @@ export const SHIPPED = {{ notCertifiable: "A UI behaviour, covered by its unit tests; no golden project uses it, and a packaged launch frame does not drive it." },"A material can read a mesh's second uv set.":{ notCertifiable: "A rendering feature, covered by its unit tests and the render-scene pixel gates where it draws; no golden project places it, and one packaged frame cannot decide a result that depends on the device." },- "Cocos scripts drive scenes as the game does.":- { notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },- "Cocos scripts load assets by path.":- { notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },- "A converted project's scripts are components the editor knows.":- { notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },- "A Cocos project's own effects are converted.":- { notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },- "Converted Cocos UI looks as it does in Cocos.":- { notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },- "A converted Cocos project is brought up to date when it is opened.":- { notCertifiable: "Cocos Creator project conversion, covered by the converter's unit tests and the editor suite; no golden project is a converted Cocos project, so no packaged frame can decide it." },+ "Paste textures onto a blank texture: `TextureCanvas`.":+ { notCertifiable: "A rendering feature, covered by its unit tests and the Texture Canvas example run in the editor; no golden project pastes textures, and one packaged frame cannot decide a result that depends on the device." },"Pack several textures onto one canvas at run time: `TextureAtlas.pack`.":{ notCertifiable: "A rendering feature, covered by its unit tests and by the Render Texture example run in the editor; no golden project packs textures, and one packaged frame cannot decide a result that depends on the device." },};diff --git a/tools/nativeScriptModules.js b/tools/nativeScriptModules.jsindex 9090caf15..da25b4184 100644--- a/tools/nativeScriptModules.js+++ b/tools/nativeScriptModules.js@@ -97,10 +97,6 @@ export const MODULES = {disposition: 'forbidden-native-script',why: 'the Node entry, for servers and tools (examples/multiplayer-arena/server) — it reaches for node: builtins a packaged game has none of',},- 'esengine/cocos': {- disposition: 'forbidden-native-script',- why: 'the Cocos Creator compatibility layer, built for the web and mini-game bundles; a native build does not carry it yet',- },'esengine/wechat': {disposition: 'forbidden-native-script',why: 'the WeChat mini-game entry, a different host with a different platform adapter',diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex c596bc167..c63f731d6 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -29,31 +29,31 @@ export const NOTES_FLOOR = 'v0.65.0';*/export const NOTED = {'feat(cocos): a document the creator edited moves from the layer Cocos.Widget to the engine RectAnchors on re-import':- {"note":"Edited Cocos documents move to RectAnchors."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},'feat(ui): RectAnchors pins world content to its parent rectangle or the screen in the engine, and the Cocos Widget is a view on it':{"note":"RectAnchors: world content that follows its parent."},'feat(cocos): a converted project keeps the Cocos fit width of its design, and cc.profiler exists in the compatibility layer':- {"note":"A converted Cocos project fits the screen as the game does."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},'fix(cocos): a renderer is put in the layer of its Cocos node, so a UI camera that culls by layer draws it':- {"note":"A Cocos node layer is its renderers layer."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},'feat(cocos): a converted project starts at the game launch scene and runs its global-defining scripts first, reads the editor built-in assets, and the layer components survive a replay':- {"note":"A converted Cocos project starts as the game does."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},'feat(cocos): the colour a script sets on a material instance is the renderer tint':- {"note":"A material colour is the renderer tint."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},'feat(cocos): MeshRenderer, UIMeshRenderer, material properties and cc.geometry in the compatibility layer':- {"note":"Mesh renderers and materials in the Cocos layer."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},'feat(cocos): cc.js, ccenum and NodePool exist in the compatibility layer':- {"note":"More of `cc`."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},'feat(bundle): the project script bundle is built again only when a file it read changed, and Cocos scripts that write the same class name each get a component of their own':{"note":"The script bundle is not rebuilt for nothing."},'fix(editor): opening a large project no longer spends seconds on strings that cannot be paths, a model texture the project lacks is left off instead of dangling, and an unlit mesh variant with tangents links':{"note":"Large projects open faster."},'feat(cocos): one script that fails to load no longer takes the others with it, a part of cc the layer lacks is a stand-in that survives use, and Director, AssetManager.Cache and the input dispatcher hook exist':- {"note":"Cocos scripts load one by one."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},'feat(cocos): a converted project links its source images instead of copying them, so conversion does not store a multi-gigabyte art folder twice':- {"note":"A converted Cocos project links its images."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},'feat(cocos): the importer reports its progress by stage, so a long conversion can show a bar':- {"note":"A Cocos conversion shows its progress."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},'feat(particle): an emitter can release bursts on a schedule (bursts), and the Cocos burst list, repeat count and burst times map onto it':{"note":"Bursts on a schedule."},'feat(physics3d): a box, sphere or capsule collider can sit off its entity origin (center), and the Cocos BoxCollider centre maps onto it':@@ -97,9 +97,9 @@ export const NOTED = {'feat(cocos): the importer maps DirectionalLight, Sorting and Canvas':{"internal":"The Cocos Creator compatibility layer and importer have not shipped; nothing a creator reaches without opting in."},'feat(editor): Re-import Cocos Project brings the Cocos side\'s changes into the converted project and keeps the documents edited here; a conversion says which components did not come across':- {"note":"Re-import a Cocos project without losing your edits."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},'feat(editor): opening a Cocos Creator folder converts it into an Estella project beside it and opens that':- {"note":"Open a Cocos Creator project from the editor."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},'feat(ui): a held pointer reports its moves (pointer_move) and a given-up hold (press_cancel), every pointer event says where the pointer is, and a ContentRect-only entity can be pressed; the Cocos touches translate the engine\'s pointer events instead of dispatching on their own':{"note":"A held pointer reports where it goes, and a hold can be given up."},'feat(ui): ContentRect, the rectangle world content occupies — Sprite and Text follow it, a UIMask on the entity clips to it, a world point can be tested against it; the Cocos UITransform and Mask are views on it, and the importer writes it':@@ -3219,35 +3219,35 @@ export const NOTED = {"fix(ci): the theme ratchet banks the inspector's new virtual-instance button":{"internal":"Moves a baseline count; no creator can observe it."},"feat(cocos): director.loadScene runs a project scene through the engine's scene manager (scenes are in the manifest, persistent roots are SceneOwner.persistent); components start in one phase before the frame's updates; Camera.screenPointToRay":- {"note":"Cocos scripts drive scenes as the game does."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"fix(cocos): getComponent finds a component by a base class it derives from, so a handler bound through the Button of a Toggle's node reaches it":- {"note":"Cocos scripts drive scenes as the game does."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(ui): TextInput stands on a world rectangle as well as a UI node, and a Cocos EditBox becomes it: the importer folds the two labels into the field and the layer's EditBox is a view on it":{"note":"A text field can stand in the world."},"fix(ui): a pointer lands on what is drawn last by its place in the hierarchy, not on what was made last; a Toggle belongs to the container its parent holds and assigning isChecked switches its group's others off":{"note":"A pointer lands on what is drawn on top."},"fix(cocos): a Label takes a game's replaced string setter (the engine's _string and friends land on the Text), and an EditBox shows its text label while it holds text":- {"note":"Converted Cocos UI looks as it does in Cocos."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"fix(cocos): a play session that follows another in the same script runtime gets the layer's systems again and none of what the last one loaded":- {"note":"Cocos scripts drive scenes as the game does."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"fix(cocos): a Label with no overflow rule does not wrap and is laid out from its anchor, as the node grows to the text in Cocos":- {"note":"Converted Cocos UI looks as it does in Cocos."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(render): layers painted in hierarchy order, so a panel covers the text of the panel under it; the Cocos UI layer uses it. Text takes an underline field; resources.load finds an image's spriteFrame and texture by path suffix":{"note":"A layer can be painted in hierarchy order."},"fix(cocos): a node's scripts load and enable as it joins an active parent or is switched, not a frame later; a converted script component's dropped fields are ignored quietly":- {"note":"Cocos scripts drive scenes as the game does."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(cocos): resources.load gives images, sprite frames and audio by path, Sprite takes a spriteFrame, Node has getParent; the script entry leaves out the editor's own scripts":- {"note":"Cocos scripts load assets by path."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(cocos): the generated script entry loads every component class of the project, since a game opens its views by class name":- {"note":"A converted project's scripts are components the editor knows."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"fix(cocos): the session check also runs when a prefab is asked for":- {"note":"Cocos scripts drive scenes as the game does."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"fix(cocos): the layer drops what it kept of a session when the asset loader gives everything back":- {"note":"Cocos scripts drive scenes as the game does."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"fix(cocos): a loaded asset is named for its file, and what the layer kept of a play session is dropped when the next begins":- {"note":"Cocos scripts load assets by path."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"fix(cocos): a directory load leaves out what the layer cannot load instead of failing, and Component.EventHandler exists":- {"note":"Cocos scripts load assets by path."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(assets): a scan reports how many documents it has read of how many":{"note":"The loading screens say how far they are."},"perf(assets): a scan keeps what each document refers to by what the file was, so a second scan of a large project reads nothing it has read; fix(cocos): a component is found by its cc. name and can be named by a script":@@ -3255,29 +3255,29 @@ export const NOTED = {"feat(shaders): the canonical vertex stage hands a mesh second uv set to a material, and a converted effect is one shader per macro combination, compiled and given its WGSL twin before it is written":{"note":"A material can read a mesh's second uv set."},"feat(shaders): a material vertex hook gets a derived WGSL twin, and an effect that displaces its vertices is converted with the displacement as that hook":- {"note":"A Cocos project's own effects are converted."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(cocos): a particle effect is converted on the engine particle stage, and a particle takes the converted material":- {"note":"A Cocos project's own effects are converted."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"fix(cocos): the sprite texture is no parameter of a converted material, and a material blend state it does not set is the effect's":- {"note":"A Cocos project's own effects are converted."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(cocos): an effect includes its chunks and its vertex program is carried into the fragment, so the project materials convert for meshes as well as sprites":- {"note":"A Cocos project's own effects are converted."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(cocos): a project's own effect is converted to an Estella shader and material, so a sprite or mesh that wore it keeps its look":- {"note":"A Cocos project's own effects are converted."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(cocos): a sprite, a label and a graphics are UIRenderers, which accept the rebuild requests scripts send":- {"note":"Cocos scripts drive scenes as the game does."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(cocos): the importer records its revision, so a project it wrote earlier is re-imported on open":- {"note":"A converted Cocos project is brought up to date when it is opened."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(cocos): director has a scheduler and fires its frame events, setSiblingIndex reorders through the engine entity order, loadAny takes a uuid, and an asset counts its holders":- {"note":"Cocos scripts drive scenes as the game does."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(cocos): a root pinned to the screen is stored where the engine places it in the design box, so the document and the viewport agree":- {"note":"Converted Cocos UI looks as it does in Cocos."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"refactor(ui): the engine anchors run in two ordered passes and the Cocos Layout is a system between them, so alignment has one owner instead of a second hand-called copy":- {"note":"Converted Cocos UI looks as it does in Cocos."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(cocos): the project design resolution is known to scripts before they run, assetManager has a downloader and factory, and a node made between frames joins the running world":- {"note":"Cocos scripts drive scenes as the game does."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(cocos): a converted project declares its script components for the editor and starts from the scripts, and the Cocos scripts bundle past the gaps Cocos tolerates (missing cc names, reassigned const, package files outside exports, preview-only imports)":- {"note":"A converted project's scripts are components the editor knows."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"fix(release): escape the apostrophe in the Cocos re-import release-note key":{"internal":"Repairs a key of the release-notes ledger; no creator can observe it."},"feat(art): preserve Qinglan native sculpt revision and comparison":@@ -3295,7 +3295,7 @@ export const NOTED = {"feat(2d): a palette effect holds the whole picture to one set of colours, dithered":{"note":"A palette effect."},"fix(import): a Cocos bitmap font's page keeps its full size, not the 2048 default cap that halved a 4096 page and softened every glyph":- {"note":"Converted Cocos UI looks as it does in Cocos."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(2d): what walks leaves rings on water and prints on soft ground":{"note":"Footprints and ripples."},"feat(text): Text draws a bitmap font (.fnt) from its page texture, through the same layout as any font; widget prefabs regenerated for the Text box defaults":@@ -3307,19 +3307,19 @@ export const NOTED = {"feat(2d): plants of a sway material lean away from a body walking through them":{"note":"Mist, wind in the grass, and roofs that fade over the player."},"fix(import): a Cocos inactive node becomes the Disabled tag, so its subtree goes with it, instead of a dropped entity that strands its children":- {"note":"Converted Cocos UI looks as it does in Cocos."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(2d): a generated world on the screen plane, laid out by the worldgen rules and published in chunks":{"note":"A generated 2D world."},"fix(art): reject Qinglan face study after visual review":{"internal":"Source art studies kept in the repository's art/ folder; no part of the engine, the editor or a build reads or ships them."},"fix(import): Cocos enums as the engine's numbers, bitmapfont meta so the page ships, and the engine's own component validation in the test":- {"note":"Converted Cocos UI looks as it does in Cocos."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(2d): 2D shadows have eight channels and reach the tiled lights past the loop's sixteen":{"note":"More 2D lights cast shadows at once."},"feat(art): add editable Qinglan face cage study":{"internal":"Source art studies kept in the repository's art/ folder; no part of the engine, the editor or a build reads or ships them."},"feat(pipeline): import a Cocos Creator 3.x project as Estella prefabs and scenes, without touching the source":- {"note":"Open a Cocos Creator project from the editor."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(2d): a fog of war remembers what a viewer has seen, and a save can keep it":{"note":"What the player can see, and what they have seen."},"feat(2d): a viewer and the walls it cannot see through hide what is not lit":@@ -3365,7 +3365,7 @@ export const NOTED = {"fix(export): a playable that is far over its cap is built at once and reports its size":{"note":"A playable far over its size cap is built at once and says its size."},"fix(editor): the project watch is quiet while a Cocos re-import writes, and the project is refreshed once at the end":- {"note":"Re-import a Cocos project without losing your edits."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(editor): a selection draws nothing over the running game unless Inspect is on; a new one shows where it is for a moment":{"note":"A selection stays off the running game unless Inspect is on."},"feat(editor): the engine step of the loading screen shows which step of the boot it is in":@@ -3373,11 +3373,11 @@ export const NOTED = {"feat(editor): the loading screens say how far they are: one bar, a line per step with its count and time, and the time so far":{"note":"The loading screens say how far they are."},"feat(cocos): the import progress has a stage for checking the converted effects":- {"note":"A Cocos project's own effects are converted."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"fix(editor): the status strip keeps each readout on one line and drops the long message and the least useful readouts when it is short of room":{"note":"The status strip fits a narrow window."},"feat(cocos): a project converted by an older importer is brought up to date when it is opened":- {"note":"A converted Cocos project is brought up to date when it is opened."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"fix(test): the MCP client adapter checks run under the throwaway home, so they no longer touch the real VS Code config on Windows":{"internal":"Points the MCP client adapter tests at a throwaway home directory; no creator can observe it."},"refactor(editor): the edit world reads the screen fit from the one runtime config derivation instead of deriving it a second time":@@ -3389,11 +3389,11 @@ export const NOTED = {"fix(play): a project script bundle that throws while it loads is logged instead of looking like no bundle":{"note":"A project script bundle that throws while it loads is reported."},"fix(cocos): the schema extractor resolves cc, so a converted project's components reach the inspector":- {"note":"A converted project's scripts are components the editor knows."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"fix(cocos): the conversion progress window carries the editor icon, has no scrollbar, and speaks the editor language":- {"note":"A Cocos conversion shows its progress."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(cocos): converting a Cocos project runs on a thread of its own with a progress bar, so the editor no longer looks hung":- {"note":"A Cocos conversion shows its progress."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"feat(editor): settings rows for the power-saving policy":{"note":"Save power when the battery is low or the device is hot."},"fix(editor): the connect dialog and its status-bar mark use the editor's own components and tokens":@@ -3421,7 +3421,7 @@ export const NOTED = {"refactor(ui): the anchoring arithmetic is a module of its own, so the Cocos importer uses it without compiling the engine into the pipeline's typecheck":{"internal":"a module split; the arithmetic and the component behave as before"},"fix(cocos): a launched scene has its scripts loaded and enabled before its callback, and the scene before it goes; an instance's mounted components land on the prefab it names; Node.forward/up/right/worldMatrix and the rest of Vec2/Vec3/Quat/Color/Vec4/Mat4 a game calls":- {"note":"Cocos scripts drive scenes as the game does."},+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},"fix(render): a material mesh reads its own tangents on WebGL again":{"internal":"undoes a regression from after 0.96.0 that no release carried"},"fix(editor): the loading screens take the type scale and the shadow token, and the play overlay's stop is a Button":@@ -3450,4 +3450,82 @@ export const NOTED = {{"note":"A 3D contact point is in the units of `Transform`."},"fix(cocos): a converted effect reads the tangent varying the engine fragment prelude declares, instead of declaring it again":{"internal":"corrects a converted Cocos effect that no release has shipped yet"},+ "fix(cocos): macros the code only reads are baked into a converted shader, and effects written as GLSL main() programs convert: 17 of the 22 effects that were not converted now are":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "feat(cocos): a mesh of several primitives is drawn whole with the material of each slot, an effect's outline pass is drawn as a second renderer, skinned parts take their material override, and a macro that defines functions is no longer cut up by the pruning":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "feat(cocos): a converted effect's ambient parameters start at what most of the project's game scenes set, so a fake-lit material is not brighter than the game draws it":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "fix(cocos): a converted effect encodes its output for the display in the gamma colour space, and a converted material is not tinted twice by the renderer":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "feat(cocos): a material put on a part of a model instance reaches that part: the part is told by the id of its renderer, read from the editor library":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "fix(assets): a model texture named by a path on the artist machine is found by its name beside the model, instead of left as a path that is not there":+ {"note":"A model texture the project does not have is left off."},+ "feat(render): TextureCanvas — a blank texture textures are pasted into at pixel positions, then shown on a Sprite; with an example and docs":+ {"note":"Paste textures onto a blank texture: `TextureCanvas`."},+ "fix(cocos): a node answers _components with its script instances, so a project that prepares a new instance's nodes before parenting it reaches them":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "feat(cocos): a scene's linear fog becomes a global distance-fog volume, and the scene settings report counts only those that are switched on":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "feat(cocos): recompileShaders makes the material take the permutation of its shader that has the macros applied, now, instead of only recording them":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "fix(assets): shrinking a texture to its Max Size keeps the colour of a footprint that is clear all through, instead of black: a weight map holds its numbers under a clear alpha":+ {"note":"A texture keeps the colour under its clear texels when it is made smaller or read back."},+ "fix(cocos): only a map-sized texture that is clear and coloured is kept as data, and the meta an earlier import wrote for one that is not is taken away":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "fix(cocos): only a texture a material samples, whose clear texels hold several colours, is kept as data: a sprite's white or black bleed is not numbers":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "fix(cocos): a texture that keeps its colour under a clear alpha holds numbers, and is imported uncompressed and not as sRGB, so a terrain's weight map reaches its shader as it was painted":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "fix(assets): a texture made smaller to fit its budget keeps the colour under its clear texels: the resize was left to premultiply, which turned a terrain's weight map black":+ {"note":"A texture keeps the colour under its clear texels when it is made smaller or read back."},+ "fix(assets): a decoded bitmap is read back through a texture instead of a 2D canvas, so the colour of a texel whose alpha is clear survives: a terrain's weight map came out black everywhere it was clear":+ {"note":"A texture keeps the colour under its clear texels when it is made smaller or read back."},+ "fix(cocos): a mesh whose converted material blends is imported as not opaque, so the engine draws it with blending: a fog that fades out was drawn black where it should have been clear":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "fix(assets): the plane of Cocos imports as builtin:cocos-plane, 10 across like the one effects were written against, so what an effect reads of its position in the mesh's own space has the scale it expects":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "fix(cocos): a material's property that is a lane of a vec4 uniform (fogLayerBlend is fogParams.x) is written under the uniform, so the values an artist set reach the shader instead of the effect's defaults":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "feat(assets): builtin:map-plane is the plane with its texture's v running along +z, and a Cocos plane imports as it, so a map laid over one lands where it was drawn":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "feat(shaders): a mesh shader that declares MESH_LOCAL_POSITION is handed the mesh's own position by the canonical vertex stage, and a converted effect that reads its vertex position in model space asks for it":+ {"internal":"a vertex-stage input only the Cocos importer's converted effects ask for; the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "fix(cocos): a vertex program that reads light-probe data only under the probe macro converts, since a material is given none: the terrain effect that draws the ground was refused for it":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "fix(cocos): a converted shader that has been given its derived WGSL twin is still the importer's own, so a re-import updates it instead of keeping it as the creator's edit":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "fix(cocos): a converted effect's uniform that properties are lanes of starts as those lanes put together, so a fragment that scales by it no longer draws black":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "feat(cocos): a scene's ambient light becomes an Ambient light entity, so a lit mesh is no longer black":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "fix(cocos): a converted effect declares the tangent varying it reads again: without it every effect failed its glslang check (294 not converted in the Cocos client) and its materials came out empty":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "fix(cocos): Material.setProperty takes a texture a script hands it by name, from an image or the frame that holds one, so the fog's region mask reaches its shader":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "feat(cocos): renderer.scene.CameraProjection has Cocos's numbers, so a script that tells an orthographic camera from a perspective one by it gets the right answer":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "fix(camera): a full-frame camera that clears no colour is drawn over the main view instead of competing to be it, so a UI camera no longer hides the world camera's picture":+ {"note":"A camera that clears no colour is drawn over the main view."},+ "fix(cocos): a camera keeps what it clears: the UI camera clears depth only, so the world camera's picture is no longer wiped by it":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "fix(cocos): onLoad waits for the node to be active in the hierarchy, a base of the built-in views (UIRenderer) is found through the one the node holds, and Node.insertChild":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "feat(cocos): Node.setWorldRotation, setWorldRotationFromEuler, setWorldScale, rotate, translate, lookAt, inverseTransformPoint, walk and NodeSpace, as a script calls them":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "fix(cocos): a prefab is handed over with the prefabs its scripts hold in Prefab fields, and Material.recompileShaders sets the shader's switches":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "fix(cocos): a @ccclass class that is not a component is not driven as a script, so the frame loop no longer calls timers it does not have":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "feat(cocos): PhysicsSystem.instance.raycast and raycastClosest cross the world's box colliders as oriented boxes, nearest first, with the point and face met":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "feat(cocos): BoxCollider and Collider are views on the engine's BoxCollider3D, in the node's units, with the static body a collider without a rigid body is":+ {"internal":"the Cocos importer and compatibility layer are held on the cocos-import branch and are not in this release"},+ "fix(play): the connections a play session opened are closed when it ends, so the next session does not log in as an account that is still connected":+ {"note":"Stopping Play closes the connections the game opened."},+ "fix(editor): a drop on an Outliner row lands even when it beats the hover's render; it asks for its own answer when the stored one is for another row":+ {"note":"A drop on an Outliner row lands."},+ "fix(editor): a play that cannot start prints every compile error to the output log, and the status line carries the reason, not only that it failed":+ {"note":"A play that cannot start says why."},};