|
| 1 | +import { DOCUMENT } from '@angular/common'; |
| 2 | +import { |
| 3 | + ChangeDetectionStrategy, |
| 4 | + Component, |
| 5 | + CUSTOM_ELEMENTS_SCHEMA, |
| 6 | + Directive, |
| 7 | + ElementRef, |
| 8 | + inject, |
| 9 | + signal, |
| 10 | + viewChild, |
| 11 | +} from '@angular/core'; |
| 12 | +import { extend, getLocalState, injectBeforeRender, injectObjectEvents, NgtCanvas } from 'angular-three'; |
| 13 | +import { NgtsEnvironment } from 'angular-three-soba/staging'; |
| 14 | +import * as THREE from 'three'; |
| 15 | +import { type Mesh, Object3D } from 'three'; |
| 16 | + |
| 17 | +extend(THREE); |
| 18 | + |
| 19 | +@Directive({ selector: '[cursor]', standalone: true }) |
| 20 | +export class Cursor { |
| 21 | + constructor() { |
| 22 | + const elementRef = inject<ElementRef<Object3D>>(ElementRef); |
| 23 | + const nativeElement = elementRef.nativeElement; |
| 24 | + |
| 25 | + if (!nativeElement.isObject3D) return; |
| 26 | + |
| 27 | + const localState = getLocalState(nativeElement); |
| 28 | + if (!localState) return; |
| 29 | + |
| 30 | + const document = inject(DOCUMENT); |
| 31 | + |
| 32 | + injectObjectEvents(() => nativeElement, { |
| 33 | + pointerover: () => { |
| 34 | + document.body.style.cursor = 'pointer'; |
| 35 | + }, |
| 36 | + pointerout: () => { |
| 37 | + document.body.style.cursor = 'default'; |
| 38 | + }, |
| 39 | + }); |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +@Component({ |
| 44 | + standalone: true, |
| 45 | + template: ` |
| 46 | + <ngt-spot-light [position]="[5, 5, 5]" [intensity]="Math.PI" [decay]="0" /> |
| 47 | + <ngt-point-light [position]="[-10, -10, -10]" [decay]="0" /> |
| 48 | +
|
| 49 | + <ngt-mesh #mesh cursor (pointerover)="hovered.set(true)" (pointerout)="hovered.set(false)"> |
| 50 | + <ngt-box-geometry /> |
| 51 | + <ngt-mesh-standard-material [color]="hovered() ? 'mediumpurple' : 'maroon'" /> |
| 52 | + </ngt-mesh> |
| 53 | + `, |
| 54 | + schemas: [CUSTOM_ELEMENTS_SCHEMA], |
| 55 | + changeDetection: ChangeDetectionStrategy.OnPush, |
| 56 | + imports: [Cursor, NgtsEnvironment], |
| 57 | +}) |
| 58 | +export class SceneGraph { |
| 59 | + hovered = signal(false); |
| 60 | + |
| 61 | + meshRef = viewChild.required<ElementRef<Mesh>>('mesh'); |
| 62 | + |
| 63 | + constructor() { |
| 64 | + injectBeforeRender(() => { |
| 65 | + const mesh = this.meshRef().nativeElement; |
| 66 | + mesh.rotation.x += 0.01; |
| 67 | + mesh.rotation.y += 0.01; |
| 68 | + }); |
| 69 | + } |
| 70 | + |
| 71 | + protected readonly Math = Math; |
| 72 | +} |
| 73 | + |
| 74 | +@Component({ |
| 75 | + standalone: true, |
| 76 | + template: ` |
| 77 | + <ngt-canvas [sceneGraph]="sceneGraph" [camera]="{ position: [0, 0, 2] }" /> |
| 78 | + `, |
| 79 | + imports: [NgtCanvas], |
| 80 | + changeDetection: ChangeDetectionStrategy.OnPush, |
| 81 | + host: { class: 'cursor-scene' }, |
| 82 | +}) |
| 83 | +export default class CursorScene { |
| 84 | + sceneGraph = SceneGraph; |
| 85 | +} |
0 commit comments