# effect/particlesystem (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/effect/particlesystem/

파티클 시스템.

## ParticleSystem extends Component

파티클 시스템.
- 유니티 ParticleSystem 의 자주 쓰는 부분을 2D 로 옮긴 컴포넌트.
  방출(rate / burst), 모양(shape), 수명 / 속도 / 크기 / 회전 / 색의 시작 범위,
  수명에 따른 크기 / 색 / 회전 변화, 중력 / 감쇠, 가산 합성, 이미지 스프라이트를 지원한다.
- 사용:
    const particleSystem = node.addComponent(ParticleSystem);
    particleSystem.setEmissionRate(40);
    particleSystem.setStartLifetime(0.6, 1.2);
    particleSystem.setStartSpeed(40, 120);
    particleSystem.setColorOverLifetime([
        { time: 0, color: new Color(1, 0.8, 0.3, 1) },
        { time: 1, color: new Color(1, 0.2, 0, 0) },
    ]);
    particleSystem.play();

예제: 노드에 붙여 불꽃 뿜기

```js
import { Engine, EngineConfiguration, Scene, WorldNode, ParticleSystem, ParticleEmitterShape, Color, Vector2 } from "./build/vanilla.js";

class MainScene extends Scene {
	initialize(engine) {
		super.initialize(engine);
		const node = new WorldNode();
		node.setLocalPosition(Vector2.create(320, 300));
		const root = this.getRoot();
		root.addChild(node);
		const particleSystem = node.addComponent(ParticleSystem);
		particleSystem.setEmitterShape(ParticleEmitterShape.cone);
		particleSystem.setShapeRadius(10);
		particleSystem.setConeAngle(0.3);
		particleSystem.setEmissionRate(60);
		particleSystem.setStartLifetime(0.6, 1.2);
		particleSystem.setStartSpeed(40, 120);
		particleSystem.setStartSize(10, 18);
		particleSystem.setSizeOverLifetime(1, 0.2);
		particleSystem.setColorOverLifetime([
			{ time: 0, color: new Color(1, 0.8, 0.3, 1) },
			{ time: 1, color: new Color(1, 0.2, 0, 0) },
		]);
		particleSystem.setAdditive(true);
		particleSystem.play();
	}
}

const engineConfiguration = new EngineConfiguration();
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());
```

- `constructor()` (constructor, since 0.3.0): 생성.
- `play()` (method, since 0.3.0): 재생 / 정지.
- `stop(isClearing = false)` (method, since 0.3.0): 정지. (방출을 멈춘다, 살아 있는 파티클은 isClearing 이 아니면 수명까지 움직인다)
  - `isClearing` boolean: 참이면 살아 있는 파티클도 지운다.
- `emit(count, worldOffset = null)` (method, since 0.3.0): 한 번에 여러 개 방출. (버튼 클릭 등 이벤트성 연출)
  - `count` number: 방출할 수. (최대 수에 닿으면 더 만들지 않는다)
  - `worldOffset` Vector2 | null: 방출 원점 보정. (노드 로컬 기준)
- `tick(timeDelta)` (method, since 0.3.0): 갱신. (노드 갱신, 수동 틱이면 건너뛴다)
  - `timeDelta` number: 지난 시간. (초)
- `simulate(timeDelta)` (method, since 0.3.0): 시간 진행. (방출 + 적분, 수동 틱 모드에서는 외부가 부른다)
  - `timeDelta` number: 진행할 시간. (초)
- `draw(graphic)` (method, since 0.3.0): 출력. (정점 색 배치, 파티클 수와 무관하게 시스템당 드로우 한 번)
  - circle 은 부드러운 원 텍스처, rect / streak 은 흰 텍스처 쿼드로 그린다.
    image 는 파티클 수가 적다는 가정으로 개별 드로우를 유지한다.
  - `graphic` Graphic: 그릴 그래픽.
