Skip to main content

FAQ

We collect frequently asked questions from previous years and from Ed Discussions here. For the most common mistakes in one table, see Common mistakes.

Something isn't working​

My node doesn't show up​

Check, in order:

  1. Is there a view spec for its class? If the console says Unsure how to create view for ... with class MyModel, add this.addModelViewSpec(MyModel, SomeView) to the controller's initModelViewSpecs(). A spec doesn't apply to a subclass that has its own @ASerializable label, and all of your model classes should have one, so subclasses of engine classes (even of AGroupNodeModel2D) need their own line. See Model–view specs.
  2. Was it added to the scene? Top-level nodes need this.addNode(node) in the scene model; other nodes need parent.addChild(node) under a node that's in the scene.
  3. Does it have a material? Polygon and mesh views draw with model.material. If you never called setMaterial(...), the view throws an error about reading threejs of undefined. See Materials.
  4. Is it on screen? Check its position and scale against the camera. Try zooming out with the Pan/Zoom interaction mode.
  5. Is it hidden? Check visible, and its zValue: values outside about -5 to 5 aren't drawn, and a lower zValue can put it behind something else. See Draw order.
  6. Are its vertices clockwise? A counterclockwise polygon still draws, but its per-vertex colors come out scrambled. See Geometry.

My node doesn't move, or doesn't update​

  • Is timeUpdate being called? The base 2D controller calls the scene model's timeUpdate every frame (if you override onAnimationFrameCallback, make sure it calls super.onAnimationFrameCallback(context)). The scene model's timeUpdate must call your node's timeUpdate; that doesn't happen automatically. See The frame loop.
  • Did you signal the change? A transform change redraws on its own, unless you set the node's autoTransformUpdate to false: then call signalTransformUpdate() after changing it. After changing geometry, call signalGeometryUpdate(). For a particle system, signalParticlesUpdated().
  • Are you editing a copy? Edit a node's transform through node.prsa, which is the node's own transform. If node.prsa throws because the transform is a Mat3, call node.convertTransformToPRSA() first. See Transforms.

Key presses do nothing​

The canvas only receives key events when it has keyboard focus. Make sure your interaction mode's onClick (and onDragStart, if you have one) calls this.eventTarget.focus(), and click the canvas before typing. Clicking the control panel moves focus away from the canvas. Also check that your mode is the current one (this.setCurrentInteractionMode("Main")) and that your handler forwards to a model method that the scene model passes on to the right node.

My sliders are cut off or missing​

