Debian Codegraph @

src/transform/castlebehaviors_soundsource.inc

raw
1 {%MainUnit castlebehaviors.pas}
2 {
3 Copyright 2006-2022 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 {$ifdef read_interface}
18
19 type
20 TCastleSoundSource = class;
21
22 { Controls a sound playback initiated by @link(TCastleSoundSource.Play).
23 See the ancestor TCastlePlayingSound for most important documentation.
24 This class simply extends the ancestor with some properties useful only
25 together with the TCastleSoundSource. }
26 TCastlePlayingSoundSource = class(TCastlePlayingSound)
27 strict private
28 FFollow: Boolean;
29 FSoundHeight: Single;
30 LastPosition: TVector3;
31 private
32 SourceBehavior: TCastleSoundSource; //< non-nil while TCastleSoundSource exists
33 HasLastPosition: Boolean;
34 procedure Update(const SecondsPassed: Single);
35 protected
36 procedure DoStop; override;
37 public
38 constructor Create(AOwner: TComponent); override;
39 function InternalFinalVolume: Single; override;
40 function InternalFinalPitch: Single; override;
41 function InternalFinalPriority: Single; override;
42
43 { If Follow then the sound position will be updated
44 as the parent TCastleTransform moves. Moreover, when TCastleSoundSource
45 will be destroyed, the sound will stop.
46 An example would be a walking sound of a creature -- the sound moves
47 together with the creature.
48
49 If not Follow, then
50 the sound will start at the parent's position, and then
51 it will continue to be played independent of the parent existence
52 or position changes.
53 An example would be an explosion sound -- the sound stays
54 at the position it happened, regardless if the object moved.
55
56 This matters only for spatial sounds (@link(TCastleSoundSource.Spatial)). }
57 property Follow: Boolean read FFollow write FFollow default true;
58
59 { The exact sound position reflects the transformation of the TCastleSoundSource,
60 either
61 @link(TCastleTransform.Translation Parent.Translation) or
62 @link(TCastleTransform.Middle Parent.Middle).
63 Use this property to control which one, it makes a linear interpolation
64 between them.
65
66 SoundHeight = 0 means to use
67 @link(TCastleTransform.Translation Parent.Translation),
68 SoundHeight = 1 means @link(TCastleTransform.Middle Parent.Middle)
69 other values imply a linear interpolation between the above two values.
70
71 You can conigure @link(TCastleTransform.Middle Parent.Middle)
72 using @link(TCastleTransform.MiddleHeight Parent.MiddleHeight). }
73 property SoundHeight: Single read FSoundHeight write FSoundHeight
74 {$ifdef FPC}default 0.0{$endif};
75 end;
76
77 { Behavior to play spatial sounds, that automatically follow
78 the parent @link(TCastleTransform) transformation.
79 Multiple such behaviors may be attached to a single TCastleTransform
80 (if you need to play multiple looping sounds, or want to have multiple
81 playback settings like different @link(Volume) control). }
82 TCastleSoundSource = class(TCastleBehavior)
83 strict private
84 FSound: TCastleSound;
85 FSpatial: Boolean;
86 FVolume: Single;
87 FPitch: Single;
88 FPriority: Single;
89 FSoundPlaying: Boolean;
90 procedure SoundChange(const Sender: TCastleSound; const Change: TSoundChange);
91 procedure SetSound(const Value: TCastleSound);
92 procedure SetSpatial(const Value: Boolean);
93 procedure SetVolume(const Value: Single);
94 procedure SetPitch(const Value: Single);
95 procedure SetPriority(const Value: Single);
96 procedure SetSoundPlaying(const Value: Boolean);
97 { Start playing current @link(Sound)
98 (ignored if Sound = @nil, ignored if SoundPlaying = @false).
99 MainPlayingSound must be @nil when calling this, so the sound cannot be already playing. }
100 procedure SoundStart;
101 { Stop playing current @link(Sound), if currently playing. }
102 procedure SoundStop;
103 private
104 type
105 TCastlePlayingSoundSourceList = {$ifdef FPC}specialize{$endif} TObjectList<TCastlePlayingSoundSource>;
106 var
107 AllPlayingSounds: TCastlePlayingSoundSourceList;
108 MainPlayingSound: TCastlePlayingSoundSource; //< TCastlePlayingSoundSource corresponding to main Sound
109 function GetSoundPosition(const SoundHeight: Single): TVector3;
110 protected
111 procedure ParentAfterAttach; override;
112 procedure ParentBeforeDetach; override;
113 procedure Notification(AComponent: TComponent; Operation: TOperation); override;
114 public
115 constructor Create(AOwner: TComponent); override;
116 destructor Destroy; override;
117 procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); override;
118 function PropertySections(const PropertyName: String): TPropertySections; override;
119
120 { Play given sound once (not looping).
121 If the sound source is spatial (@link(TCastleSoundSource.Spatial)),
122 it's 3D position will reflect the @link(Parent) (TCastleTransform) position. }
123 procedure Play(const ASound: TCastleSound); overload;
124
125 { Play given sound.
126 If the sound source is spatial (@link(TCastleSoundSource.Spatial)),
127 it's 3D position will reflect the @link(Parent) (TCastleTransform) position.
128
129 Set @link(TCastlePlayingSound.Sound) before passing it to this method.
130 Otherwise, if @link(TCastlePlayingSound.Sound) is left @nil, nothing will be played.
131
132 Use the TCastlePlayingSound properties to provide additional information
133 about the sound playback.
134 E.g. assign @link(TCastlePlayingSound.Loop)
135 @link(TCastlePlayingSound.OnStop) or control sound afterwards by
136 @link(TCastlePlayingSound.Stop), @link(TCastlePlayingSound.Offset).
137
138 Consider using @link(TCastlePlayingSound.FreeOnStop) if you don't want
139 to manage the lifetime of the @link(TCastlePlayingSound) instance. }
140 procedure Play(const PlayingSound: TCastlePlayingSoundSource); overload;
141 published
142 { Sound to play, always looping.
143 Control playback of it using @link(SoundPlaying).
144
145 Note that this is not the only sound possible to play using this
146 @link(TCastleSoundSource). You can play any other @link(TCastleSound)
147 or @link(TCastlePlayingSoundSource) instance (looping or not looping)
148 by calling @link(Play) method. }
149 property Sound: TCastleSound read FSound write SetSound;
150
151 { Is the @link(Sound) currently playing.
152 Setting it to @false and back to @true will restart playing sound from the beginning. }
153 property SoundPlaying: Boolean read FSoundPlaying write SetSoundPlaying default true;
154
155 { Is the sound playback spatialized. Affects sounds played by assigning @link(Sound)
156 or calling @link(Play) here.
157
158 Spatial sounds are louder/more silent depending on their 3D distance to listener
159 (this means a distance from TCastleTransform origin to the camera within
160 the TCastleViewport). And their relative position to the listener in 3D
161 is reflected by making them louder/more silent in the proper
162 (e.g. left or right) speaker.
163
164 Note that some sound backends (like OpenAL) can only spatialize mono sounds,
165 and play stereo sounds always as non-spatialized. }
166 property Spatial: Boolean read FSpatial write SetSpatial default true;
167
168 { Volume (how loud the playing sound is).
169
170 The effective sound volume is a multiplication of @link(TCastleSound.Volume),
171 @link(TCastlePlayingSound.Volume) and @link(TCastleSoundSource.Volume).
172 It is also affected by spatial calculations (if the sound is played
173 with @link(TCastleSoundSource.Spatial) = @true)
174 and finally by a master @link(TSoundEngine.Volume SoundEngine.Volume).
175
176 Any value > 0 is allowed. }
177 property Volume: Single read FVolume write SetVolume
178 {$ifdef FPC}default 1.0{$endif};
179
180 { Sound playing speed.
181
182 The effective sound pitch is a multiplication of @link(TCastleSound.Pitch),
183 @link(TCastlePlayingSound.Pitch) and @link(TCastleSoundSource.Pitch).
184
185 Any value > 0 is allowed. }
186 property Pitch: Single read FPitch write SetPitch
187 {$ifdef FPC}default 1.0{$endif};
188
189 { How important is the sound, between 0.0 (least important) to 1.0 (most important).
190
191 The effective priority is a multiplication of @link(TCastleSound.Priority),
192 @link(TCastlePlayingSound.Priority) and @link(TCastleSoundSource.Priority).
193
194 Any value > 0 is allowed. }
195 property Priority: Single read FPriority write SetPriority
196 {$ifdef FPC}default 1.0{$endif};
197 end;
198
199 {$endif read_interface}
200
201 {$ifdef read_implementation}
202
203 { TCastlePlayingSoundSource ---------------------------------------------- }
204
205 constructor TCastlePlayingSoundSource.Create(AOwner: TComponent);
206 begin
207 inherited;
208 FFollow := true;
209 end;
210
211 procedure TCastlePlayingSoundSource.DoStop;
212 begin
213 // we override DoStop, instead of using OnStop, to allow user code to assign OnStop as needed
214 if SourceBehavior <> nil then
215 begin
216 SourceBehavior.AllPlayingSounds.Remove(Self);
217 if SourceBehavior.MainPlayingSound = Self then
218 SourceBehavior.MainPlayingSound := nil;
219 SourceBehavior := nil;
220 end;
221 inherited;
222 end;
223
224 procedure TCastlePlayingSoundSource.Update(const SecondsPassed: Single);
225 const
226 MaxVelocityLength = 20;
227 var
228 NewPosition, NewVelocity: TVector3;
229 begin
230 if (SourceBehavior <> nil) and
231 (InternalSource <> nil) and
232 { If not Spatial, then we don't need to update Source.Position
233 (it is ignored by backends). }
234 InternalSource.Spatial and
235 Follow then
236 begin
237 NewPosition := SourceBehavior.GetSoundPosition(SoundHeight);
238 InternalSource.Position := NewPosition;
239
240 { update InternalSource.Velocity, to hear Doppler effect. }
241 if HasLastPosition and (SecondsPassed > SingleEpsilon) then
242 begin
243 NewVelocity := (NewPosition - LastPosition) / SecondsPassed;
244 { Clamp NewVelocity length, to not cause too crazy Doppler because
245 of temporary high speed.
246 Testcase: examples/audio/doppler_demo, drag with mouse fast. }
247 if NewVelocity.LengthSqr > Sqr(MaxVelocityLength) then
248 NewVelocity := NewVelocity.AdjustToLength(MaxVelocityLength);
249 InternalSource.Velocity := NewVelocity;
250 end;
251 HasLastPosition := true;
252 LastPosition := NewPosition;
253 end else
254 HasLastPosition := false;
255 end;
256
257 function TCastlePlayingSoundSource.InternalFinalVolume: Single;
258 begin
259 Result := inherited;
260 if SourceBehavior <> nil then
261 Result := Result * SourceBehavior.Volume;
262 end;
263
264 function TCastlePlayingSoundSource.InternalFinalPitch: Single;
265 begin
266 Result := inherited;
267 if SourceBehavior <> nil then
268 Result := Result * SourceBehavior.Pitch;
269 end;
270
271 function TCastlePlayingSoundSource.InternalFinalPriority: Single;
272 begin
273 Result := inherited;
274 if SourceBehavior <> nil then
275 Result := Result * SourceBehavior.Priority;
276 end;
277
278 { TCastleSoundSource ------------------------------------------------------- }
279
280 constructor TCastleSoundSource.Create(AOwner: TComponent);
281 begin
282 inherited;
283 AllPlayingSounds := TCastlePlayingSoundSourceList.Create(false);
284 FSpatial := true;
285 FVolume := 1.0;
286 FPitch := 1.0;
287 FPriority := 1.0;
288 FSoundPlaying := true;
289 end;
290
291 destructor TCastleSoundSource.Destroy;
292 var
293 Playing: TCastlePlayingSoundSource;
294 begin
295 if AllPlayingSounds <> nil then
296 begin
297 for Playing in AllPlayingSounds do
298 begin
299 { In case of Playing.Follow = true, this is needed:
300 Otherwise Playing.DoStop would call our SoundStop,
301 and this would remove it from AllPlayingSounds list, breaking our
302 indexing over this list here.
303
304 In case of Playing.Follow = false, this is needed even more:
305 the TCastlePlayingSound instance will survive destruction of this TCastleSoundSource,
306 but it should not call any of TCastleSoundSource methods. }
307 Playing.SourceBehavior := nil;
308 if Playing.Follow then
309 Playing.Stop;
310 end;
311 FreeAndNil(AllPlayingSounds);
312 end;
313
314 { We now for sure stopped this sound.
315 But we cleared SourceBehavior above, so it didn't set itself to nil
316 in TCastlePlayingSoundSource.DoStop.
317 So we need to nil it manually. }
318 MainPlayingSound := nil;
319
320 // detach free notifications
321 Sound := nil;
322
323 inherited;
324 end;
325
326 function TCastleSoundSource.PropertySections(const PropertyName: String): TPropertySections;
327 begin
328 if ArrayContainsString(PropertyName, [
329 'Sound', 'Spatial', 'Volume', 'Pitch', 'Priority', 'SoundPlaying'
330 ]) then
331 Result := [psBasic]
332 else
333 Result := inherited PropertySections(PropertyName);
334 end;
335
336 procedure TCastleSoundSource.Update(const SecondsPassed: Single; var RemoveMe: TRemoveType);
337 var
338 Playing: TCastlePlayingSoundSource;
339 begin
340 inherited;
341 for Playing in AllPlayingSounds do
342 Playing.Update(SecondsPassed);
343 end;
344
345 function TCastleSoundSource.GetSoundPosition(const SoundHeight: Single): TVector3;
346
347 function LerpLegsMiddle(const A: Single): TVector3;
348 begin
349 { Check "Parent.World <> nil", otherwise Parent.Middle not available.
350 Check also A <> 0, as just optimization -- A = 0 is an often case,
351 that avoids the need to calculate Parent.Middle. }
352 if (Parent.World <> nil) and (A <> 0) then
353 Result := Lerp(A, Parent.Translation, Parent.Middle)
354 else
355 Result := Parent.Translation;
356 end;
357
358 begin
359 Result := LerpLegsMiddle(SoundHeight);
360 if (Parent <> nil) and
361 (Parent.Parent <> nil) then // make sound position in world coordinates
362 Result := Parent.Parent.LocalToWorld(Result);
363 end;
364
365 procedure TCastleSoundSource.Play(const ASound: TCastleSound);
366 var
367 Playing: TCastlePlayingSoundSource;
368 begin
369 Playing := TCastlePlayingSoundSource.Create(nil);
370 Playing.Sound := ASound;
371 Playing.FreeOnStop := true;
372 Play(Playing);
373 end;
374
375 procedure TCastleSoundSource.Play(const PlayingSound: TCastlePlayingSoundSource);
376 var
377 SoundPosition: TVector3;
378 begin
379 if Parent = nil then
380 raise Exception.Create('Do not play sounds from a TCastleSoundSource not attached to any TCastleTransform; use SoundEngine.Play for sound playback without TCastleSoundSource');
381
382 SoundPosition := GetSoundPosition(PlayingSound.SoundHeight);
383
384 { Add to AllPlayingSounds and set PlayingSound.SourceBehavior early,
385 before calling SoundEngine.Play, as SoundEngine.Play may immediately stop it
386 (e.g. if no free TInternalSoundSource slots). }
387 PlayingSound.SourceBehavior := Self;
388 AllPlayingSounds.Add(PlayingSound);
389
390 SoundEngine.InternalPlay(PlayingSound, Spatial, SoundPosition);
391 end;
392
393 procedure TCastleSoundSource.SoundStop;
394 begin
395 if MainPlayingSound <> nil then
396 MainPlayingSound.Stop;
397 end;
398
399 procedure TCastleSoundSource.SoundStart;
400 begin
401 Assert(MainPlayingSound = nil);
402 if (Sound <> nil) and SoundPlaying and (Parent <> nil) then
403 begin
404 MainPlayingSound := TCastlePlayingSoundSource.Create(nil);
405 MainPlayingSound.Sound := Sound;
406 MainPlayingSound.FreeOnStop := true;
407 { Loop and Follow = true in this case,
408 it seems most natural for sounds set as TCastleSoundSource.Sound. }
409 MainPlayingSound.Loop := true;
410 Play(MainPlayingSound);
411 end;
412 end;
413
414 procedure TCastleSoundSource.SoundChange(const Sender: TCastleSound; const Change: TSoundChange);
415 begin
416 case Change of
417 scAfterBufferCreated: SoundStart;
418 else ;
419 // scAfterOther handled by TCastlePlayingSound
420 // scBeforeBufferDestroyed also handled by TCastlePlayingSound, it will stop sound making MainPlayingSound -> nil
421 end;
422 end;
423
424 procedure TCastleSoundSource.ParentAfterAttach;
425 var
426 Playing: TCastlePlayingSoundSource;
427 begin
428 inherited;
429
430 // start playing, once we have Parent assigned
431 if MainPlayingSound = nil then
432 SoundStart;
433
434 { Change of parent implies also a sudden change of position,
435 so do not use last position for Doppler effect calculation. }
436 for Playing in AllPlayingSounds do
437 Playing.HasLastPosition := false;
438 end;
439
440 procedure TCastleSoundSource.ParentBeforeDetach;
441 begin
442 // stop playing when Parent detached,
443 // we could not realize Follow in this case (GetSoundPosition would crash)
444 SoundStop;
445 inherited;
446 end;
447
448 procedure TCastleSoundSource.SetSound(const Value: TCastleSound);
449 begin
450 if FSound <> Value then
451 begin
452 if FSound <> nil then
453 begin
454 SoundStop;
455 FSound.InternalRemoveChangeNotification({$ifdef FPC}@{$endif}SoundChange);
456 FSound.RemoveFreeNotification(Self);
457 end;
458 FSound := Value;
459 if FSound <> nil then
460 begin
461 FSound.InternalAddChangeNotification({$ifdef FPC}@{$endif}SoundChange);
462 FSound.FreeNotification(Self);
463 SoundStart;
464 end;
465 end;
466 end;
467
468 procedure TCastleSoundSource.SetSoundPlaying(const Value: Boolean);
469 begin
470 if FSoundPlaying <> Value then
471 begin
472 FSoundPlaying := Value;
473 if Value then
474 SoundStart
475 else
476 SoundStop;
477 end;
478 end;
479
480 procedure TCastleSoundSource.Notification(AComponent: TComponent; Operation: TOperation);
481 begin
482 inherited;
483 { set to nil by setter to clean nicely }
484 if (Operation = opRemove) and (AComponent = FSound) then
485 Sound := nil;
486 end;
487
488 procedure TCastleSoundSource.SetSpatial(const Value: Boolean);
489 begin
490 if FSpatial <> Value then
491 begin
492 FSpatial := Value;
493 if (MainPlayingSound <> nil) and
494 (MainPlayingSound.InternalSource <> nil) then
495 MainPlayingSound.InternalSource.Spatial := Spatial;
496 end;
497 end;
498
499 procedure TCastleSoundSource.SetVolume(const Value: Single);
500 begin
501 if FVolume <> Value then
502 begin
503 FVolume := Value;
504 { Update because MainPlayingSound.InternalFinalVolume changed,
505 just like TCastlePlayingSound.SoundChangeDuringPlayback does. }
506 if (MainPlayingSound <> nil) and
507 (MainPlayingSound.InternalSource <> nil) then
508 MainPlayingSound.InternalSource.Volume := MainPlayingSound.InternalFinalVolume;
509 end;
510 end;
511
512 procedure TCastleSoundSource.SetPitch(const Value: Single);
513 begin
514 if FPitch <> Value then
515 begin
516 FPitch := Value;
517 { Update because MainPlayingSound.InternalFinalVolume changed,
518 just like TCastlePlayingSound.SoundChangeDuringPlayback does. }
519 if (MainPlayingSound <> nil) and
520 (MainPlayingSound.InternalSource <> nil) then
521 MainPlayingSound.InternalSource.Pitch := MainPlayingSound.InternalFinalPitch;
522 end;
523 end;
524
525 procedure TCastleSoundSource.SetPriority(const Value: Single);
526 begin
527 if FPriority <> Value then
528 begin
529 FPriority := Value;
530 { Update because MainPlayingSound.InternalFinalPriority changed,
531 just like TCastlePlayingSound.SoundChangeDuringPlayback does. }
532 if (MainPlayingSound <> nil) and
533 (MainPlayingSound.InternalSource <> nil) then
534 MainPlayingSound.InternalSource.Priority := MainPlayingSound.InternalFinalPriority;
535 end;
536 end;
537
538 {$endif read_implementation}