audio_stream_player_2d.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. /*************************************************************************/
  2. /* audio_stream_player_2d.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "audio_stream_player_2d.h"
  31. #include "core/config/project_settings.h"
  32. #include "scene/2d/area_2d.h"
  33. #include "scene/2d/audio_listener_2d.h"
  34. #include "scene/main/window.h"
  35. #include "scene/resources/world_2d.h"
  36. void AudioStreamPlayer2D::_notification(int p_what) {
  37. switch (p_what) {
  38. case NOTIFICATION_ENTER_TREE: {
  39. AudioServer::get_singleton()->add_listener_changed_callback(_listener_changed_cb, this);
  40. if (autoplay && !Engine::get_singleton()->is_editor_hint()) {
  41. play();
  42. }
  43. } break;
  44. case NOTIFICATION_EXIT_TREE: {
  45. stop();
  46. AudioServer::get_singleton()->remove_listener_changed_callback(_listener_changed_cb, this);
  47. } break;
  48. case NOTIFICATION_PAUSED: {
  49. if (!can_process()) {
  50. // Node can't process so we start fading out to silence.
  51. set_stream_paused(true);
  52. }
  53. } break;
  54. case NOTIFICATION_UNPAUSED: {
  55. set_stream_paused(false);
  56. } break;
  57. case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
  58. // Update anything related to position first, if possible of course.
  59. if (setplay.get() > 0 || (active.is_set() && last_mix_count != AudioServer::get_singleton()->get_mix_count())) {
  60. _update_panning();
  61. }
  62. if (setplay.get() >= 0 && stream.is_valid()) {
  63. active.set();
  64. Ref<AudioStreamPlayback> new_playback = stream->instantiate_playback();
  65. ERR_FAIL_COND_MSG(new_playback.is_null(), "Failed to instantiate playback.");
  66. AudioServer::get_singleton()->start_playback_stream(new_playback, _get_actual_bus(), volume_vector, setplay.get(), pitch_scale);
  67. stream_playbacks.push_back(new_playback);
  68. setplay.set(-1);
  69. }
  70. if (!stream_playbacks.is_empty() && active.is_set()) {
  71. // Stop playing if no longer active.
  72. Vector<Ref<AudioStreamPlayback>> playbacks_to_remove;
  73. for (Ref<AudioStreamPlayback> &playback : stream_playbacks) {
  74. if (playback.is_valid() && !AudioServer::get_singleton()->is_playback_active(playback) && !AudioServer::get_singleton()->is_playback_paused(playback)) {
  75. playbacks_to_remove.push_back(playback);
  76. }
  77. }
  78. // Now go through and remove playbacks that have finished. Removing elements from a Vector in a range based for is asking for trouble.
  79. for (Ref<AudioStreamPlayback> &playback : playbacks_to_remove) {
  80. stream_playbacks.erase(playback);
  81. }
  82. if (!playbacks_to_remove.is_empty() && stream_playbacks.is_empty()) {
  83. // This node is no longer actively playing audio.
  84. active.clear();
  85. set_physics_process_internal(false);
  86. }
  87. if (!playbacks_to_remove.is_empty()) {
  88. emit_signal(SNAME("finished"));
  89. }
  90. }
  91. while (stream_playbacks.size() > max_polyphony) {
  92. AudioServer::get_singleton()->stop_playback_stream(stream_playbacks[0]);
  93. stream_playbacks.remove_at(0);
  94. }
  95. } break;
  96. }
  97. }
  98. StringName AudioStreamPlayer2D::_get_actual_bus() {
  99. Vector2 global_pos = get_global_position();
  100. //check if any area is diverting sound into a bus
  101. Ref<World2D> world_2d = get_world_2d();
  102. ERR_FAIL_COND_V(world_2d.is_null(), SNAME("Master"));
  103. PhysicsDirectSpaceState2D *space_state = PhysicsServer2D::get_singleton()->space_get_direct_state(world_2d->get_space());
  104. PhysicsDirectSpaceState2D::ShapeResult sr[MAX_INTERSECT_AREAS];
  105. PhysicsDirectSpaceState2D::PointParameters point_params;
  106. point_params.position = global_pos;
  107. point_params.collision_mask = area_mask;
  108. point_params.collide_with_bodies = false;
  109. point_params.collide_with_areas = true;
  110. int areas = space_state->intersect_point(point_params, sr, MAX_INTERSECT_AREAS);
  111. for (int i = 0; i < areas; i++) {
  112. Area2D *area2d = Object::cast_to<Area2D>(sr[i].collider);
  113. if (!area2d) {
  114. continue;
  115. }
  116. if (!area2d->is_overriding_audio_bus()) {
  117. continue;
  118. }
  119. return area2d->get_audio_bus_name();
  120. }
  121. return default_bus;
  122. }
  123. void AudioStreamPlayer2D::_update_panning() {
  124. if (!active.is_set() || stream.is_null()) {
  125. return;
  126. }
  127. Ref<World2D> world_2d = get_world_2d();
  128. ERR_FAIL_COND(world_2d.is_null());
  129. Vector2 global_pos = get_global_position();
  130. HashSet<Viewport *> viewports = world_2d->get_viewports();
  131. viewports.insert(get_viewport()); // TODO: This is a mediocre workaround for #50958. Remove when that bug is fixed!
  132. volume_vector.resize(4);
  133. volume_vector.write[0] = AudioFrame(0, 0);
  134. volume_vector.write[1] = AudioFrame(0, 0);
  135. volume_vector.write[2] = AudioFrame(0, 0);
  136. volume_vector.write[3] = AudioFrame(0, 0);
  137. for (Viewport *vp : viewports) {
  138. if (!vp->is_audio_listener_2d()) {
  139. continue;
  140. }
  141. //compute matrix to convert to screen
  142. Vector2 screen_size = vp->get_visible_rect().size;
  143. Vector2 listener_in_global;
  144. Vector2 relative_to_listener;
  145. //screen in global is used for attenuation
  146. AudioListener2D *listener = vp->get_audio_listener_2d();
  147. if (listener) {
  148. listener_in_global = listener->get_global_position();
  149. relative_to_listener = global_pos - listener_in_global;
  150. } else {
  151. Transform2D to_listener = vp->get_global_canvas_transform() * vp->get_canvas_transform();
  152. listener_in_global = to_listener.affine_inverse().xform(screen_size * 0.5);
  153. relative_to_listener = to_listener.xform(global_pos) - screen_size * 0.5;
  154. }
  155. float dist = global_pos.distance_to(listener_in_global); // Distance to listener, or screen if none.
  156. if (dist > max_distance) {
  157. continue; //can't hear this sound in this viewport
  158. }
  159. float multiplier = Math::pow(1.0f - dist / max_distance, attenuation);
  160. multiplier *= Math::db_to_linear(volume_db); //also apply player volume!
  161. float pan = relative_to_listener.x / screen_size.x;
  162. // Don't let the panning effect extend (too far) beyond the screen.
  163. pan = CLAMP(pan, -1, 1);
  164. // Bake in a constant factor here to allow the project setting defaults for 2d and 3d to be normalized to 1.0.
  165. pan *= panning_strength * cached_global_panning_strength * 0.5f;
  166. pan = CLAMP(pan + 0.5, 0.0, 1.0);
  167. float l = 1.0 - pan;
  168. float r = pan;
  169. volume_vector.write[0] = AudioFrame(l, r) * multiplier;
  170. }
  171. for (const Ref<AudioStreamPlayback> &playback : stream_playbacks) {
  172. AudioServer::get_singleton()->set_playback_bus_exclusive(playback, _get_actual_bus(), volume_vector);
  173. }
  174. for (Ref<AudioStreamPlayback> &playback : stream_playbacks) {
  175. AudioServer::get_singleton()->set_playback_pitch_scale(playback, pitch_scale);
  176. }
  177. last_mix_count = AudioServer::get_singleton()->get_mix_count();
  178. }
  179. void AudioStreamPlayer2D::set_stream(Ref<AudioStream> p_stream) {
  180. stop();
  181. stream = p_stream;
  182. }
  183. Ref<AudioStream> AudioStreamPlayer2D::get_stream() const {
  184. return stream;
  185. }
  186. void AudioStreamPlayer2D::set_volume_db(float p_volume) {
  187. volume_db = p_volume;
  188. }
  189. float AudioStreamPlayer2D::get_volume_db() const {
  190. return volume_db;
  191. }
  192. void AudioStreamPlayer2D::set_pitch_scale(float p_pitch_scale) {
  193. ERR_FAIL_COND(p_pitch_scale <= 0.0);
  194. pitch_scale = p_pitch_scale;
  195. for (Ref<AudioStreamPlayback> &playback : stream_playbacks) {
  196. AudioServer::get_singleton()->set_playback_pitch_scale(playback, p_pitch_scale);
  197. }
  198. }
  199. float AudioStreamPlayer2D::get_pitch_scale() const {
  200. return pitch_scale;
  201. }
  202. void AudioStreamPlayer2D::play(float p_from_pos) {
  203. if (stream.is_null()) {
  204. return;
  205. }
  206. ERR_FAIL_COND_MSG(!is_inside_tree(), "Playback can only happen when a node is inside the scene tree");
  207. if (stream->is_monophonic() && is_playing()) {
  208. stop();
  209. }
  210. setplay.set(p_from_pos);
  211. active.set();
  212. set_physics_process_internal(true);
  213. }
  214. void AudioStreamPlayer2D::seek(float p_seconds) {
  215. if (is_playing()) {
  216. stop();
  217. play(p_seconds);
  218. }
  219. }
  220. void AudioStreamPlayer2D::stop() {
  221. setplay.set(-1);
  222. for (Ref<AudioStreamPlayback> &playback : stream_playbacks) {
  223. AudioServer::get_singleton()->stop_playback_stream(playback);
  224. }
  225. stream_playbacks.clear();
  226. active.clear();
  227. set_physics_process_internal(false);
  228. }
  229. bool AudioStreamPlayer2D::is_playing() const {
  230. for (const Ref<AudioStreamPlayback> &playback : stream_playbacks) {
  231. if (AudioServer::get_singleton()->is_playback_active(playback)) {
  232. return true;
  233. }
  234. }
  235. return false;
  236. }
  237. float AudioStreamPlayer2D::get_playback_position() {
  238. // Return the playback position of the most recently started playback stream.
  239. if (!stream_playbacks.is_empty()) {
  240. return AudioServer::get_singleton()->get_playback_position(stream_playbacks[stream_playbacks.size() - 1]);
  241. }
  242. return 0;
  243. }
  244. void AudioStreamPlayer2D::set_bus(const StringName &p_bus) {
  245. default_bus = p_bus; // This will be pushed to the audio server during the next physics timestep, which is fast enough.
  246. }
  247. StringName AudioStreamPlayer2D::get_bus() const {
  248. for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
  249. if (AudioServer::get_singleton()->get_bus_name(i) == default_bus) {
  250. return default_bus;
  251. }
  252. }
  253. return SNAME("Master");
  254. }
  255. void AudioStreamPlayer2D::set_autoplay(bool p_enable) {
  256. autoplay = p_enable;
  257. }
  258. bool AudioStreamPlayer2D::is_autoplay_enabled() {
  259. return autoplay;
  260. }
  261. void AudioStreamPlayer2D::_set_playing(bool p_enable) {
  262. if (p_enable) {
  263. play();
  264. } else {
  265. stop();
  266. }
  267. }
  268. bool AudioStreamPlayer2D::_is_active() const {
  269. return active.is_set();
  270. }
  271. void AudioStreamPlayer2D::_validate_property(PropertyInfo &p_property) const {
  272. if (p_property.name == "bus") {
  273. String options;
  274. for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
  275. if (i > 0) {
  276. options += ",";
  277. }
  278. String name = AudioServer::get_singleton()->get_bus_name(i);
  279. options += name;
  280. }
  281. p_property.hint_string = options;
  282. }
  283. }
  284. void AudioStreamPlayer2D::_bus_layout_changed() {
  285. notify_property_list_changed();
  286. }
  287. void AudioStreamPlayer2D::set_max_distance(float p_pixels) {
  288. ERR_FAIL_COND(p_pixels <= 0.0);
  289. max_distance = p_pixels;
  290. }
  291. float AudioStreamPlayer2D::get_max_distance() const {
  292. return max_distance;
  293. }
  294. void AudioStreamPlayer2D::set_attenuation(float p_curve) {
  295. attenuation = p_curve;
  296. }
  297. float AudioStreamPlayer2D::get_attenuation() const {
  298. return attenuation;
  299. }
  300. void AudioStreamPlayer2D::set_area_mask(uint32_t p_mask) {
  301. area_mask = p_mask;
  302. }
  303. uint32_t AudioStreamPlayer2D::get_area_mask() const {
  304. return area_mask;
  305. }
  306. void AudioStreamPlayer2D::set_stream_paused(bool p_pause) {
  307. // TODO this does not have perfect recall, fix that maybe? If there are zero playbacks registered with the AudioServer, this bool isn't persisted.
  308. for (Ref<AudioStreamPlayback> &playback : stream_playbacks) {
  309. AudioServer::get_singleton()->set_playback_paused(playback, p_pause);
  310. }
  311. }
  312. bool AudioStreamPlayer2D::get_stream_paused() const {
  313. // There's currently no way to pause some playback streams but not others. Check the first and don't bother looking at the rest.
  314. if (!stream_playbacks.is_empty()) {
  315. return AudioServer::get_singleton()->is_playback_paused(stream_playbacks[0]);
  316. }
  317. return false;
  318. }
  319. Ref<AudioStreamPlayback> AudioStreamPlayer2D::get_stream_playback() {
  320. if (!stream_playbacks.is_empty()) {
  321. return stream_playbacks[stream_playbacks.size() - 1];
  322. }
  323. return nullptr;
  324. }
  325. void AudioStreamPlayer2D::set_max_polyphony(int p_max_polyphony) {
  326. if (p_max_polyphony > 0) {
  327. max_polyphony = p_max_polyphony;
  328. }
  329. }
  330. int AudioStreamPlayer2D::get_max_polyphony() const {
  331. return max_polyphony;
  332. }
  333. void AudioStreamPlayer2D::set_panning_strength(float p_panning_strength) {
  334. ERR_FAIL_COND_MSG(p_panning_strength < 0, "Panning strength must be a positive number.");
  335. panning_strength = p_panning_strength;
  336. }
  337. float AudioStreamPlayer2D::get_panning_strength() const {
  338. return panning_strength;
  339. }
  340. void AudioStreamPlayer2D::_bind_methods() {
  341. ClassDB::bind_method(D_METHOD("set_stream", "stream"), &AudioStreamPlayer2D::set_stream);
  342. ClassDB::bind_method(D_METHOD("get_stream"), &AudioStreamPlayer2D::get_stream);
  343. ClassDB::bind_method(D_METHOD("set_volume_db", "volume_db"), &AudioStreamPlayer2D::set_volume_db);
  344. ClassDB::bind_method(D_METHOD("get_volume_db"), &AudioStreamPlayer2D::get_volume_db);
  345. ClassDB::bind_method(D_METHOD("set_pitch_scale", "pitch_scale"), &AudioStreamPlayer2D::set_pitch_scale);
  346. ClassDB::bind_method(D_METHOD("get_pitch_scale"), &AudioStreamPlayer2D::get_pitch_scale);
  347. ClassDB::bind_method(D_METHOD("play", "from_position"), &AudioStreamPlayer2D::play, DEFVAL(0.0));
  348. ClassDB::bind_method(D_METHOD("seek", "to_position"), &AudioStreamPlayer2D::seek);
  349. ClassDB::bind_method(D_METHOD("stop"), &AudioStreamPlayer2D::stop);
  350. ClassDB::bind_method(D_METHOD("is_playing"), &AudioStreamPlayer2D::is_playing);
  351. ClassDB::bind_method(D_METHOD("get_playback_position"), &AudioStreamPlayer2D::get_playback_position);
  352. ClassDB::bind_method(D_METHOD("set_bus", "bus"), &AudioStreamPlayer2D::set_bus);
  353. ClassDB::bind_method(D_METHOD("get_bus"), &AudioStreamPlayer2D::get_bus);
  354. ClassDB::bind_method(D_METHOD("set_autoplay", "enable"), &AudioStreamPlayer2D::set_autoplay);
  355. ClassDB::bind_method(D_METHOD("is_autoplay_enabled"), &AudioStreamPlayer2D::is_autoplay_enabled);
  356. ClassDB::bind_method(D_METHOD("_set_playing", "enable"), &AudioStreamPlayer2D::_set_playing);
  357. ClassDB::bind_method(D_METHOD("_is_active"), &AudioStreamPlayer2D::_is_active);
  358. ClassDB::bind_method(D_METHOD("set_max_distance", "pixels"), &AudioStreamPlayer2D::set_max_distance);
  359. ClassDB::bind_method(D_METHOD("get_max_distance"), &AudioStreamPlayer2D::get_max_distance);
  360. ClassDB::bind_method(D_METHOD("set_attenuation", "curve"), &AudioStreamPlayer2D::set_attenuation);
  361. ClassDB::bind_method(D_METHOD("get_attenuation"), &AudioStreamPlayer2D::get_attenuation);
  362. ClassDB::bind_method(D_METHOD("set_area_mask", "mask"), &AudioStreamPlayer2D::set_area_mask);
  363. ClassDB::bind_method(D_METHOD("get_area_mask"), &AudioStreamPlayer2D::get_area_mask);
  364. ClassDB::bind_method(D_METHOD("set_stream_paused", "pause"), &AudioStreamPlayer2D::set_stream_paused);
  365. ClassDB::bind_method(D_METHOD("get_stream_paused"), &AudioStreamPlayer2D::get_stream_paused);
  366. ClassDB::bind_method(D_METHOD("set_max_polyphony", "max_polyphony"), &AudioStreamPlayer2D::set_max_polyphony);
  367. ClassDB::bind_method(D_METHOD("get_max_polyphony"), &AudioStreamPlayer2D::get_max_polyphony);
  368. ClassDB::bind_method(D_METHOD("set_panning_strength", "panning_strength"), &AudioStreamPlayer2D::set_panning_strength);
  369. ClassDB::bind_method(D_METHOD("get_panning_strength"), &AudioStreamPlayer2D::get_panning_strength);
  370. ClassDB::bind_method(D_METHOD("get_stream_playback"), &AudioStreamPlayer2D::get_stream_playback);
  371. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "stream", PROPERTY_HINT_RESOURCE_TYPE, "AudioStream"), "set_stream", "get_stream");
  372. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "volume_db", PROPERTY_HINT_RANGE, "-80,24,suffix:dB"), "set_volume_db", "get_volume_db");
  373. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "pitch_scale", PROPERTY_HINT_RANGE, "0.01,4,0.01,or_greater"), "set_pitch_scale", "get_pitch_scale");
  374. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "playing", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "_set_playing", "is_playing");
  375. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "autoplay"), "set_autoplay", "is_autoplay_enabled");
  376. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "stream_paused", PROPERTY_HINT_NONE, ""), "set_stream_paused", "get_stream_paused");
  377. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "max_distance", PROPERTY_HINT_RANGE, "1,4096,1,or_greater,exp,suffix:px"), "set_max_distance", "get_max_distance");
  378. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "attenuation", PROPERTY_HINT_EXP_EASING, "attenuation"), "set_attenuation", "get_attenuation");
  379. ADD_PROPERTY(PropertyInfo(Variant::INT, "max_polyphony", PROPERTY_HINT_NONE, ""), "set_max_polyphony", "get_max_polyphony");
  380. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "panning_strength", PROPERTY_HINT_RANGE, "0,3,0.01,or_greater"), "set_panning_strength", "get_panning_strength");
  381. ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "bus", PROPERTY_HINT_ENUM, ""), "set_bus", "get_bus");
  382. ADD_PROPERTY(PropertyInfo(Variant::INT, "area_mask", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_area_mask", "get_area_mask");
  383. ADD_SIGNAL(MethodInfo("finished"));
  384. }
  385. AudioStreamPlayer2D::AudioStreamPlayer2D() {
  386. AudioServer::get_singleton()->connect("bus_layout_changed", callable_mp(this, &AudioStreamPlayer2D::_bus_layout_changed));
  387. cached_global_panning_strength = ProjectSettings::get_singleton()->get("audio/general/2d_panning_strength");
  388. }
  389. AudioStreamPlayer2D::~AudioStreamPlayer2D() {
  390. }