Add every control in the scene model's initAppState, or in a node class's static SetAppState(appState) called from there. Controls added later (in initScene, or in a node's constructor) may not fit in the panel. Also check that MainAppConfigs.USE_STRICT_MODE in MainApp.tsx is false (the default): with React's StrictMode on, the control panel keeps the height it had when it was first drawn, so those later controls end up hidden below the visible part of the panel. See The control panel.

Clicks land in the wrong place​

Use this.getWorldCoordinatesOfCursorEvent(event) in the controller. Positions computed from event.ndcCursor times a scale ignore the camera, and are wrong as soon as you pan or zoom. See Mouse input.

Pan and zoom stopped working​

Making your own interaction mode current replaces the default Pan/Zoom mode. Pick "Pan/Zoom" in the control panel's interaction-mode menu to look around, and switch back to your mode to interact. If your scene model moves the camera every frame, panning won't stick.

One of my classes behaves like a different class​

Two model classes probably use the same @ASerializable label. Labels must be unique across the whole app, including the example scenes, and if two classes share one, AniGraph warns in the console and the two can get mixed up (for example, one gets the other's view, or a saved file loads as the wrong class). Prefix labels with your scene's name, for example @ASerializable("MyGameCatModel"). See Every model class needs @ASerializable.

Two things move together when they shouldn't​

They probably share one Vec2 or Color object. Assigning a vector copies a reference, not the values, so a.position = b.position makes them the same object. Use .clone(). See Particles for an example.

The dev server shows errors that don't match my code​

If yarn start reports errors that can't be right, the build tool's cache is probably out of date. For example, it might say Module './nodes' has no exported member 'MyModel' when nodes/index.ts clearly exports MyModel. This can happen after you copy, move or replace scene folders. Stop the dev server (Ctrl+C), run yarn clean, then run yarn start again. Clearing the cache is safe, because it's rebuilt automatically. If the error is still there afterwards, it's a real error in your code.

How do I...​

Make stuff disappear/appear​

Use the node's visible property

Every node model has a visible property. Set it to false and the node (and all of its descendants) stops being drawn; set it to true and it's drawn again.

node.visible = false;   // hide
node.visible = true; // show

It is usually better to recycle nodes by hiding and showing them than to create and delete them. node.release() deletes a node (and its descendants and their views), and parent.removeChild(node) only detaches it, keeping it around to be added again. Recycle when you can, for two reasons:

  • Allocating resources on the graphics card very frequently can make your program slow.
  • JavaScript has garbage collection, but GPU resources have to be released explicitly. AniGraph does this when you release() a node, but depending on how you customize things, you could still leak GPU memory.

A hidden node can still be picked by getNodeModelAtCursor, so check visible if hidden nodes shouldn't respond to clicks.

Use group nodes​

Group nodes in AniGraph

A group node draws nothing itself; it just holds children, so you can move, rotate, scale or hide them together. Use AGroupNodeModel2D for the model and AGroupNodeView for the view.

There is a built-in spec for AGroupNodeModel2D itself, but not for subclasses. If you subclass it (which is common, to give a group behavior), register the subclass:

this.addModelViewSpec(MyGroupModel, AGroupNodeView);

Examples: OrbitGroupModel and ArmModel in HierarchyAndAnimation, ExhibitModel in ShapesAndMaterials, and LabCatParticlePlaygroundModel in ParticlePlayground2D.

Change the background​

Set the background color or image in the scene controller

The background is set in the scene controller's initScene, after await super.initScene() (which sets the background to white, overwriting anything set before it).

async initScene(){
await super.initScene();
this.setClearColor(Color.Black());
}

For an image, load the texture first (in the scene model's PreloadAssets, with await AssetManager.loadTexture("./images/SpaceBG.jpg", "Space")), then in the controller:

async initScene(){
await super.initScene();
this.view.setBackgroundTexture(AssetManager.getTexture("Space"));
}

To go back from an image to a plain color, clear the image with this.getThreeJSScene().background = null and set the clear color. ShapesAndMaterialsSceneController.applyBackground switches between the two from a dropdown.

Change the render window size​

The UseFullWindowLayout checkbox, and Component/style.ts

The control panel has a UseFullWindowLayout checkbox (added by src/MainApp.tsx). Check it to make the drawing area fill the window instead of sitting in a square card.

To change the default card layout, edit the CSS in src/Component/style.ts. In the card layout, the .anigraphcontainer rule sets the drawing area's size:

.anigraphcontainer{
max-height: 95%;
max-width: 95%;
aspect-ratio: 1;
...
}

Changing 95% to something smaller makes the drawing area smaller.

Use materials and textures​

What materials are, and which to use

A material is a recipe for coloring the pixels a shape covers (really a shader, which we cover later in the course). Use AssetManager.CreateBasicMaterial(color) for one flat color, AssetManager.Create2DRGBAMaterial() to blend per-vertex colors, and AssetManager.Create2DTextureMaterial(texture) for an image. Load textures in a static async PreloadAssets() with AssetManager.loadTexture(path, name), and switch a textured material's image with material.setDiffuseTexture(texture).

The full explanation, with code from ShapesAndMaterials, is on the Drawing page: Materials, Textures and Flipbooks.

Make things transparent​

Use the alpha channel
  • Per-vertex colors: with Create2DRGBAMaterial(), each vertex color's alpha is its opacity: Color.FromRGBA(1, 0, 0, 0.5) is half-transparent red.
  • Textures: PNG images with transparent pixels draw transparent with Create2DTextureMaterial. The textured material also has an overall alpha uniform: material.setUniform("alpha", 0.5).
  • Graphic elements initialized with a Color: set the opacity on their material: graphic.setMaterialAttribute("opacity", color.a).
  • Particles: each particle's color.a is its opacity. See Particles.

Transparent shapes blend with whatever was drawn behind them, so their draw order matters. Give overlapping transparent shapes different zValues.

Draw lines​

Use a LineModel2D with a view that draws an ALineGraphic

Use a LineModel2D (its verts are the points, and it has a lineWidth), and a view that draws it with an ALineGraphic and ALineMaterialModel.GlobalInstance.CreateMaterial(). Copy WaveLineView (ShapesAndMaterials). The engine's LineView2D needs the model to already have a line material, so copying WaveLineView is simpler. See Lines.

Play sounds​

AudioManager.LoadSound and AudioManager.playSound

Import AudioManager from anigraph/audio/AAudioManager (it isn't in the main anigraph index), load sounds in a node's static async PreloadAssets() with await AudioManager.LoadSound(name, path), and play them with AudioManager.playSound(name). Browsers don't play sound until the user has clicked or pressed a key. See Sound.

Use noise​

makeNoise2D from fast-simplex-noise, with a SeededRandom
import {SeededRandom} from "../../../../anigraph";     // adjust the path
import {makeNoise2D} from "fast-simplex-noise";

const noise = makeNoise2D(new SeededRandom(0).rand); // the seed picks the landscape
const value = noise(1.2, 3.4); // between -1 and 1

For fractal noise, see Procedural noise.

Show text or numbers on the page​

setReactGUIContentFunction

The app has an area on the page, outside the canvas, for your own React content, such as a score or a readout. In the scene model's initAppState, pass a function that returns JSX to the app state:

appState.setReactGUIContentFunction(MyGUIContent);

The function has to live in a .tsx file, because it returns JSX:

import {Fragment} from "react";
import {GetAppState} from "../../anigraph"; // adjust the path

export function MyGUIContent(...args: any[]){
const scene = GetAppState().sceneModel as MySceneModel;
return (<Fragment><p>Cats captured: {scene.nCaptured}</p></Fragment>);
}

GetAppState().sceneModel is the app state's reference to your scene model. Then call GetAppState().updateComponents() whenever the content should refresh (for example, in the scene model's timeUpdate, or only when the score changes). setReactGUIBottomContentFunction does the same for a second area below the canvas.

Use 3D, or another library?​

No. C1 is a 2D assignment: use ASceneModel2D and ASceneController2D, and don't use the 3D functionality of three.js. Only use code and libraries already included in AniGraph (Howler and fast-simplex-noise are fine). See the rules on the Introduction.