- `calculateDrawnRect(rect)` (method, since 0.4.0): 그리는 사각형 셈하기. (오버라이드: 살아 있는 파티클이 그리는 쿼드를 모두 품는 사각형, 노드 내용 좌표)
  - 파티클마다 그리는 크기의 반에 √2 를 곱한 만큼(돌린 사각형, 그림), 꼬리 쿼드면 머리와 꼬리를 품고 굵기의 반만큼, 흔들림 폭만큼 좌우를 넓히고 한 단위 여유를 둔다.
  - 시뮬레이션(simulate)이 돌 때마다, 방출(emit)과 지움(stop)에, 그리는 꼴을 바꾸는 세터에 다시 셈하게 알린다. (그리는 것이 화면 밖이면 그리기를 건너뛰고 시뮬레이션은 tick 이라 그대로 돈다)
  - 파티클이 없으면 크기 0 (그리지 않는다).
  - 월드 공간이면서 수동 틱이면 모른다. (노드를 옮기면 그리는 자리가 바뀌는데 그때 다시 셈할 길이 없다)
  - `rect` Rect: 그리는 사각형을 적을 곳. (노드 내용 영역의 왼쪽 위가 원점)
  - returns boolean: 알면 참.

  예제: 방출한 파티클을 품는 사각형

  ```js
  import { WorldNode, ParticleSystem, Rect } from "./build/vanilla.js";
  
  const node = new WorldNode();
  const particleSystem = node.addComponent(ParticleSystem);
  particleSystem.setStartSpeed(0);
  particleSystem.setStartSize(10);
  particleSystem.emit(3);
  const drawnRect = Rect.zero();
  console.log(particleSystem.calculateDrawnRect(drawnRect), drawnRect.size.x > 0);
  ```

- `setEmissionRate(emissionRate)` (method, since 0.3.0): 초당 방출 수 설정. (기본 20)
  - `emissionRate` number: 초당 방출 수.
- `setBurstList(burstList)` (method, since 0.3.0): 버스트 목록 설정. (정한 때에 한꺼번에 방출한다, 루프면 duration 마다 되풀이)
  - `burstList` object[]: [{ time, count }]

  예제: 한 번 터지고 끝나는 폭죽

  ```js
  import { Engine, EngineConfiguration, Scene, WorldNode, ParticleSystem, ParticleEmitterShape, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	initialize(engine) {
  		super.initialize(engine);
  		const node = new WorldNode();
  		node.setLocalPosition(Vector2.create(320, 180));
  		const root = this.getRoot();
  		root.addChild(node);
  		const particleSystem = node.addComponent(ParticleSystem);
  		particleSystem.setLooping(false);
  		particleSystem.setDuration(0.5);
  		particleSystem.setEmissionRate(0);
  		particleSystem.setBurstList([
  			{ time: 0, count: 40 },
  			{ time: 0.3, count: 20 },
  		]);
  		particleSystem.setEmitterShape(ParticleEmitterShape.circle);
  		particleSystem.setShapeRadius(4);
  		particleSystem.setStartSpeed(80, 200);
  		particleSystem.setGravity(0, 300);
  		particleSystem.play();
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `setEmitterShape(emitterShape)` (method, since 0.3.0): 방출 모양 설정. (기본 point)
  - `emitterShape` string: ParticleEmitterShape 값.
- `setShapeRadius(shapeRadius)` (method, since 0.3.0): 방출 반지름 설정. (픽셀, 기본 0)
  - `shapeRadius` number: circle / cone 반지름.
- `setConeAngle(coneAngleRadian)` (method, since 0.3.0): cone 반각 설정. (기본 0.5 라디안)
  - `coneAngleRadian` number: cone 반각. (라디안)
- `setBoxSize(width, height)` (method, since 0.3.0): box 크기 설정. (픽셀, 기본 0, 0)
  - `width` number: box 가로.
  - `height` number: box 크기.
- `setEdgeWidth(edgeWidth)` (method, since 0.3.0): edge 길이 설정. (픽셀, 기본 0)
  - `edgeWidth` number: edge 가로 길이.
- `setStartLifetime(minSeconds, maxSeconds = minSeconds)` (method, since 0.3.0): 시작 수명 범위 설정. (기본 1 초)
  - `minSeconds` number: 수명 최솟값. (초)
  - `maxSeconds` number: 수명 최댓값. (초, 주지 않으면 최솟값)
- `setStartSpeed(minSpeed, maxSpeed = minSpeed)` (method, since 0.3.0): 시작 속력 범위 설정. (기본 60)
  - `minSpeed` number: 속력 최솟값. (초당 픽셀)
  - `maxSpeed` number: 속력 최댓값. (초당 픽셀, 주지 않으면 최솟값)
- `setStartSize(minSize, maxSize = minSize)` (method, since 0.3.0): 시작 크기 범위 설정. (기본 6)
  - `minSize` number: 크기 최솟값. (픽셀)
  - `maxSize` number: 크기 최댓값. (픽셀, 주지 않으면 최솟값)
- `setStartRotation(minRadian, maxRadian = minRadian)` (method, since 0.3.0): 시작 회전 범위 설정. (기본 0)
  - `minRadian` number: 회전 최솟값. (라디안)
  - `maxRadian` number: 회전 최댓값. (라디안, 주지 않으면 최솟값)
- `setStartColor(colorA, colorB = colorA)` (method, since 0.3.0): 시작 색 범위 설정. (기본 흰색)
  - `colorA` Color | string: 시작 색. (복사해 둔다)
  - `colorB` Color | string: 둘 사이 무작위.
- `setColorOverLifetime(gradient)` (method, since 0.3.0): 수명에 따른 색 설정. (시작 색에 곱한다, 키 사이는 선형 보간)
  - `gradient` object[]: [{ time: 0~1, color }]
- `setSizeOverLifetime(startScale, endScale)` (method, since 0.3.0): 수명에 따른 크기 배율 설정. (시작에서 끝으로 선형, 기본 1, 1)
  - `startScale` number: 태어날 때의 크기 배율.
  - `endScale` number: 수명이 다할 때의 크기 배율.
- `setAngularVelocity(minRadianPerSecond, maxRadianPerSecond = minRadianPerSecond)` (method, since 0.3.0): 회전 속도 범위 설정. (기본 0)
  - `minRadianPerSecond` number: 회전 속도 최솟값. (초당 라디안)
  - `maxRadianPerSecond` number: 회전 속도 최댓값. (초당 라디안, 주지 않으면 최솟값)
- `setGravity(gravityX, gravityY)` (method, since 0.3.0): 중력 설정. (기본 0, 0)
  - `gravityX` number: 가로 가속. (매초 속도에 더하는 초당 픽셀)
  - `gravityY` number: 세로 가속. (매초 속도에 더하는 초당 픽셀, 양수가 아래)
- `setDamping(damping)` (method, since 0.3.0): 감쇠 설정. (기본 0)
  - `damping` number: 초당 감쇠 계수. (0 = 없음)
- `setRenderShape(renderShape)` (method, since 0.3.0): 렌더 모양 설정. (기본 circle)
  - `renderShape` string: ParticleRenderShape 값.
- `setImage(image)` (method, since 0.3.0): 파티클 이미지 설정.
  - `image` *: 엔진 이미지. (renderShape image 전용)
- `setAdditive(isAdditive)` (method, since 0.3.0): 가산 합성 설정.
  - `isAdditive` boolean: 가산 합성 여부. (setBlendMode("lighter") 의 설탕)
- `setBlendMode(blendMode)` (method, since 0.3.0): 블렌드 모드 설정. (기본 "source-over")
  - `blendMode` string: Graphic.setBlendMode 가 받는 이름. ("source-over" | "lighter" | "multiply" | "screen" 등 SpriteBlendMode 26 가지, 셰이더 섞기 모드는 서로 겹치지 않는 파티클끼리 모아 그린다)
- `setAttractor(x, y, strength, swirl = 0)` (method, since 0.3.0): 끌개 설정. (중심으로 끌거나 밀고, 접선으로 돌린다)
  - `x` number: 끌림 중심 x. (노드 로컬 픽셀)
  - `y` number: 끌림 중심 y. (노드 로컬 픽셀)
  - `strength` number: 중심 가속.
  - `swirl` number: 접선 가속.
- `clearAttractor()` (method, since 0.3.0): 어트랙터 해제.
- `setWobble(amplitude, frequency = 4)` (method, since 0.3.0): 살랑임 설정. (그릴 때만 좌우로 흔들고 움직임에는 넣지 않는다)
  - `amplitude` number: 살랑임 폭.
  - `frequency` number: 초당 각속도.
- `setStreakScale(streakScale)` (method, since 0.3.0): streak 길이 배율 설정. (기본 0.06)
  - `streakScale` number: streak 길이 = 속도 x 이 값.
- `setWorldSpace(isWorldSpace)` (method, since 0.3.0): 월드 공간 설정. (기본 거짓)
  - `isWorldSpace` boolean: 참이면 방출 뒤 노드 이동의 영향을 받지 않는다.
- `setLooping(isLooping)` (method, since 0.3.0): 반복 방출 설정.
  - `isLooping` boolean: 참이면 계속 방출한다. (기본 참, 거짓이면 duration 동안만)
- `setDuration(duration)` (method, since 0.3.0): 방출 시간 설정. (초, 기본 1)
  - `duration` number: 루프 꺼짐일 때 방출 시간. (버스트 반복 주기)
- `setMaxParticleCount(maxParticleCount)` (method, since 0.3.0): 최대 파티클 수 설정.
  - `maxParticleCount` number: 살아 있을 수 있는 최대 수. (기본 512)
- `applyDescription(description)` (method, since 0.3.0): 서술(JSON) 적용., vfx 애셋 로드 / 파티클 편집기 공용.
  - 모든 항목은 선택 사항이며 준 것만 반영한다. 색은 [r, g, b, a] 배열.
  - imageDataUrl 은 파티클 편집기가 고른 그림의 data: 주소다. 그 그림을 입자 이미지로 걸고(브라우저가 다 풀면 그린다), 비었거나 null 이면 그림을 비운다.
  - `description` object: 서술 객체. (looping, duration, maxParticleCount, emissionRate, bursts, shape, shapeRadius, coneAngle, boxSize, edgeWidth, lifetime, speed, size, rotation, angularVelocity, startColorA, startColorB, colorOverLifetime, sizeOverLifetime, gravity, damping, attractor, wobble, renderShape, blendMode, streakScale, worldSpace, imageDataUrl)

  예제: JSON 서술로 설정하기

  ```js
  import { ParticleSystem } from "./build/vanilla.js";
  
  const particleSystem = new ParticleSystem();
  particleSystem.applyDescription({
  	looping: false,
  	duration: 0.2,
  	emissionRate: 50,
  	shape: "box",
  	boxSize: [200, 10],
  	lifetime: [0.5, 1],
  	speed: [20, 40],
  	startColorA: [0.6, 0.8, 1, 1],
  	colorOverLifetime: [
  		{ time: 0, color: [1, 1, 1, 1] },
  		{ time: 1, color: [1, 1, 1, 0] },
  	],
  	gravity: [0, 98],
  	renderShape: "streak",
  });
  particleSystem.simulate(0.1);
  console.log(particleSystem.getParticleCount());
  ```

- `getParticleCount()` (method, since 0.3.0): 살아 있는 파티클 수 반환.
  - returns number: 살아 있는 파티클 수.
- `getParticlePositionList()` (method, since 0.4.0): 입자 자리 목록. (노드 로컬, 흔들림을 넣지 않은 적분 자리. 같은 씨앗 비교와 시험용)
  - returns Vector2[]: 파티클 자리 목록. (새로 만든 Vector2)
- `isPlaying()` (method, since 0.3.0): 방출 중인지 반환.
  - returns boolean: 방출 중이면 참. (생성 직후 참)
- `isFinished()` (method, since 0.4.0): 다 끝났는지. (방출할 것이 더 없고 남은 입자도 없음, 일회성 노드를 치울 때)
  - 정지했거나, 루프가 아니고 duration 이 지났으며 버스트를 다 냈으면 방출할 것이 없다.
  - returns boolean: 다 끝났으면 참.
- `setManualTick(isManualTick)` (method, since 0.3.0): 수동 틱 설정. (참이면 노드 갱신 대신 simulate() 로만 진행, 타임라인이 시간을 다룬다)
  - `isManualTick` boolean: 참이면 노드 갱신에서 진행하지 않는다. (기본 거짓)
- `isManualTick()` (method, since 0.3.0): 수동 틱인지 반환.
  - returns boolean: 수동 틱이면 참.
- `setRandomSeed(seed)` (method, since 0.3.0): 난수 시드 설정. (설정하면 스폰 난수가 시드 난수로 바뀌고 stop(true) 마다 시드로 되돌아간다, 되감기 재현용)
  - `seed` number: 난수 시드.

  예제: 시드로 같은 방출 되풀이하기

  ```js
  import { ParticleSystem } from "./build/vanilla.js";
  
  const particleSystem = new ParticleSystem();
  particleSystem.setManualTick(true);
  particleSystem.setRandomSeed(7);
  particleSystem.setEmissionRate(30);
  particleSystem.simulate(0.5);
  const firstPositionList = particleSystem.getParticlePositionList();
  particleSystem.stop(true);
  particleSystem.play();
  particleSystem.simulate(0.5);
  const secondPositionList = particleSystem.getParticlePositionList();
  console.log(firstPositionList.length, secondPositionList[0].x === firstPositionList[0].x);
  ```

- `getRandomSeed()` (method, since 0.3.0): 난수 시드 반환.
  - returns number | null: 난수 시드. (설정하지 않았으면 null)
- `randomRange(minValue, maxValue)` (method, since 0.3.0): 스폰용 난수. (시드가 있으면 시드 난수, 없으면 전역 난수)
  - `minValue` number: 최솟값.
  - `maxValue` number: 최댓값.
  - returns number: 최솟값과 최댓값 사이의 난수.

## ParticleEmitterShape (enum)

방출 모양.
- point: 노드 원점 한 점.
- circle: 반지름 안 무작위 위치, 바깥 방향.
- cone: 위쪽(-y) 기준 각도 부채꼴 방향, 반지름 안 위치.
- box: 사각 영역 안 무작위 위치, 위쪽 방향.
- edge: 가로 선분 위 무작위 위치, 아래쪽(+y) 방향. (눈 / 비처럼 위에서 뿌릴 때)

- `point` = `point`: 노드 원점 한 점에서 무작위 방향.
- `circle` = `circle`: 반지름 안 무작위 위치에서 중심 바깥 방향.
- `cone` = `cone`: 반지름 안 위치에서 위쪽(-y) 기준 반각 안 부채꼴 방향.
- `box` = `box`: 사각 영역 안 무작위 위치에서 위쪽(-y) 방향.
- `edge` = `edge`: 가로 선분 위 무작위 위치에서 아래쪽(+y) 방향.

## ParticleRenderShape (enum)

파티클 렌더 모양.
- circle: 부드러운 원. (기본)
- rect: 사각형. (색종이 조각처럼 회전하는 판)
- streak: 진행 방향으로 늘인 띠. (비 / 유성)
- image: setImage 로 넣은 이미지.

- `circle` = `circle`: 부드러운 원. (기본)
- `rect` = `rect`: 사각형. (회전하는 판)
- `streak` = `streak`: 진행 방향으로 늘인 띠.
- `image` = `image`: setImage 로 넣은 이미지.
