From 806228299e20838bca9ffab77abd303c6f025921 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Sun, 15 Jul 2018 10:31:48 +1200 Subject: [PATCH 01/37] Stub out Audio JSDoc --- interface/src/scripting/Audio.h | 54 ++++++++++------- libraries/audio/src/AudioEffectOptions.cpp | 43 +++++++------- libraries/audio/src/AudioEffectOptions.h | 47 ++++++++------- libraries/audio/src/AudioInjectorOptions.cpp | 12 ++++ libraries/audio/src/Sound.h | 8 ++- .../src/AudioScriptingInterface.h | 45 +++++++------- .../script-engine/src/ScriptAudioInjector.h | 58 +++++++++++++++++++ 7 files changed, 182 insertions(+), 85 deletions(-) diff --git a/interface/src/scripting/Audio.h b/interface/src/scripting/Audio.h index 8d16b06995..f7dd252c54 100644 --- a/interface/src/scripting/Audio.h +++ b/interface/src/scripting/Audio.h @@ -26,7 +26,7 @@ class Audio : public AudioScriptingInterface, protected ReadWriteLockable { SINGLETON_DEPENDENCY /**jsdoc - * The Audio API features tools to help control audio contexts and settings. + * The Audio API ... TODO * * @namespace Audio * @@ -35,12 +35,13 @@ class Audio : public AudioScriptingInterface, protected ReadWriteLockable { * @hifi-server-entity * @hifi-assignment-client * - * @property {boolean} muted - * @property {boolean} noiseReduction - * @property {number} inputVolume - * @property {number} inputLevel Read-only. - * @property {string} context Read-only. - * @property {} devices Read-only. + * @property {boolean} muted - true if TODO, otherwise false. + * @property {boolean} noiseReduction - true if TODO, otherwise false. + * @property {number} inputVolume - TODO + * @property {number} inputLevel - TODO Read-only. + * @property {string} context - TODO Read-only. + * @property {object} devices Read-only. Deprecated: This property is deprecated and will be + * removed. */ Q_PROPERTY(bool muted READ isMuted WRITE setMuted NOTIFY mutedChanged) @@ -69,87 +70,100 @@ public: /**jsdoc * @function Audio.setInputDevice - * @param {} device + * @param {object} device * @param {boolean} isHMD + * @deprecated This function is deprecated and will be removed. */ Q_INVOKABLE void setInputDevice(const QAudioDeviceInfo& device, bool isHMD); /**jsdoc * @function Audio.setOutputDevice - * @param {} device + * @param {object} device * @param {boolean} isHMD + * @deprecated This function is deprecated and will be removed. */ Q_INVOKABLE void setOutputDevice(const QAudioDeviceInfo& device, bool isHMD); /**jsdoc + * TODO * @function Audio.setReverb - * @param {boolean} enable + * @param {boolean} enable - TODO */ Q_INVOKABLE void setReverb(bool enable); /**jsdoc + * TODO * @function Audio.setReverbOptions - * @param {AudioEffectOptions} options + * @param {AudioEffectOptions} options - TODO */ Q_INVOKABLE void setReverbOptions(const AudioEffectOptions* options); /**jsdoc + * TODO * @function Audio.startRecording - * @param {string} filename - * @returns {boolean} + * @param {string} filename - TODO + * @returns {boolean} true if TODO, otherwise false. */ Q_INVOKABLE bool startRecording(const QString& filename); /**jsdoc + * TODO * @function Audio.stopRecording */ Q_INVOKABLE void stopRecording(); /**jsdoc + * TODO * @function Audio.getRecording - * @returns {boolean} + * @returns {boolean} true if TODO, otherwise false. */ Q_INVOKABLE bool getRecording(); signals: /**jsdoc + * Triggered when ... TODO * @function Audio.nop * @returns {Signal} */ void nop(); /**jsdoc + * Triggered when ... TODO * @function Audio.mutedChanged - * @param {boolean} isMuted + * @param {boolean} isMuted - TODO * @returns {Signal} */ void mutedChanged(bool isMuted); /**jsdoc + * Triggered when ... TODO * @function Audio.noiseReductionChanged - * @param {boolean} isEnabled + * @param {boolean} isEnabled - TODO * @returns {Signal} */ void noiseReductionChanged(bool isEnabled); /**jsdoc + * Triggered when ... TODO * @function Audio.inputVolumeChanged - * @param {number} volume + * @param {number} volume - TODO * @returns {Signal} */ void inputVolumeChanged(float volume); /**jsdoc + * Triggered when ... TODO * @function Audio.inputLevelChanged - * @param {number} level + * @param {number} level - TODO * @returns {Signal} */ void inputLevelChanged(float level); /**jsdoc + * Triggered when ... TODO * @function Audio.contextChanged - * @param {string} context + * @param {string} context - TODO * @returns {Signal} */ void contextChanged(const QString& context); @@ -158,7 +172,7 @@ public slots: /**jsdoc * @function Audio.onContextChanged - * @returns {Signal} + * @deprecated This function is deprecated and will be removed. */ void onContextChanged(); diff --git a/libraries/audio/src/AudioEffectOptions.cpp b/libraries/audio/src/AudioEffectOptions.cpp index edb0ff52ae..3ed1296b63 100644 --- a/libraries/audio/src/AudioEffectOptions.cpp +++ b/libraries/audio/src/AudioEffectOptions.cpp @@ -59,28 +59,29 @@ static void setOption(QScriptValue arguments, const QString name, float defaultV } /**jsdoc + * TODO * @typedef {object} AudioEffectOptions.ReverbOptions - * @property {number} bandwidth - * @property {number} preDelay - * @property {number} lateDelay - * @property {number} reverbTime - * @property {number} earlyDiffusion - * @property {number} lateDiffusion - * @property {number} roomSize - * @property {number} density - * @property {number} bassMult - * @property {number} bassFreq - * @property {number} highGain - * @property {number} highFreq - * @property {number} modRate - * @property {number} modDepth - * @property {number} earlyGain - * @property {number} lateGain - * @property {number} earlyMixLeft - * @property {number} earlyMixRight - * @property {number} lateMixLeft - * @property {number} lateMixRight - * @property {number} wetDryMix + * @property {number} bandwidth - TODO + * @property {number} preDelay - TODO + * @property {number} lateDelay - TODO + * @property {number} reverbTime - TODO + * @property {number} earlyDiffusion - TODO + * @property {number} lateDiffusion - TODO + * @property {number} roomSize - TODO + * @property {number} density - TODO + * @property {number} bassMult - TODO + * @property {number} bassFreq - TODO + * @property {number} highGain - TODO + * @property {number} highFreq - TODO + * @property {number} modRate - TODO + * @property {number} modDepth - TODO + * @property {number} earlyGain - TODO + * @property {number} lateGain - TODO + * @property {number} earlyMixLeft - TODO + * @property {number} earlyMixRight - TODO + * @property {number} lateMixLeft - TODO + * @property {number} lateMixRight - TODO + * @property {number} wetDryMix - TODO */ AudioEffectOptions::AudioEffectOptions(QScriptValue arguments) { setOption(arguments, BANDWIDTH_HANDLE, BANDWIDTH_DEFAULT, _bandwidth); diff --git a/libraries/audio/src/AudioEffectOptions.h b/libraries/audio/src/AudioEffectOptions.h index 1afd4e21be..0e2e017d49 100644 --- a/libraries/audio/src/AudioEffectOptions.h +++ b/libraries/audio/src/AudioEffectOptions.h @@ -16,35 +16,38 @@ #include /**jsdoc + * TODO + * Used in the {@link Audio} API. + * * @class AudioEffectOptions - * @param {AudioEffectOptions.ReverbOptions} [reverbOptions=null] + * @param {AudioEffectOptions.ReverbOptions} [reverbOptions=null] - TODO * * @hifi-interface * @hifi-client-entity * @hifi-server-entity * @hifi-assignment-client * - * @property {number} bandwidth=10000 - * @property {number} preDelay=20 - * @property {number} lateDelay=0 - * @property {number} reverbTime=2 - * @property {number} earlyDiffusion=100 - * @property {number} lateDiffusion=100 - * @property {number} roomSize=50 - * @property {number} density=100 - * @property {number} bassMult=1.5 - * @property {number} bassFreq=250 - * @property {number} highGain=-6 - * @property {number} highFreq=3000 - * @property {number} modRate=2.3 - * @property {number} modDepth=50 - * @property {number} earlyGain=0 - * @property {number} lateGain=0 - * @property {number} earlyMixLeft=20 - * @property {number} earlyMixRight=20 - * @property {number} lateMixLeft=90 - * @property {number} lateMixRight=90 - * @property {number} wetDryMix=50 + * @property {number} bandwidth=10000 - TODO + * @property {number} preDelay=20 - TODO + * @property {number} lateDelay=0 - TODO + * @property {number} reverbTime=2 - TODO + * @property {number} earlyDiffusion=100 - TODO + * @property {number} lateDiffusion=100 - TODO + * @property {number} roomSize=50 - TODO + * @property {number} density=100 - TODO + * @property {number} bassMult=1.5 - TODO + * @property {number} bassFreq=250 - TODO + * @property {number} highGain=-6 - TODO + * @property {number} highFreq=3000 - TODO + * @property {number} modRate=2.3 - TODO + * @property {number} modDepth=50 - TODO + * @property {number} earlyGain=0 - TODO + * @property {number} lateGain=0 - TODO + * @property {number} earlyMixLeft=20 - TODO + * @property {number} earlyMixRight=20 - TODO + * @property {number} lateMixLeft=90 - TODO + * @property {number} lateMixRight=90 - TODO + * @property {number} wetDryMix=50 - TODO */ class AudioEffectOptions : public QObject { diff --git a/libraries/audio/src/AudioInjectorOptions.cpp b/libraries/audio/src/AudioInjectorOptions.cpp index 2f82cae137..8691432bcd 100644 --- a/libraries/audio/src/AudioInjectorOptions.cpp +++ b/libraries/audio/src/AudioInjectorOptions.cpp @@ -45,6 +45,18 @@ QScriptValue injectorOptionsToScriptValue(QScriptEngine* engine, const AudioInje return obj; } +/**jsdoc + * TODO + * @typedef {object} AudioInjector.AudioInjectorOptions + * @property {Vec3} position=Vec3.ZERO - TODO + * @property {Quat} orientation=Quat.IDENTITY - TODO + * @property {number} volume=1 - TODO + * @property {boolean} loop=false - true if TODO, otherwise false. + * @property {boolean} ignorePenumbra=false - true if TODO, otherwise false. + * @property {boolean} localOnly=false - true if TODO, otherwise false. + * @property {number} secondOffset=0 - TODO + * @property {number} pitch=1 - TODO + */ void injectorOptionsFromScriptValue(const QScriptValue& object, AudioInjectorOptions& injectorOptions) { if (!object.isObject()) { qWarning() << "Audio injector options is not an object."; diff --git a/libraries/audio/src/Sound.h b/libraries/audio/src/Sound.h index 061c4a2417..0edcb59cca 100644 --- a/libraries/audio/src/Sound.h +++ b/libraries/audio/src/Sound.h @@ -79,6 +79,9 @@ private: typedef QSharedPointer SharedSoundPointer; /**jsdoc + * TODO + * Created by {@link SoundCache.getSound}. + * * @class SoundObject * * @hifi-interface @@ -86,8 +89,8 @@ typedef QSharedPointer SharedSoundPointer; * @hifi-server-entity * @hifi-assignment-client * - * @property {boolean} downloaded - * @property {number} duration + * @property {boolean} downloaded - true if TODO, otherwise false. + * @property {number} duration - TODO */ class SoundScriptingInterface : public QObject { Q_OBJECT @@ -103,6 +106,7 @@ public: float getDuration() { return _sound->getDuration(); } /**jsdoc + * Triggered when TODO * @function SoundObject.ready * @returns {Signal} */ diff --git a/libraries/script-engine/src/AudioScriptingInterface.h b/libraries/script-engine/src/AudioScriptingInterface.h index 20ca977da1..6b87b0ee67 100644 --- a/libraries/script-engine/src/AudioScriptingInterface.h +++ b/libraries/script-engine/src/AudioScriptingInterface.h @@ -35,91 +35,96 @@ protected: // these methods are protected to stop C++ callers from calling, but invokable from script /**jsdoc + * TODO * @function Audio.playSound - * @param {} sound - * @param {} [injectorOptions=null] - * @returns {object} + * @param {SoundObject} sound - TODO + * @param {AudioInjector.AudioInjectorOptions} [injectorOptions={}] - TODO + * @returns {AudioInjector} TODO */ Q_INVOKABLE ScriptAudioInjector* playSound(SharedSoundPointer sound, const AudioInjectorOptions& injectorOptions = AudioInjectorOptions()); /**jsdoc + * TODO * @function Audio.playSystemSound - * @param {} sound - * @param {} position - * @returns {object} + * @param {SoundObject} sound - TODO + * @param {Vec3} position - TODO + * @returns {AudioInjector} TODO */ // FIXME: there is no way to play a positionless sound Q_INVOKABLE ScriptAudioInjector* playSystemSound(SharedSoundPointer sound, const QVector3D& position); /**jsdoc + * TODO * @function Audio.setStereoInput - * @param {boolean} stereo + * @param {boolean} stereo - TODO */ Q_INVOKABLE void setStereoInput(bool stereo); /**jsdoc + * TODO * @function Audio.isStereoInput - * @returns {boolean} + * @returns {boolean} true if TODO, otherwise false. */ Q_INVOKABLE bool isStereoInput(); signals: /**jsdoc - * The client has been muted by the mixer. + * Triggered when the client is muted by the mixer. * @function Audio.mutedByMixer * @returns {Signal} */ void mutedByMixer(); /**jsdoc - * The entire environment has been muted by the mixer. + * Triggered when the entire environment is muted by the mixer. TODO: What is the "whole environment"? * @function Audio.environmentMuted * @returns {Signal} */ void environmentMuted(); /**jsdoc - * The client has received its first packet from the audio mixer. + * Triggered when the client receives its first packet from the audio mixer. * @function Audio.receivedFirstPacket * @returns {Signal} */ void receivedFirstPacket(); /**jsdoc - * The client has been disconnected from the audio mixer. + * Triggered when the client is disconnected from the audio mixer. * @function Audio.disconnected * @returns {Signal} */ void disconnected(); /**jsdoc - * The noise gate has opened. + * Triggered when the noise gate is opened. TODO: Description of noise gate. * @function Audio.noiseGateOpened * @returns {Signal} */ void noiseGateOpened(); /**jsdoc - * The noise gate has closed. + * Triggered when the noise gate is closed. TODO: Description of noise gate. * @function Audio.noiseGateClosed * @returns {Signal} */ void noiseGateClosed(); /**jsdoc - * A frame of mic input audio has been received and processed. + * Triggered when a frame of microphone audio input is processed. * @function Audio.inputReceived - * @param {} inputSamples + * @param {Int16Array} inputSamples - TODO * @returns {Signal} */ void inputReceived(const QByteArray& inputSamples); /**jsdoc - * @function Audio.isStereoInputChanged - * @param {boolean} isStereo - * @returns {Signal} - */ + * TODO + * @function Audio.isStereoInputChanged + * @param {boolean} isStereo - TODO + * @returns {Signal} + */ void isStereoInputChanged(bool isStereo); private: diff --git a/libraries/script-engine/src/ScriptAudioInjector.h b/libraries/script-engine/src/ScriptAudioInjector.h index 4c2871dd34..5d66461160 100644 --- a/libraries/script-engine/src/ScriptAudioInjector.h +++ b/libraries/script-engine/src/ScriptAudioInjector.h @@ -16,6 +16,21 @@ #include +/**jsdoc + * TODO + * Used in the {@link Audio} API. + * + * @class AudioInjector + * + * @hifi-interface + * @hifi-client-entity + * @hifi-server-entity + * @hifi-assignment-client + * + * @property {boolean} playing - true if TODO, otherwise false. Read-only. + * @property {number} loudness - TODO Read-only. + * @property {AudioInjector.AudioInjectorOptions} options - TODO + */ class ScriptAudioInjector : public QObject { Q_OBJECT @@ -26,19 +41,62 @@ public: ScriptAudioInjector(const AudioInjectorPointer& injector); ~ScriptAudioInjector(); public slots: + + /**jsdoc + * TODO + * @function AudioInjector.restart + */ void restart() { _injector->restart(); } + + /**jsdoc + * TODO + * @function AudioInjector.stop + */ void stop() { _injector->stop(); } + /**jsdoc + * TODO + * @function AudioInjector.getOptions + * @returns {AudioInjector.AudioInjectorOptions} TODO + */ const AudioInjectorOptions& getOptions() const { return _injector->getOptions(); } + + /**jsdoc + * TODO + * @function AudioInjector.setOptions + * @param {AudioInjector.AudioInjectorOptions} options - TODO + */ void setOptions(const AudioInjectorOptions& options) { _injector->setOptions(options); } + /**jsdoc + * TODO + * @function AudioInjector.getLoudness + * @returns {number} TODO + */ float getLoudness() const { return _injector->getLoudness(); } + + /**jsdoc + * TODO + * @function AudioInjector.isPlaying + * @returns {boolean} true if TODO, otherwise false. + */ bool isPlaying() const { return _injector->isPlaying(); } signals: + + /**jsdoc + * Triggered when TODO + * @function AudioInjector.finished + * @returns {Signal} + */ void finished(); protected slots: + + /**jsdoc + * TODO + * @function AudioInjector.stopInjectorImmediately + */ void stopInjectorImmediately(); private: AudioInjectorPointer _injector; From 396382afd7bc1930825ffcb50fb814b927f51330 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Thu, 19 Jul 2018 09:31:48 +1200 Subject: [PATCH 02/37] Fill in Audio API JSDoc --- interface/src/scripting/Audio.h | 115 +++++++++++++----- libraries/audio/src/AudioEffectOptions.cpp | 44 +++---- libraries/audio/src/AudioEffectOptions.h | 49 ++++---- libraries/audio/src/AudioInjectorOptions.cpp | 23 ++-- libraries/audio/src/Sound.h | 16 ++- libraries/audio/src/SoundCache.h | 3 +- .../src/AudioScriptingInterface.h | 65 +++++++--- .../script-engine/src/ScriptAudioInjector.h | 76 +++++++++--- 8 files changed, 263 insertions(+), 128 deletions(-) diff --git a/interface/src/scripting/Audio.h b/interface/src/scripting/Audio.h index f7dd252c54..4b8eb6aabc 100644 --- a/interface/src/scripting/Audio.h +++ b/interface/src/scripting/Audio.h @@ -26,7 +26,7 @@ class Audio : public AudioScriptingInterface, protected ReadWriteLockable { SINGLETON_DEPENDENCY /**jsdoc - * The Audio API ... TODO + * The Audio API provides facilities to interact with audio inputs and outputs and to play sounds. * * @namespace Audio * @@ -35,15 +35,23 @@ class Audio : public AudioScriptingInterface, protected ReadWriteLockable { * @hifi-server-entity * @hifi-assignment-client * - * @property {boolean} muted - true if TODO, otherwise false. - * @property {boolean} noiseReduction - true if TODO, otherwise false. - * @property {number} inputVolume - TODO - * @property {number} inputLevel - TODO Read-only. - * @property {string} context - TODO Read-only. - * @property {object} devices Read-only. Deprecated: This property is deprecated and will be + * @property {boolean} muted - true if the audio input is muted, otherwise false. + * @property {boolean} noiseReduction - true if noise reduction is enabled, otherwise false. When + * enabled, the input audio signal is blocked (fully attenuated) when it falls below an adaptive threshold set just + * above the noise floor. + * @property {number} inputLevel - The loudness of the audio input, range 0.0 (no sound) – + * 1.0 (the onset of clipping). Read-only. + * @property {number} inputVolume - Adjusts the volume of the input audio; range 0.01.0. + * If set to a value, the resulting value depends on the input device: for example, the volume can't be changed on some + * devices, and others might only support values of 0.0 and 1.0. + * @property {boolean} isStereoInput - true if the input audio is being used in stereo, otherwise + * false. Some devices do not support stereo, in which case the value is always false. + * @property {string} context - The current context of the audio: either "Desktop" or "HMD". + * Read-only. + * @property {object} devices Read-only. Deprecated: This property is deprecated and will be * removed. */ - + Q_PROPERTY(bool muted READ isMuted WRITE setMuted NOTIFY mutedChanged) Q_PROPERTY(bool noiseReduction READ noiseReductionEnabled WRITE enableNoiseReduction NOTIFY noiseReductionChanged) Q_PROPERTY(float inputVolume READ getInputVolume WRITE setInputVolume NOTIFY inputVolumeChanged) @@ -85,85 +93,132 @@ public: Q_INVOKABLE void setOutputDevice(const QAudioDeviceInfo& device, bool isHMD); /**jsdoc - * TODO + * Enable or disable reverberation. Reverberation is done by the client, on the post-mix audio. The reverberation options + * come from either the domain's audio zone if used — configured on the server — or as scripted by + * {@link Audio.setReverbOptions|setReverbOptions}. * @function Audio.setReverb - * @param {boolean} enable - TODO - */ + * @param {boolean} enable - true to enable reverberation, false to disable. + * @example Enable reverberation for a short while. + * var sound = SoundCache.getSound(Script.resourcesPath() + "sounds/sample.wav"); + * var injector; + * var injectorOptions = { + * position: MyAvatar.position + * }; + * + * Script.setTimeout(function () { + * print("Reverb OFF"); + * Audio.setReverb(false); + * injector = Audio.playSound(sound, injectorOptions); + * }, 1000); + * + * Script.setTimeout(function () { + * var reverbOptions = new AudioEffectOptions(); + * reverbOptions.roomSize = 100; + * Audio.setReverbOptions(reverbOptions); + * print("Reverb ON"); + * Audio.setReverb(true); + * }, 4000); + * + * Script.setTimeout(function () { + * print("Reverb OFF"); + * Audio.setReverb(false); + * }, 8000); */ Q_INVOKABLE void setReverb(bool enable); /**jsdoc - * TODO + * Configure reverberation options. Use {@link Audio.setReverb|setReverb} to enable or disable reverberation. * @function Audio.setReverbOptions - * @param {AudioEffectOptions} options - TODO + * @param {AudioEffectOptions} options - The reverberation options. */ Q_INVOKABLE void setReverbOptions(const AudioEffectOptions* options); /**jsdoc - * TODO + * Starts making an audio recording of the audio being played in-world (i.e., not local-only audio) to a file in WAV format. * @function Audio.startRecording - * @param {string} filename - TODO - * @returns {boolean} true if TODO, otherwise false. + * @param {string} filename - The path and name of the file to make the recording in. Should have a .wav + * extension. The file is overwritten if it already exists. + * @returns {boolean} true if the specified file could be opened and audio recording has started, otherwise + * false. + * @example Make a 10 second audio recording. + * var filename = File.getTempDir() + "/audio.wav"; + * if (Audio.startRecording(filename)) { + * Script.setTimeout(function () { + * Audio.stopRecording(); + * print("Audio recording made in: " + filename); + * }, 10000); + * + * } else { + * print("Could not make an audio recording in: " + filename); + * } */ Q_INVOKABLE bool startRecording(const QString& filename); /**jsdoc - * TODO + * Finish making an audio recording started with {@link Audio.startRecording|startRecording}. * @function Audio.stopRecording */ Q_INVOKABLE void stopRecording(); /**jsdoc - * TODO + * Check whether an audio recording is currently being made. * @function Audio.getRecording - * @returns {boolean} true if TODO, otherwise false. + * @returns {boolean} true if an audio recording is currently being made, otherwise false. */ Q_INVOKABLE bool getRecording(); signals: /**jsdoc - * Triggered when ... TODO * @function Audio.nop * @returns {Signal} + * @deprecated This signal is deprecated and will be removed. */ void nop(); /**jsdoc - * Triggered when ... TODO + * Triggered when the audio input is muted or unmuted. * @function Audio.mutedChanged - * @param {boolean} isMuted - TODO + * @param {boolean} isMuted - true if the audio input is muted, otherwise false. * @returns {Signal} + * @example Report when audio input is muted or unmuted + * Audio.mutedChanged.connect(function (isMuted) { + * print("Audio muted: " + isMuted); + * }); */ void mutedChanged(bool isMuted); /**jsdoc - * Triggered when ... TODO + * Triggered when the audio input noise reduction is enabled or disabled. * @function Audio.noiseReductionChanged - * @param {boolean} isEnabled - TODO + * @param {boolean} isEnabled - true if audio input noise reduction is enabled, otherwise false. * @returns {Signal} */ void noiseReductionChanged(bool isEnabled); /**jsdoc - * Triggered when ... TODO + * Triggered when the input audio volume changes. * @function Audio.inputVolumeChanged - * @param {number} volume - TODO + * @param {number} volume - The requested volume to be applied to the audio input, range 0.0 – + * 1.0. The resulting value of Audio.inputVolume depends on the capabilities of the device: + * for example, the volume can't be changed on some devices, and others might only support values of 0.0 + * and 1.0. * @returns {Signal} */ void inputVolumeChanged(float volume); /**jsdoc - * Triggered when ... TODO + * Triggered when the input audio level changes. * @function Audio.inputLevelChanged - * @param {number} level - TODO + * @param {number} level - The loudness of the input audio, range 0.0 (no sound) – 1.0 (the + * onset of clipping). * @returns {Signal} */ void inputLevelChanged(float level); /**jsdoc - * Triggered when ... TODO + * Triggered when the current context of the audio changes. * @function Audio.contextChanged - * @param {string} context - TODO + * @param {string} context - The current context of the audio: either "Desktop" or "HMD". * @returns {Signal} */ void contextChanged(const QString& context); diff --git a/libraries/audio/src/AudioEffectOptions.cpp b/libraries/audio/src/AudioEffectOptions.cpp index 3ed1296b63..873ce7df87 100644 --- a/libraries/audio/src/AudioEffectOptions.cpp +++ b/libraries/audio/src/AudioEffectOptions.cpp @@ -59,29 +59,29 @@ static void setOption(QScriptValue arguments, const QString name, float defaultV } /**jsdoc - * TODO + * Reverberation options that can be used to initialize an {@link AudioEffectOptions} object when created. * @typedef {object} AudioEffectOptions.ReverbOptions - * @property {number} bandwidth - TODO - * @property {number} preDelay - TODO - * @property {number} lateDelay - TODO - * @property {number} reverbTime - TODO - * @property {number} earlyDiffusion - TODO - * @property {number} lateDiffusion - TODO - * @property {number} roomSize - TODO - * @property {number} density - TODO - * @property {number} bassMult - TODO - * @property {number} bassFreq - TODO - * @property {number} highGain - TODO - * @property {number} highFreq - TODO - * @property {number} modRate - TODO - * @property {number} modDepth - TODO - * @property {number} earlyGain - TODO - * @property {number} lateGain - TODO - * @property {number} earlyMixLeft - TODO - * @property {number} earlyMixRight - TODO - * @property {number} lateMixLeft - TODO - * @property {number} lateMixRight - TODO - * @property {number} wetDryMix - TODO + * @property {number} bandwidth=10000 - The corner frequency (Hz) of the low-pass filter at reverb input. + * @property {number} preDelay=20 - The delay (milliseconds) between dry signal and the onset of early reflections. + * @property {number} lateDelay=0 - The delay (milliseconds) between early reflections and the onset of reverb tail. + * @property {number} reverbTime=2 - The time (seconds) for the reverb tail to decay by 60dB, also known as RT60. + * @property {number} earlyDiffusion=100 - Adjusts the buildup of echo density in the early reflections, normally 100%. + * @property {number} lateDiffusion=100 - Adjusts the buildup of echo density in the reverb tail, normally 100%. + * @property {number} roomSize=50 - The apparent room size, from small (0%) to large (100%). + * @property {number} density=100 - Adjusts the echo density in the reverb tail, normally 100%. + * @property {number} bassMult=1.5 - Adjusts the bass-frequency reverb time, as multiple of reverbTime. + * @property {number} bassFreq=250 - The crossover frequency (Hz) for the onset of bassMult. + * @property {number} highGain=-6 - Reduces the high-frequency reverb time, as attenuation (dB). + * @property {number} highFreq=3000 - The crossover frequency (Hz) for the onset of highGain. + * @property {number} modRate=2.3 - The rate of modulation (Hz) of the LFO-modulated delay lines. + * @property {number} modDepth=50 - The depth of modulation (percent) of the LFO-modulated delay lines. + * @property {number} earlyGain=0 - Adjusts the relative level (dB) of the early reflections. + * @property {number} lateGain=0 - Adjusts the relative level (dB) of the reverb tail. + * @property {number} earlyMixLeft=20 - The apparent distance of the source (percent) in the early reflections. + * @property {number} earlyMixRight=20 - The apparent distance of the source (percent) in the early reflections. + * @property {number} lateMixLeft=90 - The apparent distance of the source (percent) in the reverb tail. + * @property {number} lateMixRight=90 - The apparent distance of the source (percent) in the reverb tail. + * @property {number} wetDryMix=50 - Adjusts the wet/dry ratio, from completely dry (0%) to completely wet (100%). */ AudioEffectOptions::AudioEffectOptions(QScriptValue arguments) { setOption(arguments, BANDWIDTH_HANDLE, BANDWIDTH_DEFAULT, _bandwidth); diff --git a/libraries/audio/src/AudioEffectOptions.h b/libraries/audio/src/AudioEffectOptions.h index 0e2e017d49..4bc7957142 100644 --- a/libraries/audio/src/AudioEffectOptions.h +++ b/libraries/audio/src/AudioEffectOptions.h @@ -16,38 +16,39 @@ #include /**jsdoc - * TODO - * Used in the {@link Audio} API. + * Audio effect options used by the {@link Audio} API. + * + *

Create using new AudioEffectOptions(reverbOptions).

* * @class AudioEffectOptions - * @param {AudioEffectOptions.ReverbOptions} [reverbOptions=null] - TODO + * @param {AudioEffectOptions.ReverbOptions} [reverbOptions=null] - Reverberation options. * * @hifi-interface * @hifi-client-entity * @hifi-server-entity * @hifi-assignment-client * - * @property {number} bandwidth=10000 - TODO - * @property {number} preDelay=20 - TODO - * @property {number} lateDelay=0 - TODO - * @property {number} reverbTime=2 - TODO - * @property {number} earlyDiffusion=100 - TODO - * @property {number} lateDiffusion=100 - TODO - * @property {number} roomSize=50 - TODO - * @property {number} density=100 - TODO - * @property {number} bassMult=1.5 - TODO - * @property {number} bassFreq=250 - TODO - * @property {number} highGain=-6 - TODO - * @property {number} highFreq=3000 - TODO - * @property {number} modRate=2.3 - TODO - * @property {number} modDepth=50 - TODO - * @property {number} earlyGain=0 - TODO - * @property {number} lateGain=0 - TODO - * @property {number} earlyMixLeft=20 - TODO - * @property {number} earlyMixRight=20 - TODO - * @property {number} lateMixLeft=90 - TODO - * @property {number} lateMixRight=90 - TODO - * @property {number} wetDryMix=50 - TODO + * @property {number} bandwidth=10000 - The corner frequency (Hz) of the low-pass filter at reverb input. + * @property {number} preDelay=20 - The delay (milliseconds) between dry signal and the onset of early reflections. + * @property {number} lateDelay=0 - The delay (milliseconds) between early reflections and the onset of reverb tail. + * @property {number} reverbTime=2 - The time (seconds) for the reverb tail to decay by 60dB, also known as RT60. + * @property {number} earlyDiffusion=100 - Adjusts the buildup of echo density in the early reflections, normally 100%. + * @property {number} lateDiffusion=100 - Adjusts the buildup of echo density in the reverb tail, normally 100%. + * @property {number} roomSize=50 - The apparent room size, from small (0%) to large (100%). + * @property {number} density=100 - Adjusts the echo density in the reverb tail, normally 100%. + * @property {number} bassMult=1.5 - Adjusts the bass-frequency reverb time, as multiple of reverbTime. + * @property {number} bassFreq=250 - The crossover frequency (Hz) for the onset of bassMult. + * @property {number} highGain=-6 - Reduces the high-frequency reverb time, as attenuation (dB). + * @property {number} highFreq=3000 - The crossover frequency (Hz) for the onset of highGain. + * @property {number} modRate=2.3 - The rate of modulation (Hz) of the LFO-modulated delay lines. + * @property {number} modDepth=50 - The depth of modulation (percent) of the LFO-modulated delay lines. + * @property {number} earlyGain=0 - Adjusts the relative level (dB) of the early reflections. + * @property {number} lateGain=0 - Adjusts the relative level (dB) of the reverb tail. + * @property {number} earlyMixLeft=20 - The apparent distance of the source (percent) in the early reflections. + * @property {number} earlyMixRight=20 - The apparent distance of the source (percent) in the early reflections. + * @property {number} lateMixLeft=90 - The apparent distance of the source (percent) in the reverb tail. + * @property {number} lateMixRight=90 - The apparent distance of the source (percent) in the reverb tail. + * @property {number} wetDryMix=50 - Adjusts the wet/dry ratio, from completely dry (0%) to completely wet (100%). */ class AudioEffectOptions : public QObject { diff --git a/libraries/audio/src/AudioInjectorOptions.cpp b/libraries/audio/src/AudioInjectorOptions.cpp index 8691432bcd..0f4ab7ff42 100644 --- a/libraries/audio/src/AudioInjectorOptions.cpp +++ b/libraries/audio/src/AudioInjectorOptions.cpp @@ -46,16 +46,21 @@ QScriptValue injectorOptionsToScriptValue(QScriptEngine* engine, const AudioInje } /**jsdoc - * TODO + * Configures how an audio injector plays its audio. * @typedef {object} AudioInjector.AudioInjectorOptions - * @property {Vec3} position=Vec3.ZERO - TODO - * @property {Quat} orientation=Quat.IDENTITY - TODO - * @property {number} volume=1 - TODO - * @property {boolean} loop=false - true if TODO, otherwise false. - * @property {boolean} ignorePenumbra=false - true if TODO, otherwise false. - * @property {boolean} localOnly=false - true if TODO, otherwise false. - * @property {number} secondOffset=0 - TODO - * @property {number} pitch=1 - TODO + * @property {Vec3} position=Vec3.ZERO - The position in the domain to play the sound. + * @property {Quat} orientation=Quat.IDENTITY - The orientation in the domain to play the sound in. + * @property {number} volume=1.0 - Playback volume, between 0.0 and 1.0. + * @property {number} pitch=1.0 - Alter the pitch of the sound, within +/- 2 octaves. The value is the relative sample rate to + * resample the sound at, range 0.062516.0. A value of 0.0625 lowers the + * pitch by 2 octaves; 1.0 is no change in pitch; 16.0 raises the pitch by 2 octaves. + * @property {boolean} loop=false - If true, the sound is played repeatedly until playback is stopped. + * @property {number} secondOffset=0 - Starts playback from a specified time (seconds) within the sound file, ≥ + * 0. + * @property {boolean} localOnly=false - IF true, the sound is played back locally on the client rather than to + * others via the audio mixer. + * @property {boolean} ignorePenumbra=false - Deprecated: This property is deprecated and will be + * removed. */ void injectorOptionsFromScriptValue(const QScriptValue& object, AudioInjectorOptions& injectorOptions) { if (!object.isObject()) { diff --git a/libraries/audio/src/Sound.h b/libraries/audio/src/Sound.h index 0edcb59cca..348600e4ae 100644 --- a/libraries/audio/src/Sound.h +++ b/libraries/audio/src/Sound.h @@ -79,8 +79,13 @@ private: typedef QSharedPointer SharedSoundPointer; /**jsdoc - * TODO - * Created by {@link SoundCache.getSound}. + * An audio resource, created by {@link SoundCache.getSound}, to be played back using {@link Audio.playSound}. + *

Supported formats:

+ *
    + *
  • WAV: 16-bit uncompressed WAV at any sample rate, with 1 (mono), 2(stereo), or 4 (ambisonic) channels.
  • + *
  • MP3: Mono or stereo, at any sample rate.
  • + *
  • RAW: 48khz 16-bit mono or stereo. Filename must include ".stereo" to be interpreted as stereo.
  • + *
* * @class SoundObject * @@ -89,8 +94,9 @@ typedef QSharedPointer SharedSoundPointer; * @hifi-server-entity * @hifi-assignment-client * - * @property {boolean} downloaded - true if TODO, otherwise false. - * @property {number} duration - TODO + * @property {boolean} downloaded - true if the sound has been downloaded and is ready to be played, otherwise + * false. + * @property {number} duration - The duration of the sound, in seconds. */ class SoundScriptingInterface : public QObject { Q_OBJECT @@ -106,7 +112,7 @@ public: float getDuration() { return _sound->getDuration(); } /**jsdoc - * Triggered when TODO + * Triggered when the sound has been downloaded and is ready to be played. * @function SoundObject.ready * @returns {Signal} */ diff --git a/libraries/audio/src/SoundCache.h b/libraries/audio/src/SoundCache.h index 4352b1d459..ecb4451153 100644 --- a/libraries/audio/src/SoundCache.h +++ b/libraries/audio/src/SoundCache.h @@ -78,8 +78,9 @@ public: /**jsdoc + * Loads the content of an audio file into an object, ready for playback by {@link Audio.playSound}. * @function SoundCache.getSound - * @param {string} url + * @param {string} url - The URL of the audio file to load. See {@link SoundObject} for supported formats. * @returns {SoundObject} */ Q_INVOKABLE SharedSoundPointer getSound(const QUrl& url); diff --git a/libraries/script-engine/src/AudioScriptingInterface.h b/libraries/script-engine/src/AudioScriptingInterface.h index 6b87b0ee67..72b9541763 100644 --- a/libraries/script-engine/src/AudioScriptingInterface.h +++ b/libraries/script-engine/src/AudioScriptingInterface.h @@ -23,6 +23,7 @@ class AudioScriptingInterface : public QObject, public Dependency { Q_OBJECT SINGLETON_DEPENDENCY + // JSDoc for property is in Audio.h. Q_PROPERTY(bool isStereoInput READ isStereoInput WRITE setStereoInput NOTIFY isStereoInputChanged) public: @@ -35,49 +36,69 @@ protected: // these methods are protected to stop C++ callers from calling, but invokable from script /**jsdoc - * TODO + * Starts playing — "injecting" — the content of an audio file. The sound is played globally (sent to the audio + * mixer) so that everyone hears it, unless the injectorOptions has localOnly set to + * true in which case only the client hears the sound played. No sound is played if sent to the audio mixer + * but the client is not connected to an audio mixer. The {@link AudioInjector} object returned by the function can be used + * to control the playback and get information about its current state. * @function Audio.playSound - * @param {SoundObject} sound - TODO - * @param {AudioInjector.AudioInjectorOptions} [injectorOptions={}] - TODO - * @returns {AudioInjector} TODO + * @param {SoundObject} sound - The content of an audio file, loaded using {@link SoundCache.getSound}. See + * {@link SoundObject} for supported formats. + * @param {AudioInjector.AudioInjectorOptions} [injectorOptions={}] - Audio injector configuration. + * @returns {AudioInjector} The audio injector that plays the audio file. + * @example Play a sound. + * var sound = SoundCache.getSound(Script.resourcesPath() + "sounds/sample.wav"); + * var injector; + * var injectorOptions = { + * position: MyAvatar.position + * }; + * + * Script.setTimeout(function () { // Give the sound time to load. + * injector = Audio.playSound(sound, injectorOptions); + * }, 1000); */ Q_INVOKABLE ScriptAudioInjector* playSound(SharedSoundPointer sound, const AudioInjectorOptions& injectorOptions = AudioInjectorOptions()); /**jsdoc - * TODO + * Start playing the content of an audio file, locally (isn't sent to the audio mixer). This is the same as calling + * {@link Audio.playSound} with {@link AudioInjector.AudioInjectorOptions} localOnly set true and + * the specified position. * @function Audio.playSystemSound - * @param {SoundObject} sound - TODO - * @param {Vec3} position - TODO - * @returns {AudioInjector} TODO + * @param {SoundObject} sound - The content of an audio file, loaded using {@link SoundCache.getSound}. See + * {@link SoundObject} for supported formats. + * @param {Vec3} position - The position in the domain to play the sound. + * @returns {AudioInjector} The audio injector that plays the audio file. */ // FIXME: there is no way to play a positionless sound Q_INVOKABLE ScriptAudioInjector* playSystemSound(SharedSoundPointer sound, const QVector3D& position); /**jsdoc - * TODO + * Set whether or not the audio input should be used in stereo. If the audio input does not support stereo then setting a + * value of true has no effect. * @function Audio.setStereoInput - * @param {boolean} stereo - TODO + * @param {boolean} stereo - true if the audio input should be used in stereo, otherwise false. */ Q_INVOKABLE void setStereoInput(bool stereo); /**jsdoc - * TODO + * Get whether or not the audio input is used in stereo. * @function Audio.isStereoInput - * @returns {boolean} true if TODO, otherwise false. + * @returns {boolean} true if the audio input is used in stereo, otherwise false. */ Q_INVOKABLE bool isStereoInput(); signals: /**jsdoc - * Triggered when the client is muted by the mixer. + * Triggered when the client is muted by the mixer because their loudness value for the noise background has reached the + * threshold set for the domain in the server settings. * @function Audio.mutedByMixer * @returns {Signal} */ void mutedByMixer(); /**jsdoc - * Triggered when the entire environment is muted by the mixer. TODO: What is the "whole environment"? + * Triggered when everyone is muted by the mixer. * @function Audio.environmentMuted * @returns {Signal} */ @@ -98,31 +119,35 @@ signals: void disconnected(); /**jsdoc - * Triggered when the noise gate is opened. TODO: Description of noise gate. + * Triggered when the noise gate is opened: the input audio signal is no longer blocked (fully attenuated) because it has + * risen above an adaptive threshold set just above the noise floor. Only occurs if Audio.noiseReduction is + * true. * @function Audio.noiseGateOpened * @returns {Signal} */ void noiseGateOpened(); /**jsdoc - * Triggered when the noise gate is closed. TODO: Description of noise gate. + * Triggered when the noise gate is closed: the input audio signal is blocked (fully attenuated) because it has fallen + * below an adaptive threshold set just above the noise floor. Only occurs if Audio.noiseReduction is + * true. * @function Audio.noiseGateClosed * @returns {Signal} */ void noiseGateClosed(); /**jsdoc - * Triggered when a frame of microphone audio input is processed. + * Triggered when a frame of audio input is processed. * @function Audio.inputReceived - * @param {Int16Array} inputSamples - TODO + * @param {Int16Array} inputSamples - The audio input processed. * @returns {Signal} */ void inputReceived(const QByteArray& inputSamples); /**jsdoc - * TODO + * Triggered when the input audio use changes between mono and stereo. * @function Audio.isStereoInputChanged - * @param {boolean} isStereo - TODO + * @param {boolean} isStereo - true if the input audio is stereo, otherwise false. * @returns {Signal} */ void isStereoInputChanged(bool isStereo); diff --git a/libraries/script-engine/src/ScriptAudioInjector.h b/libraries/script-engine/src/ScriptAudioInjector.h index 5d66461160..2c88d618e1 100644 --- a/libraries/script-engine/src/ScriptAudioInjector.h +++ b/libraries/script-engine/src/ScriptAudioInjector.h @@ -17,8 +17,7 @@ #include /**jsdoc - * TODO - * Used in the {@link Audio} API. + * Plays — "injects" — the content of an audio file. Used in the {@link Audio} API. * * @class AudioInjector * @@ -27,9 +26,11 @@ * @hifi-server-entity * @hifi-assignment-client * - * @property {boolean} playing - true if TODO, otherwise false. Read-only. - * @property {number} loudness - TODO Read-only. - * @property {AudioInjector.AudioInjectorOptions} options - TODO + * @property {boolean} playing - true if the audio is currently playing, otherwise false. + * Read-only. + * @property {number} loudness - The loudness in the last frame of audio, range 0.01.0. + * Read-only. + * @property {AudioInjector.AudioInjectorOptions} options - Configures how the injector plays the audio. */ class ScriptAudioInjector : public QObject { Q_OBJECT @@ -43,58 +44,99 @@ public: public slots: /**jsdoc - * TODO + * Stop current playback, if any, and start playing from the beginning. * @function AudioInjector.restart */ void restart() { _injector->restart(); } /**jsdoc - * TODO + * Stop audio playback. * @function AudioInjector.stop + * @example Stop playing a sound before it finishes. + * var sound = SoundCache.getSound(Script.resourcesPath() + "sounds/sample.wav"); + * var injector; + * var injectorOptions = { + * position: MyAvatar.position + * }; + * + * Script.setTimeout(function () { // Give the sound time to load. + * injector = Audio.playSound(sound, injectorOptions); + * }, 1000); + * + * Script.setTimeout(function () { + * injector.stop(); + * }, 2000); */ void stop() { _injector->stop(); } /**jsdoc - * TODO + * Get the current configuration of the audio injector. * @function AudioInjector.getOptions - * @returns {AudioInjector.AudioInjectorOptions} TODO + * @returns {AudioInjector.AudioInjectorOptions} Configuration of how the injector plays the audio. */ const AudioInjectorOptions& getOptions() const { return _injector->getOptions(); } /**jsdoc - * TODO + * Configure how the injector plays the audio. * @function AudioInjector.setOptions - * @param {AudioInjector.AudioInjectorOptions} options - TODO + * @param {AudioInjector.AudioInjectorOptions} options - Configuration of how the injector plays the audio. */ void setOptions(const AudioInjectorOptions& options) { _injector->setOptions(options); } /**jsdoc - * TODO + * Get the loudness of the most recent frame of audio played. * @function AudioInjector.getLoudness - * @returns {number} TODO + * @returns {number} The loudness of the most recent frame of audio played, range 0.01.0. */ float getLoudness() const { return _injector->getLoudness(); } /**jsdoc - * TODO + * Get whether or not the audio is currently playing. * @function AudioInjector.isPlaying - * @returns {boolean} true if TODO, otherwise false. + * @returns {boolean} true if the audio is currently playing, otherwise false. + * @example See if a sound is playing. + * var sound = SoundCache.getSound(Script.resourcesPath() + "sounds/sample.wav"); + * var injector; + * var injectorOptions = { + * position: MyAvatar.position + * }; + * + * Script.setTimeout(function () { // Give the sound time to load. + * injector = Audio.playSound(sound, injectorOptions); + * }, 1000); + * + * Script.setTimeout(function () { + * print("Sound is playing: " + injector.isPlaying()); + * }, 2000); */ bool isPlaying() const { return _injector->isPlaying(); } signals: /**jsdoc - * Triggered when TODO + * Triggered when the audio has finished playing. * @function AudioInjector.finished * @returns {Signal} + * @example Report when a sound has finished playing. + * var sound = SoundCache.getSound(Script.resourcesPath() + "sounds/sample.wav"); + * var injector; + * var injectorOptions = { + * position: MyAvatar.position + * }; + * + * Script.setTimeout(function () { // Give the sound time to load. + * injector = Audio.playSound(sound, injectorOptions); + * injector.finished.connect(function () { + * print("Finished playing sound"); + * }); + * }, 1000); */ void finished(); protected slots: /**jsdoc - * TODO + * Stop audio playback. (Synonym of {@link AudioInjector.stop|stop}.) * @function AudioInjector.stopInjectorImmediately */ void stopInjectorImmediately(); From 3002abeddc5500692279e17b66d7a90a82712451 Mon Sep 17 00:00:00 2001 From: Simon Walton Date: Wed, 18 Jul 2018 18:22:36 -0700 Subject: [PATCH 03/37] Add DS option to turn off packet authentication --- domain-server/resources/describe-settings.json | 8 ++++++++ domain-server/src/DomainServer.cpp | 6 +++++- libraries/networking/src/LimitedNodeList.cpp | 7 ++++--- libraries/networking/src/LimitedNodeList.h | 3 +++ libraries/networking/src/NodeList.cpp | 4 ++++ 5 files changed, 24 insertions(+), 4 deletions(-) diff --git a/domain-server/resources/describe-settings.json b/domain-server/resources/describe-settings.json index 83dd633d22..4e68d29e85 100644 --- a/domain-server/resources/describe-settings.json +++ b/domain-server/resources/describe-settings.json @@ -46,6 +46,14 @@ "default": "40102", "type": "int", "advanced": true + }, + { + "name": "enable_authentication", + "label": "Enable Authentication", + "help": "Enable secure checksums on communication that uses the High Fidelity protocol. Increases security with possibly a small performance penalty.", + "default": true, + "type": "checkbox", + "advanced": true } ] }, diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index eccd1c1e20..5324bb407d 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -630,6 +630,7 @@ bool DomainServer::isPacketVerified(const udt::Packet& packet) { void DomainServer::setupNodeListAndAssignments() { const QString CUSTOM_LOCAL_PORT_OPTION = "metaverse.local_port"; + static const QString ENABLE_PACKET_AUTHENTICATION = "metaverse.enable_authentication"; QVariant localPortValue = _settingsManager.valueOrDefaultValueForKeyPath(CUSTOM_LOCAL_PORT_OPTION); int domainServerPort = localPortValue.toInt(); @@ -696,6 +697,9 @@ void DomainServer::setupNodeListAndAssignments() { } } + bool isAuthEnabled = _settingsManager.valueOrDefaultValueForKeyPath(ENABLE_PACKET_AUTHENTICATION).toBool(); + nodeList->setAuthenticatePackets(isAuthEnabled); + connect(nodeList.data(), &LimitedNodeList::nodeAdded, this, &DomainServer::nodeAdded); connect(nodeList.data(), &LimitedNodeList::nodeKilled, this, &DomainServer::nodeKilled); @@ -1133,7 +1137,7 @@ void DomainServer::sendDomainListToNode(const SharedNodePointer& node, const Hif extendedHeaderStream << node->getUUID(); extendedHeaderStream << node->getLocalID(); extendedHeaderStream << node->getPermissions(); - + extendedHeaderStream << limitedNodeList->getAuthenticatePackets(); auto domainListPackets = NLPacketList::create(PacketType::DomainList, extendedHeader); // always send the node their own UUID back diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index 502874fbfb..b6b2369703 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -328,9 +328,10 @@ bool LimitedNodeList::packetSourceAndHashMatchAndTrackBandwidth(const udt::Packe if (sourceNode) { bool verifiedPacket = !PacketTypeEnum::getNonVerifiedPackets().contains(headerType); - bool ignoreVerification = isDomainServer() && PacketTypeEnum::getDomainIgnoredVerificationPackets().contains(headerType); + bool verificationEnabled = !(isDomainServer() && PacketTypeEnum::getDomainIgnoredVerificationPackets().contains(headerType)) + && _useAuthentication; - if (verifiedPacket && !ignoreVerification) { + if (verifiedPacket && verificationEnabled) { QByteArray packetHeaderHash = NLPacket::verificationHashInHeader(packet); QByteArray expectedHash; @@ -383,7 +384,7 @@ void LimitedNodeList::fillPacketHeader(const NLPacket& packet, HMACAuth* hmacAut packet.writeSourceID(getSessionLocalID()); } - if (hmacAuth + if (_useAuthentication && hmacAuth && !PacketTypeEnum::getNonSourcedPackets().contains(packet.getType()) && !PacketTypeEnum::getNonVerifiedPackets().contains(packet.getType())) { packet.writeVerificationHash(*hmacAuth); diff --git a/libraries/networking/src/LimitedNodeList.h b/libraries/networking/src/LimitedNodeList.h index 05374bbfbb..cffc49521a 100644 --- a/libraries/networking/src/LimitedNodeList.h +++ b/libraries/networking/src/LimitedNodeList.h @@ -307,6 +307,8 @@ public: bool isPacketVerifiedWithSource(const udt::Packet& packet, Node* sourceNode = nullptr); bool isPacketVerified(const udt::Packet& packet) { return isPacketVerifiedWithSource(packet); } + void setAuthenticatePackets(bool useAuthentication) { _useAuthentication = useAuthentication; } + bool getAuthenticatePackets() const { return _useAuthentication; } static void makeSTUNRequestPacket(char* stunRequestPacket); @@ -394,6 +396,7 @@ protected: HifiSockAddr _publicSockAddr; HifiSockAddr _stunSockAddr { STUN_SERVER_HOSTNAME, STUN_SERVER_PORT }; bool _hasTCPCheckedLocalSocket { false }; + bool _useAuthentication { true }; PacketReceiver* _packetReceiver; diff --git a/libraries/networking/src/NodeList.cpp b/libraries/networking/src/NodeList.cpp index 2ce734dd26..dd351ef940 100644 --- a/libraries/networking/src/NodeList.cpp +++ b/libraries/networking/src/NodeList.cpp @@ -665,6 +665,10 @@ void NodeList::processDomainServerList(QSharedPointer message) NodePermissions newPermissions; packetStream >> newPermissions; setPermissions(newPermissions); + // Is packet authentication enabled? + bool isAuthenticated; + packetStream >> isAuthenticated; + setAuthenticatePackets(isAuthenticated); // pull each node in the packet while (packetStream.device()->pos() < message->getSize()) { From 5d13f6c030676dac17911679b37c1fe4c19b23ef Mon Sep 17 00:00:00 2001 From: Simon Walton Date: Thu, 19 Jul 2018 09:55:28 -0700 Subject: [PATCH 04/37] Bump DomainListVersion for new protocol --- libraries/networking/src/udt/PacketHeaders.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libraries/networking/src/udt/PacketHeaders.h b/libraries/networking/src/udt/PacketHeaders.h index 6e1aca83e5..3c47cdcf09 100644 --- a/libraries/networking/src/udt/PacketHeaders.h +++ b/libraries/networking/src/udt/PacketHeaders.h @@ -313,7 +313,8 @@ enum class DomainListVersion : PacketVersion { PrePermissionsGrid = 18, PermissionsGrid, GetUsernameFromUUIDSupport, - GetMachineFingerprintFromUUIDSupport + GetMachineFingerprintFromUUIDSupport, + AuthenticationOptional }; enum class AudioVersion : PacketVersion { From d147d17b707f53c32c5b8b784dbf2ee49ebb0868 Mon Sep 17 00:00:00 2001 From: Simon Walton Date: Thu, 19 Jul 2018 10:04:29 -0700 Subject: [PATCH 05/37] Update PacketType version for domain list --- libraries/networking/src/udt/PacketHeaders.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/networking/src/udt/PacketHeaders.cpp b/libraries/networking/src/udt/PacketHeaders.cpp index 13ffcb5120..3536ab832c 100644 --- a/libraries/networking/src/udt/PacketHeaders.cpp +++ b/libraries/networking/src/udt/PacketHeaders.cpp @@ -27,7 +27,7 @@ PacketVersion versionForPacketType(PacketType packetType) { case PacketType::StunResponse: return 17; case PacketType::DomainList: - return static_cast(DomainListVersion::GetMachineFingerprintFromUUIDSupport); + return static_cast(DomainListVersion::AuthenticationOptional); case PacketType::EntityAdd: case PacketType::EntityClone: case PacketType::EntityEdit: From 81c8fe611445434203ce33612084ac34fa0d2e92 Mon Sep 17 00:00:00 2001 From: Simon Walton Date: Tue, 24 Jul 2018 17:06:09 -0700 Subject: [PATCH 06/37] Change 'Enable Authentication' to 'Enable Packet Verification' --- domain-server/resources/describe-settings.json | 4 ++-- domain-server/src/DomainServer.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/domain-server/resources/describe-settings.json b/domain-server/resources/describe-settings.json index 4e68d29e85..db25e247d3 100644 --- a/domain-server/resources/describe-settings.json +++ b/domain-server/resources/describe-settings.json @@ -48,8 +48,8 @@ "advanced": true }, { - "name": "enable_authentication", - "label": "Enable Authentication", + "name": "enable_packet_verification", + "label": "Enable Packet Verification", "help": "Enable secure checksums on communication that uses the High Fidelity protocol. Increases security with possibly a small performance penalty.", "default": true, "type": "checkbox", diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 5324bb407d..b381da159d 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -630,7 +630,7 @@ bool DomainServer::isPacketVerified(const udt::Packet& packet) { void DomainServer::setupNodeListAndAssignments() { const QString CUSTOM_LOCAL_PORT_OPTION = "metaverse.local_port"; - static const QString ENABLE_PACKET_AUTHENTICATION = "metaverse.enable_authentication"; + static const QString ENABLE_PACKET_AUTHENTICATION = "metaverse.enable_packet_verification"; QVariant localPortValue = _settingsManager.valueOrDefaultValueForKeyPath(CUSTOM_LOCAL_PORT_OPTION); int domainServerPort = localPortValue.toInt(); From fde77add79563ed00146c78f10a30eea1966c6ab Mon Sep 17 00:00:00 2001 From: luiscuenca Date: Wed, 1 Aug 2018 11:49:18 -0700 Subject: [PATCH 07/37] Elbow pole vectors fixes --- libraries/animation/src/Rig.cpp | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/libraries/animation/src/Rig.cpp b/libraries/animation/src/Rig.cpp index 33f14e121e..64f4708903 100644 --- a/libraries/animation/src/Rig.cpp +++ b/libraries/animation/src/Rig.cpp @@ -1547,16 +1547,18 @@ bool Rig::calculateElbowPoleVector(int handIndex, int elbowIndex, int armIndex, glm::vec3 backVector = oppositeArmPose.trans() - armPose.trans(); glm::vec3 backCenter = armPose.trans() + 0.5f * backVector; - const float OVER_BACK_HEAD_PERCENTAGE = 0.2f; + glm::vec3 frontVector = glm::normalize(glm::cross(backVector, Vectors::UNIT_Y)); + glm::vec3 topVector = glm::normalize(glm::cross(frontVector, backVector)); + + glm::vec3 centerToHand = handPose.trans() - backCenter; + glm::vec3 headCenter = backCenter + glm::length(backVector) * topVector; - glm::vec3 headCenter = backCenter + glm::vec3(0, OVER_BACK_HEAD_PERCENTAGE * backVector.length(), 0); - glm::vec3 frontVector = glm::normalize(glm::cross(backVector, glm::vec3(0, 1, 0))); // Make sure is pointing forward frontVector = frontVector.z < 0 ? -frontVector : frontVector; - float horizontalModule = glm::dot(armToHand, glm::vec3(0, -1, 0)); - glm::vec3 headForward = headCenter + horizontalModule * frontVector; + float horizontalModule = glm::dot(centerToHand, -topVector); + glm::vec3 headForward = headCenter + glm::max(0.0f, horizontalModule) * frontVector; glm::vec3 armToHead = headForward - armPose.trans(); float armToHandDistance = glm::length(armToHand); @@ -1570,8 +1572,10 @@ bool Rig::calculateElbowPoleVector(int handIndex, int elbowIndex, int armIndex, // How much the hand is reaching for the opposite side float oppositeProjection = glm::dot(armToHandDir, glm::normalize(backVector)); - // Don't use pole vector when the hands are behind - if (glm::dot(frontVector, armToHand) < 0 && oppositeProjection < 0.5f * armTotalDistance) { + bool isCrossed = glm::dot(centerToHand, backVector) > 0; + bool isBehind = glm::dot(frontVector, armToHand) < 0; + // Don't use pole vector when the hands are behind the back and the arms are not crossed + if (isBehind && !isCrossed) { return false; } @@ -1585,7 +1589,7 @@ bool Rig::calculateElbowPoleVector(int handIndex, int elbowIndex, int armIndex, glm::vec3 correctionVector = glm::vec3(0, 0, 0); const float FORWARD_TRIGGER_PERCENTAGE = 0.2f; - const float FORWARD_CORRECTOR_WEIGHT = 3.0f; + const float FORWARD_CORRECTOR_WEIGHT = 2.3f; float elbowForwardTrigger = FORWARD_TRIGGER_PERCENTAGE * armToHandDistance; From 3e9e00f1d6889f2263949ad8bfa4e85715468d36 Mon Sep 17 00:00:00 2001 From: David Back Date: Wed, 1 Aug 2018 12:42:50 -0700 Subject: [PATCH 08/37] use key codes for entity camera keys --- scripts/system/libraries/entityCameraTool.js | 27 +++++++++++--------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/scripts/system/libraries/entityCameraTool.js b/scripts/system/libraries/entityCameraTool.js index fb808cc7ea..3869ff2fe8 100644 --- a/scripts/system/libraries/entityCameraTool.js +++ b/scripts/system/libraries/entityCameraTool.js @@ -39,6 +39,9 @@ var EASING_MULTIPLIER = 8; var INITIAL_ZOOM_DISTANCE = 2; var INITIAL_ZOOM_DISTANCE_FIRST_PERSON = 3; +var KEY_A = 80; +var KEY_D = 80; + var easeOutCubic = function(t) { t--; return t * t * t + 1; @@ -77,17 +80,17 @@ CameraManager = function() { } var keyToActionMapping = { - "a": "orbitLeft", - "d": "orbitRight", - "w": "orbitForward", - "s": "orbitBackward", - "e": "orbitUp", - "c": "orbitDown", - - "LEFT": "orbitLeft", - "RIGHT": "orbitRight", - "UP": "orbitForward", - "DOWN": "orbitBackward", + 65: "orbitLeft", // "a" + 68: "orbitRight", // "d" + 87: "orbitForward", // "w" + 83: "orbitBackward",// "s" + 69: "orbitUp", // "e" + 67: "orbitDown", // "c" + + 16777234: "orbitLeft", //"LEFT" + 16777236: "orbitRight", //"RIGHT" + 16777235: "orbitForward", //"UP" + 16777237: "orbitBackward",//"DOWN" } var CAPTURED_KEYS = []; @@ -96,7 +99,7 @@ CameraManager = function() { } function getActionForKeyEvent(event) { - var action = keyToActionMapping[event.text]; + var action = keyToActionMapping[event.key]; if (action !== undefined) { if (event.isShifted) { if (action === "orbitForward") { From 97e45643b009fbcce63d2b05902508ffec910eb3 Mon Sep 17 00:00:00 2001 From: David Back Date: Wed, 1 Aug 2018 12:44:40 -0700 Subject: [PATCH 09/37] spacing --- scripts/system/libraries/entityCameraTool.js | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/scripts/system/libraries/entityCameraTool.js b/scripts/system/libraries/entityCameraTool.js index 3869ff2fe8..5f56c6edf6 100644 --- a/scripts/system/libraries/entityCameraTool.js +++ b/scripts/system/libraries/entityCameraTool.js @@ -80,17 +80,17 @@ CameraManager = function() { } var keyToActionMapping = { - 65: "orbitLeft", // "a" - 68: "orbitRight", // "d" - 87: "orbitForward", // "w" - 83: "orbitBackward",// "s" - 69: "orbitUp", // "e" - 67: "orbitDown", // "c" + 65: "orbitLeft", // "a" + 68: "orbitRight", // "d" + 87: "orbitForward", // "w" + 83: "orbitBackward", // "s" + 69: "orbitUp", // "e" + 67: "orbitDown", // "c" - 16777234: "orbitLeft", //"LEFT" - 16777236: "orbitRight", //"RIGHT" - 16777235: "orbitForward", //"UP" - 16777237: "orbitBackward",//"DOWN" + 16777234: "orbitLeft", // "LEFT" + 16777236: "orbitRight", // "RIGHT" + 16777235: "orbitForward", // "UP" + 16777237: "orbitBackward", // "DOWN" } var CAPTURED_KEYS = []; From f946bb73eff2ede58241547e8f6a350cb979d727 Mon Sep 17 00:00:00 2001 From: David Back Date: Wed, 1 Aug 2018 12:46:17 -0700 Subject: [PATCH 10/37] remove constants --- scripts/system/libraries/entityCameraTool.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/scripts/system/libraries/entityCameraTool.js b/scripts/system/libraries/entityCameraTool.js index 5f56c6edf6..36c45515e5 100644 --- a/scripts/system/libraries/entityCameraTool.js +++ b/scripts/system/libraries/entityCameraTool.js @@ -39,8 +39,6 @@ var EASING_MULTIPLIER = 8; var INITIAL_ZOOM_DISTANCE = 2; var INITIAL_ZOOM_DISTANCE_FIRST_PERSON = 3; -var KEY_A = 80; -var KEY_D = 80; var easeOutCubic = function(t) { t--; From cdbf75666fe22437145d58d815e128c1b2bf5951 Mon Sep 17 00:00:00 2001 From: David Back Date: Wed, 1 Aug 2018 12:46:49 -0700 Subject: [PATCH 11/37] new line --- scripts/system/libraries/entityCameraTool.js | 1 - 1 file changed, 1 deletion(-) diff --git a/scripts/system/libraries/entityCameraTool.js b/scripts/system/libraries/entityCameraTool.js index 36c45515e5..f554f45722 100644 --- a/scripts/system/libraries/entityCameraTool.js +++ b/scripts/system/libraries/entityCameraTool.js @@ -39,7 +39,6 @@ var EASING_MULTIPLIER = 8; var INITIAL_ZOOM_DISTANCE = 2; var INITIAL_ZOOM_DISTANCE_FIRST_PERSON = 3; - var easeOutCubic = function(t) { t--; return t * t * t + 1; From 4b317a84d811e4e04c0909ee1e87df018aab92c5 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Fri, 27 Jul 2018 15:25:57 -0700 Subject: [PATCH 12/37] Don't allow Web surfaces created by non-client scripts to access files --- interface/resources/qml/QmlWebWindow.qml | 1 + interface/src/Application.cpp | 7 ++-- libraries/qml/src/qml/OffscreenSurface.cpp | 11 +++-- libraries/qml/src/qml/OffscreenSurface.h | 31 +++++++++----- libraries/ui/src/QmlFragmentClass.cpp | 6 +-- libraries/ui/src/QmlFragmentClass.h | 14 ++++++- libraries/ui/src/QmlWebWindowClass.cpp | 4 +- libraries/ui/src/QmlWebWindowClass.h | 12 +++++- libraries/ui/src/QmlWindowClass.cpp | 30 ++++++++++--- libraries/ui/src/QmlWindowClass.h | 17 +++++++- libraries/ui/src/ui/OffscreenQmlSurface.cpp | 24 +++++------ .../ui/src/ui/TabletScriptingInterface.cpp | 2 + .../ui/src/ui/types/ContextAwareProfile.cpp | 32 ++++++++++++++ .../ui/src/ui/types/ContextAwareProfile.h | 42 +++++++++++++++++++ libraries/ui/src/ui/types/FileTypeProfile.cpp | 21 ++++++++-- libraries/ui/src/ui/types/FileTypeProfile.h | 17 ++++++-- .../ui/types/FileTypeRequestInterceptor.cpp | 25 ----------- .../src/ui/types/FileTypeRequestInterceptor.h | 30 ------------- .../src/ui/types/HFTabletWebEngineProfile.h | 23 ---------- .../HFTabletWebEngineRequestInterceptor.h | 30 ------------- .../ui/src/ui/types/HFWebEngineProfile.cpp | 20 ++++++--- .../ui/src/ui/types/HFWebEngineProfile.h | 17 ++++++-- .../types/HFWebEngineRequestInterceptor.cpp | 25 ----------- .../ui/types/HFWebEngineRequestInterceptor.h | 30 ------------- libraries/ui/src/ui/types/RequestFilters.cpp | 32 +++++++++++--- libraries/ui/src/ui/types/RequestFilters.h | 6 ++- 26 files changed, 275 insertions(+), 234 deletions(-) create mode 100644 libraries/ui/src/ui/types/ContextAwareProfile.cpp create mode 100644 libraries/ui/src/ui/types/ContextAwareProfile.h delete mode 100644 libraries/ui/src/ui/types/FileTypeRequestInterceptor.cpp delete mode 100644 libraries/ui/src/ui/types/FileTypeRequestInterceptor.h delete mode 100644 libraries/ui/src/ui/types/HFTabletWebEngineProfile.h delete mode 100644 libraries/ui/src/ui/types/HFTabletWebEngineRequestInterceptor.h delete mode 100644 libraries/ui/src/ui/types/HFWebEngineRequestInterceptor.cpp delete mode 100644 libraries/ui/src/ui/types/HFWebEngineRequestInterceptor.h diff --git a/interface/resources/qml/QmlWebWindow.qml b/interface/resources/qml/QmlWebWindow.qml index d73a574081..8c4d6145ec 100644 --- a/interface/resources/qml/QmlWebWindow.qml +++ b/interface/resources/qml/QmlWebWindow.qml @@ -62,6 +62,7 @@ Windows.ScrollingWindow { url: "about:blank" anchors.fill: parent focus: true + profile: HFWebEngineProfile; property string userScriptUrl: "" diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 65fbefa381..ecd091ba2b 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -6603,11 +6603,12 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEnginePointe scriptEngine->registerGetterSetter("location", LocationScriptingInterface::locationGetter, LocationScriptingInterface::locationSetter); + bool clientScript = scriptEngine->isClientScript(); + scriptEngine->registerFunction("OverlayWindow", clientScript ? QmlWindowClass::constructor : QmlWindowClass::restricted_constructor); #if !defined(Q_OS_ANDROID) - scriptEngine->registerFunction("OverlayWebWindow", QmlWebWindowClass::constructor); + scriptEngine->registerFunction("OverlayWebWindow", clientScript ? QmlWebWindowClass::constructor : QmlWebWindowClass::restricted_constructor); #endif - scriptEngine->registerFunction("OverlayWindow", QmlWindowClass::constructor); - scriptEngine->registerFunction("QmlFragment", QmlFragmentClass::constructor); + scriptEngine->registerFunction("QmlFragment", clientScript ? QmlFragmentClass::constructor : QmlFragmentClass::restricted_constructor); scriptEngine->registerGlobalObject("Menu", MenuScriptingInterface::getInstance()); scriptEngine->registerGlobalObject("DesktopPreviewProvider", DependencyManager::get().data()); diff --git a/libraries/qml/src/qml/OffscreenSurface.cpp b/libraries/qml/src/qml/OffscreenSurface.cpp index ea6f1ce324..bbffee2407 100644 --- a/libraries/qml/src/qml/OffscreenSurface.cpp +++ b/libraries/qml/src/qml/OffscreenSurface.cpp @@ -40,7 +40,8 @@ static QSize clampSize(const QSize& qsize, uint32_t maxDimension) { return fromGlm(clampSize(toGlm(qsize), maxDimension)); } -const QmlContextObjectCallback OffscreenSurface::DEFAULT_CONTEXT_CALLBACK = [](QQmlContext*, QQuickItem*) {}; +const QmlContextObjectCallback OffscreenSurface::DEFAULT_CONTEXT_OBJECT_CALLBACK = [](QQmlContext*, QQuickItem*) {}; +const QmlContextCallback OffscreenSurface::DEFAULT_CONTEXT_CALLBACK = [](QQmlContext*) {}; void OffscreenSurface::initializeEngine(QQmlEngine* engine) { } @@ -266,8 +267,8 @@ void OffscreenSurface::load(const QUrl& qmlSource, bool createNewContext, const loadInternal(qmlSource, createNewContext, nullptr, callback); } -void OffscreenSurface::loadInNewContext(const QUrl& qmlSource, const QmlContextObjectCallback& callback) { - load(qmlSource, true, callback); +void OffscreenSurface::loadInNewContext(const QUrl& qmlSource, const QmlContextObjectCallback& callback, const QmlContextCallback& contextCallback) { + loadInternal(qmlSource, true, nullptr, callback, contextCallback); } void OffscreenSurface::load(const QUrl& qmlSource, const QmlContextObjectCallback& callback) { @@ -281,7 +282,8 @@ void OffscreenSurface::load(const QString& qmlSourceFile, const QmlContextObject void OffscreenSurface::loadInternal(const QUrl& qmlSource, bool createNewContext, QQuickItem* parent, - const QmlContextObjectCallback& callback) { + const QmlContextObjectCallback& callback, + const QmlContextCallback& contextCallback) { PROFILE_RANGE_EX(app, "OffscreenSurface::loadInternal", 0xffff00ff, 0, { std::make_pair("url", qmlSource.toDisplayString()) }); if (QThread::currentThread() != thread()) { qFatal("Called load on a non-surface thread"); @@ -310,6 +312,7 @@ void OffscreenSurface::loadInternal(const QUrl& qmlSource, } auto targetContext = contextForUrl(finalQmlSource, parent, createNewContext); + contextCallback(targetContext); QQmlComponent* qmlComponent; { PROFILE_RANGE(app, "new QQmlComponent"); diff --git a/libraries/qml/src/qml/OffscreenSurface.h b/libraries/qml/src/qml/OffscreenSurface.h index 555f2ee6a4..b3539e7709 100644 --- a/libraries/qml/src/qml/OffscreenSurface.h +++ b/libraries/qml/src/qml/OffscreenSurface.h @@ -37,13 +37,15 @@ namespace impl { class SharedObject; } +using QmlContextCallback = ::std::function; using QmlContextObjectCallback = ::std::function; class OffscreenSurface : public QObject { Q_OBJECT public: - static const QmlContextObjectCallback DEFAULT_CONTEXT_CALLBACK; + static const QmlContextObjectCallback DEFAULT_CONTEXT_OBJECT_CALLBACK; + static const QmlContextCallback DEFAULT_CONTEXT_CALLBACK; using TextureAndFence = std::pair; using MouseTranslator = std::function; @@ -85,10 +87,15 @@ public: Q_INVOKABLE void load(const QUrl& qmlSource, QQuickItem* parent, const QJSValue& callback); // For use from C++ - Q_INVOKABLE void load(const QUrl& qmlSource, const QmlContextObjectCallback& callback = DEFAULT_CONTEXT_CALLBACK); - Q_INVOKABLE void load(const QUrl& qmlSource, bool createNewContext, const QmlContextObjectCallback& callback = DEFAULT_CONTEXT_CALLBACK); - Q_INVOKABLE void load(const QString& qmlSourceFile, const QmlContextObjectCallback& callback = DEFAULT_CONTEXT_CALLBACK); - Q_INVOKABLE void loadInNewContext(const QUrl& qmlSource, const QmlContextObjectCallback& callback = DEFAULT_CONTEXT_CALLBACK); + Q_INVOKABLE void load(const QUrl& qmlSource, const QmlContextObjectCallback& callback = DEFAULT_CONTEXT_OBJECT_CALLBACK); + Q_INVOKABLE void load(const QUrl& qmlSource, + bool createNewContext, + const QmlContextObjectCallback& callback = DEFAULT_CONTEXT_OBJECT_CALLBACK); + Q_INVOKABLE void load(const QString& qmlSourceFile, + const QmlContextObjectCallback& callback = DEFAULT_CONTEXT_OBJECT_CALLBACK); + Q_INVOKABLE void loadInNewContext(const QUrl& qmlSource, + const QmlContextObjectCallback& callback = DEFAULT_CONTEXT_OBJECT_CALLBACK, + const QmlContextCallback& contextCallback = DEFAULT_CONTEXT_CALLBACK); public slots: virtual void onFocusObjectChanged(QObject* newFocus) {} @@ -103,19 +110,21 @@ protected: virtual void initializeEngine(QQmlEngine* engine); virtual void loadInternal(const QUrl& qmlSource, - bool createNewContext, - QQuickItem* parent, - const QmlContextObjectCallback& callback) final; + bool createNewContext, + QQuickItem* parent, + const QmlContextObjectCallback& callback, + const QmlContextCallback& contextCallback = DEFAULT_CONTEXT_CALLBACK) final; virtual void finishQmlLoad(QQmlComponent* qmlComponent, - QQmlContext* qmlContext, - QQuickItem* parent, - const QmlContextObjectCallback& onQmlLoadedCallback) final; + QQmlContext* qmlContext, + QQuickItem* parent, + const QmlContextObjectCallback& onQmlLoadedCallback) final; virtual void onRootCreated() {} virtual void onItemCreated(QQmlContext* context, QQuickItem* newItem) {} virtual void onRootContextCreated(QQmlContext* qmlContext) {} virtual QQmlContext* contextForUrl(const QUrl& qmlSource, QQuickItem* parent, bool forceNewContext); + private: MouseTranslator _mouseTranslator{ [](const QPointF& p) { return p.toPoint(); } }; friend class hifi::qml::impl::SharedObject; diff --git a/libraries/ui/src/QmlFragmentClass.cpp b/libraries/ui/src/QmlFragmentClass.cpp index c4cac73b2d..13e3527ded 100644 --- a/libraries/ui/src/QmlFragmentClass.cpp +++ b/libraries/ui/src/QmlFragmentClass.cpp @@ -20,10 +20,10 @@ std::mutex QmlFragmentClass::_mutex; std::map QmlFragmentClass::_fragments; -QmlFragmentClass::QmlFragmentClass(QString id) : qml(id) { } +QmlFragmentClass::QmlFragmentClass(bool restricted, QString id) : QmlWindowClass(restricted), qml(id) { } // Method called by Qt scripts to create a new bottom menu bar in Android -QScriptValue QmlFragmentClass::constructor(QScriptContext* context, QScriptEngine* engine) { +QScriptValue QmlFragmentClass::internal_constructor(QScriptContext* context, QScriptEngine* engine, bool restricted) { std::lock_guard guard(_mutex); auto qml = context->argument(0).toVariant().toMap().value("qml"); @@ -41,7 +41,7 @@ QScriptValue QmlFragmentClass::constructor(QScriptContext* context, QScriptEngin auto properties = parseArguments(context); auto offscreenUi = DependencyManager::get(); - QmlFragmentClass* retVal = new QmlFragmentClass(qml.toString()); + QmlFragmentClass* retVal = new QmlFragmentClass(restricted, qml.toString()); Q_ASSERT(retVal); if (QThread::currentThread() != qApp->thread()) { retVal->moveToThread(qApp->thread()); diff --git a/libraries/ui/src/QmlFragmentClass.h b/libraries/ui/src/QmlFragmentClass.h index 8a8d0e1732..ea80b2bd13 100644 --- a/libraries/ui/src/QmlFragmentClass.h +++ b/libraries/ui/src/QmlFragmentClass.h @@ -13,9 +13,19 @@ class QmlFragmentClass : public QmlWindowClass { Q_OBJECT + +private: + static QScriptValue internal_constructor(QScriptContext* context, QScriptEngine* engine, bool restricted); public: - QmlFragmentClass(QString id); - static QScriptValue constructor(QScriptContext* context, QScriptEngine* engine); + static QScriptValue constructor(QScriptContext* context, QScriptEngine* engine) { + return internal_constructor(context, engine, false); + } + + static QScriptValue restricted_constructor(QScriptContext* context, QScriptEngine* engine ){ + return internal_constructor(context, engine, true); + } + + QmlFragmentClass(bool restricted, QString id); /**jsdoc * Creates a new button, adds it to this and returns it. diff --git a/libraries/ui/src/QmlWebWindowClass.cpp b/libraries/ui/src/QmlWebWindowClass.cpp index 44a0af7787..282161497a 100644 --- a/libraries/ui/src/QmlWebWindowClass.cpp +++ b/libraries/ui/src/QmlWebWindowClass.cpp @@ -20,10 +20,10 @@ static const char* const URL_PROPERTY = "source"; static const char* const SCRIPT_PROPERTY = "scriptUrl"; // Method called by Qt scripts to create a new web window in the overlay -QScriptValue QmlWebWindowClass::constructor(QScriptContext* context, QScriptEngine* engine) { +QScriptValue QmlWebWindowClass::internal_constructor(QScriptContext* context, QScriptEngine* engine, bool restricted) { auto properties = parseArguments(context); auto offscreenUi = DependencyManager::get(); - QmlWebWindowClass* retVal = new QmlWebWindowClass(); + QmlWebWindowClass* retVal = new QmlWebWindowClass(restricted); Q_ASSERT(retVal); if (QThread::currentThread() != qApp->thread()) { retVal->moveToThread(qApp->thread()); diff --git a/libraries/ui/src/QmlWebWindowClass.h b/libraries/ui/src/QmlWebWindowClass.h index 8cf77e4286..e3aea22e3d 100644 --- a/libraries/ui/src/QmlWebWindowClass.h +++ b/libraries/ui/src/QmlWebWindowClass.h @@ -57,8 +57,18 @@ class QmlWebWindowClass : public QmlWindowClass { Q_OBJECT Q_PROPERTY(QString url READ getURL CONSTANT) +private: + static QScriptValue internal_constructor(QScriptContext* context, QScriptEngine* engine, bool restricted); public: - static QScriptValue constructor(QScriptContext* context, QScriptEngine* engine); + QmlWebWindowClass(bool restricted) : QmlWindowClass(restricted) {} + + static QScriptValue constructor(QScriptContext* context, QScriptEngine* engine) { + return internal_constructor(context, engine, false); + } + + static QScriptValue restricted_constructor(QScriptContext* context, QScriptEngine* engine ){ + return internal_constructor(context, engine, true); + } public slots: diff --git a/libraries/ui/src/QmlWindowClass.cpp b/libraries/ui/src/QmlWindowClass.cpp index 64fa27c8c6..0182e3adc3 100644 --- a/libraries/ui/src/QmlWindowClass.cpp +++ b/libraries/ui/src/QmlWindowClass.cpp @@ -25,6 +25,8 @@ #include #include "OffscreenUi.h" +#include "ui/types/HFWebEngineProfile.h" +#include "ui/types/FileTypeProfile.h" static const char* const SOURCE_PROPERTY = "source"; static const char* const TITLE_PROPERTY = "title"; @@ -68,10 +70,10 @@ QVariantMap QmlWindowClass::parseArguments(QScriptContext* context) { // Method called by Qt scripts to create a new web window in the overlay -QScriptValue QmlWindowClass::constructor(QScriptContext* context, QScriptEngine* engine) { +QScriptValue QmlWindowClass::internal_constructor(QScriptContext* context, QScriptEngine* engine, bool restricted) { auto properties = parseArguments(context); auto offscreenUi = DependencyManager::get(); - QmlWindowClass* retVal = new QmlWindowClass(); + QmlWindowClass* retVal = new QmlWindowClass(restricted); Q_ASSERT(retVal); if (QThread::currentThread() != qApp->thread()) { retVal->moveToThread(qApp->thread()); @@ -83,7 +85,7 @@ QScriptValue QmlWindowClass::constructor(QScriptContext* context, QScriptEngine* return engine->newQObject(retVal); } -QmlWindowClass::QmlWindowClass() { +QmlWindowClass::QmlWindowClass(bool restricted) : _restricted(restricted) { } @@ -99,8 +101,7 @@ void QmlWindowClass::initQml(QVariantMap properties) { auto offscreenUi = DependencyManager::get(); _source = properties[SOURCE_PROPERTY].toString(); - // Build the event bridge and wrapper on the main thread - offscreenUi->loadInNewContext(qmlSource(), [&](QQmlContext* context, QObject* object) { + auto objectInitLambda = [&](QQmlContext* context, QObject* object) { _qmlWindow = object; context->setContextProperty(EVENT_BRIDGE_PROPERTY, this); context->engine()->setObjectOwnership(this, QQmlEngine::CppOwnership); @@ -128,7 +129,24 @@ void QmlWindowClass::initQml(QVariantMap properties) { if (metaObject->indexOfSignal("moved") >= 0) connect(_qmlWindow, SIGNAL(moved(QVector2D)), this, SLOT(hasMoved(QVector2D)), Qt::QueuedConnection); connect(_qmlWindow, SIGNAL(windowClosed()), this, SLOT(hasClosed()), Qt::QueuedConnection); - }); + }; + + auto contextInitLambda = [&](QQmlContext* context) { +#if !defined(Q_OS_ANDROID) + // If the restricted flag is on, override the FileTypeProfile and HFWebEngineProfile objects in the + // QML surface root context with local ones + qDebug() << "Context initialization lambda"; + if (_restricted) { + qDebug() << "Restricting web content"; + ContextAwareProfile::restrictContext(context); + FileTypeProfile::registerWithContext(context); + HFWebEngineProfile::registerWithContext(context); + } +#endif + }; + + // Build the event bridge and wrapper on the main thread + offscreenUi->loadInNewContext(qmlSource(), objectInitLambda, contextInitLambda); Q_ASSERT(_qmlWindow); Q_ASSERT(dynamic_cast(_qmlWindow.data())); diff --git a/libraries/ui/src/QmlWindowClass.h b/libraries/ui/src/QmlWindowClass.h index 2b01c028ea..18ee1fedd5 100644 --- a/libraries/ui/src/QmlWindowClass.h +++ b/libraries/ui/src/QmlWindowClass.h @@ -38,9 +38,18 @@ class QmlWindowClass : public QObject { Q_PROPERTY(glm::vec2 size READ getSize WRITE setSize NOTIFY sizeChanged) Q_PROPERTY(bool visible READ isVisible WRITE setVisible NOTIFY visibleChanged) +private: + static QScriptValue internal_constructor(QScriptContext* context, QScriptEngine* engine, bool restricted); public: - static QScriptValue constructor(QScriptContext* context, QScriptEngine* engine); - QmlWindowClass(); + static QScriptValue constructor(QScriptContext* context, QScriptEngine* engine) { + return internal_constructor(context, engine, false); + } + + static QScriptValue restricted_constructor(QScriptContext* context, QScriptEngine* engine ){ + return internal_constructor(context, engine, true); + } + + QmlWindowClass(bool restricted); ~QmlWindowClass(); /**jsdoc @@ -51,6 +60,8 @@ public: QQuickItem* asQuickItem() const; + + public slots: /**jsdoc @@ -250,10 +261,12 @@ protected: QPointer _qmlWindow; QString _source; + const bool _restricted; private: // QmlWindow content may include WebView requiring EventBridge. void setKeyboardRaised(QObject* object, bool raised, bool numeric = false); + }; #endif diff --git a/libraries/ui/src/ui/OffscreenQmlSurface.cpp b/libraries/ui/src/ui/OffscreenQmlSurface.cpp index 48e778c063..2c947aea20 100644 --- a/libraries/ui/src/ui/OffscreenQmlSurface.cpp +++ b/libraries/ui/src/ui/OffscreenQmlSurface.cpp @@ -265,19 +265,6 @@ void OffscreenQmlSurface::initializeEngine(QQmlEngine* engine) { if (!javaScriptToInject.isEmpty()) { rootContext->setContextProperty("eventBridgeJavaScriptToInject", QVariant(javaScriptToInject)); } -#if !defined(Q_OS_ANDROID) - rootContext->setContextProperty("FileTypeProfile", new FileTypeProfile(rootContext)); - rootContext->setContextProperty("HFWebEngineProfile", new HFWebEngineProfile(rootContext)); - { - PROFILE_RANGE(startup, "FileTypeProfile"); - rootContext->setContextProperty("FileTypeProfile", new FileTypeProfile(rootContext)); - } - { - PROFILE_RANGE(startup, "HFWebEngineProfile"); - rootContext->setContextProperty("HFWebEngineProfile", new HFWebEngineProfile(rootContext)); - - } -#endif rootContext->setContextProperty("Paths", DependencyManager::get().data()); rootContext->setContextProperty("Tablet", DependencyManager::get().data()); rootContext->setContextProperty("Toolbars", DependencyManager::get().data()); @@ -300,6 +287,17 @@ void OffscreenQmlSurface::onRootContextCreated(QQmlContext* qmlContext) { // FIXME Compatibility mechanism for existing HTML and JS that uses eventBridgeWrapper // Find a way to flag older scripts using this mechanism and wanr that this is deprecated qmlContext->setContextProperty("eventBridgeWrapper", new EventBridgeWrapper(this, qmlContext)); +#if !defined(Q_OS_ANDROID) + { + PROFILE_RANGE(startup, "FileTypeProfile"); + FileTypeProfile::registerWithContext(qmlContext); + } + { + PROFILE_RANGE(startup, "HFWebEngineProfile"); + HFWebEngineProfile::registerWithContext(qmlContext); + + } +#endif } QQmlContext* OffscreenQmlSurface::contextForUrl(const QUrl& qmlSource, QQuickItem* parent, bool forceNewContext) { diff --git a/libraries/ui/src/ui/TabletScriptingInterface.cpp b/libraries/ui/src/ui/TabletScriptingInterface.cpp index 6f00e046af..4e920e430b 100644 --- a/libraries/ui/src/ui/TabletScriptingInterface.cpp +++ b/libraries/ui/src/ui/TabletScriptingInterface.cpp @@ -334,6 +334,8 @@ static const char* VRMENU_SOURCE_URL = "hifi/tablet/TabletMenu.qml"; class TabletRootWindow : public QmlWindowClass { virtual QString qmlSource() const override { return "hifi/tablet/WindowRoot.qml"; } +public: + TabletRootWindow() : QmlWindowClass(false) {} }; TabletProxy::TabletProxy(QObject* parent, const QString& name) : QObject(parent), _name(name) { diff --git a/libraries/ui/src/ui/types/ContextAwareProfile.cpp b/libraries/ui/src/ui/types/ContextAwareProfile.cpp new file mode 100644 index 0000000000..98cc94ec10 --- /dev/null +++ b/libraries/ui/src/ui/types/ContextAwareProfile.cpp @@ -0,0 +1,32 @@ +// +// FileTypeProfile.cpp +// interface/src/networking +// +// Created by Kunal Gosar on 2017-03-10. +// Copyright 2017 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "ContextAwareProfile.h" + +#if !defined(Q_OS_ANDROID) + +#include + +static const QString RESTRICTED_FLAG_PROPERTY = "RestrictFileAccess"; + +ContextAwareProfile::ContextAwareProfile(QQmlContext* parent) : + QQuickWebEngineProfile(parent), _context(parent) { } + + +void ContextAwareProfile::restrictContext(QQmlContext* context) { + context->setContextProperty(RESTRICTED_FLAG_PROPERTY, true); +} + +bool ContextAwareProfile::isRestricted(QQmlContext* context) { + return context->contextProperty(RESTRICTED_FLAG_PROPERTY).toBool(); +} + +#endif \ No newline at end of file diff --git a/libraries/ui/src/ui/types/ContextAwareProfile.h b/libraries/ui/src/ui/types/ContextAwareProfile.h new file mode 100644 index 0000000000..8fa5b98878 --- /dev/null +++ b/libraries/ui/src/ui/types/ContextAwareProfile.h @@ -0,0 +1,42 @@ +// +// Created by Bradley Austin Davis on 2018/07/27 +// Copyright 2013-2018 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#pragma once + +#ifndef hifi_ContextAwareProfile_h +#define hifi_ContextAwareProfile_h + +#include + +#if !defined(Q_OS_ANDROID) +#include +#include + +class QQmlContext; + +class ContextAwareProfile : public QQuickWebEngineProfile { +public: + static void restrictContext(QQmlContext* context); + static bool isRestricted(QQmlContext* context); + QQmlContext* getContext() const { return _context; } +protected: + + class RequestInterceptor : public QWebEngineUrlRequestInterceptor { + public: + RequestInterceptor(ContextAwareProfile* parent) : QWebEngineUrlRequestInterceptor(parent), _profile(parent) {} + QQmlContext* getContext() const { return _profile->getContext(); } + protected: + ContextAwareProfile* _profile; + }; + + ContextAwareProfile(QQmlContext* parent); + QQmlContext* _context; +}; +#endif + +#endif // hifi_FileTypeProfile_h diff --git a/libraries/ui/src/ui/types/FileTypeProfile.cpp b/libraries/ui/src/ui/types/FileTypeProfile.cpp index 90a2c6ba18..073460903e 100644 --- a/libraries/ui/src/ui/types/FileTypeProfile.cpp +++ b/libraries/ui/src/ui/types/FileTypeProfile.cpp @@ -11,18 +11,31 @@ #include "FileTypeProfile.h" -#include "FileTypeRequestInterceptor.h" +#include + +#include "RequestFilters.h" #if !defined(Q_OS_ANDROID) static const QString QML_WEB_ENGINE_STORAGE_NAME = "qmlWebEngine"; -FileTypeProfile::FileTypeProfile(QObject* parent) : - QQuickWebEngineProfile(parent) +FileTypeProfile::FileTypeProfile(QQmlContext* parent) : + ContextAwareProfile(parent) { static const QString WEB_ENGINE_USER_AGENT = "Chrome/48.0 (HighFidelityInterface)"; setHttpUserAgent(WEB_ENGINE_USER_AGENT); - auto requestInterceptor = new FileTypeRequestInterceptor(this); + auto requestInterceptor = new RequestInterceptor(this); setRequestInterceptor(requestInterceptor); } + +void FileTypeProfile::RequestInterceptor::interceptRequest(QWebEngineUrlRequestInfo& info) { + RequestFilters::interceptHFWebEngineRequest(info, getContext()); + RequestFilters::interceptFileType(info, getContext()); +} + +void FileTypeProfile::registerWithContext(QQmlContext* context) { + context->setContextProperty("FileTypeProfile", new FileTypeProfile(context)); +} + + #endif \ No newline at end of file diff --git a/libraries/ui/src/ui/types/FileTypeProfile.h b/libraries/ui/src/ui/types/FileTypeProfile.h index c7d07cd822..7ddfdd0aed 100644 --- a/libraries/ui/src/ui/types/FileTypeProfile.h +++ b/libraries/ui/src/ui/types/FileTypeProfile.h @@ -17,12 +17,23 @@ #include #if !defined(Q_OS_ANDROID) -#include +#include "ContextAwareProfile.h" + +class FileTypeProfile : public ContextAwareProfile { + using Parent = ContextAwareProfile; -class FileTypeProfile : public QQuickWebEngineProfile { public: - FileTypeProfile(QObject* parent = Q_NULLPTR); + static void registerWithContext(QQmlContext* parent); + +protected: + FileTypeProfile(QQmlContext* parent); + class RequestInterceptor : public Parent::RequestInterceptor { + public: + RequestInterceptor(ContextAwareProfile* parent) : Parent::RequestInterceptor(parent) {} + void interceptRequest(QWebEngineUrlRequestInfo& info) override; + }; }; + #endif #endif // hifi_FileTypeProfile_h diff --git a/libraries/ui/src/ui/types/FileTypeRequestInterceptor.cpp b/libraries/ui/src/ui/types/FileTypeRequestInterceptor.cpp deleted file mode 100644 index 25866ad395..0000000000 --- a/libraries/ui/src/ui/types/FileTypeRequestInterceptor.cpp +++ /dev/null @@ -1,25 +0,0 @@ -// -// FileTypeRequestInterceptor.cpp -// interface/src/networking -// -// Created by Kunal Gosar on 2017-03-10. -// Copyright 2017 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#include "FileTypeRequestInterceptor.h" - -#include - -#include "RequestFilters.h" - -#if !defined(Q_OS_ANDROID) - -void FileTypeRequestInterceptor::interceptRequest(QWebEngineUrlRequestInfo& info) { - RequestFilters::interceptHFWebEngineRequest(info); - RequestFilters::interceptFileType(info); -} - -#endif \ No newline at end of file diff --git a/libraries/ui/src/ui/types/FileTypeRequestInterceptor.h b/libraries/ui/src/ui/types/FileTypeRequestInterceptor.h deleted file mode 100644 index b8a01a53fa..0000000000 --- a/libraries/ui/src/ui/types/FileTypeRequestInterceptor.h +++ /dev/null @@ -1,30 +0,0 @@ -// -// FileTypeRequestInterceptor.h -// interface/src/networking -// -// Created by Kunal Gosar on 2017-03-10. -// Copyright 2017 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#pragma once - -#ifndef hifi_FileTypeRequestInterceptor_h -#define hifi_FileTypeRequestInterceptor_h - -#include - -#if !defined(Q_OS_ANDROID) -#include - -class FileTypeRequestInterceptor : public QWebEngineUrlRequestInterceptor { -public: - FileTypeRequestInterceptor(QObject* parent) : QWebEngineUrlRequestInterceptor(parent) {}; - - virtual void interceptRequest(QWebEngineUrlRequestInfo& info) override; -}; -#endif - -#endif // hifi_FileTypeRequestInterceptor_h diff --git a/libraries/ui/src/ui/types/HFTabletWebEngineProfile.h b/libraries/ui/src/ui/types/HFTabletWebEngineProfile.h deleted file mode 100644 index 406cb1a19a..0000000000 --- a/libraries/ui/src/ui/types/HFTabletWebEngineProfile.h +++ /dev/null @@ -1,23 +0,0 @@ -// -// HFTabletWebEngineProfile.h -// interface/src/networking -// -// Created by Dante Ruiz on 2017-03-31. -// Copyright 2017 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - - -#ifndef hifi_HFTabletWebEngineProfile_h -#define hifi_HFTabletWebEngineProfile_h - -#include - -class HFTabletWebEngineProfile : public QQuickWebEngineProfile { -public: - HFTabletWebEngineProfile(QObject* parent = Q_NULLPTR); -}; - -#endif // hifi_HFTabletWebEngineProfile_h diff --git a/libraries/ui/src/ui/types/HFTabletWebEngineRequestInterceptor.h b/libraries/ui/src/ui/types/HFTabletWebEngineRequestInterceptor.h deleted file mode 100644 index 8be2974782..0000000000 --- a/libraries/ui/src/ui/types/HFTabletWebEngineRequestInterceptor.h +++ /dev/null @@ -1,30 +0,0 @@ -// -// HFTabletWebEngineRequestInterceptor.h -// interface/src/networking -// -// Created by Dante Ruiz on 2017-3-31. -// Copyright 2017 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#ifndef hifi_HFTabletWebEngineRequestInterceptor_h -#define hifi_HFTabletWebEngineRequestInterceptor_h -#if !defined(Q_OS_ANDROID) -#include - -#include - -class HFTabletWebEngineRequestInterceptor - : public QWebEngineUrlRequestInterceptor -{ -public: - HFTabletWebEngineRequestInterceptor(QObject* parent) - : QWebEngineUrlRequestInterceptor(parent) - {}; - virtual void interceptRequest(QWebEngineUrlRequestInfo& info) override; -}; -#endif - -#endif // hifi_HFWebEngineRequestInterceptor_h diff --git a/libraries/ui/src/ui/types/HFWebEngineProfile.cpp b/libraries/ui/src/ui/types/HFWebEngineProfile.cpp index 381bdb10bd..ef1d009f09 100644 --- a/libraries/ui/src/ui/types/HFWebEngineProfile.cpp +++ b/libraries/ui/src/ui/types/HFWebEngineProfile.cpp @@ -11,20 +11,28 @@ #include "HFWebEngineProfile.h" -#include "HFWebEngineRequestInterceptor.h" +#include + +#include "RequestFilters.h" #if !defined(Q_OS_ANDROID) static const QString QML_WEB_ENGINE_STORAGE_NAME = "qmlWebEngine"; -HFWebEngineProfile::HFWebEngineProfile(QObject* parent) : - QQuickWebEngineProfile(parent) +HFWebEngineProfile::HFWebEngineProfile(QQmlContext* parent) : Parent(parent) { setStorageName(QML_WEB_ENGINE_STORAGE_NAME); // we use the HFWebEngineRequestInterceptor to make sure that web requests are authenticated for the interface user - auto requestInterceptor = new HFWebEngineRequestInterceptor(this); - setRequestInterceptor(requestInterceptor); + setRequestInterceptor(new RequestInterceptor(this)); } -#endif \ No newline at end of file +void HFWebEngineProfile::RequestInterceptor::interceptRequest(QWebEngineUrlRequestInfo& info) { + RequestFilters::interceptHFWebEngineRequest(info, getContext()); +} + +void HFWebEngineProfile::registerWithContext(QQmlContext* context) { + context->setContextProperty("HFWebEngineProfile", new HFWebEngineProfile(context)); +} + +#endif diff --git a/libraries/ui/src/ui/types/HFWebEngineProfile.h b/libraries/ui/src/ui/types/HFWebEngineProfile.h index 30da489c92..6b84ad6f80 100644 --- a/libraries/ui/src/ui/types/HFWebEngineProfile.h +++ b/libraries/ui/src/ui/types/HFWebEngineProfile.h @@ -14,15 +14,24 @@ #ifndef hifi_HFWebEngineProfile_h #define hifi_HFWebEngineProfile_h -#include +#include "ContextAwareProfile.h" #if !defined(Q_OS_ANDROID) -#include -class HFWebEngineProfile : public QQuickWebEngineProfile { +class HFWebEngineProfile : public ContextAwareProfile { + using Parent = ContextAwareProfile; public: - HFWebEngineProfile(QObject* parent = Q_NULLPTR); + static void registerWithContext(QQmlContext* parent); + +protected: + HFWebEngineProfile(QQmlContext* parent); + class RequestInterceptor : public Parent::RequestInterceptor { + public: + RequestInterceptor(ContextAwareProfile* parent) : Parent::RequestInterceptor(parent) {} + void interceptRequest(QWebEngineUrlRequestInfo& info) override; + }; }; + #endif #endif // hifi_HFWebEngineProfile_h diff --git a/libraries/ui/src/ui/types/HFWebEngineRequestInterceptor.cpp b/libraries/ui/src/ui/types/HFWebEngineRequestInterceptor.cpp deleted file mode 100644 index 5a11c32efa..0000000000 --- a/libraries/ui/src/ui/types/HFWebEngineRequestInterceptor.cpp +++ /dev/null @@ -1,25 +0,0 @@ -// -// HFWebEngineRequestInterceptor.cpp -// interface/src/networking -// -// Created by Stephen Birarda on 2016-10-14. -// Copyright 2016 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#include "HFWebEngineRequestInterceptor.h" - -#include - -#include "AccountManager.h" -#include "RequestFilters.h" - -#if !defined(Q_OS_ANDROID) - -void HFWebEngineRequestInterceptor::interceptRequest(QWebEngineUrlRequestInfo& info) { - RequestFilters::interceptHFWebEngineRequest(info); -} - -#endif \ No newline at end of file diff --git a/libraries/ui/src/ui/types/HFWebEngineRequestInterceptor.h b/libraries/ui/src/ui/types/HFWebEngineRequestInterceptor.h deleted file mode 100644 index b5521a106e..0000000000 --- a/libraries/ui/src/ui/types/HFWebEngineRequestInterceptor.h +++ /dev/null @@ -1,30 +0,0 @@ -// -// HFWebEngineRequestInterceptor.h -// interface/src/networking -// -// Created by Stephen Birarda on 2016-10-14. -// Copyright 2016 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#pragma once - -#ifndef hifi_HFWebEngineRequestInterceptor_h -#define hifi_HFWebEngineRequestInterceptor_h - -#include - -#if !defined(Q_OS_ANDROID) -#include - -class HFWebEngineRequestInterceptor : public QWebEngineUrlRequestInterceptor { -public: - HFWebEngineRequestInterceptor(QObject* parent) : QWebEngineUrlRequestInterceptor(parent) {}; - - virtual void interceptRequest(QWebEngineUrlRequestInfo& info) override; -}; -#endif - -#endif // hifi_HFWebEngineRequestInterceptor_h diff --git a/libraries/ui/src/ui/types/RequestFilters.cpp b/libraries/ui/src/ui/types/RequestFilters.cpp index 4cd51c6d98..9d831a1758 100644 --- a/libraries/ui/src/ui/types/RequestFilters.cpp +++ b/libraries/ui/src/ui/types/RequestFilters.cpp @@ -10,12 +10,15 @@ // #include "RequestFilters.h" -#include "NetworkingConstants.h" #include -#include +#include -#include "AccountManager.h" +#include +#include +#include + +#include "ContextAwareProfile.h" #if !defined(Q_OS_ANDROID) @@ -42,9 +45,28 @@ namespace { return filename.endsWith(".json", Qt::CaseInsensitive); } + bool blockLocalFiles(QWebEngineUrlRequestInfo& info) { + auto requestUrl = info.requestUrl(); + if (!requestUrl.isLocalFile()) { + // Not a local file, do not block + return false; + } + + QString targetFilePath = QFileInfo(requestUrl.toLocalFile()).canonicalFilePath(); + + // If we get here, then it's a local file that isn't whitelisted and the + // developer mode environment variable is not enabled. Block access to the file + qWarning() << "Blocking web access to local file path" << targetFilePath; + info.block(true); + return true; + } } -void RequestFilters::interceptHFWebEngineRequest(QWebEngineUrlRequestInfo& info) { +void RequestFilters::interceptHFWebEngineRequest(QWebEngineUrlRequestInfo& info, QQmlContext* context) { + if (ContextAwareProfile::isRestricted(context) && blockLocalFiles(info)) { + return; + } + // check if this is a request to a highfidelity URL bool isAuthable = isAuthableHighFidelityURL(info.requestUrl()); if (isAuthable) { @@ -71,7 +93,7 @@ void RequestFilters::interceptHFWebEngineRequest(QWebEngineUrlRequestInfo& info) info.setHttpHeader(USER_AGENT.toLocal8Bit(), tokenString.toLocal8Bit()); } -void RequestFilters::interceptFileType(QWebEngineUrlRequestInfo& info) { +void RequestFilters::interceptFileType(QWebEngineUrlRequestInfo& info, QQmlContext* context) { QString filename = info.requestUrl().fileName(); if (isScript(filename) || isJSON(filename)) { static const QString CONTENT_HEADER = "Accept"; diff --git a/libraries/ui/src/ui/types/RequestFilters.h b/libraries/ui/src/ui/types/RequestFilters.h index ccab6a6ee3..8fde94a1b4 100644 --- a/libraries/ui/src/ui/types/RequestFilters.h +++ b/libraries/ui/src/ui/types/RequestFilters.h @@ -20,10 +20,12 @@ #include #include +class QQmlContext; + class RequestFilters : public QObject { public: - static void interceptHFWebEngineRequest(QWebEngineUrlRequestInfo& info); - static void interceptFileType(QWebEngineUrlRequestInfo& info); + static void interceptHFWebEngineRequest(QWebEngineUrlRequestInfo& info, QQmlContext* context); + static void interceptFileType(QWebEngineUrlRequestInfo& info, QQmlContext* context); }; #endif From 2f358f3380082a44438958c969c96b324a072d56 Mon Sep 17 00:00:00 2001 From: SamGondelman Date: Thu, 2 Aug 2018 11:33:39 -0700 Subject: [PATCH 13/37] fix shapes always drawing as transparents --- libraries/entities-renderer/src/RenderableEntityItem.cpp | 9 +++++++++ .../entities-renderer/src/RenderableShapeEntityItem.cpp | 9 ++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/libraries/entities-renderer/src/RenderableEntityItem.cpp b/libraries/entities-renderer/src/RenderableEntityItem.cpp index 78801df715..f04ee28d7f 100644 --- a/libraries/entities-renderer/src/RenderableEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderableEntityItem.cpp @@ -336,6 +336,11 @@ bool EntityRenderer::needsRenderUpdate() const { if (_needsRenderUpdate) { return true; } + + if (isFading()) { + return true; + } + if (_prevIsTransparent != isTransparent()) { return true; } @@ -380,6 +385,10 @@ void EntityRenderer::updateModelTransformAndBound() { void EntityRenderer::doRenderUpdateSynchronous(const ScenePointer& scene, Transaction& transaction, const EntityItemPointer& entity) { DETAILED_PROFILE_RANGE(simulation_physics, __FUNCTION__); withWriteLock([&] { + if (isFading()) { + emit requestRenderUpdate(); + } + auto transparent = isTransparent(); if (_prevIsTransparent && !transparent) { _isFading = false; diff --git a/libraries/entities-renderer/src/RenderableShapeEntityItem.cpp b/libraries/entities-renderer/src/RenderableShapeEntityItem.cpp index c50b3bd760..3fd79ffad1 100644 --- a/libraries/entities-renderer/src/RenderableShapeEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderableShapeEntityItem.cpp @@ -216,7 +216,14 @@ ShapeKey ShapeEntityRenderer::getShapeKey() { return builder.build(); } else { - return Parent::getShapeKey(); + ShapeKey::Builder builder; + if (_procedural.isReady()) { + builder.withOwnPipeline(); + } + if (isTransparent()) { + builder.withTranslucent(); + } + return builder.build(); } } From da252a70c1ddb3180929e8169c5b9e75b0931083 Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Fri, 3 Aug 2018 09:22:29 -0700 Subject: [PATCH 14/37] Same as https://github.com/highfidelity/hifi/pull/13747 --- interface/src/avatar/AvatarManager.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/interface/src/avatar/AvatarManager.cpp b/interface/src/avatar/AvatarManager.cpp index fab512f787..dbafd06611 100644 --- a/interface/src/avatar/AvatarManager.cpp +++ b/interface/src/avatar/AvatarManager.cpp @@ -412,9 +412,6 @@ void AvatarManager::clearOtherAvatars() { while (avatarIterator != _avatarHash.end()) { auto avatar = std::static_pointer_cast(avatarIterator.value()); if (avatar != _myAvatar) { - if (avatar->isInScene()) { - avatar->removeFromScene(avatar, scene, transaction); - } handleRemovedAvatar(avatar); avatarIterator = _avatarHash.erase(avatarIterator); } else { From 0565e0400cd450c37f0c3413d9421b62b2d0a5a3 Mon Sep 17 00:00:00 2001 From: David Back Date: Fri, 3 Aug 2018 11:08:56 -0700 Subject: [PATCH 15/37] fix edit log spam with -1 hand --- scripts/system/libraries/controllers.js | 48 +++++++++++++------------ 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/scripts/system/libraries/controllers.js b/scripts/system/libraries/controllers.js index d99fd0db48..cc20c196aa 100644 --- a/scripts/system/libraries/controllers.js +++ b/scripts/system/libraries/controllers.js @@ -38,30 +38,34 @@ getGrabPointSphereOffset = function(handController, ignoreSensorToWorldScale) { getControllerWorldLocation = function (handController, doOffset) { var orientation; var position; - var pose = Controller.getPoseValue(handController); - var valid = pose.valid; - var controllerJointIndex; - if (pose.valid) { - if (handController === Controller.Standard.RightHand) { - controllerJointIndex = MyAvatar.getJointIndex("_CAMERA_RELATIVE_CONTROLLER_RIGHTHAND"); - } else { - controllerJointIndex = MyAvatar.getJointIndex("_CAMERA_RELATIVE_CONTROLLER_LEFTHAND"); - } - orientation = Quat.multiply(MyAvatar.orientation, MyAvatar.getAbsoluteJointRotationInObjectFrame(controllerJointIndex)); - position = Vec3.sum(MyAvatar.position, Vec3.multiplyQbyV(MyAvatar.orientation, MyAvatar.getAbsoluteJointTranslationInObjectFrame(controllerJointIndex))); + var valid = false; + + if (handController >= 0) { + var pose = Controller.getPoseValue(handController); + valid = pose.valid; + var controllerJointIndex; + if (pose.valid) { + if (handController === Controller.Standard.RightHand) { + controllerJointIndex = MyAvatar.getJointIndex("_CAMERA_RELATIVE_CONTROLLER_RIGHTHAND"); + } else { + controllerJointIndex = MyAvatar.getJointIndex("_CAMERA_RELATIVE_CONTROLLER_LEFTHAND"); + } + orientation = Quat.multiply(MyAvatar.orientation, MyAvatar.getAbsoluteJointRotationInObjectFrame(controllerJointIndex)); + position = Vec3.sum(MyAvatar.position, Vec3.multiplyQbyV(MyAvatar.orientation, MyAvatar.getAbsoluteJointTranslationInObjectFrame(controllerJointIndex))); - // add to the real position so the grab-point is out in front of the hand, a bit - if (doOffset) { - var offset = getGrabPointSphereOffset(handController); - position = Vec3.sum(position, Vec3.multiplyQbyV(orientation, offset)); - } + // add to the real position so the grab-point is out in front of the hand, a bit + if (doOffset) { + var offset = getGrabPointSphereOffset(handController); + position = Vec3.sum(position, Vec3.multiplyQbyV(orientation, offset)); + } - } else if (!HMD.isHandControllerAvailable()) { - // NOTE: keep this offset in sync with scripts/system/controllers/handControllerPointer.js:493 - var VERTICAL_HEAD_LASER_OFFSET = 0.1 * MyAvatar.sensorToWorldScale; - position = Vec3.sum(Camera.position, Vec3.multiplyQbyV(Camera.orientation, {x: 0, y: VERTICAL_HEAD_LASER_OFFSET, z: 0})); - orientation = Quat.multiply(Camera.orientation, Quat.angleAxis(-90, { x: 1, y: 0, z: 0 })); - valid = true; + } else if (!HMD.isHandControllerAvailable()) { + // NOTE: keep this offset in sync with scripts/system/controllers/handControllerPointer.js:493 + var VERTICAL_HEAD_LASER_OFFSET = 0.1 * MyAvatar.sensorToWorldScale; + position = Vec3.sum(Camera.position, Vec3.multiplyQbyV(Camera.orientation, {x: 0, y: VERTICAL_HEAD_LASER_OFFSET, z: 0})); + orientation = Quat.multiply(Camera.orientation, Quat.angleAxis(-90, { x: 1, y: 0, z: 0 })); + valid = true; + } } return {position: position, From 8e9c1e5c0a80b8d64d0d1a8116526d00f555cca2 Mon Sep 17 00:00:00 2001 From: Bradley Austin Davis Date: Fri, 3 Aug 2018 11:38:39 -0700 Subject: [PATCH 16/37] Fix out of date comment --- libraries/ui/src/ui/types/RequestFilters.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/libraries/ui/src/ui/types/RequestFilters.cpp b/libraries/ui/src/ui/types/RequestFilters.cpp index 9d831a1758..7f192d6e52 100644 --- a/libraries/ui/src/ui/types/RequestFilters.cpp +++ b/libraries/ui/src/ui/types/RequestFilters.cpp @@ -52,10 +52,11 @@ namespace { return false; } + // We can potentially add whitelisting logic or development environment variables that + // will allow people to override this setting on a per-client basis here. QString targetFilePath = QFileInfo(requestUrl.toLocalFile()).canonicalFilePath(); - // If we get here, then it's a local file that isn't whitelisted and the - // developer mode environment variable is not enabled. Block access to the file + // If we get here, we've determined it's a local file and we have no reason not to block it qWarning() << "Blocking web access to local file path" << targetFilePath; info.block(true); return true; @@ -101,4 +102,4 @@ void RequestFilters::interceptFileType(QWebEngineUrlRequestInfo& info, QQmlConte info.setHttpHeader(CONTENT_HEADER.toLocal8Bit(), TYPE_VALUE.toLocal8Bit()); } } -#endif \ No newline at end of file +#endif From 2270255d88fdaa4c23051e9b45f48471c862717d Mon Sep 17 00:00:00 2001 From: David Rowe Date: Sat, 4 Aug 2018 07:22:12 +1200 Subject: [PATCH 17/37] JSDoc review --- libraries/audio/src/SoundCacheScriptingInterface.h | 7 ++++--- libraries/script-engine/src/AudioScriptingInterface.h | 3 ++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/libraries/audio/src/SoundCacheScriptingInterface.h b/libraries/audio/src/SoundCacheScriptingInterface.h index 9e660a2d04..c985e8c211 100644 --- a/libraries/audio/src/SoundCacheScriptingInterface.h +++ b/libraries/audio/src/SoundCacheScriptingInterface.h @@ -48,10 +48,11 @@ public: SoundCacheScriptingInterface(); /**jsdoc - * Loads the content of an audio file into an object, ready for playback by {@link Audio.playSound}. + * Loads the content of an audio file into a {@link SoundObject}, ready for playback by {@link Audio.playSound}. * @function SoundCache.getSound - * @param {string} url - The URL of the audio file to load. See {@link SoundObject} for supported formats. - * @returns {SoundObject} + * @param {string} url - The URL of the audio file to load — Web, ATP, or file. See {@link SoundObject} for supported + * formats. + * @returns {SoundObject} The sound ready for playback. */ Q_INVOKABLE SharedSoundPointer getSound(const QUrl& url); }; diff --git a/libraries/script-engine/src/AudioScriptingInterface.h b/libraries/script-engine/src/AudioScriptingInterface.h index 72b9541763..1220a9b769 100644 --- a/libraries/script-engine/src/AudioScriptingInterface.h +++ b/libraries/script-engine/src/AudioScriptingInterface.h @@ -98,7 +98,8 @@ signals: void mutedByMixer(); /**jsdoc - * Triggered when everyone is muted by the mixer. + * Triggered when the client is muted by the mixer because they're within a certain radius (50m) of someone who requested + * the mute through Developer > Audio > Mute Environment. * @function Audio.environmentMuted * @returns {Signal} */ From fdd6b7e07b5e9b073d8acf447ba2665ed9ac1dad Mon Sep 17 00:00:00 2001 From: David Rowe Date: Sat, 4 Aug 2018 07:29:57 +1200 Subject: [PATCH 18/37] Delete erroneous merge file --- libraries/audio/src/SoundCache.h.orig | 97 --------------------------- 1 file changed, 97 deletions(-) delete mode 100644 libraries/audio/src/SoundCache.h.orig diff --git a/libraries/audio/src/SoundCache.h.orig b/libraries/audio/src/SoundCache.h.orig deleted file mode 100644 index f1ff40ae42..0000000000 --- a/libraries/audio/src/SoundCache.h.orig +++ /dev/null @@ -1,97 +0,0 @@ -// -// SoundCache.h -// libraries/audio/src -// -// Created by Stephen Birarda on 2014-11-13. -// Copyright 2014 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#ifndef hifi_SoundCache_h -#define hifi_SoundCache_h - -#include - -#include "Sound.h" - -class SoundCache : public ResourceCache, public Dependency { - Q_OBJECT - SINGLETON_DEPENDENCY - -public: -<<<<<<< .merge_file_a15692 - - // Properties are copied over from ResourceCache (see ResourceCache.h for reason). - - /**jsdoc - * API to manage sound cache resources. - * @namespace SoundCache - * - * @hifi-interface - * @hifi-client-entity - * @hifi-server-entity - * @hifi-assignment-client - * - * @property {number} numTotal - Total number of total resources. Read-only. - * @property {number} numCached - Total number of cached resource. Read-only. - * @property {number} sizeTotal - Size in bytes of all resources. Read-only. - * @property {number} sizeCached - Size in bytes of all cached resources. Read-only. - */ - - - // Functions are copied over from ResourceCache (see ResourceCache.h for reason). - - /**jsdoc - * Get the list of all resource URLs. - * @function SoundCache.getResourceList - * @returns {string[]} - */ - - /**jsdoc - * @function SoundCache.dirty - * @returns {Signal} - */ - - /**jsdoc - * @function SoundCache.updateTotalSize - * @param {number} deltaSize - */ - - /**jsdoc - * Prefetches a resource. - * @function SoundCache.prefetch - * @param {string} url - URL of the resource to prefetch. - * @param {object} [extra=null] - * @returns {ResourceObject} - */ - - /**jsdoc - * Asynchronously loads a resource from the specified URL and returns it. - * @function SoundCache.getResource - * @param {string} url - URL of the resource to load. - * @param {string} [fallback=""] - Fallback URL if load of the desired URL fails. - * @param {} [extra=null] - * @returns {object} - */ - - - /**jsdoc - * Loads the content of an audio file into an object, ready for playback by {@link Audio.playSound}. - * @function SoundCache.getSound - * @param {string} url - The URL of the audio file to load. See {@link SoundObject} for supported formats. - * @returns {SoundObject} - */ -======= ->>>>>>> .merge_file_a28756 - Q_INVOKABLE SharedSoundPointer getSound(const QUrl& url); - -protected: - virtual QSharedPointer createResource(const QUrl& url, const QSharedPointer& fallback, - const void* extra) override; -private: - SoundCache(QObject* parent = NULL); -}; - -#endif // hifi_SoundCache_h From d6bcdcde3f2b6fdeced7994911debc81edd7b390 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Fri, 25 May 2018 12:02:36 -0700 Subject: [PATCH 19/37] Fix DISABLE_QML behavior --- interface/src/Application.cpp | 13 +++--- libraries/qml/src/qml/OffscreenSurface.cpp | 2 +- .../qml/src/qml/impl/RenderEventHandler.cpp | 3 ++ .../qml/src/qml/impl/RenderEventHandler.h | 4 ++ libraries/qml/src/qml/impl/SharedObject.cpp | 42 ++++++++++++++++++- libraries/qml/src/qml/impl/SharedObject.h | 16 ++++--- libraries/ui/src/OffscreenUi.cpp | 11 +++-- 7 files changed, 73 insertions(+), 18 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index ba7c15ad33..b859dc4b66 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -4574,11 +4574,14 @@ void Application::idle() { _lastTimeUpdated.start(); // If the offscreen Ui has something active that is NOT the root, then assume it has keyboard focus. - if (_keyboardDeviceHasFocus && offscreenUi && offscreenUi->getWindow()->activeFocusItem() != offscreenUi->getRootItem()) { - _keyboardMouseDevice->pluginFocusOutEvent(); - _keyboardDeviceHasFocus = false; - } else if (offscreenUi && offscreenUi->getWindow()->activeFocusItem() == offscreenUi->getRootItem()) { - _keyboardDeviceHasFocus = true; + if (offscreenUi && offscreenUi->getWindow()) { + auto activeFocusItem = offscreenUi->getWindow()->activeFocusItem(); + if (_keyboardDeviceHasFocus && activeFocusItem != offscreenUi->getRootItem()) { + _keyboardMouseDevice->pluginFocusOutEvent(); + _keyboardDeviceHasFocus = false; + } else if (activeFocusItem == offscreenUi->getRootItem()) { + _keyboardDeviceHasFocus = true; + } } checkChangeCursor(); diff --git a/libraries/qml/src/qml/OffscreenSurface.cpp b/libraries/qml/src/qml/OffscreenSurface.cpp index ea6f1ce324..3c39d72a28 100644 --- a/libraries/qml/src/qml/OffscreenSurface.cpp +++ b/libraries/qml/src/qml/OffscreenSurface.cpp @@ -99,7 +99,7 @@ QPointF OffscreenSurface::mapToVirtualScreen(const QPointF& originalPoint) { // bool OffscreenSurface::filterEnabled(QObject* originalDestination, QEvent* event) const { - if (!_sharedObject || _sharedObject->getWindow() == originalDestination) { + if (!_sharedObject || !_sharedObject->getWindow() || _sharedObject->getWindow() == originalDestination) { return false; } // Only intercept events while we're in an active state diff --git a/libraries/qml/src/qml/impl/RenderEventHandler.cpp b/libraries/qml/src/qml/impl/RenderEventHandler.cpp index 945a469611..39f3123d40 100644 --- a/libraries/qml/src/qml/impl/RenderEventHandler.cpp +++ b/libraries/qml/src/qml/impl/RenderEventHandler.cpp @@ -8,6 +8,8 @@ #include "RenderEventHandler.h" +#ifndef DISABLE_QML + #include #include @@ -165,3 +167,4 @@ void RenderEventHandler::onQuit() { moveToThread(qApp->thread()); QThread::currentThread()->quit(); } +#endif \ No newline at end of file diff --git a/libraries/qml/src/qml/impl/RenderEventHandler.h b/libraries/qml/src/qml/impl/RenderEventHandler.h index d1e079cc85..1e2f9945f3 100644 --- a/libraries/qml/src/qml/impl/RenderEventHandler.h +++ b/libraries/qml/src/qml/impl/RenderEventHandler.h @@ -7,6 +7,8 @@ // #pragma once +#ifndef DISABLE_QML + #include #include #include @@ -54,3 +56,5 @@ private: }; }}} // namespace hifi::qml::impl + +#endif \ No newline at end of file diff --git a/libraries/qml/src/qml/impl/SharedObject.cpp b/libraries/qml/src/qml/impl/SharedObject.cpp index 2fde057ca8..3b8d0bb743 100644 --- a/libraries/qml/src/qml/impl/SharedObject.cpp +++ b/libraries/qml/src/qml/impl/SharedObject.cpp @@ -55,6 +55,8 @@ QOpenGLContext* SharedObject::getSharedContext() { } SharedObject::SharedObject() { +#ifndef DISABLE_QML + // Create render control _renderControl = new RenderControl(); @@ -68,6 +70,7 @@ SharedObject::SharedObject() { _quickWindow->setColor(QColor(255, 255, 255, 0)); _quickWindow->setClearBeforeRendering(true); +#endif QObject::connect(qApp, &QCoreApplication::aboutToQuit, this, &SharedObject::onAboutToQuit); } @@ -78,7 +81,7 @@ SharedObject::~SharedObject() { destroy(); // _renderTimer is created with `this` as the parent, so need no explicit destruction - +#ifndef DISABLE_QML // Destroy the event hand if (_renderObject) { delete _renderObject; @@ -89,18 +92,20 @@ SharedObject::~SharedObject() { delete _renderControl; _renderControl = nullptr; } +#endif if (_rootItem) { delete _rootItem; _rootItem = nullptr; } +#ifndef DISABLE_QML if (_quickWindow) { _quickWindow->destroy(); delete _quickWindow; _quickWindow = nullptr; } - +#endif if (_qmlContext) { auto engine = _qmlContext->engine(); delete _qmlContext; @@ -114,7 +119,9 @@ void SharedObject::create(OffscreenSurface* surface) { qFatal("QML surface root item already set"); } +#ifndef DISABLE_QML QObject::connect(_quickWindow, &QQuickWindow::focusObjectChanged, surface, &OffscreenSurface::onFocusObjectChanged); +#endif // Create a QML engine. auto qmlEngine = acquireEngine(surface); @@ -125,10 +132,12 @@ void SharedObject::create(OffscreenSurface* surface) { surface->onRootContextCreated(_qmlContext); emit surface->rootContextCreated(_qmlContext); +#ifndef DISABLE_QML if (!qmlEngine->incubationController()) { qmlEngine->setIncubationController(_quickWindow->incubationController()); } _qmlContext->setContextProperty("offscreenWindow", QVariant::fromValue(_quickWindow)); +#endif } void SharedObject::setRootItem(QQuickItem* rootItem) { @@ -137,6 +146,7 @@ void SharedObject::setRootItem(QQuickItem* rootItem) { } _rootItem = rootItem; +#ifndef DISABLE_QML _rootItem->setSize(_quickWindow->size()); // Create the render thread @@ -150,6 +160,8 @@ void SharedObject::setRootItem(QQuickItem* rootItem) { QObject::connect(_renderControl, &QQuickRenderControl::renderRequested, this, &SharedObject::requestRender); QObject::connect(_renderControl, &QQuickRenderControl::sceneChanged, this, &SharedObject::requestRenderSync); +#endif + } void SharedObject::destroy() { @@ -163,6 +175,7 @@ void SharedObject::destroy() { } _paused = true; +#ifndef DISABLE_QML if (_renderTimer) { _renderTimer->stop(); QObject::disconnect(_renderTimer); @@ -171,9 +184,11 @@ void SharedObject::destroy() { if (_renderControl) { QObject::disconnect(_renderControl); } +#endif QObject::disconnect(qApp); +#ifndef DISABLE_QML { QMutexLocker lock(&_mutex); _quit = true; @@ -190,6 +205,7 @@ void SharedObject::destroy() { delete _renderThread; _renderThread = nullptr; } +#endif } @@ -240,6 +256,7 @@ void SharedObject::releaseEngine(QQmlEngine* engine) { } bool SharedObject::event(QEvent* e) { +#ifndef DISABLE_QML switch (static_cast(e->type())) { case OffscreenEvent::Initialize: onInitialize(); @@ -252,6 +269,7 @@ bool SharedObject::event(QEvent* e) { default: break; } +#endif return QObject::event(e); } @@ -261,22 +279,28 @@ void SharedObject::initializeRenderControl(QOpenGLContext* context) { qFatal("QML rendering context has no share context"); } +#ifndef DISABLE_QML if (!nsightActive()) { _renderControl->initialize(context); } +#endif } void SharedObject::releaseTextureAndFence() { +#ifndef DISABLE_QML QMutexLocker lock(&_mutex); // If the most recent texture was unused, we can directly recycle it if (_latestTextureAndFence.first) { getTextureCache().releaseTexture(_latestTextureAndFence); _latestTextureAndFence = TextureAndFence{ 0, 0 }; } +#endif } void SharedObject::setRenderTarget(uint32_t fbo, const QSize& size) { +#ifndef DISABLE_QML _quickWindow->setRenderTarget(fbo, size); +#endif } QSize SharedObject::getSize() const { @@ -295,6 +319,7 @@ void SharedObject::setSize(const QSize& size) { } qCDebug(qmlLogging) << "Offscreen UI resizing to " << size.width() << "x" << size.height(); +#ifndef DISABLE_QML _quickWindow->setGeometry(QRect(QPoint(), size)); _quickWindow->contentItem()->setSize(size); @@ -304,9 +329,11 @@ void SharedObject::setSize(const QSize& size) { } requestRenderSync(); +#endif } bool SharedObject::preRender() { +#ifndef DISABLE_QML QMutexLocker lock(&_mutex); if (_paused) { if (_syncRequested) { @@ -327,6 +354,7 @@ bool SharedObject::preRender() { } _syncRequested = false; } +#endif return true; } @@ -339,8 +367,10 @@ void SharedObject::shutdownRendering(OffscreenGLCanvas& canvas, const QSize& siz getTextureCache().releaseTexture(_latestTextureAndFence); } } +#ifndef DISABLE_QML _renderControl->invalidate(); canvas.doneCurrent(); +#endif wake(); } @@ -381,8 +411,10 @@ bool SharedObject::fetchTexture(TextureAndFence& textureAndFence) { } void SharedObject::setProxyWindow(QWindow* window) { +#ifndef DISABLE_QML _proxyWindow = window; _renderControl->setRenderWindow(window); +#endif } void SharedObject::wait() { @@ -394,6 +426,7 @@ void SharedObject::wake() { } void SharedObject::onInitialize() { +#ifndef DISABLE_QML // Associate root item with the window. _rootItem->setParentItem(_quickWindow->contentItem()); _renderControl->prepareThread(_renderThread); @@ -410,9 +443,11 @@ void SharedObject::onInitialize() { _renderTimer->setTimerType(Qt::PreciseTimer); _renderTimer->setInterval(MIN_TIMER_MS); // 5ms, Qt::PreciseTimer required _renderTimer->start(); +#endif } void SharedObject::onRender() { +#ifndef DISABLE_QML PROFILE_RANGE(render_qml, __FUNCTION__); if (_quit) { return; @@ -430,6 +465,7 @@ void SharedObject::onRender() { QCoreApplication::postEvent(_renderObject, new OffscreenEvent(OffscreenEvent::Render)); } _renderRequested = false; +#endif } void SharedObject::onTimer() { @@ -455,7 +491,9 @@ void SharedObject::onTimer() { } } +#ifndef DISABLE_QML QCoreApplication::postEvent(this, new OffscreenEvent(OffscreenEvent::Render)); +#endif } void SharedObject::onAboutToQuit() { diff --git a/libraries/qml/src/qml/impl/SharedObject.h b/libraries/qml/src/qml/impl/SharedObject.h index 76dde611fc..002679c44d 100644 --- a/libraries/qml/src/qml/impl/SharedObject.h +++ b/libraries/qml/src/qml/impl/SharedObject.h @@ -93,17 +93,21 @@ private: // Texture management TextureAndFence _latestTextureAndFence{ 0, 0 }; - RenderControl* _renderControl{ nullptr }; - RenderEventHandler* _renderObject{ nullptr }; - QQuickWindow* _quickWindow{ nullptr }; - QWindow* _proxyWindow{ nullptr }; QQuickItem* _item{ nullptr }; QQuickItem* _rootItem{ nullptr }; + QQuickWindow* _quickWindow{ nullptr }; QQmlContext* _qmlContext{ nullptr }; + mutable QMutex _mutex; + QWaitCondition _cond; + +#ifndef DISABLE_QML + QWindow* _proxyWindow{ nullptr }; + RenderControl* _renderControl{ nullptr }; + RenderEventHandler* _renderObject{ nullptr }; + QTimer* _renderTimer{ nullptr }; QThread* _renderThread{ nullptr }; - QWaitCondition _cond; - mutable QMutex _mutex; +#endif uint64_t _lastRenderTime{ 0 }; QSize _size{ 100, 100 }; diff --git a/libraries/ui/src/OffscreenUi.cpp b/libraries/ui/src/OffscreenUi.cpp index 25f0652496..a5ef1457db 100644 --- a/libraries/ui/src/OffscreenUi.cpp +++ b/libraries/ui/src/OffscreenUi.cpp @@ -96,10 +96,13 @@ static OffscreenFlags* offscreenFlags { nullptr }; // so I think it's OK for the time being. bool OffscreenUi::shouldSwallowShortcut(QEvent* event) { Q_ASSERT(event->type() == QEvent::ShortcutOverride); - QObject* focusObject = getWindow()->focusObject(); - if (focusObject != getWindow() && focusObject != getRootItem()) { - event->accept(); - return true; + auto window = getWindow(); + if (window) { + QObject* focusObject = getWindow()->focusObject(); + if (focusObject != getWindow() && focusObject != getRootItem()) { + event->accept(); + return true; + } } return false; } From 04e84f1d23617cd3313aa2d3108e1a942889f0fd Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Sat, 2 Jun 2018 11:02:05 -0700 Subject: [PATCH 20/37] Moving to cmake time shader compiling --- cmake/macros/AutoScribeShader.cmake | 232 +++++++++--- cmake/macros/LinkHifiLibraries.cmake | 6 +- interface/CMakeLists.txt | 1 + .../src/workload/GameWorkloadRenderer.cpp | 14 +- libraries/display-plugins/CMakeLists.txt | 2 +- .../display-plugins/OpenGLDisplayPlugin.cpp | 20 +- .../display-plugins/hmd/HmdDisplayPlugin.cpp | 8 +- .../stereo/InterleavedStereoDisplayPlugin.cpp | 4 +- libraries/entities-renderer/CMakeLists.txt | 4 +- .../RenderableParticleEffectEntityItem.cpp | 8 +- .../src/RenderablePolyLineEntityItem.cpp | 11 +- .../src/RenderablePolyVoxEntityItem.cpp | 18 +- .../src/RenderableShapeEntityItem.cpp | 13 +- libraries/gpu/CMakeLists.txt | 4 +- libraries/gpu/src/gpu/DrawNada.slf | 5 + libraries/gpu/src/gpu/Shader.cpp | 58 ++- libraries/gpu/src/gpu/Shader.h | 34 +- libraries/gpu/src/gpu/StandardShaderLib.cpp | 163 --------- libraries/gpu/src/gpu/StandardShaderLib.h | 84 ----- libraries/graphics/CMakeLists.txt | 4 +- libraries/graphics/src/graphics/Skybox.cpp | 7 +- libraries/procedural/CMakeLists.txt | 3 +- .../procedural/src/procedural/Procedural.cpp | 5 +- .../src/procedural/ProceduralSkybox.cpp | 9 +- libraries/render-utils/CMakeLists.txt | 5 +- .../src/AmbientOcclusionEffect.cpp | 26 +- libraries/render-utils/src/AnimDebugDraw.cpp | 10 +- .../render-utils/src/AntialiasingEffect.cpp | 19 +- libraries/render-utils/src/BloomEffect.cpp | 25 +- .../render-utils/src/DebugDeferredBuffer.cpp | 8 +- .../src/DeferredLightingEffect.cpp | 38 +- libraries/render-utils/src/DrawHaze.cpp | 9 +- libraries/render-utils/src/GeometryCache.cpp | 76 ++-- .../render-utils/src/HighlightEffect.cpp | 61 ++-- libraries/render-utils/src/LightClusters.cpp | 30 +- .../render-utils/src/RenderForwardTask.cpp | 3 - .../render-utils/src/RenderPipelines.cpp | 341 +++++------------- .../render-utils/src/StencilMaskPass.cpp | 14 +- .../render-utils/src/SubsurfaceScattering.cpp | 38 +- .../render-utils/src/SurfaceGeometryPass.cpp | 22 +- libraries/render-utils/src/TextRenderer3D.cpp | 4 +- .../render-utils/src/ToneMappingEffect.cpp | 8 +- .../render-utils/src/VelocityBufferPass.cpp | 11 +- libraries/render-utils/src/ZoneRenderer.cpp | 20 +- .../render-utils/src/skin_model_shadow.slf | 20 - .../src/skin_model_shadow_fade.slf | 30 -- libraries/render-utils/src/text/Font.cpp | 12 +- libraries/render/CMakeLists.txt | 3 +- libraries/render/src/render/BlurTask.cpp | 24 +- .../render/src/render/DrawSceneOctree.cpp | 24 +- libraries/render/src/render/DrawStatus.cpp | 15 +- libraries/render/src/render/DrawTask.cpp | 13 +- libraries/render/src/render/ResampleTask.cpp | 8 +- libraries/shaders/CMakeLists.txt | 175 +++++++++ libraries/shaders/Shaders.cpp.in | 11 + libraries/shaders/Shaders.h.in | 14 + libraries/shaders/shaders.qrc.in | 6 + .../shaders/src/shaders/ShadersCommon.cpp | 16 + tests/shaders/CMakeLists.txt | 9 + tests/shaders/src/ShaderTests.cpp | 100 +++++ tests/shaders/src/ShaderTests.h | 29 ++ 61 files changed, 883 insertions(+), 1111 deletions(-) create mode 100644 libraries/gpu/src/gpu/DrawNada.slf delete mode 100755 libraries/gpu/src/gpu/StandardShaderLib.cpp delete mode 100755 libraries/gpu/src/gpu/StandardShaderLib.h delete mode 100644 libraries/render-utils/src/skin_model_shadow.slf delete mode 100644 libraries/render-utils/src/skin_model_shadow_fade.slf create mode 100644 libraries/shaders/CMakeLists.txt create mode 100644 libraries/shaders/Shaders.cpp.in create mode 100644 libraries/shaders/Shaders.h.in create mode 100644 libraries/shaders/shaders.qrc.in create mode 100644 libraries/shaders/src/shaders/ShadersCommon.cpp create mode 100644 tests/shaders/CMakeLists.txt create mode 100644 tests/shaders/src/ShaderTests.cpp create mode 100644 tests/shaders/src/ShaderTests.h diff --git a/cmake/macros/AutoScribeShader.cmake b/cmake/macros/AutoScribeShader.cmake index c4cd2d186a..7d1b5395b9 100755 --- a/cmake/macros/AutoScribeShader.cmake +++ b/cmake/macros/AutoScribeShader.cmake @@ -8,6 +8,12 @@ # See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html # +function(global_append varName varValue) + get_property(LOCAL_LIST GLOBAL PROPERTY ${varName}) + list(APPEND LOCAL_LIST ${varValue}) + set_property(GLOBAL PROPERTY ${varName} ${LOCAL_LIST}) +endfunction() + function(AUTOSCRIBE_SHADER SHADER_FILE) # Grab include files foreach(includeFile ${ARGN}) @@ -45,11 +51,8 @@ function(AUTOSCRIBE_SHADER SHADER_FILE) elseif(${SHADER_EXT} STREQUAL .slg) set(SHADER_TYPE geom) endif() - set(SHADER_TARGET ${SHADER_TARGET}_${SHADER_TYPE}) - - set(SHADER_TARGET "${SHADERS_DIR}/${SHADER_TARGET}") - set(SHADER_TARGET_HEADER ${SHADER_TARGET}.h) - set(SHADER_TARGET_SOURCE ${SHADER_TARGET}.cpp) + file(MAKE_DIRECTORY "${SHADERS_DIR}/${SHADER_LIB}") + set(SHADER_TARGET "${SHADERS_DIR}/${SHADER_LIB}/${SHADER_TARGET}.${SHADER_TYPE}") set(SCRIBE_COMMAND scribe) # Target dependant Custom rule on the SHADER_FILE @@ -63,65 +66,200 @@ function(AUTOSCRIBE_SHADER SHADER_FILE) else () set(GLPROFILE PC_GL) endif() - set(SCRIBE_ARGS -c++ -T ${SHADER_TYPE} -D GLPROFILE ${GLPROFILE} ${SCRIBE_INCLUDES} -o ${SHADER_TARGET} ${SHADER_FILE}) + set(SCRIBE_ARGS -T ${SHADER_TYPE} -D GLPROFILE ${GLPROFILE} ${SCRIBE_INCLUDES} -o ${SHADER_TARGET} ${SHADER_FILE}) add_custom_command( - OUTPUT ${SHADER_TARGET_HEADER} ${SHADER_TARGET_SOURCE} + OUTPUT ${SHADER_TARGET} COMMAND ${SCRIBE_COMMAND} ${SCRIBE_ARGS} - DEPENDS ${SCRIBE_COMMAND} ${SHADER_INCLUDE_FILES} ${SHADER_FILE} + DEPENDS ${SHADER_FILE} ${SCRIBE_COMMAND} ${SHADER_INCLUDE_FILES} ) #output the generated file name - set(AUTOSCRIBE_SHADER_RETURN ${SHADER_TARGET_HEADER} ${SHADER_TARGET_SOURCE} PARENT_SCOPE) - - file(GLOB INCLUDE_FILES ${SHADER_TARGET_HEADER}) - + set(AUTOSCRIBE_SHADER_RETURN ${SHADER_TARGET} PARENT_SCOPE) endfunction() +macro(AUTOSCRIBE_APPEND_SHADER_SOURCES) + if (NOT("${ARGN}" STREQUAL "")) + set_property(GLOBAL PROPERTY ${TARGET_NAME}_SHADER_SOURCES "${ARGN}") + global_append(GLOBAL_SHADER_LIBS ${TARGET_NAME}) + global_append(GLOBAL_SHADER_SOURCES "${ARGN}") + endif() +endmacro() macro(AUTOSCRIBE_SHADER_LIB) + set(GLOBAL_SHADER_SOURCES "") set(HIFI_LIBRARIES_SHADER_INCLUDE_FILES "") + set(SRC_FOLDER "${CMAKE_SOURCE_DIR}/libraries/${TARGET_NAME}/src") + file(GLOB_RECURSE SHADER_INCLUDE_FILES ${SRC_FOLDER}/*.slh) + file(GLOB_RECURSE SHADER_VERTEX_FILES ${SRC_FOLDER}/*.slv) + file(GLOB_RECURSE SHADER_FRAGMENT_FILES ${SRC_FOLDER}/*.slf) + file(GLOB_RECURSE SHADER_GEOMETRY_FILES ${SRC_FOLDER}/*.slg) + file(GLOB_RECURSE SHADER_COMPUTE_FILES ${SRC_FOLDER}/*.slc) + + list(APPEND SHADER_SOURCE_FILES ${SHADER_VERTEX_FILES}) + list(APPEND SHADER_SOURCE_FILES ${SHADER_FRAGMENT_FILES}) + list(APPEND SHADER_SOURCE_FILES ${SHADER_GEOMETRY_FILES}) + list(APPEND SHADER_SOURCE_FILES ${SHADER_COMPUTE_FILES}) + + list(APPEND GLOBAL_SHADER_SOURCES ${SHADER_SOURCE_FILES}) + list(APPEND GLOBAL_SHADER_SOURCES ${SHADER_INCLUDE_FILES}) + AUTOSCRIBE_APPEND_SHADER_SOURCES(${GLOBAL_SHADER_SOURCES}) + file(RELATIVE_PATH RELATIVE_LIBRARY_DIR_PATH ${CMAKE_CURRENT_SOURCE_DIR} "${HIFI_LIBRARY_DIR}") foreach(HIFI_LIBRARY ${ARGN}) - #if (NOT TARGET ${HIFI_LIBRARY}) - # file(GLOB_RECURSE HIFI_LIBRARIES_SHADER_INCLUDE_FILES ${RELATIVE_LIBRARY_DIR_PATH}/${HIFI_LIBRARY}/src/) - #endif () - - #file(GLOB_RECURSE HIFI_LIBRARIES_SHADER_INCLUDE_FILES ${HIFI_LIBRARY_DIR}/${HIFI_LIBRARY}/src/*.slh) list(APPEND HIFI_LIBRARIES_SHADER_INCLUDE_FILES ${HIFI_LIBRARY_DIR}/${HIFI_LIBRARY}/src) endforeach() - #message("${TARGET_NAME} ${HIFI_LIBRARIES_SHADER_INCLUDE_FILES}") +endmacro() - file(GLOB_RECURSE SHADER_INCLUDE_FILES src/*.slh) - file(GLOB_RECURSE SHADER_SOURCE_FILES src/*.slv src/*.slf src/*.slg) +macro(AUTOSCRIBE_PROGRAM) + set(oneValueArgs NAME VERTEX FRAGMENT GEOMETRY COMPUTE) + cmake_parse_arguments(AUTOSCRIBE_PROGRAM "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) + if (NOT (DEFINED AUTOSCRIBE_PROGRAM_NAME)) + message(FATAL_ERROR "Programs must have a name and both a vertex and fragment shader") + endif() + if (NOT (DEFINED AUTOSCRIBE_PROGRAM_VERTEX)) + set(AUTOSCRIBE_PROGRAM_VERTEX ${AUTOSCRIBE_PROGRAM_NAME}) + endif() + if (NOT (DEFINED AUTOSCRIBE_PROGRAM_FRAGMENT)) + set(AUTOSCRIBE_PROGRAM_FRAGMENT ${AUTOSCRIBE_PROGRAM_NAME}) + endif() - #make the shader folder - set(SHADERS_DIR "${CMAKE_CURRENT_BINARY_DIR}/shaders/${TARGET_NAME}") - file(MAKE_DIRECTORY ${SHADERS_DIR}) + if (NOT (${AUTOSCRIBE_PROGRAM_VERTEX} MATCHES ".*::.*")) + set(AUTOSCRIBE_PROGRAM_VERTEX "vertex::${AUTOSCRIBE_PROGRAM_VERTEX}") + endif() + if (NOT (${AUTOSCRIBE_PROGRAM_FRAGMENT} MATCHES ".*::.*")) + set(AUTOSCRIBE_PROGRAM_FRAGMENT "fragment::${AUTOSCRIBE_PROGRAM_FRAGMENT}") + endif() - #message("${TARGET_NAME} ${SHADER_INCLUDE_FILES}") - set(AUTOSCRIBE_SHADER_SRC "") - foreach(SHADER_FILE ${SHADER_SOURCE_FILES}) - AUTOSCRIBE_SHADER(${SHADER_FILE} ${SHADER_INCLUDE_FILES}) + unset(AUTOSCRIBE_PROGRAM_MAP) + list(APPEND AUTOSCRIBE_PROGRAM_MAP AUTOSCRIBE_PROGRAM_VERTEX) + list(APPEND AUTOSCRIBE_PROGRAM_MAP ${AUTOSCRIBE_PROGRAM_VERTEX}) + list(APPEND AUTOSCRIBE_PROGRAM_MAP AUTOSCRIBE_PROGRAM_FRAGMENT) + list(APPEND AUTOSCRIBE_PROGRAM_MAP ${AUTOSCRIBE_PROGRAM_FRAGMENT}) + global_append(${TARGET_NAME}_PROGRAMS ${AUTOSCRIBE_PROGRAM_NAME}) + set_property(GLOBAL PROPERTY ${AUTOSCRIBE_PROGRAM_NAME} "${AUTOSCRIBE_PROGRAM_MAP}") +endmacro() + +macro(unpack_map) + set(MAP_VAR "${ARGN}") + list(LENGTH MAP_VAR MAP_SIZE) + MATH(EXPR MAP_ENTRY_RANGE "(${MAP_SIZE} / 2) - 1") + foreach(INDEX RANGE ${MAP_ENTRY_RANGE}) + MATH(EXPR INDEX_NAME "${INDEX} * 2") + MATH(EXPR INDEX_VAL "${INDEX_NAME} + 1") + list(GET MAP_VAR ${INDEX_NAME} VAR_NAME) + list(GET MAP_VAR ${INDEX_VAL} VAR_VAL) + set(${VAR_NAME} ${VAR_VAL}) + endforeach() +endmacro() + +macro(PROCESS_SHADER_FILE) + AUTOSCRIBE_SHADER(${SHADER} ${ALL_SHADER_HEADERS} ${HIFI_LIBRARIES_SHADER_INCLUDE_FILES}) file(TO_CMAKE_PATH "${AUTOSCRIBE_SHADER_RETURN}" AUTOSCRIBE_GENERATED_FILE) set_property(SOURCE ${AUTOSCRIBE_GENERATED_FILE} PROPERTY SKIP_AUTOMOC ON) - list(APPEND AUTOSCRIBE_SHADER_SRC ${AUTOSCRIBE_GENERATED_FILE}) - endforeach() - #message(${TARGET_NAME} ${AUTOSCRIBE_SHADER_SRC}) - - if (WIN32) - source_group("Shaders" FILES ${SHADER_INCLUDE_FILES}) - source_group("Shaders" FILES ${SHADER_SOURCE_FILES}) - source_group("Shaders\\generated" FILES ${AUTOSCRIBE_SHADER_SRC}) - endif() - - list(APPEND AUTOSCRIBE_SHADER_LIB_SRC ${SHADER_INCLUDE_FILES}) - list(APPEND AUTOSCRIBE_SHADER_LIB_SRC ${SHADER_SOURCE_FILES}) - list(APPEND AUTOSCRIBE_SHADER_LIB_SRC ${AUTOSCRIBE_SHADER_SRC}) - - # Link library shaders, if they exist - include_directories("${SHADERS_DIR}") - - # Add search directory to find gpu/Shader.h - include_directories("${HIFI_LIBRARY_DIR}/gpu/src") - + source_group("Compiled/${SHADER_LIB}" FILES ${AUTOSCRIBE_GENERATED_FILE}) + list(APPEND COMPILED_SHADERS ${AUTOSCRIBE_GENERATED_FILE}) + get_filename_component(ENUM_NAME ${SHADER} NAME_WE) + string(CONCAT SHADER_ENUMS "${SHADER_ENUMS}" "${ENUM_NAME} = ${SHADER_COUNT},\n") + MATH(EXPR SHADER_COUNT "${SHADER_COUNT}+1") +endmacro() + +macro(AUTOSCRIBE_SHADER_FINISH) + get_property(GLOBAL_SHADER_LIBS GLOBAL PROPERTY GLOBAL_SHADER_LIBS) + list(REMOVE_DUPLICATES GLOBAL_SHADER_LIBS) + set(SHADER_COUNT 0) + set(PROGRAM_COUNT 0) + set(SHADERS_DIR "${CMAKE_CURRENT_BINARY_DIR}/shaders") + set(SHADER_ENUMS "") + file(MAKE_DIRECTORY ${SHADERS_DIR}) + + unset(COMPILED_SHADERS) + foreach(SHADER_LIB ${GLOBAL_SHADER_LIBS}) + get_property(LIB_SHADER_SOURCES GLOBAL PROPERTY ${SHADER_LIB}_SHADER_SOURCES) + get_property(LIB_PROGRAMS GLOBAL PROPERTY ${SHADER_LIB}_PROGRAMS) + list(REMOVE_DUPLICATES LIB_SHADER_SOURCES) + string(REGEX REPLACE "[-]" "_" SHADER_NAMESPACE ${SHADER_LIB}) + list(APPEND HIFI_LIBRARIES_SHADER_INCLUDE_FILES "${CMAKE_SOURCE_DIR}/libraries/${SHADER_LIB}/src") + + unset(VERTEX_SHADERS) + unset(FRAGMENT_SHADERS) + unset(SHADER_HEADERS) + + foreach(SHADER_FILE ${LIB_SHADER_SOURCES}) + if (SHADER_FILE MATCHES ".*\\.slv") + list(APPEND VERTEX_SHADERS ${SHADER_FILE}) + elseif (SHADER_FILE MATCHES ".*\\.slf") + list(APPEND FRAGMENT_SHADERS ${SHADER_FILE}) + elseif (SHADER_FILE MATCHES ".*\\.slh") + list(APPEND SHADER_HEADERS ${SHADER_FILE}) + endif() + endforeach() + + if (DEFINED SHADER_HEADERS) + source_group("Shaders/${SHADER_LIB}/Headers" FILES ${SHADER_HEADERS}) + list(APPEND ALL_SHADER_HEADERS ${SHADER_HEADERS}) + endif() + + string(CONCAT SHADER_ENUMS "${SHADER_ENUMS}" "namespace ${SHADER_NAMESPACE} {\n") + if (DEFINED VERTEX_SHADERS) + list(REMOVE_DUPLICATES VERTEX_SHADERS) + source_group("Shaders/${SHADER_LIB}/Vertex" FILES ${VERTEX_SHADERS}) + string(CONCAT SHADER_ENUMS "${SHADER_ENUMS}" "namespace vertex { enum {\n") + foreach(SHADER ${VERTEX_SHADERS}) + process_shader_file() + endforeach() + string(CONCAT SHADER_ENUMS "${SHADER_ENUMS}" "}; } // vertex \n") + endif() + + if (DEFINED FRAGMENT_SHADERS) + list(REMOVE_DUPLICATES FRAGMENT_SHADERS) + source_group("Shaders/${SHADER_LIB}/Fragment" FILES ${FRAGMENT_SHADERS}) + string(CONCAT SHADER_ENUMS "${SHADER_ENUMS}" "namespace fragment { enum {\n") + foreach(SHADER ${FRAGMENT_SHADERS}) + process_shader_file() + endforeach() + string(CONCAT SHADER_ENUMS "${SHADER_ENUMS}" "}; } // fragment \n") + endif() + + if (DEFINED LIB_PROGRAMS) + string(CONCAT SHADER_ENUMS "${SHADER_ENUMS}" "namespace program { enum {\n") + foreach(LIB_PROGRAM ${LIB_PROGRAMS}) + get_property(LIB_PROGRAM_MAP GLOBAL PROPERTY ${LIB_PROGRAM}) + unpack_map(${LIB_PROGRAM_MAP}) + string(CONCAT SHADER_ENUMS "${SHADER_ENUMS}" "${LIB_PROGRAM} = (${AUTOSCRIBE_PROGRAM_VERTEX} << 16) | ${AUTOSCRIBE_PROGRAM_FRAGMENT},\n") + MATH(EXPR PROGRAM_COUNT "${PROGRAM_COUNT}+1") + list(APPEND SHADER_ALL_PROGRAMS "${SHADER_NAMESPACE}::program::${LIB_PROGRAM}") + endforeach() + string(CONCAT SHADER_ENUMS "${SHADER_ENUMS}" "}; } // program \n") + endif() + string(CONCAT SHADER_ENUMS "${SHADER_ENUMS}" "} // namespace ${SHADER_NAMESPACE}\n") + endforeach() + + set(SHADER_PROGRAMS_ARRAY "") + foreach(SHADER_PROGRAM ${SHADER_ALL_PROGRAMS}) + string(CONCAT SHADER_PROGRAMS_ARRAY "${SHADER_PROGRAMS_ARRAY}" " ${SHADER_PROGRAM},\n") + endforeach() + + set(SHADER_COUNT 0) + foreach(COMPILED_SHADER ${COMPILED_SHADERS}) + string(CONCAT SHADER_QRC "${SHADER_QRC}" "${COMPILED_SHADER}\n") + MATH(EXPR SHADER_COUNT "${SHADER_COUNT}+1") + endforeach() + + configure_file( + Shaders.cpp.in + ${CMAKE_CURRENT_BINARY_DIR}/shaders/Shaders.cpp + ) + configure_file( + Shaders.h.in + ${CMAKE_CURRENT_BINARY_DIR}/shaders/Shaders.h + ) + configure_file( + shaders.qrc.in + ${CMAKE_CURRENT_BINARY_DIR}/shaders.qrc + ) + set(AUTOSCRIBE_SHADER_LIB_SRC "${CMAKE_CURRENT_BINARY_DIR}/shaders/Shaders.h;${CMAKE_CURRENT_BINARY_DIR}/shaders/Shaders.cpp") + set(QT_RESOURCES_FILE ${CMAKE_CURRENT_BINARY_DIR}/shaders.qrc) + get_property(GLOBAL_SHADER_SOURCES GLOBAL PROPERTY GLOBAL_SHADER_SOURCES) + list(REMOVE_DUPLICATES GLOBAL_SHADER_SOURCES) + #add_custom_target(shader-sources SOURCES ${GLOBAL_SHADER_SOURCES} ${COMPILED_SHADERS} "${CMAKE_BINARY_DIR}/shaders/Shaders.h") endmacro() diff --git a/cmake/macros/LinkHifiLibraries.cmake b/cmake/macros/LinkHifiLibraries.cmake index 395af01f8d..7a6a136799 100644 --- a/cmake/macros/LinkHifiLibraries.cmake +++ b/cmake/macros/LinkHifiLibraries.cmake @@ -19,12 +19,8 @@ function(LINK_HIFI_LIBRARIES) endforeach() foreach(HIFI_LIBRARY ${LIBRARIES_TO_LINK}) - include_directories("${HIFI_LIBRARY_DIR}/${HIFI_LIBRARY}/src") - include_directories("${CMAKE_BINARY_DIR}/libraries/${HIFI_LIBRARY}/shaders") - - #add_dependencies(${TARGET_NAME} ${HIFI_LIBRARY}) - + include_directories("${CMAKE_BINARY_DIR}/libraries/${HIFI_LIBRARY}") # link the actual library - it is static so don't bubble it up target_link_libraries(${TARGET_NAME} ${HIFI_LIBRARY}) endforeach() diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index ea30909a08..990d84a774 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -214,6 +214,7 @@ link_hifi_libraries( controllers plugins image trackers ui-plugins display-plugins input-plugins ${PLATFORM_GL_BACKEND} + shaders ) # include the binary directory of render-utils for shader includes diff --git a/interface/src/workload/GameWorkloadRenderer.cpp b/interface/src/workload/GameWorkloadRenderer.cpp index a8b65492d3..c0aaad8100 100644 --- a/interface/src/workload/GameWorkloadRenderer.cpp +++ b/interface/src/workload/GameWorkloadRenderer.cpp @@ -14,11 +14,7 @@ #include #include - -#include "render-utils/drawWorkloadProxy_vert.h" -#include "render-utils/drawWorkloadView_vert.h" -#include "render-utils/drawWorkloadProxy_frag.h" -#include "render-utils/drawWorkloadView_frag.h" +#include void GameSpaceToRender::configure(const Config& config) { @@ -149,9 +145,7 @@ void GameWorkloadRenderItem::setAllViews(const workload::Views& views) { const gpu::PipelinePointer GameWorkloadRenderItem::getProxiesPipeline() { if (!_drawAllProxiesPipeline) { - auto vs = drawWorkloadProxy_vert::getShader(); - auto ps = drawWorkloadProxy_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::drawWorkloadProxy); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding("workloadProxiesBuffer", 0)); @@ -173,9 +167,7 @@ const gpu::PipelinePointer GameWorkloadRenderItem::getProxiesPipeline() { const gpu::PipelinePointer GameWorkloadRenderItem::getViewsPipeline() { if (!_drawAllViewsPipeline) { - auto vs = drawWorkloadView_vert::getShader(); - auto ps = drawWorkloadView_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::drawWorkloadView); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding("workloadViewsBuffer", 1)); diff --git a/libraries/display-plugins/CMakeLists.txt b/libraries/display-plugins/CMakeLists.txt index 7d34258c96..529ef4c921 100644 --- a/libraries/display-plugins/CMakeLists.txt +++ b/libraries/display-plugins/CMakeLists.txt @@ -1,7 +1,7 @@ set(TARGET_NAME display-plugins) AUTOSCRIBE_SHADER_LIB(gpu display-plugins) setup_hifi_library(Gui) -link_hifi_libraries(shared plugins ui-plugins gl ui render-utils ${PLATFORM_GL_BACKEND}) +link_hifi_libraries(shared shaders plugins ui-plugins gl ui render-utils ${PLATFORM_GL_BACKEND}) include_hifi_library_headers(gpu) include_hifi_library_headers(model-networking) include_hifi_library_headers(networking) diff --git a/libraries/display-plugins/src/display-plugins/OpenGLDisplayPlugin.cpp b/libraries/display-plugins/src/display-plugins/OpenGLDisplayPlugin.cpp index 9200843cf8..b9328e01c3 100644 --- a/libraries/display-plugins/src/display-plugins/OpenGLDisplayPlugin.cpp +++ b/libraries/display-plugins/src/display-plugins/OpenGLDisplayPlugin.cpp @@ -30,7 +30,7 @@ #include #include -#include +#include #include #include #include @@ -391,8 +391,8 @@ void OpenGLDisplayPlugin::customizeContext() { if (!_presentPipeline) { { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = gpu::StandardShaderLib::getDrawTexturePS(); + auto vs = gpu::Shader::createVertex(shader::gpu::vertex::DrawUnitQuadTexcoord); + auto ps = gpu::Shader::createPixel(shader::gpu::fragment::DrawTexture); gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); gpu::Shader::makeProgram(*program); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); @@ -402,7 +402,7 @@ void OpenGLDisplayPlugin::customizeContext() { } { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); + auto vs = gpu::Shader::createVertex(shader::gpu::vertex::DrawUnitQuadTexcoord); auto ps = gpu::Shader::createPixel(std::string(SRGB_TO_LINEAR_FRAG)); gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); gpu::Shader::makeProgram(*program); @@ -413,8 +413,8 @@ void OpenGLDisplayPlugin::customizeContext() { } { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = gpu::StandardShaderLib::getDrawTexturePS(); + auto vs = gpu::Shader::createVertex(shader::gpu::vertex::DrawUnitQuadTexcoord); + auto ps = gpu::Shader::createPixel(shader::gpu::fragment::DrawTexture); gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); gpu::Shader::makeProgram(*program); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); @@ -426,8 +426,8 @@ void OpenGLDisplayPlugin::customizeContext() { } { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = gpu::StandardShaderLib::getDrawTextureMirroredXPS(); + auto vs = gpu::Shader::createVertex(shader::gpu::vertex::DrawUnitQuadTexcoord); + auto ps = gpu::Shader::createPixel(shader::gpu::fragment::DrawTextureMirroredX); gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); gpu::Shader::makeProgram(*program); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); @@ -439,8 +439,8 @@ void OpenGLDisplayPlugin::customizeContext() { } { - auto vs = gpu::StandardShaderLib::getDrawTransformUnitQuadVS(); - auto ps = gpu::StandardShaderLib::getDrawTexturePS(); + auto vs = gpu::Shader::createVertex(shader::gpu::vertex::DrawTransformUnitQuad); + auto ps = gpu::Shader::createPixel(shader::gpu::fragment::DrawTexture); gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); gpu::Shader::makeProgram(*program); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); diff --git a/libraries/display-plugins/src/display-plugins/hmd/HmdDisplayPlugin.cpp b/libraries/display-plugins/src/display-plugins/hmd/HmdDisplayPlugin.cpp index 98283b0ef6..9966fb4357 100644 --- a/libraries/display-plugins/src/display-plugins/hmd/HmdDisplayPlugin.cpp +++ b/libraries/display-plugins/src/display-plugins/hmd/HmdDisplayPlugin.cpp @@ -24,8 +24,8 @@ #include #include #include -#include #include +#include #include #include @@ -34,8 +34,6 @@ #include "../CompositorHelper.h" #include "DesktopPreviewProvider.h" -#include "render-utils/hmd_ui_vert.h" -#include "render-utils/hmd_ui_frag.h" static const QString MONO_PREVIEW = "Mono Preview"; static const QString DISABLE_PREVIEW = "Disable Preview"; @@ -409,9 +407,7 @@ void HmdDisplayPlugin::HUDRenderer::build() { void HmdDisplayPlugin::HUDRenderer::updatePipeline() { if (!pipeline) { - auto vs = hmd_ui_vert::getShader(); - auto ps = hmd_ui_frag::getShader(); - auto program = gpu::Shader::createProgram(vs, ps); + auto program = gpu::Shader::createProgram(shader::render_utils::program::hmd_ui); gpu::Shader::makeProgram(*program, gpu::Shader::BindingSet()); uniformsLocation = program->getUniformBuffers().findLocation("hudBuffer"); diff --git a/libraries/display-plugins/src/display-plugins/stereo/InterleavedStereoDisplayPlugin.cpp b/libraries/display-plugins/src/display-plugins/stereo/InterleavedStereoDisplayPlugin.cpp index 0b20d0bf30..fe3f54a9a8 100644 --- a/libraries/display-plugins/src/display-plugins/stereo/InterleavedStereoDisplayPlugin.cpp +++ b/libraries/display-plugins/src/display-plugins/stereo/InterleavedStereoDisplayPlugin.cpp @@ -8,10 +8,10 @@ #include "InterleavedStereoDisplayPlugin.h" -#include #include #include #include +#include static const char* INTERLEAVED_SRGB_TO_LINEAR_FRAG = R"SCRIBE( @@ -46,7 +46,7 @@ const QString InterleavedStereoDisplayPlugin::NAME("3D TV - Interleaved"); void InterleavedStereoDisplayPlugin::customizeContext() { StereoDisplayPlugin::customizeContext(); if (!_interleavedPresentPipeline) { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); + auto vs = gpu::Shader::createVertex(shader::gpu::vertex::DrawUnitQuadTexcoord); auto ps = gpu::Shader::createPixel(std::string(INTERLEAVED_SRGB_TO_LINEAR_FRAG)); gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); gpu::Shader::makeProgram(*program); diff --git a/libraries/entities-renderer/CMakeLists.txt b/libraries/entities-renderer/CMakeLists.txt index 12b9b3dea5..cf887bfeff 100644 --- a/libraries/entities-renderer/CMakeLists.txt +++ b/libraries/entities-renderer/CMakeLists.txt @@ -1,7 +1,6 @@ set(TARGET_NAME entities-renderer) -AUTOSCRIBE_SHADER_LIB(gpu graphics procedural render render-utils) setup_hifi_library(Network Script) -link_hifi_libraries(shared workload gpu procedural graphics model-networking script-engine render render-utils image qml ui pointers) +link_hifi_libraries(shared workload gpu shaders procedural graphics model-networking script-engine render render-utils image qml ui pointers) include_hifi_library_headers(networking) include_hifi_library_headers(gl) include_hifi_library_headers(ktx) @@ -18,3 +17,4 @@ include_hifi_library_headers(graphics-scripting) # for Forward.h target_bullet() target_polyvox() + diff --git a/libraries/entities-renderer/src/RenderableParticleEffectEntityItem.cpp b/libraries/entities-renderer/src/RenderableParticleEffectEntityItem.cpp index 73f46245c4..f5118b3570 100644 --- a/libraries/entities-renderer/src/RenderableParticleEffectEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderableParticleEffectEntityItem.cpp @@ -13,9 +13,8 @@ #include #include +#include -#include "textured_particle_vert.h" -#include "textured_particle_frag.h" using namespace render; using namespace render::entities; @@ -36,10 +35,7 @@ static ShapePipelinePointer shapePipelineFactory(const ShapePlumber& plumber, co gpu::State::FACTOR_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::ONE); PrepareStencil::testMask(*state); - auto vertShader = textured_particle_vert::getShader(); - auto fragShader = textured_particle_frag::getShader(); - - auto program = gpu::Shader::createProgram(vertShader, fragShader); + auto program = gpu::Shader::createProgram(shader::entities_renderer::program::textured_particle); _texturedPipeline = texturedPipeline = gpu::Pipeline::create(program, state); batch.runLambda([program] { diff --git a/libraries/entities-renderer/src/RenderablePolyLineEntityItem.cpp b/libraries/entities-renderer/src/RenderablePolyLineEntityItem.cpp index 7cab57123d..fac2fd5841 100644 --- a/libraries/entities-renderer/src/RenderablePolyLineEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderablePolyLineEntityItem.cpp @@ -17,18 +17,13 @@ #include #include #include +#include //#define POLYLINE_ENTITY_USE_FADE_EFFECT #ifdef POLYLINE_ENTITY_USE_FADE_EFFECT # include #endif -#include "paintStroke_vert.h" -#include "paintStroke_frag.h" - -#include "paintStroke_fade_vert.h" -#include "paintStroke_fade_frag.h" - using namespace render; using namespace render::entities; @@ -48,9 +43,7 @@ struct PolyLineUniforms { static render::ShapePipelinePointer shapePipelineFactory(const render::ShapePlumber& plumber, const render::ShapeKey& key, gpu::Batch& batch) { if (!polylinePipeline) { - auto VS = paintStroke_vert::getShader(); - auto PS = paintStroke_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(VS, PS); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::entities_renderer::program::paintStroke); #ifdef POLYLINE_ENTITY_USE_FADE_EFFECT auto fadeVS = gpu::Shader::createVertex(std::string(paintStroke_fade_vert)); auto fadePS = gpu::Shader::createPixel(std::string(paintStroke_fade_frag)); diff --git a/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp b/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp index 2de6316d74..0157db4cb0 100644 --- a/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp @@ -26,12 +26,9 @@ #include #include -#include "EntityTreeRenderer.h" +#include -#include "polyvox_vert.h" -#include "polyvox_frag.h" -#include "polyvox_fade_vert.h" -#include "polyvox_fade_frag.h" +#include "EntityTreeRenderer.h" #ifdef POLYVOX_ENTITY_USE_FADE_EFFECT # include @@ -72,11 +69,6 @@ #include "EntityTreeRenderer.h" -#include "polyvox_vert.h" -#include "polyvox_frag.h" -#include "polyvox_fade_vert.h" -#include "polyvox_fade_frag.h" - #include "RenderablePolyVoxEntityItem.h" #include "EntityEditPacketSender.h" #include "PhysicalEntitySimulation.h" @@ -1572,8 +1564,8 @@ static gpu::Stream::FormatPointer _vertexFormat; ShapePipelinePointer shapePipelineFactory(const ShapePlumber& plumber, const ShapeKey& key, gpu::Batch& batch) { if (!_pipelines[0]) { - gpu::ShaderPointer vertexShaders[2] = { polyvox_vert::getShader(), polyvox_fade_vert::getShader() }; - gpu::ShaderPointer pixelShaders[2] = { polyvox_frag::getShader(), polyvox_fade_frag::getShader() }; + using namespace shader::entities_renderer::program; + int programsIds[2] = { polyvox, polyvox_fade }; gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("materialBuffer"), MATERIAL_GPU_SLOT)); @@ -1597,7 +1589,7 @@ ShapePipelinePointer shapePipelineFactory(const ShapePlumber& plumber, const Sha // Two sets of pipelines: normal and fading for (auto i = 0; i < 2; i++) { - gpu::ShaderPointer program = gpu::Shader::createProgram(vertexShaders[i], pixelShaders[i]); + gpu::ShaderPointer program = gpu::Shader::createProgram(programsIds[i]); batch.runLambda([program, slotBindings] { gpu::Shader::makeProgram(*program, slotBindings); diff --git a/libraries/entities-renderer/src/RenderableShapeEntityItem.cpp b/libraries/entities-renderer/src/RenderableShapeEntityItem.cpp index c50b3bd760..b73ceb3269 100644 --- a/libraries/entities-renderer/src/RenderableShapeEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderableShapeEntityItem.cpp @@ -15,12 +15,7 @@ #include #include #include - -#include "render-utils/simple_vert.h" -#include "render-utils/simple_frag.h" -#include "render-utils/simple_transparent_frag.h" -#include "render-utils/forward_simple_frag.h" -#include "render-utils/forward_simple_transparent_frag.h" +#include #include "RenderPipelines.h" @@ -37,12 +32,12 @@ static const float SPHERE_ENTITY_SCALE = 0.5f; ShapeEntityRenderer::ShapeEntityRenderer(const EntityItemPointer& entity) : Parent(entity) { - _procedural._vertexSource = simple_vert::getSource(); + _procedural._vertexSource = gpu::Shader::getVertexShaderSource(shader::render_utils::vertex::simple).getCode(); // FIXME: Setup proper uniform slots and use correct pipelines for forward rendering - _procedural._opaquefragmentSource = simple_frag::getSource(); + _procedural._opaquefragmentSource = gpu::Shader::getFragmentShaderSource(shader::render_utils::fragment::simple).getCode(); // FIXME: Transparent procedural entities only seem to work if they use the opaque pipelines //_procedural._transparentfragmentSource = simple_transparent_frag::getSource(); - _procedural._transparentfragmentSource = simple_frag::getSource(); + _procedural._transparentfragmentSource = _procedural._opaquefragmentSource; _procedural._opaqueState->setCullMode(gpu::State::CULL_NONE); _procedural._opaqueState->setDepthTest(true, true, gpu::LESS_EQUAL); PrepareStencil::testMaskDrawShape(*_procedural._opaqueState); diff --git a/libraries/gpu/CMakeLists.txt b/libraries/gpu/CMakeLists.txt index 207431d8c7..7573cc5473 100644 --- a/libraries/gpu/CMakeLists.txt +++ b/libraries/gpu/CMakeLists.txt @@ -1,6 +1,6 @@ set(TARGET_NAME gpu) -autoscribe_shader_lib(gpu) + setup_hifi_library() -link_hifi_libraries(shared ktx) +link_hifi_libraries(shared ktx shaders) target_nsight() diff --git a/libraries/gpu/src/gpu/DrawNada.slf b/libraries/gpu/src/gpu/DrawNada.slf new file mode 100644 index 0000000000..6f286a5164 --- /dev/null +++ b/libraries/gpu/src/gpu/DrawNada.slf @@ -0,0 +1,5 @@ +<@include gpu/Config.slh@> + +<$VERSION_HEADER$> + +void main(void) { } diff --git a/libraries/gpu/src/gpu/Shader.cpp b/libraries/gpu/src/gpu/Shader.cpp index b539a84925..ca1613bd0b 100755 --- a/libraries/gpu/src/gpu/Shader.cpp +++ b/libraries/gpu/src/gpu/Shader.cpp @@ -13,6 +13,8 @@ #include #include +#include + #include "Context.h" using namespace gpu; @@ -62,17 +64,6 @@ Shader::Pointer Shader::createOrReuseDomainShader(Type type, const Source& sourc return shader; } -Shader::Pointer Shader::createVertex(const Source& source) { - return createOrReuseDomainShader(VERTEX, source); -} - -Shader::Pointer Shader::createPixel(const Source& source) { - return createOrReuseDomainShader(PIXEL, source); -} - -Shader::Pointer Shader::createGeometry(const Source& source) { - return createOrReuseDomainShader(GEOMETRY, source); -} ShaderPointer Shader::createOrReuseProgramShader(Type type, const Pointer& vertexShader, const Pointer& geometryShader, const Pointer& pixelShader) { PROFILE_RANGE(app, "createOrReuseProgramShader"); @@ -116,15 +107,6 @@ ShaderPointer Shader::createOrReuseProgramShader(Type type, const Pointer& verte return program; } - -Shader::Pointer Shader::createProgram(const Pointer& vertexShader, const Pointer& pixelShader) { - return createOrReuseProgramShader(PROGRAM, vertexShader, nullptr, pixelShader); -} - -Shader::Pointer Shader::createProgram(const Pointer& vertexShader, const Pointer& geometryShader, const Pointer& pixelShader) { - return createOrReuseProgramShader(PROGRAM, vertexShader, geometryShader, pixelShader); -} - void Shader::defineSlots(const SlotSet& uniforms, const SlotSet& uniformBuffers, const SlotSet& resourceBuffers, const SlotSet& textures, const SlotSet& samplers, const SlotSet& inputs, const SlotSet& outputs) { _uniforms = uniforms; _uniformBuffers = uniformBuffers; @@ -153,3 +135,39 @@ void Shader::incrementCompilationAttempt() const { _numCompilationAttempts++; } + +Shader::Source Shader::getShaderSource(Type type, int shaderId) { + return shader::loadShaderSource(shaderId); +} + +Shader::Pointer Shader::createVertex(const Source& source) { + return createOrReuseDomainShader(VERTEX, source); +} + +Shader::Pointer Shader::createPixel(const Source& source) { + return createOrReuseDomainShader(FRAGMENT, source); +} + +Shader::Pointer Shader::createVertex(int id) { + return createVertex(getShaderSource(VERTEX, id)); +} + +Shader::Pointer Shader::createPixel(int id) { + return createPixel(getShaderSource(FRAGMENT, id)); +} + +Shader::Pointer Shader::createProgram(const Pointer& vertexShader, const Pointer& pixelShader) { + return createOrReuseProgramShader(PROGRAM, vertexShader, nullptr, pixelShader); +} + +Shader::Pointer Shader::createProgram(int programId) { + int vertexId = (programId >> 16) & 0xFFFF; + int fragmentId = programId & 0xFFFF; + auto vertexShader = createVertex(vertexId); + auto fragmentShader = createPixel(fragmentId); + return createOrReuseProgramShader(PROGRAM, vertexShader, nullptr, fragmentShader); +} + +//Shader::Pointer Shader::createProgram(const Pointer& vertexShader, const Pointer& geometryShader, const Pointer& pixelShader) { +// return createOrReuseProgramShader(PROGRAM, vertexShader, geometryShader, pixelShader); +//} diff --git a/libraries/gpu/src/gpu/Shader.h b/libraries/gpu/src/gpu/Shader.h index fe92da1469..64a2fc3f4f 100755 --- a/libraries/gpu/src/gpu/Shader.h +++ b/libraries/gpu/src/gpu/Shader.h @@ -26,9 +26,21 @@ public: // unique identifier of a shader using ID = uint32_t; + enum Type { + VERTEX = 0, + PIXEL, + FRAGMENT = PIXEL, + GEOMETRY, + NUM_DOMAINS, + + PROGRAM, + }; + typedef std::shared_ptr< Shader > Pointer; typedef std::vector< Pointer > Shaders; + + class Source { public: enum Language { @@ -52,6 +64,10 @@ public: Language _lang = GLSL; }; + static Source getShaderSource(Type type, int shaderId); + static Source getVertexShaderSource(int shaderId) { return getShaderSource(VERTEX, shaderId); } + static Source getFragmentShaderSource(int shaderId) { return getShaderSource(FRAGMENT, shaderId); } + struct CompilationLog { std::string message; bool compiled{ false }; @@ -121,21 +137,17 @@ public: typedef std::set> BindingSet; - enum Type { - VERTEX = 0, - PIXEL, - GEOMETRY, - NUM_DOMAINS, - - PROGRAM, - }; - static Pointer createVertex(const Source& source); static Pointer createPixel(const Source& source); - static Pointer createGeometry(const Source& source); + //static Pointer createGeometry(const Source& source); + static Pointer createVertex(int shaderId); + static Pointer createPixel(int shaderId); + static Pointer createGeometry(int shaderId); + static Pointer createProgram(int programId); static Pointer createProgram(const Pointer& vertexShader, const Pointer& pixelShader); - static Pointer createProgram(const Pointer& vertexShader, const Pointer& geometryShader, const Pointer& pixelShader); + //static Pointer createProgram(int vertexId, int fragmentId); + //static Pointer createProgram(const Pointer& vertexShader, const Pointer& geometryShader, const Pointer& pixelShader); ~Shader(); diff --git a/libraries/gpu/src/gpu/StandardShaderLib.cpp b/libraries/gpu/src/gpu/StandardShaderLib.cpp deleted file mode 100755 index 0d829fb21f..0000000000 --- a/libraries/gpu/src/gpu/StandardShaderLib.cpp +++ /dev/null @@ -1,163 +0,0 @@ -// -// StandardShaderLib.cpp -// libraries/gpu/src/gpu -// -// Collection of standard shaders that can be used all over the place -// -// Created by Sam Gateau on 6/22/2015. -// Copyright 2015 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// -#include "StandardShaderLib.h" - -#include "DrawUnitQuadTexcoord_vert.h" -#include "DrawTransformUnitQuad_vert.h" -#include "DrawTexcoordRectTransformUnitQuad_vert.h" -#include "DrawViewportQuadTransformTexcoord_vert.h" -#include "DrawVertexPosition_vert.h" -#include "DrawTransformVertexPosition_vert.h" - -const char DrawNada_frag[] = "void main(void) {}"; // DrawNada is really simple... - -#include "DrawWhite_frag.h" -#include "DrawColor_frag.h" -#include "DrawTexture_frag.h" -#include "DrawTextureMirroredX_frag.h" -#include "DrawTextureOpaque_frag.h" -#include "DrawColoredTexture_frag.h" - -using namespace gpu; - -ShaderPointer StandardShaderLib::_drawUnitQuadTexcoordVS; -ShaderPointer StandardShaderLib::_drawTransformUnitQuadVS; -ShaderPointer StandardShaderLib::_drawTexcoordRectTransformUnitQuadVS; -ShaderPointer StandardShaderLib::_drawViewportQuadTransformTexcoordVS; -ShaderPointer StandardShaderLib::_drawVertexPositionVS; -ShaderPointer StandardShaderLib::_drawTransformVertexPositionVS; -ShaderPointer StandardShaderLib::_drawNadaPS; -ShaderPointer StandardShaderLib::_drawWhitePS; -ShaderPointer StandardShaderLib::_drawColorPS; -ShaderPointer StandardShaderLib::_drawTexturePS; -ShaderPointer StandardShaderLib::_drawTextureMirroredXPS; -ShaderPointer StandardShaderLib::_drawTextureOpaquePS; -ShaderPointer StandardShaderLib::_drawColoredTexturePS; -StandardShaderLib::ProgramMap StandardShaderLib::_programs; - -ShaderPointer StandardShaderLib::getProgram(GetShader getVS, GetShader getPS) { - - auto programIt = _programs.find(std::pair(getVS, getPS)); - if (programIt != _programs.end()) { - return (*programIt).second; - } else { - auto vs = (getVS)(); - auto ps = (getPS)(); - auto program = gpu::Shader::createProgram(vs, ps); - if (program) { - // Program created, let's try to make it - if (gpu::Shader::makeProgram((*program))) { - // All good, backup and return that program - _programs.insert(ProgramMap::value_type(std::pair(getVS, getPS), program)); - return program; - } else { - // Failed to make the program probably because vs and ps cannot work together? - } - } else { - // Failed to create the program maybe because ps and vs are not true vertex and pixel shaders? - } - } - return ShaderPointer(); -} - - -ShaderPointer StandardShaderLib::getDrawUnitQuadTexcoordVS() { - if (!_drawUnitQuadTexcoordVS) { - _drawUnitQuadTexcoordVS = DrawUnitQuadTexcoord_vert::getShader(); - } - return _drawUnitQuadTexcoordVS; -} - -ShaderPointer StandardShaderLib::getDrawTransformUnitQuadVS() { - if (!_drawTransformUnitQuadVS) { - _drawTransformUnitQuadVS = DrawTransformUnitQuad_vert::getShader(); - } - return _drawTransformUnitQuadVS; -} - -ShaderPointer StandardShaderLib::getDrawTexcoordRectTransformUnitQuadVS() { - if (!_drawTexcoordRectTransformUnitQuadVS) { - _drawTexcoordRectTransformUnitQuadVS = DrawTexcoordRectTransformUnitQuad_vert::getShader(); - } - return _drawTexcoordRectTransformUnitQuadVS; -} - -ShaderPointer StandardShaderLib::getDrawViewportQuadTransformTexcoordVS() { - if (!_drawViewportQuadTransformTexcoordVS) { - _drawViewportQuadTransformTexcoordVS = DrawViewportQuadTransformTexcoord_vert::getShader(); - } - return _drawViewportQuadTransformTexcoordVS; -} - -ShaderPointer StandardShaderLib::getDrawVertexPositionVS() { - if (!_drawVertexPositionVS) { - _drawVertexPositionVS = DrawVertexPosition_vert::getShader(); - } - return _drawVertexPositionVS; -} - -ShaderPointer StandardShaderLib::getDrawTransformVertexPositionVS() { - if (!_drawTransformVertexPositionVS) { - _drawTransformVertexPositionVS = DrawTransformVertexPosition_vert::getShader(); - } - return _drawTransformVertexPositionVS; -} - -ShaderPointer StandardShaderLib::getDrawNadaPS() { - if (!_drawNadaPS) { - _drawNadaPS = gpu::Shader::createPixel(std::string(DrawNada_frag)); - } - return _drawNadaPS; -} - -ShaderPointer StandardShaderLib::getDrawWhitePS() { - if (!_drawWhitePS) { - _drawWhitePS = DrawWhite_frag::getShader(); - } - return _drawWhitePS; -} - -ShaderPointer StandardShaderLib::getDrawColorPS() { - if (!_drawColorPS) { - _drawColorPS = DrawColor_frag::getShader(); - } - return _drawColorPS; -} - -ShaderPointer StandardShaderLib::getDrawTexturePS() { - if (!_drawTexturePS) { - _drawTexturePS = DrawTexture_frag::getShader(); - } - return _drawTexturePS; -} - -ShaderPointer StandardShaderLib::getDrawTextureMirroredXPS() { - if (!_drawTextureMirroredXPS) { - _drawTextureMirroredXPS = DrawTextureMirroredX_frag::getShader(); - } - return _drawTextureMirroredXPS; -} - -ShaderPointer StandardShaderLib::getDrawTextureOpaquePS() { - if (!_drawTextureOpaquePS) { - _drawTextureOpaquePS = DrawTextureOpaque_frag::getShader(); - } - return _drawTextureOpaquePS; -} - -ShaderPointer StandardShaderLib::getDrawColoredTexturePS() { - if (!_drawColoredTexturePS) { - _drawColoredTexturePS = DrawColoredTexture_frag::getShader(); - } - return _drawColoredTexturePS; -} diff --git a/libraries/gpu/src/gpu/StandardShaderLib.h b/libraries/gpu/src/gpu/StandardShaderLib.h deleted file mode 100755 index 9c11f6cc3a..0000000000 --- a/libraries/gpu/src/gpu/StandardShaderLib.h +++ /dev/null @@ -1,84 +0,0 @@ -// -// StandardShaderLib.h -// libraries/gpu/src/gpu -// -// Collection of standard shaders that can be used all over the place -// -// Created by Sam Gateau on 6/22/2015. -// Copyright 2015 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// -#ifndef hifi_gpu_StandardShaderLib_h -#define hifi_gpu_StandardShaderLib_h - -#include -#include - -#include "Shader.h" - -namespace gpu { - -class StandardShaderLib { -public: - - // Shader draws the unit quad in the full viewport clipPos = ([(-1,-1),(1,1)]) and the unit texcoord = [(0,0),(1,1)]. - static ShaderPointer getDrawUnitQuadTexcoordVS(); - - // Shader draw the unit quad objectPos = ([(-1,-1),(1,1)]) and transform it by the full model transform stack (Model, View, Proj). - // A texcoord attribute is also generated texcoord = [(0,0),(1,1)] - static ShaderPointer getDrawTransformUnitQuadVS(); - - // Shader draw the unit quad objectPos = ([(-1,-1),(1,1)]) and transform it by the full model transform stack (Model, View, Proj). - // A texcoord attribute is also generated covering a rect defined from the uniform vec4 texcoordRect: texcoord = [texcoordRect.xy,texcoordRect.xy + texcoordRect.zw] - static ShaderPointer getDrawTexcoordRectTransformUnitQuadVS(); - - // Shader draws the unit quad in the full viewport clipPos = ([(-1,-1),(1,1)]) and transform the texcoord = [(0,0),(1,1)] by the model transform. - static ShaderPointer getDrawViewportQuadTransformTexcoordVS(); - - // Shader draw the fed vertex position and transform it by the full model transform stack (Model, View, Proj). - // simply output the world pos and the clip pos to the next stage - static ShaderPointer getDrawVertexPositionVS(); - static ShaderPointer getDrawTransformVertexPositionVS(); - - // PShader does nothing, no really nothing, but still needed for defining a program triggering rasterization - static ShaderPointer getDrawNadaPS(); - - static ShaderPointer getDrawWhitePS(); - static ShaderPointer getDrawColorPS(); - static ShaderPointer getDrawTexturePS(); - static ShaderPointer getDrawTextureMirroredXPS(); - static ShaderPointer getDrawTextureOpaquePS(); - static ShaderPointer getDrawColoredTexturePS(); - - // The shader program combining the shaders available above, so they are unique - typedef ShaderPointer (*GetShader) (); - static ShaderPointer getProgram(GetShader vs, GetShader ps); - -protected: - - static ShaderPointer _drawUnitQuadTexcoordVS; - static ShaderPointer _drawTransformUnitQuadVS; - static ShaderPointer _drawTexcoordRectTransformUnitQuadVS; - static ShaderPointer _drawViewportQuadTransformTexcoordVS; - - static ShaderPointer _drawVertexPositionVS; - static ShaderPointer _drawTransformVertexPositionVS; - - static ShaderPointer _drawNadaPS; - static ShaderPointer _drawWhitePS; - static ShaderPointer _drawColorPS; - static ShaderPointer _drawTexturePS; - static ShaderPointer _drawTextureMirroredXPS; - static ShaderPointer _drawTextureOpaquePS; - static ShaderPointer _drawColoredTexturePS; - - typedef std::map, ShaderPointer> ProgramMap; - static ProgramMap _programs; -}; - - -}; - -#endif diff --git a/libraries/graphics/CMakeLists.txt b/libraries/graphics/CMakeLists.txt index 2b15604fdf..556d4ef53f 100755 --- a/libraries/graphics/CMakeLists.txt +++ b/libraries/graphics/CMakeLists.txt @@ -1,4 +1,4 @@ set(TARGET_NAME graphics) -AUTOSCRIBE_SHADER_LIB(gpu graphics) setup_hifi_library() -link_hifi_libraries(shared ktx gpu image) \ No newline at end of file + +link_hifi_libraries(shared ktx gpu shaders image) \ No newline at end of file diff --git a/libraries/graphics/src/graphics/Skybox.cpp b/libraries/graphics/src/graphics/Skybox.cpp index 6ad0045aa9..6c044444f0 100755 --- a/libraries/graphics/src/graphics/Skybox.cpp +++ b/libraries/graphics/src/graphics/Skybox.cpp @@ -15,8 +15,7 @@ #include #include -#include "skybox_vert.h" -#include "skybox_frag.h" +#include using namespace graphics; @@ -91,9 +90,7 @@ void Skybox::render(gpu::Batch& batch, const ViewFrustum& viewFrustum, const Sky static std::once_flag once; std::call_once(once, [&] { { - auto skyVS = skybox_vert::getShader(); - auto skyFS = skybox_frag::getShader(); - auto skyShader = gpu::Shader::createProgram(skyVS, skyFS); + auto skyShader = gpu::Shader::createProgram(shader::graphics::program::skybox); batch.runLambda([skyShader] { gpu::Shader::BindingSet bindings; diff --git a/libraries/procedural/CMakeLists.txt b/libraries/procedural/CMakeLists.txt index 9ec7cb6431..6d6610a323 100644 --- a/libraries/procedural/CMakeLists.txt +++ b/libraries/procedural/CMakeLists.txt @@ -1,5 +1,4 @@ set(TARGET_NAME procedural) -AUTOSCRIBE_SHADER_LIB(gpu graphics) setup_hifi_library() -link_hifi_libraries(shared gpu networking graphics model-networking ktx image) +link_hifi_libraries(shared gpu shaders networking graphics model-networking ktx image) diff --git a/libraries/procedural/src/procedural/Procedural.cpp b/libraries/procedural/src/procedural/Procedural.cpp index 7bf020094a..8f0c9ab4f0 100644 --- a/libraries/procedural/src/procedural/Procedural.cpp +++ b/libraries/procedural/src/procedural/Procedural.cpp @@ -20,7 +20,7 @@ #include #include #include -#include "ProceduralCommon_frag.h" +#include #include "Logging.h" @@ -223,9 +223,10 @@ bool Procedural::isReady() const { std::string Procedural::replaceProceduralBlock(const std::string& fragmentSource) { std::string fragmentShaderSource = fragmentSource; + static const auto proceduralCommonSource = gpu::Shader::getFragmentShaderSource(shader::procedural::fragment::ProceduralCommon); size_t replaceIndex = fragmentShaderSource.find(PROCEDURAL_COMMON_BLOCK); if (replaceIndex != std::string::npos) { - fragmentShaderSource.replace(replaceIndex, PROCEDURAL_COMMON_BLOCK.size(), ProceduralCommon_frag::getSource()); + fragmentShaderSource.replace(replaceIndex, PROCEDURAL_COMMON_BLOCK.size(), proceduralCommonSource.getCode()); } replaceIndex = fragmentShaderSource.find(PROCEDURAL_VERSION); diff --git a/libraries/procedural/src/procedural/ProceduralSkybox.cpp b/libraries/procedural/src/procedural/ProceduralSkybox.cpp index 0c6501928b..26a90e1894 100644 --- a/libraries/procedural/src/procedural/ProceduralSkybox.cpp +++ b/libraries/procedural/src/procedural/ProceduralSkybox.cpp @@ -13,14 +13,13 @@ #include #include +#include #include - -#include -#include +#include ProceduralSkybox::ProceduralSkybox() : graphics::Skybox() { - _procedural._vertexSource = skybox_vert::getSource(); - _procedural._opaquefragmentSource = skybox_frag::getSource(); + _procedural._vertexSource = gpu::Shader::getVertexShaderSource(shader::graphics::vertex::skybox).getCode(); + _procedural._opaquefragmentSource = gpu::Shader::getFragmentShaderSource(shader::graphics::fragment::skybox).getCode(); // Adjust the pipeline state for background using the stencil test _procedural.setDoesFade(false); // Must match PrepareStencil::STENCIL_BACKGROUND diff --git a/libraries/render-utils/CMakeLists.txt b/libraries/render-utils/CMakeLists.txt index 319b6ad415..eaa3b4dbf5 100644 --- a/libraries/render-utils/CMakeLists.txt +++ b/libraries/render-utils/CMakeLists.txt @@ -1,9 +1,9 @@ set(TARGET_NAME render-utils) -AUTOSCRIBE_SHADER_LIB(gpu graphics render) + # pull in the resources.qrc file qt5_add_resources(QT_RESOURCES_FILE "${CMAKE_CURRENT_SOURCE_DIR}/res/fonts/fonts.qrc") setup_hifi_library(Gui Network Qml Quick Script) -link_hifi_libraries(shared task ktx gpu graphics graphics-scripting model-networking render animation fbx image procedural) +link_hifi_libraries(shared task ktx gpu shaders graphics graphics-scripting model-networking render animation fbx image procedural) include_hifi_library_headers(audio) include_hifi_library_headers(networking) include_hifi_library_headers(octree) @@ -14,3 +14,4 @@ set_property(SOURCE qrc_fonts.cpp PROPERTY SKIP_AUTOMOC ON) if (NOT ANDROID) target_nsight() endif () + diff --git a/libraries/render-utils/src/AmbientOcclusionEffect.cpp b/libraries/render-utils/src/AmbientOcclusionEffect.cpp index 2ac8e77898..aca71636ff 100644 --- a/libraries/render-utils/src/AmbientOcclusionEffect.cpp +++ b/libraries/render-utils/src/AmbientOcclusionEffect.cpp @@ -18,7 +18,8 @@ #include #include #include -#include +#include + #include "RenderUtilsLogging.h" #include "DeferredLightingEffect.h" @@ -27,11 +28,6 @@ #include "DependencyManager.h" #include "ViewFrustum.h" -#include "ssao_makePyramid_frag.h" -#include "ssao_makeOcclusion_frag.h" -#include "ssao_debugOcclusion_frag.h" -#include "ssao_makeHorizontalBlur_frag.h" -#include "ssao_makeVerticalBlur_frag.h" AmbientOcclusionFramebuffer::AmbientOcclusionFramebuffer() { @@ -261,9 +257,7 @@ void AmbientOcclusionEffect::configure(const Config& config) { const gpu::PipelinePointer& AmbientOcclusionEffect::getOcclusionPipeline() { if (!_occlusionPipeline) { - auto vs = gpu::StandardShaderLib::getDrawViewportQuadTransformTexcoordVS(); - auto ps = ssao_makeOcclusion_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::ssao_makeOcclusion); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), AmbientOcclusionEffect_FrameTransformSlot)); @@ -286,9 +280,7 @@ const gpu::PipelinePointer& AmbientOcclusionEffect::getOcclusionPipeline() { const gpu::PipelinePointer& AmbientOcclusionEffect::getHBlurPipeline() { if (!_hBlurPipeline) { - auto vs = gpu::StandardShaderLib::getDrawViewportQuadTransformTexcoordVS(); - auto ps = ssao_makeHorizontalBlur_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::ssao_makeHorizontalBlur); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("ambientOcclusionFrameTransformBuffer"), AmbientOcclusionEffect_FrameTransformSlot)); @@ -309,9 +301,7 @@ const gpu::PipelinePointer& AmbientOcclusionEffect::getHBlurPipeline() { const gpu::PipelinePointer& AmbientOcclusionEffect::getVBlurPipeline() { if (!_vBlurPipeline) { - auto vs = gpu::StandardShaderLib::getDrawViewportQuadTransformTexcoordVS(); - auto ps = ssao_makeVerticalBlur_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::ssao_makeVerticalBlur); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("ambientOcclusionFrameTransformBuffer"), AmbientOcclusionEffect_FrameTransformSlot)); @@ -456,10 +446,8 @@ void DebugAmbientOcclusion::configure(const Config& config) { const gpu::PipelinePointer& DebugAmbientOcclusion::getDebugPipeline() { if (!_debugPipeline) { - auto vs = gpu::StandardShaderLib::getDrawViewportQuadTransformTexcoordVS(); - auto ps = ssao_debugOcclusion_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::ssao_debugOcclusion); + gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), AmbientOcclusionEffect_FrameTransformSlot)); slotBindings.insert(gpu::Shader::Binding(std::string("ambientOcclusionParamsBuffer"), AmbientOcclusionEffect_ParamsSlot)); diff --git a/libraries/render-utils/src/AnimDebugDraw.cpp b/libraries/render-utils/src/AnimDebugDraw.cpp index eca500f36c..74afded28f 100644 --- a/libraries/render-utils/src/AnimDebugDraw.cpp +++ b/libraries/render-utils/src/AnimDebugDraw.cpp @@ -12,17 +12,13 @@ #include #include #include +#include #include "AbstractViewStateInterface.h" #include "RenderUtilsLogging.h" #include "DebugDraw.h" #include "StencilMaskPass.h" -#include "animdebugdraw_vert.h" -#include "animdebugdraw_frag.h" - -#include "animdebugdraw_vert.h" -#include "animdebugdraw_frag.h" class AnimDebugDrawData { public: @@ -106,9 +102,7 @@ AnimDebugDraw::AnimDebugDraw() : gpu::State::INV_SRC_ALPHA, gpu::State::FACTOR_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::ONE); PrepareStencil::testMaskDrawShape(*state.get()); - auto vertShader = animdebugdraw_vert::getShader(); - auto fragShader = animdebugdraw_frag::getShader(); - auto program = gpu::Shader::createProgram(vertShader, fragShader); + auto program = gpu::Shader::createProgram(shader::render_utils::program::animdebugdraw); _pipeline = gpu::Pipeline::create(program, state); _animDebugDrawData = std::make_shared(); diff --git a/libraries/render-utils/src/AntialiasingEffect.cpp b/libraries/render-utils/src/AntialiasingEffect.cpp index 8317568fc6..52105f1390 100644 --- a/libraries/render-utils/src/AntialiasingEffect.cpp +++ b/libraries/render-utils/src/AntialiasingEffect.cpp @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include "StencilMaskPass.h" #include "TextureCache.h" @@ -172,10 +172,6 @@ void Antialiasing::run(const render::RenderContextPointer& renderContext, const } #else -#include "taa_frag.h" -#include "fxaa_blend_frag.h" -#include "taa_blend_frag.h" - const int AntialiasingPass_ParamsSlot = 0; const int AntialiasingPass_FrameTransformSlot = 1; @@ -200,10 +196,7 @@ Antialiasing::~Antialiasing() { const gpu::PipelinePointer& Antialiasing::getAntialiasingPipeline(const render::RenderContextPointer& renderContext) { if (!_antialiasingPipeline) { - - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = taa_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::taa); gpu::Shader::BindingSet slotBindings; @@ -235,9 +228,7 @@ const gpu::PipelinePointer& Antialiasing::getAntialiasingPipeline(const render:: const gpu::PipelinePointer& Antialiasing::getBlendPipeline() { if (!_blendPipeline) { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = fxaa_blend_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::fxaa_blend); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("colorTexture"), AntialiasingPass_NextMapSlot)); @@ -258,9 +249,7 @@ const gpu::PipelinePointer& Antialiasing::getBlendPipeline() { const gpu::PipelinePointer& Antialiasing::getDebugBlendPipeline() { if (!_debugBlendPipeline) { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = taa_blend_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::taa_blend); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("taaParamsBuffer"), AntialiasingPass_ParamsSlot)); diff --git a/libraries/render-utils/src/BloomEffect.cpp b/libraries/render-utils/src/BloomEffect.cpp index 0e95655370..604919ad2d 100644 --- a/libraries/render-utils/src/BloomEffect.cpp +++ b/libraries/render-utils/src/BloomEffect.cpp @@ -10,15 +10,13 @@ // #include "BloomEffect.h" -#include "gpu/Context.h" -#include "gpu/StandardShaderLib.h" +#include + +#include #include #include -#include "BloomThreshold_frag.h" -#include "BloomApply_frag.h" - #define BLOOM_BLUR_LEVEL_COUNT 3 BloomThreshold::BloomThreshold(unsigned int downsamplingFactor) { @@ -65,9 +63,7 @@ void BloomThreshold::run(const render::RenderContextPointer& renderContext, cons static const int PARAMETERS_SLOT = 1; if (!_pipeline) { - auto vs = gpu::StandardShaderLib::getDrawTransformUnitQuadVS(); - auto ps = BloomThreshold_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::bloomThreshold); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding("colorMap", COLOR_MAP_SLOT)); @@ -124,9 +120,7 @@ void BloomApply::run(const render::RenderContextPointer& renderContext, const In static const auto PARAMETERS_SLOT = 0; if (!_pipeline) { - auto vs = gpu::StandardShaderLib::getDrawTransformUnitQuadVS(); - auto ps = BloomApply_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::bloomApply); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding("blurMap0", BLUR0_SLOT)); @@ -178,10 +172,7 @@ void BloomDraw::run(const render::RenderContextPointer& renderContext, const Inp const auto framebufferSize = frameBuffer->getSize(); if (!_pipeline) { - auto vs = gpu::StandardShaderLib::getDrawTransformUnitQuadVS(); - auto ps = gpu::StandardShaderLib::getDrawTextureOpaquePS(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::gpu::program::drawTransformUnitQuadTextureOpaque); gpu::Shader::BindingSet slotBindings; gpu::Shader::makeProgram(*program, slotBindings); @@ -237,9 +228,7 @@ void DebugBloom::run(const render::RenderContextPointer& renderContext, const In static auto TEXCOORD_RECT_SLOT = 1; if (!_pipeline) { - auto vs = gpu::StandardShaderLib::getDrawTexcoordRectTransformUnitQuadVS(); - auto ps = gpu::StandardShaderLib::getDrawTextureOpaquePS(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::gpu::program::drawTextureOpaqueTexcoordRect); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("texcoordRect"), TEXCOORD_RECT_SLOT)); diff --git a/libraries/render-utils/src/DebugDeferredBuffer.cpp b/libraries/render-utils/src/DebugDeferredBuffer.cpp index 8575df399e..4844c821e5 100644 --- a/libraries/render-utils/src/DebugDeferredBuffer.cpp +++ b/libraries/render-utils/src/DebugDeferredBuffer.cpp @@ -18,14 +18,12 @@ #include #include #include +#include #include "GeometryCache.h" #include "TextureCache.h" #include "DeferredLightingEffect.h" -#include "debug_deferred_buffer_vert.h" -#include "debug_deferred_buffer_frag.h" - using namespace render; void DebugDeferredBufferConfig::setMode(int newMode) { @@ -378,7 +376,7 @@ bool DebugDeferredBuffer::pipelineNeedsUpdate(Mode mode, std::string customFile) const gpu::PipelinePointer& DebugDeferredBuffer::getPipeline(Mode mode, std::string customFile) { if (pipelineNeedsUpdate(mode, customFile)) { - static const std::string FRAGMENT_SHADER { debug_deferred_buffer_frag::getSource() }; + static const std::string FRAGMENT_SHADER { gpu::Shader::getFragmentShaderSource(shader::render_utils::fragment::debug_deferred_buffer).getCode() }; static const std::string SOURCE_PLACEHOLDER { "//SOURCE_PLACEHOLDER" }; static const auto SOURCE_PLACEHOLDER_INDEX = FRAGMENT_SHADER.find(SOURCE_PLACEHOLDER); Q_ASSERT_X(SOURCE_PLACEHOLDER_INDEX != std::string::npos, Q_FUNC_INFO, @@ -388,7 +386,7 @@ const gpu::PipelinePointer& DebugDeferredBuffer::getPipeline(Mode mode, std::str bakedFragmentShader.replace(SOURCE_PLACEHOLDER_INDEX, SOURCE_PLACEHOLDER.size(), getShaderSourceCode(mode, customFile)); - const auto vs = debug_deferred_buffer_vert::getShader(); + const auto vs = gpu::Shader::createVertex(shader::render_utils::vertex::debug_deferred_buffer); const auto ps = gpu::Shader::createPixel(bakedFragmentShader); const auto program = gpu::Shader::createProgram(vs, ps); diff --git a/libraries/render-utils/src/DeferredLightingEffect.cpp b/libraries/render-utils/src/DeferredLightingEffect.cpp index 62d8dffe3a..0d077b19d8 100644 --- a/libraries/render-utils/src/DeferredLightingEffect.cpp +++ b/libraries/render-utils/src/DeferredLightingEffect.cpp @@ -17,9 +17,9 @@ #include #include #include - #include #include +#include #include "StencilMaskPass.h" #include "AbstractViewStateInterface.h" @@ -27,20 +27,6 @@ #include "TextureCache.h" #include "FramebufferCache.h" -#include "deferred_light_vert.h" -#include "deferred_light_point_vert.h" -#include "deferred_light_spot_vert.h" - -#include "directional_ambient_light_frag.h" -#include "directional_skybox_light_frag.h" - -#include "directional_ambient_light_shadow_frag.h" -#include "directional_skybox_light_shadow_frag.h" - -#include "local_lights_shading_frag.h" -#include "local_lights_drawOutline_frag.h" - - using namespace render; struct LightLocations { @@ -85,7 +71,7 @@ enum DeferredShader_BufferSlot { LIGHT_CLUSTER_GRID_CLUSTER_CONTENT_SLOT, }; -static void loadLightProgram(const gpu::ShaderPointer& vertShader, const gpu::ShaderPointer& fragShader, bool lightVolume, gpu::PipelinePointer& program, LightLocationsPtr& locations); +static void loadLightProgram(int programId, bool lightVolume, gpu::PipelinePointer& program, LightLocationsPtr& locations); void DeferredLightingEffect::init() { _directionalAmbientSphereLightLocations = std::make_shared(); @@ -97,14 +83,14 @@ void DeferredLightingEffect::init() { _localLightLocations = std::make_shared(); _localLightOutlineLocations = std::make_shared(); - loadLightProgram(deferred_light_vert::getShader(), directional_ambient_light_frag::getShader(), false, _directionalAmbientSphereLight, _directionalAmbientSphereLightLocations); - loadLightProgram(deferred_light_vert::getShader(), directional_skybox_light_frag::getShader(), false, _directionalSkyboxLight, _directionalSkyboxLightLocations); + loadLightProgram(shader::render_utils::program::directional_ambient_light, false, _directionalAmbientSphereLight, _directionalAmbientSphereLightLocations); + loadLightProgram(shader::render_utils::program::directional_skybox_light, false, _directionalSkyboxLight, _directionalSkyboxLightLocations); - loadLightProgram(deferred_light_vert::getShader(), directional_ambient_light_shadow_frag::getShader(), false, _directionalAmbientSphereLightShadow, _directionalAmbientSphereLightShadowLocations); - loadLightProgram(deferred_light_vert::getShader(), directional_skybox_light_shadow_frag::getShader(), false, _directionalSkyboxLightShadow, _directionalSkyboxLightShadowLocations); + loadLightProgram(shader::render_utils::program::directional_ambient_light_shadow, false, _directionalAmbientSphereLightShadow, _directionalAmbientSphereLightShadowLocations); + loadLightProgram(shader::render_utils::program::directional_skybox_light_shadow, false, _directionalSkyboxLightShadow, _directionalSkyboxLightShadowLocations); - loadLightProgram(deferred_light_vert::getShader(), local_lights_shading_frag::getShader(), true, _localLight, _localLightLocations); - loadLightProgram(deferred_light_vert::getShader(), local_lights_drawOutline_frag::getShader(), true, _localLightOutline, _localLightOutlineLocations); + loadLightProgram(shader::render_utils::program::local_lights_shading, true, _localLight, _localLightLocations); + loadLightProgram(shader::render_utils::program::local_lights_drawOutline, true, _localLightOutline, _localLightOutlineLocations); } void DeferredLightingEffect::setupKeyLightBatch(const RenderArgs* args, gpu::Batch& batch, int lightBufferUnit, int ambientBufferUnit, int skyboxCubemapUnit) { @@ -176,8 +162,8 @@ void DeferredLightingEffect::unsetLocalLightsBatch(gpu::Batch& batch, int lightA } } -static gpu::ShaderPointer makeLightProgram(const gpu::ShaderPointer& vertShader, const gpu::ShaderPointer& fragShader, LightLocationsPtr& locations) { - gpu::ShaderPointer program = gpu::Shader::createProgram(vertShader, fragShader); +static gpu::ShaderPointer makeLightProgram(int programId, LightLocationsPtr& locations) { + gpu::ShaderPointer program = gpu::Shader::createProgram(programId); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("colorMap"), DEFERRED_BUFFER_COLOR_UNIT)); slotBindings.insert(gpu::Shader::Binding(std::string("normalMap"), DEFERRED_BUFFER_NORMAL_UNIT)); @@ -226,9 +212,9 @@ static gpu::ShaderPointer makeLightProgram(const gpu::ShaderPointer& vertShader, return program; } -static void loadLightProgram(const gpu::ShaderPointer& vertShader, const gpu::ShaderPointer& fragShader, bool lightVolume, gpu::PipelinePointer& pipeline, LightLocationsPtr& locations) { +static void loadLightProgram(int programId, bool lightVolume, gpu::PipelinePointer& pipeline, LightLocationsPtr& locations) { - gpu::ShaderPointer program = makeLightProgram(vertShader, fragShader, locations); + gpu::ShaderPointer program = makeLightProgram(programId, locations); auto state = std::make_shared(); state->setColorWriteMask(true, true, true, false); diff --git a/libraries/render-utils/src/DrawHaze.cpp b/libraries/render-utils/src/DrawHaze.cpp index 94bac4e3ac..587f997887 100644 --- a/libraries/render-utils/src/DrawHaze.cpp +++ b/libraries/render-utils/src/DrawHaze.cpp @@ -12,15 +12,13 @@ #include "DrawHaze.h" #include -#include +#include #include "StencilMaskPass.h" #include "FramebufferCache.h" #include "HazeStage.h" #include "LightStage.h" -#include "Haze_frag.h" - void HazeConfig::setHazeColor(const glm::vec3 value) { hazeColor = value; } @@ -132,10 +130,7 @@ void DrawHaze::run(const render::RenderContextPointer& renderContext, const Inpu RenderArgs* args = renderContext->args; if (!_hazePipeline) { - gpu::ShaderPointer ps = Haze_frag::getShader(); - gpu::ShaderPointer vs = gpu::StandardShaderLib::getDrawViewportQuadTransformTexcoordVS(); - - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::haze); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setBlendFunction(true, diff --git a/libraries/render-utils/src/GeometryCache.cpp b/libraries/render-utils/src/GeometryCache.cpp index f8f49921a3..60ac75619e 100644 --- a/libraries/render-utils/src/GeometryCache.cpp +++ b/libraries/render-utils/src/GeometryCache.cpp @@ -23,36 +23,17 @@ #include #include +#include +#include +#include +#include #include "TextureCache.h" #include "RenderUtilsLogging.h" #include "StencilMaskPass.h" #include "FadeEffect.h" -#include "gpu/StandardShaderLib.h" -#include "graphics/TextureMap.h" -#include "graphics/BufferViewHelpers.h" -#include "render/Args.h" - -#include "standardTransformPNTC_vert.h" -#include "standardDrawTexture_frag.h" - -#include "simple_vert.h" -#include "simple_textured_frag.h" -#include "simple_transparent_textured_frag.h" -#include "simple_textured_unlit_frag.h" -#include "simple_fade_vert.h" -#include "simple_textured_fade_frag.h" -#include "simple_textured_unlit_fade_frag.h" -#include "simple_opaque_web_browser_frag.h" -#include "simple_transparent_web_browser_frag.h" -#include "glowLine_vert.h" -#include "glowLine_frag.h" - -#include "forward_simple_textured_frag.h" -#include "forward_simple_textured_transparent_frag.h" -#include "forward_simple_textured_unlit_frag.h" #include "DeferredLightingEffect.h" @@ -63,8 +44,6 @@ static const QString RENDER_FORWARD{ "HIFI_RENDER_FORWARD" }; static bool DISABLE_DEFERRED = QProcessEnvironment::systemEnvironment().contains(RENDER_FORWARD); #endif -#include "grid_frag.h" - //#define WANT_DEBUG // @note: Originally size entity::NUM_SHAPES @@ -2052,9 +2031,7 @@ void GeometryCache::renderGlowLine(gpu::Batch& batch, const glm::vec3& p1, const static std::once_flag once; std::call_once(once, [&] { auto state = std::make_shared(); - auto VS = glowLine_vert::getShader(); - auto PS = glowLine_frag::getShader(); - auto program = gpu::Shader::createProgram(VS, PS); + auto program = gpu::Shader::createProgram(shader::render_utils::program::glowLine); state->setCullMode(gpu::State::CULL_NONE); state->setDepthTest(true, false, gpu::LESS_EQUAL); state->setBlendFunction(true, @@ -2109,9 +2086,7 @@ void GeometryCache::renderGlowLine(gpu::Batch& batch, const glm::vec3& p1, const void GeometryCache::useSimpleDrawPipeline(gpu::Batch& batch, bool noBlend) { static std::once_flag once; std::call_once(once, [&]() { - auto vs = standardTransformPNTC_vert::getShader(); - auto ps = standardDrawTexture_frag::getShader(); - auto program = gpu::Shader::createProgram(vs, ps); + auto program = gpu::Shader::createProgram(shader::render_utils::program::standardDrawTexture); auto state = std::make_shared(); @@ -2125,8 +2100,8 @@ void GeometryCache::useSimpleDrawPipeline(gpu::Batch& batch, bool noBlend) { auto stateNoBlend = std::make_shared(); PrepareStencil::testMaskDrawShape(*stateNoBlend); - auto noBlendPS = gpu::StandardShaderLib::getDrawTextureOpaquePS(); - auto programNoBlend = gpu::Shader::createProgram(vs, noBlendPS); + auto noBlendPS = gpu::Shader::createVertex(shader::gpu::fragment::DrawTextureOpaque); + auto programNoBlend = gpu::Shader::createProgram(shader::render_utils::program::standardDrawTextureNoBlend); _standardDrawPipelineNoBlend = gpu::Pipeline::create(programNoBlend, stateNoBlend); @@ -2145,9 +2120,7 @@ void GeometryCache::useSimpleDrawPipeline(gpu::Batch& batch, bool noBlend) { void GeometryCache::useGridPipeline(gpu::Batch& batch, GridBuffer gridBuffer, bool isLayered) { if (!_gridPipeline) { - auto vs = standardTransformPNTC_vert::getShader(); - auto ps = grid_frag::getShader(); - auto program = gpu::Shader::createProgram(vs, ps); + auto program = gpu::Shader::createProgram(shader::render_utils::program::grid); gpu::Shader::makeProgram((*program)); _gridSlot = program->getUniformBuffers().findLocation("gridBuffer"); @@ -2229,9 +2202,9 @@ inline bool operator==(const SimpleProgramKey& a, const SimpleProgramKey& b) { return a.getRaw() == b.getRaw(); } -static void buildWebShader(const gpu::ShaderPointer& vertShader, const gpu::ShaderPointer& fragShader, bool blendEnable, +static void buildWebShader(int programId, bool blendEnable, gpu::ShaderPointer& shaderPointerOut, gpu::PipelinePointer& pipelinePointerOut) { - shaderPointerOut = gpu::Shader::createProgram(vertShader, fragShader); + shaderPointerOut = gpu::Shader::createProgram(programId); gpu::Shader::BindingSet slotBindings; gpu::Shader::makeProgram(*shaderPointerOut, slotBindings); @@ -2254,8 +2227,8 @@ void GeometryCache::bindWebBrowserProgram(gpu::Batch& batch, bool transparent) { gpu::PipelinePointer GeometryCache::getWebBrowserProgram(bool transparent) { static std::once_flag once; std::call_once(once, [&]() { - buildWebShader(simple_vert::getShader(), simple_opaque_web_browser_frag::getShader(), false, _simpleOpaqueWebBrowserShader, _simpleOpaqueWebBrowserPipeline); - buildWebShader(simple_vert::getShader(), simple_transparent_web_browser_frag::getShader(), true, _simpleTransparentWebBrowserShader, _simpleTransparentWebBrowserPipeline); + buildWebShader(shader::render_utils::program::simple_opaque_web_browser, false, _simpleOpaqueWebBrowserShader, _simpleOpaqueWebBrowserPipeline); + buildWebShader(shader::render_utils::program::simple_transparent_web_browser, true, _simpleTransparentWebBrowserShader, _simpleTransparentWebBrowserPipeline); }); return transparent ? _simpleTransparentWebBrowserPipeline : _simpleOpaqueWebBrowserPipeline; @@ -2284,15 +2257,15 @@ gpu::PipelinePointer GeometryCache::getSimplePipeline(bool textured, bool transp if (!fading) { static std::once_flag once; std::call_once(once, [&]() { - auto VS = simple_vert::getShader(); - auto PS = DISABLE_DEFERRED ? forward_simple_textured_frag::getShader() : simple_textured_frag::getShader(); + using namespace shader::render_utils::program; + auto PS = DISABLE_DEFERRED ? forward_simple_textured : simple_textured; // Use the forward pipeline for both here, otherwise transparents will be unlit - auto PSTransparent = DISABLE_DEFERRED ? forward_simple_textured_transparent_frag::getShader() : forward_simple_textured_transparent_frag::getShader(); - auto PSUnlit = DISABLE_DEFERRED ? forward_simple_textured_unlit_frag::getShader() : simple_textured_unlit_frag::getShader(); + auto PSTransparent = DISABLE_DEFERRED ? forward_simple_textured_transparent : forward_simple_textured_transparent; + auto PSUnlit = DISABLE_DEFERRED ? forward_simple_textured_unlit : simple_textured_unlit; - _simpleShader = gpu::Shader::createProgram(VS, PS); - _transparentShader = gpu::Shader::createProgram(VS, PSTransparent); - _unlitShader = gpu::Shader::createProgram(VS, PSUnlit); + _simpleShader = gpu::Shader::createProgram(PS); + _transparentShader = gpu::Shader::createProgram(PSTransparent); + _unlitShader = gpu::Shader::createProgram(PSUnlit); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("originalTexture"), render::ShapePipeline::Slot::MAP::ALBEDO)); @@ -2307,12 +2280,9 @@ gpu::PipelinePointer GeometryCache::getSimplePipeline(bool textured, bool transp } else { static std::once_flag once; std::call_once(once, [&]() { - auto VS = simple_fade_vert::getShader(); - auto PS = DISABLE_DEFERRED ? forward_simple_textured_frag::getShader() : simple_textured_fade_frag::getShader(); - auto PSUnlit = DISABLE_DEFERRED ? forward_simple_textured_unlit_frag::getShader() : simple_textured_unlit_fade_frag::getShader(); - - _simpleFadeShader = gpu::Shader::createProgram(VS, PS); - _unlitFadeShader = gpu::Shader::createProgram(VS, PSUnlit); + using namespace shader::render_utils::program; + _simpleFadeShader = gpu::Shader::createProgram(DISABLE_DEFERRED ? forward_simple_textured : simple_textured_fade); + _unlitFadeShader = gpu::Shader::createProgram(DISABLE_DEFERRED ? forward_simple_textured_unlit : simple_textured_unlit_fade); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("originalTexture"), render::ShapePipeline::Slot::MAP::ALBEDO)); diff --git a/libraries/render-utils/src/HighlightEffect.cpp b/libraries/render-utils/src/HighlightEffect.cpp index 6c8a90da81..a07d24c106 100644 --- a/libraries/render-utils/src/HighlightEffect.cpp +++ b/libraries/render-utils/src/HighlightEffect.cpp @@ -10,25 +10,19 @@ // #include "HighlightEffect.h" -#include "GeometryCache.h" - -#include "CubeProjectedPolygon.h" +#include #include #include -#include "gpu/Context.h" -#include "gpu/StandardShaderLib.h" +#include +#include + +#include "GeometryCache.h" +#include "CubeProjectedPolygon.h" + -#include -#include "surfaceGeometry_copyDepth_frag.h" -#include "debug_deferred_buffer_vert.h" -#include "debug_deferred_buffer_frag.h" -#include "Highlight_frag.h" -#include "Highlight_filled_frag.h" -#include "Highlight_aabox_vert.h" -#include "nop_frag.h" using namespace render; @@ -133,9 +127,7 @@ void DrawHighlightMask::run(const render::RenderContextPointer& renderContext, c fillState->setColorWriteMask(false, false, false, false); fillState->setCullMode(gpu::State::CULL_FRONT); - auto vs = Highlight_aabox_vert::getShader(); - auto ps = nop_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::highlight_aabox); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("ssbo0Buffer"), BOUNDS_SLOT)); @@ -327,9 +319,7 @@ const gpu::PipelinePointer& DrawHighlight::getPipeline(const render::HighlightSt state->setBlendFunction(true, gpu::State::SRC_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::INV_SRC_ALPHA); state->setStencilTest(true, 0, gpu::State::StencilTest(OUTLINE_STENCIL_MASK, 0xFF, gpu::EQUAL)); - auto vs = gpu::StandardShaderLib::getDrawViewportQuadTransformTexcoordVS(); - auto ps = Highlight_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::highlight); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding("highlightParamsBuffer", HIGHLIGHT_PARAMS_SLOT)); @@ -340,8 +330,7 @@ const gpu::PipelinePointer& DrawHighlight::getPipeline(const render::HighlightSt _pipeline = gpu::Pipeline::create(program, state); - ps = Highlight_filled_frag::getShader(); - program = gpu::Shader::createProgram(vs, ps); + program = gpu::Shader::createProgram(shader::render_utils::program::highlight_filled); gpu::Shader::makeProgram(*program, slotBindings); _pipelineFilled = gpu::Pipeline::create(program, state); } @@ -406,7 +395,7 @@ void DebugHighlight::run(const render::RenderContextPointer& renderContext, cons } void DebugHighlight::initializePipelines() { - static const std::string FRAGMENT_SHADER{ debug_deferred_buffer_frag::getSource() }; + static const std::string FRAGMENT_SHADER{ gpu::Shader::getFragmentShaderSource(shader::render_utils::fragment::debug_deferred_buffer).getCode() }; static const std::string SOURCE_PLACEHOLDER{ "//SOURCE_PLACEHOLDER" }; static const auto SOURCE_PLACEHOLDER_INDEX = FRAGMENT_SHADER.find(SOURCE_PLACEHOLDER); Q_ASSERT_X(SOURCE_PLACEHOLDER_INDEX != std::string::npos, Q_FUNC_INFO, @@ -416,17 +405,17 @@ void DebugHighlight::initializePipelines() { state->setDepthTest(gpu::State::DepthTest(false, false)); state->setStencilTest(true, 0, gpu::State::StencilTest(OUTLINE_STENCIL_MASK, 0xFF, gpu::EQUAL)); - const auto vs = debug_deferred_buffer_vert::getShader(); + const auto vs = gpu::Shader::createVertex(shader::render_utils::vertex::debug_deferred_buffer); // Depth shader { - static const std::string DEPTH_SHADER{ - "vec4 getFragmentColor() {" - " float Zdb = texelFetch(depthMap, ivec2(gl_FragCoord.xy), 0).x;" - " Zdb = 1.0-(1.0-Zdb)*100;" - " return vec4(Zdb, Zdb, Zdb, 1.0); " - "}" - }; + static const std::string DEPTH_SHADER{ R"SHADER( + vec4 getFragmentColor() { + float Zdb = texelFetch(depthMap, ivec2(gl_FragCoord.xy), 0).x; + Zdb = 1.0-(1.0-Zdb)*100; + return vec4(Zdb, Zdb, Zdb, 1.0); + } + )SHADER" }; auto fragmentShader = FRAGMENT_SHADER; fragmentShader.replace(SOURCE_PLACEHOLDER_INDEX, SOURCE_PLACEHOLDER.size(), DEPTH_SHADER); @@ -572,21 +561,13 @@ const render::Varying DrawHighlightTask::addSelectItemJobs(JobModel& task, const return task.addJob("TransparentSelection", selectItemInput); } -#include "model_shadow_vert.h" -#include "skin_model_shadow_vert.h" - -#include "model_shadow_frag.h" - void DrawHighlightTask::initMaskPipelines(render::ShapePlumber& shapePlumber, gpu::StatePointer state) { - auto modelVertex = model_shadow_vert::getShader(); - auto modelPixel = model_shadow_frag::getShader(); - gpu::ShaderPointer modelProgram = gpu::Shader::createProgram(modelVertex, modelPixel); + gpu::ShaderPointer modelProgram = gpu::Shader::createProgram(shader::render_utils::program::model_shadow); shapePlumber.addPipeline( ShapeKey::Filter::Builder().withoutSkinned(), modelProgram, state); - auto skinVertex = skin_model_shadow_vert::getShader(); - gpu::ShaderPointer skinProgram = gpu::Shader::createProgram(skinVertex, modelPixel); + gpu::ShaderPointer skinProgram = gpu::Shader::createProgram(shader::render_utils::program::skin_model_shadow); shapePlumber.addPipeline( ShapeKey::Filter::Builder().withSkinned(), skinProgram, state); diff --git a/libraries/render-utils/src/LightClusters.cpp b/libraries/render-utils/src/LightClusters.cpp index fdd9ea461f..87698cab44 100644 --- a/libraries/render-utils/src/LightClusters.cpp +++ b/libraries/render-utils/src/LightClusters.cpp @@ -9,24 +9,13 @@ // #include "LightClusters.h" -#include "RenderUtilsLogging.h" - #include +#include -#include - +#include "RenderUtilsLogging.h" #include "StencilMaskPass.h" -#include "lightClusters_drawGrid_vert.h" -#include "lightClusters_drawGrid_frag.h" - -//#include "lightClusters_drawClusterFromDepth_vert.h" -#include "lightClusters_drawClusterFromDepth_frag.h" - - -#include "lightClusters_drawClusterContent_vert.h" -#include "lightClusters_drawClusterContent_frag.h" enum LightClusterGridShader_MapSlot { DEFERRED_BUFFER_LINEAR_DEPTH_UNIT = 0, @@ -605,9 +594,7 @@ void DebugLightClusters::configure(const Config& config) { const gpu::PipelinePointer DebugLightClusters::getDrawClusterGridPipeline() { if (!_drawClusterGrid) { - auto vs = lightClusters_drawGrid_vert::getShader(); - auto ps = lightClusters_drawGrid_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::lightClusters_drawGrid); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("frustumGridBuffer"), LIGHT_CLUSTER_GRID_FRUSTUM_GRID_SLOT)); @@ -633,10 +620,7 @@ const gpu::PipelinePointer DebugLightClusters::getDrawClusterGridPipeline() { const gpu::PipelinePointer DebugLightClusters::getDrawClusterFromDepthPipeline() { if (!_drawClusterFromDepth) { - // auto vs = gpu::Shader::createVertex(std::string(lightClusters_drawGrid_vert)); - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = lightClusters_drawClusterFromDepth_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::lightClusters_drawClusterFromDepth); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("frustumGridBuffer"), LIGHT_CLUSTER_GRID_FRUSTUM_GRID_SLOT)); @@ -663,11 +647,7 @@ const gpu::PipelinePointer DebugLightClusters::getDrawClusterFromDepthPipeline() const gpu::PipelinePointer DebugLightClusters::getDrawClusterContentPipeline() { if (!_drawClusterContent) { - // auto vs = gpu::Shader::createVertex(std::string(lightClusters_drawClusterContent_vert)); - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = lightClusters_drawClusterContent_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::lightClusters_drawClusterContent); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("lightBuffer"), LIGHT_GPU_SLOT)); diff --git a/libraries/render-utils/src/RenderForwardTask.cpp b/libraries/render-utils/src/RenderForwardTask.cpp index d2933627f4..c6cc97f0b6 100755 --- a/libraries/render-utils/src/RenderForwardTask.cpp +++ b/libraries/render-utils/src/RenderForwardTask.cpp @@ -17,7 +17,6 @@ #include #include #include -#include #include @@ -34,8 +33,6 @@ #include "RenderCommonTask.h" #include "LightStage.h" -#include "nop_frag.h" - using namespace render; extern void initForwardPipelines(ShapePlumber& plumber); diff --git a/libraries/render-utils/src/RenderPipelines.cpp b/libraries/render-utils/src/RenderPipelines.cpp index 6a653bb192..f44325d353 100644 --- a/libraries/render-utils/src/RenderPipelines.cpp +++ b/libraries/render-utils/src/RenderPipelines.cpp @@ -15,89 +15,13 @@ #include #include -#include #include +#include +#include #include "StencilMaskPass.h" #include "DeferredLightingEffect.h" #include "TextureCache.h" -#include "render/DrawTask.h" - -#include "model_vert.h" -#include "model_normal_map_vert.h" -#include "model_lightmap_vert.h" -#include "model_lightmap_normal_map_vert.h" -#include "skin_model_vert.h" -#include "skin_model_normal_map_vert.h" -#include "skin_model_dq_vert.h" -#include "skin_model_normal_map_dq_vert.h" - -#include "model_lightmap_fade_vert.h" -#include "model_lightmap_normal_map_fade_vert.h" -#include "model_translucent_vert.h" -#include "model_translucent_normal_map_vert.h" -#include "skin_model_fade_vert.h" -#include "skin_model_normal_map_fade_vert.h" -#include "skin_model_fade_dq_vert.h" -#include "skin_model_normal_map_fade_dq_vert.h" - -#include "simple_vert.h" -#include "simple_textured_frag.h" -#include "simple_textured_unlit_frag.h" -#include "simple_transparent_textured_frag.h" -#include "simple_transparent_textured_unlit_frag.h" - -#include "simple_fade_vert.h" -#include "simple_textured_fade_frag.h" -#include "simple_textured_unlit_fade_frag.h" -#include "simple_transparent_textured_fade_frag.h" -#include "simple_transparent_textured_unlit_fade_frag.h" - -#include "model_frag.h" -#include "model_unlit_frag.h" -#include "model_normal_map_frag.h" -#include "model_fade_vert.h" -#include "model_normal_map_fade_vert.h" - -#include "model_fade_frag.h" -#include "model_unlit_fade_frag.h" -#include "model_normal_map_fade_frag.h" - -#include "forward_model_frag.h" -#include "forward_model_unlit_frag.h" -#include "forward_model_normal_map_frag.h" -#include "forward_model_translucent_frag.h" - -#include "model_lightmap_frag.h" -#include "model_lightmap_normal_map_frag.h" -#include "model_translucent_frag.h" -#include "model_translucent_unlit_frag.h" -#include "model_translucent_normal_map_frag.h" - -#include "model_lightmap_fade_frag.h" -#include "model_lightmap_normal_map_fade_frag.h" -#include "model_translucent_fade_frag.h" -#include "model_translucent_unlit_fade_frag.h" -#include "model_translucent_normal_map_fade_frag.h" - -#include "model_shadow_vert.h" -#include "skin_model_shadow_vert.h" -#include "skin_model_shadow_dq_vert.h" -#include "skin_model_shadow_fade_dq_vert.h" - -#include "model_shadow_frag.h" -#include "skin_model_shadow_frag.h" - -#include "model_shadow_fade_vert.h" -#include "skin_model_shadow_fade_vert.h" - -#include "model_shadow_fade_frag.h" -#include "skin_model_shadow_fade_frag.h" - -#include "simple_vert.h" -#include "forward_simple_textured_frag.h" -#include "forward_simple_textured_transparent_frag.h" -#include "forward_simple_textured_unlit_frag.h" using namespace render; using namespace std::placeholders; @@ -107,7 +31,7 @@ void initForwardPipelines(ShapePlumber& plumber); void initZPassPipelines(ShapePlumber& plumber, gpu::StatePointer state); void addPlumberPipeline(ShapePlumber& plumber, - const ShapeKey& key, const gpu::ShaderPointer& vertex, const gpu::ShaderPointer& pixel, + const ShapeKey& key, int programId, const render::ShapePipeline::BatchSetter& batchSetter, const render::ShapePipeline::ItemSetter& itemSetter); void batchSetter(const ShapePipeline& pipeline, gpu::Batch& batch, RenderArgs* args); @@ -115,326 +39,239 @@ void lightBatchSetter(const ShapePipeline& pipeline, gpu::Batch& batch, RenderAr static bool forceLightBatchSetter{ false }; void initDeferredPipelines(render::ShapePlumber& plumber, const render::ShapePipeline::BatchSetter& batchSetter, const render::ShapePipeline::ItemSetter& itemSetter) { - // Vertex shaders - auto simpleVertex = simple_vert::getShader(); - auto modelVertex = model_vert::getShader(); - auto modelNormalMapVertex = model_normal_map_vert::getShader(); - auto modelLightmapVertex = model_lightmap_vert::getShader(); - auto modelLightmapNormalMapVertex = model_lightmap_normal_map_vert::getShader(); - auto modelTranslucentVertex = model_translucent_vert::getShader(); - auto modelTranslucentNormalMapVertex = model_translucent_normal_map_vert::getShader(); - auto modelShadowVertex = model_shadow_vert::getShader(); - - auto modelLightmapFadeVertex = model_lightmap_fade_vert::getShader(); - auto modelLightmapNormalMapFadeVertex = model_lightmap_normal_map_fade_vert::getShader(); - - // matrix palette skinned - auto skinModelVertex = skin_model_vert::getShader(); - auto skinModelNormalMapVertex = skin_model_normal_map_vert::getShader(); - auto skinModelShadowVertex = skin_model_shadow_vert::getShader(); - auto skinModelFadeVertex = skin_model_fade_vert::getShader(); - auto skinModelNormalMapFadeVertex = skin_model_normal_map_fade_vert::getShader(); - auto skinModelTranslucentVertex = skinModelFadeVertex; // We use the same because it ouputs world position per vertex - auto skinModelNormalMapTranslucentVertex = skinModelNormalMapFadeVertex; // We use the same because it ouputs world position per vertex - - // dual quaternion skinned - auto skinModelDualQuatVertex = skin_model_dq_vert::getShader(); - auto skinModelNormalMapDualQuatVertex = skin_model_normal_map_dq_vert::getShader(); - auto skinModelShadowDualQuatVertex = skin_model_shadow_dq_vert::getShader(); - auto skinModelShadowFadeDualQuatVertex = skin_model_shadow_fade_dq_vert::getShader(); - auto skinModelFadeDualQuatVertex = skin_model_fade_dq_vert::getShader(); - auto skinModelNormalMapFadeDualQuatVertex = skin_model_normal_map_fade_dq_vert::getShader(); - auto skinModelTranslucentDualQuatVertex = skinModelFadeDualQuatVertex; // We use the same because it ouputs world position per vertex - auto skinModelNormalMapTranslucentDualQuatVertex = skinModelNormalMapFadeDualQuatVertex; // We use the same because it ouputs world position per vertex - - auto modelFadeVertex = model_fade_vert::getShader(); - auto modelNormalMapFadeVertex = model_normal_map_fade_vert::getShader(); - auto simpleFadeVertex = simple_fade_vert::getShader(); - auto modelShadowFadeVertex = model_shadow_fade_vert::getShader(); - auto skinModelShadowFadeVertex = skin_model_shadow_fade_vert::getShader(); - - // Pixel shaders - auto simplePixel = simple_textured_frag::getShader(); - auto simpleUnlitPixel = simple_textured_unlit_frag::getShader(); - auto simpleTranslucentPixel = simple_transparent_textured_frag::getShader(); - auto simpleTranslucentUnlitPixel = simple_transparent_textured_unlit_frag::getShader(); - auto modelPixel = model_frag::getShader(); - auto modelUnlitPixel = model_unlit_frag::getShader(); - auto modelNormalMapPixel = model_normal_map_frag::getShader(); - auto modelTranslucentPixel = model_translucent_frag::getShader(); - auto modelTranslucentUnlitPixel = model_translucent_unlit_frag::getShader(); - auto modelTranslucentNormalMapPixel = model_translucent_normal_map_frag::getShader(); - auto modelShadowPixel = model_shadow_frag::getShader(); - auto modelLightmapPixel = model_lightmap_frag::getShader(); - auto modelLightmapNormalMapPixel = model_lightmap_normal_map_frag::getShader(); - auto modelLightmapFadePixel = model_lightmap_fade_frag::getShader(); - auto modelLightmapNormalMapFadePixel = model_lightmap_normal_map_fade_frag::getShader(); - - auto modelFadePixel = model_fade_frag::getShader(); - auto modelUnlitFadePixel = model_unlit_fade_frag::getShader(); - auto modelNormalMapFadePixel = model_normal_map_fade_frag::getShader(); - auto modelShadowFadePixel = model_shadow_fade_frag::getShader(); - auto modelTranslucentFadePixel = model_translucent_fade_frag::getShader(); - auto modelTranslucentUnlitFadePixel = model_translucent_unlit_fade_frag::getShader(); - auto modelTranslucentNormalMapFadePixel = model_translucent_normal_map_fade_frag::getShader(); - auto simpleFadePixel = simple_textured_fade_frag::getShader(); - auto simpleUnlitFadePixel = simple_textured_unlit_fade_frag::getShader(); - auto simpleTranslucentFadePixel = simple_transparent_textured_fade_frag::getShader(); - auto simpleTranslucentUnlitFadePixel = simple_transparent_textured_unlit_fade_frag::getShader(); - + using namespace shader::render_utils::program; using Key = render::ShapeKey; - auto addPipeline = std::bind(&addPlumberPipeline, std::ref(plumber), _1, _2, _3, _4, _5); + auto addPipeline = std::bind(&addPlumberPipeline, std::ref(plumber), _1, _2, _3, _4); // TODO: Refactor this to use a filter // Opaques addPipeline( Key::Builder().withMaterial(), - modelVertex, modelPixel, nullptr, nullptr); + model, nullptr, nullptr); addPipeline( Key::Builder(), - simpleVertex, simplePixel, nullptr, nullptr); + simple_textured, nullptr, nullptr); addPipeline( Key::Builder().withMaterial().withUnlit(), - modelVertex, modelUnlitPixel, nullptr, nullptr); + model_unlit, nullptr, nullptr); addPipeline( Key::Builder().withUnlit(), - simpleVertex, simpleUnlitPixel, nullptr, nullptr); + simple_textured_unlit, nullptr, nullptr); addPipeline( Key::Builder().withMaterial().withTangents(), - modelNormalMapVertex, modelNormalMapPixel, nullptr, nullptr); + model_normal_map, nullptr, nullptr); // Same thing but with Fade on addPipeline( Key::Builder().withMaterial().withFade(), - modelFadeVertex, modelFadePixel, batchSetter, itemSetter); + model_fade, batchSetter, itemSetter); addPipeline( Key::Builder().withFade(), - simpleFadeVertex, simpleFadePixel, batchSetter, itemSetter); + simple_textured_fade, batchSetter, itemSetter); addPipeline( Key::Builder().withMaterial().withUnlit().withFade(), - modelFadeVertex, modelUnlitFadePixel, batchSetter, itemSetter); + model_unlit_fade, batchSetter, itemSetter); addPipeline( Key::Builder().withUnlit().withFade(), - simpleFadeVertex, simpleUnlitFadePixel, batchSetter, itemSetter); + simple_textured_unlit_fade, batchSetter, itemSetter); addPipeline( Key::Builder().withMaterial().withTangents().withFade(), - modelNormalMapFadeVertex, modelNormalMapFadePixel, batchSetter, itemSetter); + model_normal_map_fade, batchSetter, itemSetter); // Translucents addPipeline( Key::Builder().withMaterial().withTranslucent(), - modelTranslucentVertex, modelTranslucentPixel, nullptr, nullptr); + model_translucent, nullptr, nullptr); addPipeline( Key::Builder().withTranslucent(), - simpleVertex, simpleTranslucentPixel, nullptr, nullptr); + simple_transparent_textured, nullptr, nullptr); addPipeline( Key::Builder().withMaterial().withTranslucent().withUnlit(), - modelVertex, modelTranslucentUnlitPixel, nullptr, nullptr); + model_translucent_unlit, nullptr, nullptr); addPipeline( Key::Builder().withTranslucent().withUnlit(), - simpleVertex, simpleTranslucentUnlitPixel, nullptr, nullptr); + simple_transparent_textured_unlit, nullptr, nullptr); addPipeline( Key::Builder().withMaterial().withTranslucent().withTangents(), - modelTranslucentNormalMapVertex, modelTranslucentNormalMapPixel, nullptr, nullptr); + model_translucent_normal_map, nullptr, nullptr); addPipeline( // FIXME: Ignore lightmap for translucents meshpart Key::Builder().withMaterial().withTranslucent().withLightmap(), - modelTranslucentVertex, modelTranslucentPixel, nullptr, nullptr); + model_translucent, nullptr, nullptr); // Same thing but with Fade on addPipeline( Key::Builder().withMaterial().withTranslucent().withFade(), - modelTranslucentVertex, modelTranslucentFadePixel, batchSetter, itemSetter); + model_translucent_fade, batchSetter, itemSetter); addPipeline( Key::Builder().withTranslucent().withFade(), - simpleFadeVertex, simpleTranslucentFadePixel, batchSetter, itemSetter); + simple_transparent_textured_fade, batchSetter, itemSetter); addPipeline( Key::Builder().withMaterial().withTranslucent().withUnlit().withFade(), - modelFadeVertex, modelTranslucentUnlitFadePixel, batchSetter, itemSetter); + model_translucent_unlit_fade, batchSetter, itemSetter); addPipeline( Key::Builder().withTranslucent().withUnlit().withFade(), - simpleFadeVertex, simpleTranslucentUnlitFadePixel, batchSetter, itemSetter); + simple_transparent_textured_unlit_fade, batchSetter, itemSetter); addPipeline( Key::Builder().withMaterial().withTranslucent().withTangents().withFade(), - modelTranslucentNormalMapVertex, modelTranslucentNormalMapFadePixel, batchSetter, itemSetter); + model_translucent_normal_map_fade, batchSetter, itemSetter); addPipeline( // FIXME: Ignore lightmap for translucents meshpart Key::Builder().withMaterial().withTranslucent().withLightmap().withFade(), - modelFadeVertex, modelTranslucentFadePixel, batchSetter, itemSetter); - + model_translucent_fade, batchSetter, itemSetter); // Lightmapped addPipeline( Key::Builder().withMaterial().withLightmap(), - modelLightmapVertex, modelLightmapPixel, nullptr, nullptr); + model_lightmap, nullptr, nullptr); addPipeline( Key::Builder().withMaterial().withLightmap().withTangents(), - modelLightmapNormalMapVertex, modelLightmapNormalMapPixel, nullptr, nullptr); + model_lightmap_normal_map, nullptr, nullptr); // Same thing but with Fade on addPipeline( Key::Builder().withMaterial().withLightmap().withFade(), - modelLightmapFadeVertex, modelLightmapFadePixel, batchSetter, itemSetter); + model_lightmap_fade, batchSetter, itemSetter); addPipeline( Key::Builder().withMaterial().withLightmap().withTangents().withFade(), - modelLightmapNormalMapFadeVertex, modelLightmapNormalMapFadePixel, batchSetter, itemSetter); + model_lightmap_normal_map_fade, batchSetter, itemSetter); // matrix palette skinned addPipeline( Key::Builder().withMaterial().withSkinned(), - skinModelVertex, modelPixel, nullptr, nullptr); + skin_model, nullptr, nullptr); addPipeline( Key::Builder().withMaterial().withSkinned().withTangents(), - skinModelNormalMapVertex, modelNormalMapPixel, nullptr, nullptr); + skin_model_normal_map, nullptr, nullptr); // Same thing but with Fade on addPipeline( Key::Builder().withMaterial().withSkinned().withFade(), - skinModelFadeVertex, modelFadePixel, batchSetter, itemSetter); + skin_model_fade, batchSetter, itemSetter); addPipeline( Key::Builder().withMaterial().withSkinned().withTangents().withFade(), - skinModelNormalMapFadeVertex, modelNormalMapFadePixel, batchSetter, itemSetter); - + skin_model_normal_map_fade, batchSetter, itemSetter); // matrix palette skinned and translucent addPipeline( Key::Builder().withMaterial().withSkinned().withTranslucent(), - skinModelTranslucentVertex, modelTranslucentPixel, nullptr, nullptr); + skin_model_translucent, nullptr, nullptr); addPipeline( Key::Builder().withMaterial().withSkinned().withTranslucent().withTangents(), - skinModelNormalMapTranslucentVertex, modelTranslucentNormalMapPixel, nullptr, nullptr); + skin_model_normal_map_translucent, nullptr, nullptr); // Same thing but with Fade on addPipeline( Key::Builder().withMaterial().withSkinned().withTranslucent().withFade(), - skinModelFadeVertex, modelTranslucentFadePixel, batchSetter, itemSetter); + skin_model_translucent_fade, batchSetter, itemSetter); addPipeline( Key::Builder().withMaterial().withSkinned().withTranslucent().withTangents().withFade(), - skinModelNormalMapFadeVertex, modelTranslucentNormalMapFadePixel, batchSetter, itemSetter); + skin_model_normal_map_translucent_fade, batchSetter, itemSetter); // dual quaternion skinned addPipeline( Key::Builder().withMaterial().withSkinned().withDualQuatSkinned(), - skinModelDualQuatVertex, modelPixel, nullptr, nullptr); + skin_model_dq, nullptr, nullptr); addPipeline( Key::Builder().withMaterial().withSkinned().withDualQuatSkinned().withTangents(), - skinModelNormalMapDualQuatVertex, modelNormalMapPixel, nullptr, nullptr); + skin_model_normal_map_dq, nullptr, nullptr); // Same thing but with Fade on addPipeline( Key::Builder().withMaterial().withSkinned().withDualQuatSkinned().withFade(), - skinModelFadeDualQuatVertex, modelFadePixel, batchSetter, itemSetter); + skin_model_fade_dq, batchSetter, itemSetter); addPipeline( Key::Builder().withMaterial().withSkinned().withDualQuatSkinned().withTangents().withFade(), - skinModelNormalMapFadeDualQuatVertex, modelNormalMapFadePixel, batchSetter, itemSetter); - + skin_model_normal_map_fade_dq, batchSetter, itemSetter); // dual quaternion skinned and translucent addPipeline( Key::Builder().withMaterial().withSkinned().withDualQuatSkinned().withTranslucent(), - skinModelTranslucentDualQuatVertex, modelTranslucentPixel, nullptr, nullptr); + skin_model_translucent_dq, nullptr, nullptr); addPipeline( Key::Builder().withMaterial().withSkinned().withDualQuatSkinned().withTranslucent().withTangents(), - skinModelNormalMapTranslucentDualQuatVertex, modelTranslucentNormalMapPixel, nullptr, nullptr); + skin_model_normal_map_translucent_dq, nullptr, nullptr); // Same thing but with Fade on addPipeline( Key::Builder().withMaterial().withSkinned().withDualQuatSkinned().withTranslucent().withFade(), - skinModelFadeDualQuatVertex, modelTranslucentFadePixel, batchSetter, itemSetter); + skin_model_translucent_fade_dq, batchSetter, itemSetter); addPipeline( Key::Builder().withMaterial().withSkinned().withDualQuatSkinned().withTranslucent().withTangents().withFade(), - skinModelNormalMapFadeDualQuatVertex, modelTranslucentNormalMapFadePixel, batchSetter, itemSetter); + skin_model_normal_map_translucent_fade_dq, batchSetter, itemSetter); // Depth-only addPipeline( Key::Builder().withDepthOnly(), - modelShadowVertex, modelShadowPixel, nullptr, nullptr); + model_shadow, nullptr, nullptr); addPipeline( Key::Builder().withSkinned().withDepthOnly(), - skinModelShadowVertex, modelShadowPixel, nullptr, nullptr); + skin_model_shadow, nullptr, nullptr); // Same thing but with Fade on addPipeline( Key::Builder().withDepthOnly().withFade(), - modelShadowFadeVertex, modelShadowFadePixel, batchSetter, itemSetter); + model_shadow_fade, batchSetter, itemSetter); addPipeline( Key::Builder().withSkinned().withDepthOnly().withFade(), - skinModelShadowFadeVertex, modelShadowFadePixel, batchSetter, itemSetter); + skin_model_shadow_fade, batchSetter, itemSetter); // Now repeat for dual quaternion // Depth-only addPipeline( Key::Builder().withSkinned().withDualQuatSkinned().withDepthOnly(), - skinModelShadowDualQuatVertex, modelShadowPixel, nullptr, nullptr); + skin_model_shadow_dq, nullptr, nullptr); // Same thing but with Fade on addPipeline( Key::Builder().withSkinned().withDualQuatSkinned().withDepthOnly().withFade(), - skinModelShadowFadeDualQuatVertex, modelShadowFadePixel, batchSetter, itemSetter); + skin_model_shadow_fade_dq, batchSetter, itemSetter); } void initForwardPipelines(ShapePlumber& plumber) { - // Vertex shaders - auto simpleVertex = simple_vert::getShader(); - auto modelVertex = model_vert::getShader(); - auto modelNormalMapVertex = model_normal_map_vert::getShader(); - auto skinModelVertex = skin_model_vert::getShader(); - auto skinModelNormalMapVertex = skin_model_normal_map_vert::getShader(); - - auto skinModelDualQuatVertex = skin_model_dq_vert::getShader(); - auto skinModelNormalMapDualQuatVertex = skin_model_normal_map_dq_vert::getShader(); - - // Pixel shaders - auto simplePixel = forward_simple_textured_frag::getShader(); - auto simpleTranslucentPixel = forward_simple_textured_transparent_frag::getShader(); - auto simpleUnlitPixel = forward_simple_textured_unlit_frag::getShader(); - auto simpleTranslucentUnlitPixel = simple_transparent_textured_unlit_frag::getShader(); - auto modelPixel = forward_model_frag::getShader(); - auto modelUnlitPixel = forward_model_unlit_frag::getShader(); - auto modelNormalMapPixel = forward_model_normal_map_frag::getShader(); - auto modelTranslucentPixel = forward_model_translucent_frag::getShader(); + using namespace shader::render_utils::program; using Key = render::ShapeKey; - auto addPipelineBind = std::bind(&addPlumberPipeline, std::ref(plumber), _1, _2, _3, _4, _5); + auto addPipelineBind = std::bind(&addPlumberPipeline, std::ref(plumber), _1, _2, _3, _4); // Disable fade on the forward pipeline, all shaders get added twice, once with the fade key and once without - auto addPipeline = [&](const ShapeKey& key, const gpu::ShaderPointer& vertex, const gpu::ShaderPointer& pixel) { - addPipelineBind(key, vertex, pixel, nullptr, nullptr); - addPipelineBind(Key::Builder(key).withFade(), vertex, pixel, nullptr, nullptr); + auto addPipeline = [&](const ShapeKey& key, int programId) { + addPipelineBind(key, programId, nullptr, nullptr); + addPipelineBind(Key::Builder(key).withFade(), programId, nullptr, nullptr); }; // Forward pipelines need the lightBatchSetter for opaques and transparents forceLightBatchSetter = true; // Simple Opaques - addPipeline(Key::Builder(), simpleVertex, simplePixel); - addPipeline(Key::Builder().withUnlit(), simpleVertex, simpleUnlitPixel); + addPipeline(Key::Builder(), simple); + addPipeline(Key::Builder().withUnlit(), simpleUnlit); // Simple Translucents - addPipeline(Key::Builder().withTranslucent(), simpleVertex, simpleTranslucentPixel); - addPipeline(Key::Builder().withTranslucent().withUnlit(), simpleVertex, simpleTranslucentUnlitPixel); + addPipeline(Key::Builder().withTranslucent(), simpleTranslucent); + addPipeline(Key::Builder().withTranslucent().withUnlit(), simpleTranslucentUnlit); // Opaques - addPipeline(Key::Builder().withMaterial(), modelVertex, modelPixel); - addPipeline(Key::Builder().withMaterial().withUnlit(), modelVertex, modelUnlitPixel); - addPipeline(Key::Builder().withMaterial().withTangents(), modelNormalMapVertex, modelNormalMapPixel); + addPipeline(Key::Builder().withMaterial(), forward_model); + addPipeline(Key::Builder().withMaterial().withUnlit(), forward_model_unlit); + addPipeline(Key::Builder().withMaterial().withTangents(), forward_model_translucent); // Skinned Opaques - addPipeline(Key::Builder().withMaterial().withSkinned(), skinModelVertex, modelPixel); - addPipeline(Key::Builder().withMaterial().withSkinned().withTangents(), skinModelNormalMapVertex, modelNormalMapPixel); - addPipeline(Key::Builder().withMaterial().withSkinned().withDualQuatSkinned(), skinModelDualQuatVertex, modelPixel); - addPipeline(Key::Builder().withMaterial().withSkinned().withTangents().withDualQuatSkinned(), skinModelNormalMapDualQuatVertex, modelNormalMapPixel); + addPipeline(Key::Builder().withMaterial().withSkinned(), forward_skin_model); + addPipeline(Key::Builder().withMaterial().withSkinned().withTangents(), forward_skin_model_normal_map); + addPipeline(Key::Builder().withMaterial().withSkinned().withDualQuatSkinned(), forward_skin_model_dq); + addPipeline(Key::Builder().withMaterial().withSkinned().withTangents().withDualQuatSkinned(), forward_skin_model_normal_map_dq); // Translucents - addPipeline(Key::Builder().withMaterial().withTranslucent(), modelVertex, modelTranslucentPixel); - addPipeline(Key::Builder().withMaterial().withTranslucent().withTangents(), modelNormalMapVertex, modelTranslucentPixel); + addPipeline(Key::Builder().withMaterial().withTranslucent(), forward_model_translucent); + addPipeline(Key::Builder().withMaterial().withTranslucent().withTangents(), forward_model_normal_map_translucent); // Skinned Translucents - addPipeline(Key::Builder().withMaterial().withSkinned().withTranslucent(), skinModelVertex, modelTranslucentPixel); - addPipeline(Key::Builder().withMaterial().withSkinned().withTranslucent().withTangents(), skinModelNormalMapVertex, modelTranslucentPixel); - addPipeline(Key::Builder().withMaterial().withSkinned().withTranslucent().withDualQuatSkinned(), skinModelDualQuatVertex, modelTranslucentPixel); - addPipeline(Key::Builder().withMaterial().withSkinned().withTranslucent().withTangents().withDualQuatSkinned(), skinModelNormalMapDualQuatVertex, modelTranslucentPixel); + addPipeline(Key::Builder().withMaterial().withSkinned().withTranslucent(), forward_skin_translucent); + addPipeline(Key::Builder().withMaterial().withSkinned().withTranslucent().withTangents(), forward_skin_translucent_normal_map); + addPipeline(Key::Builder().withMaterial().withSkinned().withTranslucent().withDualQuatSkinned(), forward_skin_translucent_dq); + addPipeline(Key::Builder().withMaterial().withSkinned().withTranslucent().withTangents().withDualQuatSkinned(), forward_skin_translucent_normal_map_dq); forceLightBatchSetter = false; } void addPlumberPipeline(ShapePlumber& plumber, - const ShapeKey& key, const gpu::ShaderPointer& vertex, const gpu::ShaderPointer& pixel, + const ShapeKey& key, int programId, const render::ShapePipeline::BatchSetter& extraBatchSetter, const render::ShapePipeline::ItemSetter& itemSetter) { // These key-values' pipelines are added by this functor in addition to the key passed assert(!key.isWireframe()); assert(!key.isDepthBiased()); assert(key.isCullFace()); - gpu::ShaderPointer program = gpu::Shader::createProgram(vertex, pixel); + gpu::ShaderPointer program = gpu::Shader::createProgram(programId); for (int i = 0; i < 8; i++) { bool isCulled = (i & 1); @@ -517,43 +354,33 @@ void lightBatchSetter(const ShapePipeline& pipeline, gpu::Batch& batch, RenderAr } void initZPassPipelines(ShapePlumber& shapePlumber, gpu::StatePointer state) { - auto modelVertex = model_shadow_vert::getShader(); - auto modelPixel = model_shadow_frag::getShader(); - gpu::ShaderPointer modelProgram = gpu::Shader::createProgram(modelVertex, modelPixel); + using namespace shader::render_utils::program; + gpu::ShaderPointer modelProgram = gpu::Shader::createProgram(model_shadow); shapePlumber.addPipeline( ShapeKey::Filter::Builder().withoutSkinned().withoutFade(), modelProgram, state); - auto skinVertex = skin_model_shadow_vert::getShader(); - auto skinPixel = skin_model_shadow_frag::getShader(); - gpu::ShaderPointer skinProgram = gpu::Shader::createProgram(skinVertex, skinPixel); + gpu::ShaderPointer skinProgram = gpu::Shader::createProgram(skin_model_shadow); shapePlumber.addPipeline( ShapeKey::Filter::Builder().withSkinned().withoutDualQuatSkinned().withoutFade(), skinProgram, state); - auto modelFadeVertex = model_shadow_fade_vert::getShader(); - auto modelFadePixel = model_shadow_fade_frag::getShader(); - gpu::ShaderPointer modelFadeProgram = gpu::Shader::createProgram(modelFadeVertex, modelFadePixel); + gpu::ShaderPointer modelFadeProgram = gpu::Shader::createProgram(model_shadow_fade); shapePlumber.addPipeline( ShapeKey::Filter::Builder().withoutSkinned().withFade(), modelFadeProgram, state); - auto skinFadeVertex = skin_model_shadow_fade_vert::getShader(); - auto skinFadePixel = skin_model_shadow_fade_frag::getShader(); - gpu::ShaderPointer skinFadeProgram = gpu::Shader::createProgram(skinFadeVertex, skinFadePixel); + gpu::ShaderPointer skinFadeProgram = gpu::Shader::createProgram(skin_model_shadow_fade); shapePlumber.addPipeline( ShapeKey::Filter::Builder().withSkinned().withoutDualQuatSkinned().withFade(), skinFadeProgram, state); - //Added for dual quaternions - auto skinModelShadowDualQuatVertex = skin_model_shadow_dq_vert::getShader(); - gpu::ShaderPointer skinModelShadowDualQuatProgram = gpu::Shader::createProgram(skinModelShadowDualQuatVertex, skinPixel); + gpu::ShaderPointer skinModelShadowDualQuatProgram = gpu::Shader::createProgram(skin_model_shadow_dq); shapePlumber.addPipeline( ShapeKey::Filter::Builder().withSkinned().withDualQuatSkinned().withoutFade(), skinModelShadowDualQuatProgram, state); - auto skinModelShadowFadeDualQuatVertex = skin_model_shadow_fade_dq_vert::getShader(); - gpu::ShaderPointer skinModelShadowFadeDualQuatProgram = gpu::Shader::createProgram(skinModelShadowFadeDualQuatVertex, skinFadePixel); + gpu::ShaderPointer skinModelShadowFadeDualQuatProgram = gpu::Shader::createProgram(skin_model_shadow_fade_dq); shapePlumber.addPipeline( ShapeKey::Filter::Builder().withSkinned().withDualQuatSkinned().withFade(), skinModelShadowFadeDualQuatProgram, state); diff --git a/libraries/render-utils/src/StencilMaskPass.cpp b/libraries/render-utils/src/StencilMaskPass.cpp index b9b8274039..08fe1bf35a 100644 --- a/libraries/render-utils/src/StencilMaskPass.cpp +++ b/libraries/render-utils/src/StencilMaskPass.cpp @@ -13,11 +13,7 @@ #include #include - - -#include - -#include "stencil_drawMask_frag.h" +#include using namespace render; @@ -43,9 +39,7 @@ graphics::MeshPointer PrepareStencil::getMesh() { gpu::PipelinePointer PrepareStencil::getMeshStencilPipeline() { if (!_meshStencilPipeline) { - auto vs = gpu::StandardShaderLib::getDrawVertexPositionVS(); - auto ps = gpu::StandardShaderLib::getDrawNadaPS(); - auto program = gpu::Shader::createProgram(vs, ps); + auto program = gpu::Shader::createProgram(shader::gpu::program::drawNothing); gpu::Shader::makeProgram((*program)); auto state = std::make_shared(); @@ -59,9 +53,7 @@ gpu::PipelinePointer PrepareStencil::getMeshStencilPipeline() { gpu::PipelinePointer PrepareStencil::getPaintStencilPipeline() { if (!_paintStencilPipeline) { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = stencil_drawMask_frag::getShader(); - auto program = gpu::Shader::createProgram(vs, ps); + auto program = gpu::Shader::createProgram(shader::render_utils::program::stencil_drawMask); gpu::Shader::makeProgram((*program)); auto state = std::make_shared(); diff --git a/libraries/render-utils/src/SubsurfaceScattering.cpp b/libraries/render-utils/src/SubsurfaceScattering.cpp index 1ffa0d2e5c..2c27569269 100644 --- a/libraries/render-utils/src/SubsurfaceScattering.cpp +++ b/libraries/render-utils/src/SubsurfaceScattering.cpp @@ -11,17 +11,12 @@ #include "SubsurfaceScattering.h" #include -#include +#include #include "FramebufferCache.h" #include "DeferredLightingEffect.h" -#include "subsurfaceScattering_makeProfile_frag.h" -#include "subsurfaceScattering_makeLUT_frag.h" -#include "subsurfaceScattering_makeSpecularBeckmann_frag.h" - -#include "subsurfaceScattering_drawScattering_frag.h" enum ScatteringShaderBufferSlots { ScatteringTask_FrameTransformSlot = 0, @@ -307,9 +302,7 @@ void diffuseProfileGPU(gpu::TexturePointer& profileMap, RenderArgs* args) { gpu::PipelinePointer makePipeline; { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = subsurfaceScattering_makeProfile_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::subsurfaceScattering_makeProfile); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); @@ -338,15 +331,11 @@ void diffuseScatterGPU(const gpu::TexturePointer& profileMap, gpu::TexturePointe int width = lut->getWidth(); int height = lut->getHeight(); - gpu::PipelinePointer makePipeline; - - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = subsurfaceScattering_makeLUT_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::subsurfaceScattering_makeLUT); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); - makePipeline = gpu::Pipeline::create(program, state); + gpu::PipelinePointer makePipeline = gpu::Pipeline::create(program, state); auto makeFramebuffer = gpu::FramebufferPointer(gpu::Framebuffer::create("diffuseScatter")); makeFramebuffer->setRenderBuffer(0, lut); @@ -379,9 +368,7 @@ void computeSpecularBeckmannGPU(gpu::TexturePointer& beckmannMap, RenderArgs* ar gpu::PipelinePointer makePipeline; { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = subsurfaceScattering_makeSpecularBeckmann_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::subsurfaceScattering_makeSpecularBeckmann); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); @@ -451,9 +438,7 @@ void DebugSubsurfaceScattering::configure(const Config& config) { gpu::PipelinePointer DebugSubsurfaceScattering::getScatteringPipeline() { if (!_scatteringPipeline) { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = subsurfaceScattering_drawScattering_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::subsurfaceScattering_drawScattering); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), ScatteringTask_FrameTransformSlot)); @@ -480,19 +465,12 @@ gpu::PipelinePointer DebugSubsurfaceScattering::getScatteringPipeline() { return _scatteringPipeline; } - gpu::PipelinePointer _showLUTPipeline; -gpu::PipelinePointer getShowLUTPipeline(); + gpu::PipelinePointer DebugSubsurfaceScattering::getShowLUTPipeline() { if (!_showLUTPipeline) { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = gpu::StandardShaderLib::getDrawTextureOpaquePS(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - - gpu::Shader::BindingSet slotBindings; - + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::gpu::program::drawUnitQuatTextureOpaque); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); - _showLUTPipeline = gpu::Pipeline::create(program, state); } diff --git a/libraries/render-utils/src/SurfaceGeometryPass.cpp b/libraries/render-utils/src/SurfaceGeometryPass.cpp index 51046f10b3..fd0200b369 100644 --- a/libraries/render-utils/src/SurfaceGeometryPass.cpp +++ b/libraries/render-utils/src/SurfaceGeometryPass.cpp @@ -13,7 +13,8 @@ #include #include -#include +#include + #include "StencilMaskPass.h" const int DepthLinearPass_FrameTransformSlot = 0; @@ -25,13 +26,6 @@ const int SurfaceGeometryPass_ParamsSlot = 1; const int SurfaceGeometryPass_DepthMapSlot = 0; const int SurfaceGeometryPass_NormalMapSlot = 1; -#include "surfaceGeometry_makeLinearDepth_frag.h" -#include "surfaceGeometry_downsampleDepthNormal_frag.h" - -#include "surfaceGeometry_makeCurvature_frag.h" - - - LinearDepthFramebuffer::LinearDepthFramebuffer() { } @@ -212,9 +206,7 @@ void LinearDepthPass::run(const render::RenderContextPointer& renderContext, con const gpu::PipelinePointer& LinearDepthPass::getLinearDepthPipeline(const render::RenderContextPointer& renderContext) { gpu::ShaderPointer program; if (!_linearDepthPipeline) { - auto vs = gpu::StandardShaderLib::getDrawViewportQuadTransformTexcoordVS(); - auto ps = surfaceGeometry_makeLinearDepth_frag::getShader(); - program = gpu::Shader::createProgram(vs, ps); + program = gpu::Shader::createProgram(shader::render_utils::program::surfaceGeometry_makeLinearDepth); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); @@ -243,9 +235,7 @@ const gpu::PipelinePointer& LinearDepthPass::getLinearDepthPipeline(const render const gpu::PipelinePointer& LinearDepthPass::getDownsamplePipeline(const render::RenderContextPointer& renderContext) { if (!_downsamplePipeline) { - auto vs = gpu::StandardShaderLib::getDrawViewportQuadTransformTexcoordVS(); - auto ps = surfaceGeometry_downsampleDepthNormal_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::surfaceGeometry_downsampleDepthNormal); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); PrepareStencil::testShape(*state); @@ -546,9 +536,7 @@ void SurfaceGeometryPass::run(const render::RenderContextPointer& renderContext, const gpu::PipelinePointer& SurfaceGeometryPass::getCurvaturePipeline(const render::RenderContextPointer& renderContext) { if (!_curvaturePipeline) { - auto vs = gpu::StandardShaderLib::getDrawViewportQuadTransformTexcoordVS(); - auto ps = surfaceGeometry_makeCurvature_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::surfaceGeometry_makeCurvature); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); diff --git a/libraries/render-utils/src/TextRenderer3D.cpp b/libraries/render-utils/src/TextRenderer3D.cpp index 9c85952107..dd9167d248 100644 --- a/libraries/render-utils/src/TextRenderer3D.cpp +++ b/libraries/render-utils/src/TextRenderer3D.cpp @@ -19,15 +19,13 @@ #include #include +#include #include "text/Font.h" #include "GLMHelpers.h" #include "MatrixStack.h" #include "RenderUtilsLogging.h" -#include "sdf_text3D_vert.h" -#include "sdf_text3D_frag.h" - #include "GeometryCache.h" const float TextRenderer3D::DEFAULT_POINT_SIZE = 12; diff --git a/libraries/render-utils/src/ToneMappingEffect.cpp b/libraries/render-utils/src/ToneMappingEffect.cpp index 12152fd6ba..5403f3e2f8 100644 --- a/libraries/render-utils/src/ToneMappingEffect.cpp +++ b/libraries/render-utils/src/ToneMappingEffect.cpp @@ -12,12 +12,11 @@ #include "ToneMappingEffect.h" #include -#include +#include #include "StencilMaskPass.h" #include "FramebufferCache.h" -#include "toneMapping_frag.h" const int ToneMappingEffect_ParamsSlot = 0; const int ToneMappingEffect_LightingMapSlot = 0; @@ -28,10 +27,7 @@ ToneMappingEffect::ToneMappingEffect() { } void ToneMappingEffect::init(RenderArgs* args) { - auto blitPS = toneMapping_frag::getShader(); - - auto blitVS = gpu::StandardShaderLib::getDrawViewportQuadTransformTexcoordVS(); - auto blitProgram = gpu::ShaderPointer(gpu::Shader::createProgram(blitVS, blitPS)); + auto blitProgram = gpu::Shader::createProgram(shader::render_utils::program::toneMapping); auto blitState = std::make_shared(); blitState->setColorWriteMask(true, true, true, true); diff --git a/libraries/render-utils/src/VelocityBufferPass.cpp b/libraries/render-utils/src/VelocityBufferPass.cpp index 3f7da4cdcd..1431316aed 100644 --- a/libraries/render-utils/src/VelocityBufferPass.cpp +++ b/libraries/render-utils/src/VelocityBufferPass.cpp @@ -13,15 +13,13 @@ #include #include -#include +#include + #include "StencilMaskPass.h" const int VelocityBufferPass_FrameTransformSlot = 0; const int VelocityBufferPass_DepthMapSlot = 0; - -#include "velocityBuffer_cameraMotion_frag.h" - VelocityFramebuffer::VelocityFramebuffer() { } @@ -145,10 +143,7 @@ void VelocityBufferPass::run(const render::RenderContextPointer& renderContext, const gpu::PipelinePointer& VelocityBufferPass::getCameraMotionPipeline(const render::RenderContextPointer& renderContext) { if (!_cameraMotionPipeline) { - auto vs = gpu::StandardShaderLib::getDrawViewportQuadTransformTexcoordVS(); - auto ps = velocityBuffer_cameraMotion_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::velocityBuffer_cameraMotion); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); // Stencil test the curvature pass for objects pixels only, not the background diff --git a/libraries/render-utils/src/ZoneRenderer.cpp b/libraries/render-utils/src/ZoneRenderer.cpp index 51939efd4f..fc0cccd9e3 100644 --- a/libraries/render-utils/src/ZoneRenderer.cpp +++ b/libraries/render-utils/src/ZoneRenderer.cpp @@ -10,21 +10,15 @@ // #include "ZoneRenderer.h" - #include -#include #include #include +#include #include "StencilMaskPass.h" #include "DeferredLightingEffect.h" -#include "zone_drawKeyLight_frag.h" -#include "zone_drawAmbient_frag.h" -#include "zone_drawSkybox_frag.h" - - using namespace render; class SetupZones { @@ -77,9 +71,7 @@ void SetupZones::run(const RenderContextPointer& context, const Inputs& inputs) const gpu::PipelinePointer& DebugZoneLighting::getKeyLightPipeline() { if (!_keyLightPipeline) { - auto vs = gpu::StandardShaderLib::getDrawTransformUnitQuadVS(); - auto ps = zone_drawKeyLight_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::zone_drawKeyLight); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), ZONE_DEFERRED_TRANSFORM_BUFFER)); @@ -98,9 +90,7 @@ const gpu::PipelinePointer& DebugZoneLighting::getKeyLightPipeline() { const gpu::PipelinePointer& DebugZoneLighting::getAmbientPipeline() { if (!_ambientPipeline) { - auto vs = gpu::StandardShaderLib::getDrawTransformUnitQuadVS(); - auto ps = zone_drawAmbient_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::zone_drawAmbient); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), ZONE_DEFERRED_TRANSFORM_BUFFER)); @@ -119,9 +109,7 @@ const gpu::PipelinePointer& DebugZoneLighting::getAmbientPipeline() { } const gpu::PipelinePointer& DebugZoneLighting::getBackgroundPipeline() { if (!_backgroundPipeline) { - auto vs = gpu::StandardShaderLib::getDrawTransformUnitQuadVS(); - auto ps = zone_drawSkybox_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::zone_drawSkybox); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), ZONE_DEFERRED_TRANSFORM_BUFFER)); diff --git a/libraries/render-utils/src/skin_model_shadow.slf b/libraries/render-utils/src/skin_model_shadow.slf deleted file mode 100644 index e464d6e6c8..0000000000 --- a/libraries/render-utils/src/skin_model_shadow.slf +++ /dev/null @@ -1,20 +0,0 @@ -<@include gpu/Config.slh@> -<$VERSION_HEADER$> -// Generated on <$_SCRIBE_DATE$> -// -// skin_model_shadow.frag -// fragment shader -// -// Created by Andrzej Kapolka on 3/24/14. -// Copyright 2013 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -layout(location = 0) out vec4 _fragColor; - -void main(void) { - // pass-through to set z-buffer - _fragColor = vec4(1.0, 1.0, 1.0, 0.0); -} diff --git a/libraries/render-utils/src/skin_model_shadow_fade.slf b/libraries/render-utils/src/skin_model_shadow_fade.slf deleted file mode 100644 index 214fc72e42..0000000000 --- a/libraries/render-utils/src/skin_model_shadow_fade.slf +++ /dev/null @@ -1,30 +0,0 @@ -<@include gpu/Config.slh@> -<$VERSION_HEADER$> -// Generated on <$_SCRIBE_DATE$> -// -// skin_model_shadow_fade.frag -// fragment shader -// -// Created by Olivier Prat on 06/08/17. -// Copyright 2017 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -<@include Fade.slh@> -<$declareFadeFragment()$> - -in vec4 _positionWS; - -layout(location = 0) out vec4 _fragColor; - -void main(void) { - FadeObjectParams fadeParams; - - <$fetchFadeObjectParams(fadeParams)$> - applyFadeClip(fadeParams, _positionWS.xyz); - - // pass-through to set z-buffer - _fragColor = vec4(1.0, 1.0, 1.0, 0.0); -} diff --git a/libraries/render-utils/src/text/Font.cpp b/libraries/render-utils/src/text/Font.cpp index cd171db855..66f052e25f 100644 --- a/libraries/render-utils/src/text/Font.cpp +++ b/libraries/render-utils/src/text/Font.cpp @@ -6,10 +6,7 @@ #include #include - -#include "sdf_text3D_vert.h" -#include "sdf_text3D_frag.h" -#include "sdf_text3D_transparent_frag.h" +#include #include "../RenderUtilsLogging.h" #include "FontFamilies.h" @@ -223,11 +220,8 @@ void Font::setupGPU() { // Setup render pipeline { - auto vertexShader = sdf_text3D_vert::getShader(); - auto pixelShader = sdf_text3D_frag::getShader(); - auto pixelShaderTransparent = sdf_text3D_transparent_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vertexShader, pixelShader); - gpu::ShaderPointer programTransparent = gpu::Shader::createProgram(vertexShader, pixelShaderTransparent); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::sdf_text3D); + gpu::ShaderPointer programTransparent = gpu::Shader::createProgram(shader::render_utils::program::sdf_text3D_transparent); gpu::Shader::BindingSet slotBindings; gpu::Shader::makeProgram(*program, slotBindings); diff --git a/libraries/render/CMakeLists.txt b/libraries/render/CMakeLists.txt index 2a888a5b18..e3aa4bd491 100644 --- a/libraries/render/CMakeLists.txt +++ b/libraries/render/CMakeLists.txt @@ -1,8 +1,7 @@ set(TARGET_NAME render) -AUTOSCRIBE_SHADER_LIB(gpu graphics) setup_hifi_library() # render needs octree only for getAccuracyAngle(float, int) -link_hifi_libraries(shared task ktx gpu graphics octree) +link_hifi_libraries(shared task ktx gpu shaders graphics octree) target_nsight() diff --git a/libraries/render/src/render/BlurTask.cpp b/libraries/render/src/render/BlurTask.cpp index 896482eb2a..3699922074 100644 --- a/libraries/render/src/render/BlurTask.cpp +++ b/libraries/render/src/render/BlurTask.cpp @@ -11,13 +11,7 @@ #include "BlurTask.h" #include -#include - -#include "blurGaussianV_frag.h" -#include "blurGaussianH_frag.h" - -#include "blurGaussianDepthAwareV_frag.h" -#include "blurGaussianDepthAwareH_frag.h" +#include using namespace render; @@ -209,9 +203,7 @@ BlurGaussian::BlurGaussian(bool generateOutputFramebuffer, unsigned int downsamp gpu::PipelinePointer BlurGaussian::getBlurVPipeline() { if (!_blurVPipeline) { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = blurGaussianV_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::blurGaussianV); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("blurParamsBuffer"), BlurTask_ParamsSlot)); @@ -231,9 +223,7 @@ gpu::PipelinePointer BlurGaussian::getBlurVPipeline() { gpu::PipelinePointer BlurGaussian::getBlurHPipeline() { if (!_blurHPipeline) { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = blurGaussianH_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::blurGaussianH); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("blurParamsBuffer"), BlurTask_ParamsSlot)); @@ -323,9 +313,7 @@ BlurGaussianDepthAware::BlurGaussianDepthAware(bool generateOutputFramebuffer, c gpu::PipelinePointer BlurGaussianDepthAware::getBlurVPipeline() { if (!_blurVPipeline) { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = blurGaussianDepthAwareV_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::blurGaussianDepthAwareV); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("blurParamsBuffer"), BlurTask_ParamsSlot)); @@ -346,9 +334,7 @@ gpu::PipelinePointer BlurGaussianDepthAware::getBlurVPipeline() { gpu::PipelinePointer BlurGaussianDepthAware::getBlurHPipeline() { if (!_blurHPipeline) { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = blurGaussianDepthAwareH_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::blurGaussianDepthAwareH); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("blurParamsBuffer"), BlurTask_ParamsSlot)); diff --git a/libraries/render/src/render/DrawSceneOctree.cpp b/libraries/render/src/render/DrawSceneOctree.cpp index 433851eec2..5de538759a 100644 --- a/libraries/render/src/render/DrawSceneOctree.cpp +++ b/libraries/render/src/render/DrawSceneOctree.cpp @@ -18,25 +18,17 @@ #include #include -#include +#include #include "Args.h" -#include "drawCellBounds_vert.h" -#include "drawCellBounds_frag.h" -#include "drawLODReticle_frag.h" - -#include "drawItemBounds_vert.h" -#include "drawItemBounds_frag.h" using namespace render; const gpu::PipelinePointer DrawSceneOctree::getDrawCellBoundsPipeline() { if (!_drawCellBoundsPipeline) { - auto vs = drawCellBounds_vert::getShader(); - auto ps = drawCellBounds_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::drawCellBounds); gpu::Shader::BindingSet slotBindings; gpu::Shader::makeProgram(*program, slotBindings); @@ -58,12 +50,8 @@ const gpu::PipelinePointer DrawSceneOctree::getDrawCellBoundsPipeline() { const gpu::PipelinePointer DrawSceneOctree::getDrawLODReticlePipeline() { if (!_drawLODReticlePipeline) { - auto vs = gpu::StandardShaderLib::getDrawTransformUnitQuadVS(); - auto ps = drawLODReticle_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - - gpu::Shader::BindingSet slotBindings; - gpu::Shader::makeProgram(*program, slotBindings); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::drawLODReticle); + gpu::Shader::makeProgram(*program); // _drawCellLocationLoc = program->getUniforms().findLocation("inCellLocation"); @@ -162,9 +150,7 @@ void DrawSceneOctree::run(const RenderContextPointer& renderContext, const ItemS const gpu::PipelinePointer DrawItemSelection::getDrawItemBoundPipeline() { if (!_drawItemBoundPipeline) { - auto vs = drawItemBounds_vert::getShader(); - auto ps = drawItemBounds_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::drawItemBounds); gpu::Shader::BindingSet slotBindings; gpu::Shader::makeProgram(*program, slotBindings); diff --git a/libraries/render/src/render/DrawStatus.cpp b/libraries/render/src/render/DrawStatus.cpp index 496b2000a9..b8fef0d987 100644 --- a/libraries/render/src/render/DrawStatus.cpp +++ b/libraries/render/src/render/DrawStatus.cpp @@ -19,12 +19,9 @@ #include -#include "Args.h" +#include -#include "drawItemBounds_vert.h" -#include "drawItemBounds_frag.h" -#include "drawItemStatus_vert.h" -#include "drawItemStatus_frag.h" +#include "Args.h" using namespace render; @@ -35,9 +32,7 @@ void DrawStatusConfig::dirtyHelper() { const gpu::PipelinePointer DrawStatus::getDrawItemBoundsPipeline() { if (!_drawItemBoundsPipeline) { - auto vs = drawItemBounds_vert::getShader(); - auto ps = drawItemBounds_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::drawItemBounds); gpu::Shader::BindingSet slotBindings; gpu::Shader::makeProgram(*program, slotBindings); @@ -63,9 +58,7 @@ const gpu::PipelinePointer DrawStatus::getDrawItemBoundsPipeline() { const gpu::PipelinePointer DrawStatus::getDrawItemStatusPipeline() { if (!_drawItemStatusPipeline) { - auto vs = drawItemStatus_vert::getShader(); - auto ps = drawItemStatus_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::drawItemStatus); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("iconStatusMap"), 0)); diff --git a/libraries/render/src/render/DrawTask.cpp b/libraries/render/src/render/DrawTask.cpp index 3a7555f790..08be053ddf 100755 --- a/libraries/render/src/render/DrawTask.cpp +++ b/libraries/render/src/render/DrawTask.cpp @@ -18,13 +18,10 @@ #include #include #include -#include +#include #include "Logging.h" -#include "drawItemBounds_vert.h" -#include "drawItemBounds_frag.h" - using namespace render; void render::renderItems(const RenderContextPointer& renderContext, const ItemBounds& inItems, int maxDrawnItems) { @@ -160,9 +157,7 @@ void DrawLight::run(const RenderContextPointer& renderContext, const ItemBounds& const gpu::PipelinePointer DrawBounds::getPipeline() { if (!_boundsPipeline) { - auto vs = drawItemBounds_vert::getShader(); - auto ps = drawItemBounds_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::drawItemBounds); gpu::Shader::BindingSet slotBindings; gpu::Shader::makeProgram(*program, slotBindings); @@ -267,9 +262,7 @@ gpu::PipelinePointer DrawQuadVolume::getPipeline() { static gpu::PipelinePointer pipeline; if (!pipeline) { - auto vs = gpu::StandardShaderLib::getDrawTransformVertexPositionVS(); - auto ps = gpu::StandardShaderLib::getDrawColorPS(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::gpu::program::drawColor); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding("color", 0)); diff --git a/libraries/render/src/render/ResampleTask.cpp b/libraries/render/src/render/ResampleTask.cpp index 008234b437..880d13fde1 100644 --- a/libraries/render/src/render/ResampleTask.cpp +++ b/libraries/render/src/render/ResampleTask.cpp @@ -12,8 +12,8 @@ // #include "ResampleTask.h" -#include "gpu/Context.h" -#include "gpu/StandardShaderLib.h" +#include +#include using namespace render; @@ -51,9 +51,7 @@ void HalfDownsample::run(const RenderContextPointer& renderContext, const gpu::F resampledFrameBuffer = getResampledFrameBuffer(sourceFramebuffer); if (!_pipeline) { - auto vs = gpu::StandardShaderLib::getDrawTransformUnitQuadVS(); - auto ps = gpu::StandardShaderLib::getDrawTextureOpaquePS(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::gpu::program::drawTransformUnitQuadTextureOpaque); gpu::Shader::BindingSet slotBindings; gpu::Shader::makeProgram(*program, slotBindings); diff --git a/libraries/shaders/CMakeLists.txt b/libraries/shaders/CMakeLists.txt new file mode 100644 index 0000000000..de188089a6 --- /dev/null +++ b/libraries/shaders/CMakeLists.txt @@ -0,0 +1,175 @@ + +set(TARGET_NAME gpu) +AUTOSCRIBE_SHADER_LIB(gpu) +AUTOSCRIBE_PROGRAM(NAME drawColor VERTEX DrawTransformVertexPosition FRAGMENT DrawColor) +AUTOSCRIBE_PROGRAM(NAME drawTransformUnitQuadTextureOpaque VERTEX DrawTransformUnitQuad FRAGMENT DrawTextureOpaque) +AUTOSCRIBE_PROGRAM(NAME drawUnitQuatTextureOpaque VERTEX DrawUnitQuadTexcoord FRAGMENT DrawTextureOpaque) +AUTOSCRIBE_PROGRAM(NAME drawTextureOpaqueTexcoordRect VERTEX DrawTexcoordRectTransformUnitQuad FRAGMENT DrawTextureOpaque) +AUTOSCRIBE_PROGRAM(NAME drawNothing VERTEX DrawVertexPosition FRAGMENT DrawNada) + +set(TARGET_NAME graphics) +AUTOSCRIBE_SHADER_LIB(gpu) +AUTOSCRIBE_PROGRAM(NAME skybox) + +set(TARGET_NAME procedural) +AUTOSCRIBE_SHADER_LIB(gpu graphics) + +set(TARGET_NAME render) +AUTOSCRIBE_SHADER_LIB(gpu graphics) +AUTOSCRIBE_PROGRAM(NAME drawCellBounds) +AUTOSCRIBE_PROGRAM(NAME drawItemBounds) +AUTOSCRIBE_PROGRAM(NAME drawItemStatus) +AUTOSCRIBE_PROGRAM(NAME drawLODReticle VERTEX gpu::vertex::DrawTransformUnitQuad) +AUTOSCRIBE_PROGRAM(NAME blurGaussianV VERTEX gpu::vertex::DrawUnitQuadTexcoord) +AUTOSCRIBE_PROGRAM(NAME blurGaussianH VERTEX gpu::vertex::DrawUnitQuadTexcoord) +AUTOSCRIBE_PROGRAM(NAME blurGaussianDepthAwareV VERTEX gpu::vertex::DrawUnitQuadTexcoord) +AUTOSCRIBE_PROGRAM(NAME blurGaussianDepthAwareH VERTEX gpu::vertex::DrawUnitQuadTexcoord) + +set(TARGET_NAME render-utils) +AUTOSCRIBE_SHADER_LIB(gpu graphics render) +AUTOSCRIBE_PROGRAM(NAME animdebugdraw) +AUTOSCRIBE_PROGRAM(NAME bloomThreshold VERTEX gpu::vertex::DrawTransformUnitQuad FRAGMENT BloomThreshold) +AUTOSCRIBE_PROGRAM(NAME bloomApply VERTEX gpu::vertex::DrawTransformUnitQuad FRAGMENT BloomApply) +AUTOSCRIBE_PROGRAM(NAME directional_ambient_light VERTEX deferred_light) +AUTOSCRIBE_PROGRAM(NAME directional_ambient_light_shadow VERTEX deferred_light) +AUTOSCRIBE_PROGRAM(NAME directional_skybox_light VERTEX deferred_light) +AUTOSCRIBE_PROGRAM(NAME directional_skybox_light_shadow VERTEX deferred_light) +AUTOSCRIBE_PROGRAM(NAME local_lights_shading VERTEX deferred_light) +AUTOSCRIBE_PROGRAM(NAME local_lights_drawOutline VERTEX deferred_light) +AUTOSCRIBE_PROGRAM(NAME forward_simple_textured VERTEX simple) +AUTOSCRIBE_PROGRAM(NAME forward_simple_textured_unlit VERTEX simple) +AUTOSCRIBE_PROGRAM(NAME forward_simple_textured_transparent VERTEX simple) +AUTOSCRIBE_PROGRAM(NAME fxaa_blend VERTEX gpu::vertex::DrawUnitQuadTexcoord) +AUTOSCRIBE_PROGRAM(NAME glowLine) +AUTOSCRIBE_PROGRAM(NAME grid VERTEX standardTransformPNTC) +AUTOSCRIBE_PROGRAM(NAME hmd_ui) +AUTOSCRIBE_PROGRAM(NAME drawWorkloadProxy) +AUTOSCRIBE_PROGRAM(NAME drawWorkloadView) +AUTOSCRIBE_PROGRAM(NAME haze VERTEX gpu::vertex::DrawViewportQuadTransformTexcoord FRAGMENT Haze) +AUTOSCRIBE_PROGRAM(NAME highlight_aabox VERTEX Highlight_aabox FRAGMENT nop) +AUTOSCRIBE_PROGRAM(NAME highlight VERTEX gpu::vertex::DrawViewportQuadTransformTexcoord FRAGMENT Highlight) +AUTOSCRIBE_PROGRAM(NAME highlight_filled VERTEX gpu::vertex::DrawViewportQuadTransformTexcoord FRAGMENT Highlight_filled) +AUTOSCRIBE_PROGRAM(NAME lightClusters_drawGrid) +AUTOSCRIBE_PROGRAM(NAME lightClusters_drawClusterFromDepth VERTEX gpu::vertex::DrawUnitQuadTexcoord) +AUTOSCRIBE_PROGRAM(NAME lightClusters_drawClusterContent VERTEX gpu::vertex::DrawUnitQuadTexcoord) +AUTOSCRIBE_PROGRAM(NAME simple_opaque_web_browser VERTEX simple) +AUTOSCRIBE_PROGRAM(NAME simple_transparent_web_browser VERTEX simple) +AUTOSCRIBE_PROGRAM(NAME simple_textured VERTEX simple) +AUTOSCRIBE_PROGRAM(NAME simple_textured_unlit VERTEX simple) +AUTOSCRIBE_PROGRAM(NAME simple_transparent_textured VERTEX simple) +AUTOSCRIBE_PROGRAM(NAME simple_transparent_textured_unlit VERTEX simple) +AUTOSCRIBE_PROGRAM(NAME simple_textured_fade VERTEX simple_fade) +AUTOSCRIBE_PROGRAM(NAME simple_textured_unlit_fade VERTEX simple_fade) +AUTOSCRIBE_PROGRAM(NAME simple_transparent_textured_fade VERTEX simple_fade) +AUTOSCRIBE_PROGRAM(NAME simple_transparent_textured_unlit_fade VERTEX simple_fade) + +AUTOSCRIBE_PROGRAM(NAME sdf_text3D) +AUTOSCRIBE_PROGRAM(NAME sdf_text3D_transparent VERTEX sdf_text3D) + +AUTOSCRIBE_PROGRAM(NAME ssao_makeOcclusion VERTEX gpu::vertex::DrawViewportQuadTransformTexcoord) +AUTOSCRIBE_PROGRAM(NAME ssao_makeHorizontalBlur VERTEX gpu::vertex::DrawViewportQuadTransformTexcoord) +AUTOSCRIBE_PROGRAM(NAME ssao_makeVerticalBlur VERTEX gpu::vertex::DrawViewportQuadTransformTexcoord) +AUTOSCRIBE_PROGRAM(NAME ssao_debugOcclusion VERTEX gpu::vertex::DrawViewportQuadTransformTexcoord) + +AUTOSCRIBE_PROGRAM(NAME stencil_drawMask VERTEX gpu::vertex::DrawUnitQuadTexcoord) + +AUTOSCRIBE_PROGRAM(NAME standardDrawTexture VERTEX standardTransformPNTC) +AUTOSCRIBE_PROGRAM(NAME standardDrawTextureNoBlend VERTEX standardTransformPNTC FRAGMENT gpu::fragment::DrawTextureOpaque) + +AUTOSCRIBE_PROGRAM(NAME subsurfaceScattering_makeProfile VERTEX gpu::vertex::DrawUnitQuadTexcoord) +AUTOSCRIBE_PROGRAM(NAME subsurfaceScattering_makeLUT VERTEX gpu::vertex::DrawUnitQuadTexcoord) +AUTOSCRIBE_PROGRAM(NAME subsurfaceScattering_makeSpecularBeckmann VERTEX gpu::vertex::DrawUnitQuadTexcoord) +AUTOSCRIBE_PROGRAM(NAME subsurfaceScattering_drawScattering VERTEX gpu::vertex::DrawUnitQuadTexcoord) + +AUTOSCRIBE_PROGRAM(NAME surfaceGeometry_makeLinearDepth VERTEX gpu::vertex::DrawViewportQuadTransformTexcoord) +AUTOSCRIBE_PROGRAM(NAME surfaceGeometry_downsampleDepthNormal VERTEX gpu::vertex::DrawViewportQuadTransformTexcoord) +AUTOSCRIBE_PROGRAM(NAME surfaceGeometry_makeCurvature VERTEX gpu::vertex::DrawViewportQuadTransformTexcoord) + + +AUTOSCRIBE_PROGRAM(NAME taa VERTEX gpu::vertex::DrawUnitQuadTexcoord) +AUTOSCRIBE_PROGRAM(NAME taa_blend VERTEX gpu::vertex::DrawUnitQuadTexcoord) + +AUTOSCRIBE_PROGRAM(NAME simple FRAGMENT forward_simple_textured) +AUTOSCRIBE_PROGRAM(NAME simpleUnlit VERTEX simple FRAGMENT forward_simple_textured_unlit) +AUTOSCRIBE_PROGRAM(NAME simpleTranslucent VERTEX simple FRAGMENT forward_simple_textured_transparent) +AUTOSCRIBE_PROGRAM(NAME simpleTranslucentUnlit VERTEX simple FRAGMENT simple_transparent_textured_unlit) + +AUTOSCRIBE_PROGRAM(NAME forward_model VERTEX model) +AUTOSCRIBE_PROGRAM(NAME forward_model_translucent VERTEX model) +AUTOSCRIBE_PROGRAM(NAME forward_model_unlit VERTEX model) +AUTOSCRIBE_PROGRAM(NAME forward_model_normal_map VERTEX model_normal_map) +AUTOSCRIBE_PROGRAM(NAME forward_model_normal_map_translucent VERTEX model_normal_map FRAGMENT forward_model_translucent) + +AUTOSCRIBE_PROGRAM(NAME forward_skin_model VERTEX skin_model FRAGMENT forward_model) +AUTOSCRIBE_PROGRAM(NAME forward_skin_model_normal_map VERTEX skin_model_normal_map FRAGMENT forward_model_normal_map) +AUTOSCRIBE_PROGRAM(NAME forward_skin_model_dq VERTEX skin_model_dq FRAGMENT forward_model) +AUTOSCRIBE_PROGRAM(NAME forward_skin_model_normal_map_dq VERTEX skin_model_normal_map_dq FRAGMENT forward_model_normal_map) + +AUTOSCRIBE_PROGRAM(NAME forward_skin_translucent VERTEX skin_model FRAGMENT forward_model_translucent) +AUTOSCRIBE_PROGRAM(NAME forward_skin_translucent_normal_map VERTEX skin_model_normal_map FRAGMENT forward_model_translucent) +AUTOSCRIBE_PROGRAM(NAME forward_skin_translucent_dq VERTEX skin_model_dq FRAGMENT forward_model_translucent) +AUTOSCRIBE_PROGRAM(NAME forward_skin_translucent_normal_map_dq VERTEX skin_model_normal_map_dq FRAGMENT forward_model_translucent) + +AUTOSCRIBE_PROGRAM(NAME model) +AUTOSCRIBE_PROGRAM(NAME model_unlit VERTEX model) +AUTOSCRIBE_PROGRAM(NAME model_normal_map) +AUTOSCRIBE_PROGRAM(NAME model_translucent) +AUTOSCRIBE_PROGRAM(NAME model_translucent_normal_map) +AUTOSCRIBE_PROGRAM(NAME model_translucent_unlit VERTEX model) +AUTOSCRIBE_PROGRAM(NAME model_lightmap) +AUTOSCRIBE_PROGRAM(NAME model_lightmap_normal_map) +AUTOSCRIBE_PROGRAM(NAME model_shadow) +AUTOSCRIBE_PROGRAM(NAME model_shadow_fade) + +AUTOSCRIBE_PROGRAM(NAME skin_model FRAGMENT model) +AUTOSCRIBE_PROGRAM(NAME skin_model_normal_map FRAGMENT model_normal_map) +AUTOSCRIBE_PROGRAM(NAME skin_model_normal_map_fade FRAGMENT model_normal_map_fade) +AUTOSCRIBE_PROGRAM(NAME skin_model_translucent VERTEX skin_model_fade FRAGMENT model_translucent) +AUTOSCRIBE_PROGRAM(NAME skin_model_translucent_fade VERTEX skin_model_fade FRAGMENT model_translucent_fade) +AUTOSCRIBE_PROGRAM(NAME skin_model_normal_map_translucent VERTEX skin_model_normal_map_fade FRAGMENT model_translucent_normal_map) +AUTOSCRIBE_PROGRAM(NAME skin_model_normal_map_translucent_fade VERTEX skin_model_normal_map_fade FRAGMENT model_translucent_normal_map_fade) +AUTOSCRIBE_PROGRAM(NAME skin_model_fade FRAGMENT model_fade) +AUTOSCRIBE_PROGRAM(NAME skin_model_shadow FRAGMENT model_shadow) +AUTOSCRIBE_PROGRAM(NAME skin_model_shadow_fade FRAGMENT model_shadow) + + +AUTOSCRIBE_PROGRAM(NAME skin_model_dq FRAGMENT model) +AUTOSCRIBE_PROGRAM(NAME skin_model_fade_dq FRAGMENT model_fade) +AUTOSCRIBE_PROGRAM(NAME skin_model_normal_map_dq FRAGMENT model_normal_map) +AUTOSCRIBE_PROGRAM(NAME skin_model_normal_map_fade_dq FRAGMENT model_normal_map_fade) +AUTOSCRIBE_PROGRAM(NAME skin_model_translucent_dq VERTEX skin_model_fade_dq FRAGMENT model_translucent) +AUTOSCRIBE_PROGRAM(NAME skin_model_translucent_fade_dq VERTEX skin_model_fade_dq FRAGMENT model_translucent_fade) +AUTOSCRIBE_PROGRAM(NAME skin_model_normal_map_translucent_dq VERTEX skin_model_normal_map_fade_dq FRAGMENT model_translucent_normal_map) +AUTOSCRIBE_PROGRAM(NAME skin_model_normal_map_translucent_fade_dq VERTEX skin_model_normal_map_fade_dq FRAGMENT model_translucent_normal_map_fade) + +AUTOSCRIBE_PROGRAM(NAME skin_model_shadow_dq FRAGMENT model_shadow) +AUTOSCRIBE_PROGRAM(NAME skin_model_shadow_fade_dq FRAGMENT model_shadow_fade) + +AUTOSCRIBE_PROGRAM(NAME model_fade) +AUTOSCRIBE_PROGRAM(NAME model_unlit_fade VERTEX model_fade) +AUTOSCRIBE_PROGRAM(NAME model_translucent_unlit_fade VERTEX model_fade) +AUTOSCRIBE_PROGRAM(NAME model_normal_map_fade) +AUTOSCRIBE_PROGRAM(NAME model_translucent_normal_map_fade VERTEX model_translucent_normal_map) +AUTOSCRIBE_PROGRAM(NAME model_translucent_fade VERTEX model_fade) +AUTOSCRIBE_PROGRAM(NAME model_lightmap_fade) +AUTOSCRIBE_PROGRAM(NAME model_lightmap_normal_map_fade) + +AUTOSCRIBE_PROGRAM(NAME zone_drawKeyLight VERTEX gpu::vertex::DrawTransformUnitQuad) +AUTOSCRIBE_PROGRAM(NAME zone_drawSkybox VERTEX gpu::vertex::DrawTransformUnitQuad) +AUTOSCRIBE_PROGRAM(NAME zone_drawAmbient VERTEX gpu::vertex::DrawTransformUnitQuad) + +AUTOSCRIBE_PROGRAM(NAME toneMapping VERTEX gpu::vertex::DrawViewportQuadTransformTexcoord) +AUTOSCRIBE_PROGRAM(NAME velocityBuffer_cameraMotion VERTEX gpu::vertex::DrawViewportQuadTransformTexcoord) + +set(TARGET_NAME entities-renderer) +AUTOSCRIBE_SHADER_LIB(gpu graphics procedural render render-utils) +AUTOSCRIBE_PROGRAM(NAME polyvox) +AUTOSCRIBE_PROGRAM(NAME polyvox_fade) +AUTOSCRIBE_PROGRAM(NAME paintStroke) +AUTOSCRIBE_PROGRAM(NAME textured_particle) + +set(TARGET_NAME shaders) +autoscribe_shader_finish() +setup_hifi_library(Gui) +link_hifi_libraries(shared) + diff --git a/libraries/shaders/Shaders.cpp.in b/libraries/shaders/Shaders.cpp.in new file mode 100644 index 0000000000..795367cc4e --- /dev/null +++ b/libraries/shaders/Shaders.cpp.in @@ -0,0 +1,11 @@ +#include "Shaders.h" + +namespace shader { + +uint32_t all_programs[] = { +@SHADER_PROGRAMS_ARRAY@ + INVALID_SHADER +}; + +} + diff --git a/libraries/shaders/Shaders.h.in b/libraries/shaders/Shaders.h.in new file mode 100644 index 0000000000..fd9b5c9ba9 --- /dev/null +++ b/libraries/shaders/Shaders.h.in @@ -0,0 +1,14 @@ +#include +#include + +namespace shader { + +@SHADER_ENUMS@ + +extern uint32_t all_programs[]; + +static const uint32_t INVALID_SHADER = (uint32_t)-1; + +std::string loadShaderSource(uint32_t shaderId); +} + diff --git a/libraries/shaders/shaders.qrc.in b/libraries/shaders/shaders.qrc.in new file mode 100644 index 0000000000..6078b4a9e9 --- /dev/null +++ b/libraries/shaders/shaders.qrc.in @@ -0,0 +1,6 @@ + + + +@SHADER_QRC@ + + \ No newline at end of file diff --git a/libraries/shaders/src/shaders/ShadersCommon.cpp b/libraries/shaders/src/shaders/ShadersCommon.cpp new file mode 100644 index 0000000000..03c8bd2918 --- /dev/null +++ b/libraries/shaders/src/shaders/ShadersCommon.cpp @@ -0,0 +1,16 @@ +#include +#include + +namespace shader { + +std::string loadShaderSource(uint32_t shaderId) { + static std::once_flag once; + std::call_once(once, [] { + Q_INIT_RESOURCE(shaders); + }); + auto shaderPath = std::string(":/shaders/") + std::to_string(shaderId); + auto shaderData = FileUtils::readFile(shaderPath.c_str()); + return shaderData.toStdString(); +} + +} diff --git a/tests/shaders/CMakeLists.txt b/tests/shaders/CMakeLists.txt new file mode 100644 index 0000000000..08678c1c26 --- /dev/null +++ b/tests/shaders/CMakeLists.txt @@ -0,0 +1,9 @@ + +# Declare dependencies +macro (setup_testcase_dependencies) + # link in the shared libraries + link_hifi_libraries(shared test-utils gpu shaders gl ${PLATFORM_GL_BACKEND}) + package_libraries_for_deployment() +endmacro () + +setup_hifi_testcase(Gui) diff --git a/tests/shaders/src/ShaderTests.cpp b/tests/shaders/src/ShaderTests.cpp new file mode 100644 index 0000000000..3953c5042c --- /dev/null +++ b/tests/shaders/src/ShaderTests.cpp @@ -0,0 +1,100 @@ +// +// ShaderTests.cpp +// tests/octree/src +// +// Created by Andrew Meadows on 2016.02.19 +// Copyright 2016 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "ShaderTests.h" + +#include +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include + +QTEST_MAIN(ShaderTests) + +void ShaderTests::initTestCase() { + getDefaultOpenGLSurfaceFormat(); + _canvas.create(); + if (!_canvas.makeCurrent()) { + qFatal("Unable to make test GL context current"); + } + gl::initModuleGl(); + gpu::Context::init(); + _gpuContext = std::make_shared(); +} + +void ShaderTests::cleanupTestCase() { +} + + +QVariantList slotSetToVariantList(const gpu::Shader::SlotSet& slotSet) { + QVariantList result; + for (const auto slot : slotSet) { + QVariantMap inputMap; + inputMap["name"] = slot._name.c_str(); + inputMap["location"] = slot._location; + result.append(inputMap); + } + return result; +} + +std::string reflect(const gpu::ShaderPointer& program) { + QVariantMap result; + if (!program->getInputs().empty()) { + result["inputs"] = slotSetToVariantList(program->getInputs()); + } + if (!program->getOutputs().empty()) { + result["outputs"] = slotSetToVariantList(program->getOutputs()); + } + if (!program->getResourceBuffers().empty()) { + result["storage_buffers"] = slotSetToVariantList(program->getResourceBuffers()); + } + if (!program->getSamplers().empty()) { + result["samplers"] = slotSetToVariantList(program->getSamplers()); + } + if (!program->getTextures().empty()) { + result["textures"] = slotSetToVariantList(program->getTextures()); + } + if (!program->getUniforms().empty()) { + result["uniforms"] = slotSetToVariantList(program->getUniforms()); + } + if (!program->getUniformBuffers().empty()) { + result["uniform_buffers"] = slotSetToVariantList(program->getUniformBuffers()); + } + + return QJsonDocument::fromVariant(result).toJson(QJsonDocument::Indented).toStdString(); +} + +void ShaderTests::testShaderLoad() { + size_t index = 0; + uint32_t INVALID_SHADER_ID = (uint32_t)-1; + while (INVALID_SHADER_ID != shader::all_programs[index]) { + auto programId = shader::all_programs[index]; + uint32_t vertexId = programId >> 16; + uint32_t fragmentId = programId & 0xFF; + auto vertexSource = shader::loadShaderSource(vertexId); + QVERIFY(!vertexSource.empty()); + auto fragmentSource = shader::loadShaderSource(fragmentId); + QVERIFY(!fragmentSource.empty()); + auto program = gpu::Shader::createProgram(programId); + QVERIFY(gpu::Shader::makeProgram(*program, {})); + auto reflectionData = reflect(program); + std::ofstream(std::string("d:/reflection/") + std::to_string(index) + std::string(".json")) << reflectionData; + ++index; + } +} diff --git a/tests/shaders/src/ShaderTests.h b/tests/shaders/src/ShaderTests.h new file mode 100644 index 0000000000..2b731899cc --- /dev/null +++ b/tests/shaders/src/ShaderTests.h @@ -0,0 +1,29 @@ +// +// Created by Bradley Austin Davis on 2018/06/21 +// Copyright 2013-2018 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_ShaderTests_h +#define hifi_ShaderTests_h + +#include +#include +#include + +class ShaderTests : public QObject { + Q_OBJECT + +private slots: + void initTestCase(); + void cleanupTestCase(); + void testShaderLoad(); + +private: + OffscreenGLCanvas _canvas; + gpu::ContextPointer _gpuContext; +}; + +#endif // hifi_ViewFruxtumTests_h From ae8f841912c3d3c60928aed01f987228cdb60f56 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Thu, 24 May 2018 10:53:27 -0700 Subject: [PATCH 21/37] Shader refactoring for explicit bindings --- CMakeLists.txt | 1 + android/app/build.gradle | 1 + android/build.gradle | 31 +- cmake/compiler.cmake | 45 +-- cmake/externals/json/CMakeLists.txt | 22 ++ cmake/macros/AutoScribeShader.cmake | 48 ++- cmake/macros/TargetJson.cmake | 13 + cmake/modules/FindJSON.cmake | 19 + interface/src/Application.cpp | 2 - .../src/workload/GameWorkloadRenderer.cpp | 12 +- .../InterleavedSrgbToLinear.slf | 21 + .../display-plugins/OpenGLDisplayPlugin.cpp | 40 +- .../src/display-plugins/SrgbToLinear.slf | 22 ++ .../display-plugins/hmd/HmdDisplayPlugin.cpp | 6 +- .../display-plugins/hmd/HmdDisplayPlugin.h | 1 - .../stereo/InterleavedStereoDisplayPlugin.cpp | 33 +- .../RenderableParticleEffectEntityItem.cpp | 10 +- .../src/RenderablePolyLineEntityItem.cpp | 15 - .../src/RenderablePolyVoxEntityItem.cpp | 22 +- .../src/RenderableShapeEntityItem.cpp | 4 +- .../src/entities-renderer/ShaderConstants.h | 61 +++ .../entities-renderer/src/paintStroke.slf | 10 +- .../entities-renderer/src/paintStroke.slv | 6 +- .../src/paintStroke_fade.slf | 14 +- .../src/paintStroke_fade.slv | 10 +- libraries/entities-renderer/src/polyvox.slf | 16 +- libraries/entities-renderer/src/polyvox.slv | 8 +- .../entities-renderer/src/polyvox_fade.slf | 19 +- .../entities-renderer/src/polyvox_fade.slv | 10 +- .../src/textured_particle.slf | 11 +- .../src/textured_particle.slv | 8 +- libraries/gl/src/gl/GLShaders.cpp | 321 ++++++++++----- libraries/gl/src/gl/GLShaders.h | 114 ++++-- .../gpu-gl-common/src/gpu/gl/GLBackend.cpp | 74 +++- .../gpu-gl-common/src/gpu/gl/GLBackend.h | 55 ++- .../src/gpu/gl/GLBackendPipeline.cpp | 79 ++-- .../src/gpu/gl/GLBackendShader.cpp | 223 +---------- .../src/gpu/gl/GLBackendTransform.cpp | 5 +- .../gpu-gl-common/src/gpu/gl/GLPipeline.cpp | 3 +- .../gpu-gl-common/src/gpu/gl/GLPipeline.h | 2 +- .../gpu-gl-common/src/gpu/gl/GLShader.cpp | 47 --- libraries/gpu-gl-common/src/gpu/gl/GLShader.h | 21 +- .../src/gpu/gl/GLTextureTransfer.cpp | 5 +- .../gpu-gl/src/gpu/gl/GLDesktopBackend.cpp | 4 - libraries/gpu-gl/src/gpu/gl41/GL41Backend.h | 5 +- .../gpu-gl/src/gpu/gl41/GL41BackendShader.cpp | 158 ++++---- .../src/gpu/gl41/GL41BackendTransform.cpp | 4 +- libraries/gpu-gl/src/gpu/gl45/GL45Backend.cpp | 16 + libraries/gpu-gl/src/gpu/gl45/GL45Backend.h | 13 +- .../gpu-gl/src/gpu/gl45/GL45BackendShader.cpp | 149 ------- .../src/gpu/gl45/GL45BackendTransform.cpp | 6 +- libraries/gpu-gles/src/gpu/gl/GLESBackend.cpp | 4 - libraries/gpu-gles/src/gpu/gles/GLESBackend.h | 5 +- .../src/gpu/gles/GLESBackendShader.cpp | 90 ----- .../src/gpu/gles/GLESBackendTransform.cpp | 6 +- libraries/gpu/src/gpu/Batch.h | 21 +- libraries/gpu/src/gpu/Context.cpp | 15 - libraries/gpu/src/gpu/Context.h | 11 +- libraries/gpu/src/gpu/DrawColor.slf | 9 +- libraries/gpu/src/gpu/DrawColoredTexture.slf | 11 +- .../gpu/DrawTexcoordRectTransformUnitQuad.slv | 8 +- libraries/gpu/src/gpu/DrawTexture.slf | 8 +- .../gpu/src/gpu/DrawTextureMirroredX.slf | 8 +- libraries/gpu/src/gpu/DrawTextureOpaque.slf | 10 +- .../gpu/src/gpu/DrawTransformUnitQuad.slv | 4 +- .../src/gpu/DrawTransformVertexPosition.slv | 6 +- .../gpu/src/gpu/DrawUnitQuadTexcoord.slv | 4 +- libraries/gpu/src/gpu/DrawVertexPosition.slv | 4 +- .../gpu/DrawViewportQuadTransformTexcoord.slv | 4 +- libraries/gpu/src/gpu/DrawWhite.slf | 4 +- libraries/gpu/src/gpu/Inputs.slh | 25 +- libraries/gpu/src/gpu/Shader.cpp | 144 +++++-- libraries/gpu/src/gpu/Shader.h | 238 +++++------ libraries/gpu/src/gpu/ShaderConstants.h | 126 ++++++ libraries/gpu/src/gpu/Transform.slh | 15 +- libraries/gpu/src/gpu/null/NullBackend.h | 1 - libraries/graphics/src/graphics/Light.slh | 9 +- libraries/graphics/src/graphics/Material.slh | 4 +- .../src/graphics}/MaterialTextures.slh | 24 +- .../graphics/src/graphics/ShaderConstants.h | 78 ++++ libraries/graphics/src/graphics/Skybox.cpp | 31 +- libraries/graphics/src/graphics/Skybox.h | 5 +- libraries/graphics/src/graphics/skybox.slf | 33 +- libraries/graphics/src/graphics/skybox.slv | 2 +- libraries/procedural/src/procedural/Logging.h | 2 +- .../procedural/src/procedural/Procedural.cpp | 175 ++++----- .../procedural/src/procedural/Procedural.h | 18 +- .../src/procedural/ProceduralCommon.slf | 52 --- .../src/procedural/ProceduralCommon.slh | 56 +++ .../src/procedural/ProceduralSkybox.cpp | 8 +- .../src/procedural/ShaderConstants.h | 72 ++++ .../src/procedural/proceduralSkybox.slf | 45 +++ .../src/AmbientOcclusionEffect.cpp | 64 +-- .../render-utils/src/AntialiasingEffect.cpp | 112 ++---- .../render-utils/src/AntialiasingEffect.h | 1 - libraries/render-utils/src/BloomApply.slf | 14 +- libraries/render-utils/src/BloomEffect.cpp | 40 +- libraries/render-utils/src/BloomThreshold.slf | 11 +- .../src/CauterizedMeshPartPayload.cpp | 3 +- .../render-utils/src/DebugDeferredBuffer.cpp | 128 +++--- .../render-utils/src/DeferredBufferRead.slh | 21 +- .../render-utils/src/DeferredBufferWrite.slh | 9 +- .../render-utils/src/DeferredFrameTransform.h | 18 +- .../src/DeferredLightingEffect.cpp | 254 ++++-------- .../render-utils/src/DeferredLightingEffect.h | 8 +- .../render-utils/src/DeferredTransform.slh | 7 +- libraries/render-utils/src/DrawHaze.cpp | 56 ++- libraries/render-utils/src/Fade.slh | 24 +- libraries/render-utils/src/FadeEffect.cpp | 12 +- libraries/render-utils/src/GeometryCache.cpp | 65 +-- libraries/render-utils/src/Haze.slf | 8 +- libraries/render-utils/src/Haze.slh | 5 +- libraries/render-utils/src/Highlight.slf | 2 +- libraries/render-utils/src/Highlight.slh | 6 +- .../render-utils/src/HighlightEffect.cpp | 54 ++- libraries/render-utils/src/HighlightEffect.h | 8 - .../render-utils/src/Highlight_aabox.slv | 13 +- .../render-utils/src/Highlight_filled.slf | 2 +- libraries/render-utils/src/LightAmbient.slh | 3 +- .../render-utils/src/LightClusterGrid.slh | 8 +- libraries/render-utils/src/LightClusters.cpp | 106 ++--- .../render-utils/src/LightDirectional.slh | 2 +- libraries/render-utils/src/LightLocal.slh | 13 +- libraries/render-utils/src/LightPoint.slh | 2 +- libraries/render-utils/src/LightSpot.slh | 2 +- libraries/render-utils/src/LightingModel.slh | 225 +---------- .../render-utils/src/MeshPartPayload.cpp | 4 +- .../render-utils/src/RenderCommonTask.cpp | 21 +- .../render-utils/src/RenderDeferredTask.cpp | 44 +-- .../render-utils/src/RenderForwardTask.cpp | 22 +- .../render-utils/src/RenderPipelines.cpp | 61 +-- libraries/render-utils/src/ShadingModel.slh | 237 +++++++++++ libraries/render-utils/src/Shadow.slh | 3 +- libraries/render-utils/src/ShadowCore.slh | 2 +- libraries/render-utils/src/Skinning.slh | 4 +- .../render-utils/src/StencilMaskPass.cpp | 6 +- .../render-utils/src/SubsurfaceScattering.cpp | 73 ++-- .../render-utils/src/SubsurfaceScattering.slh | 8 +- .../render-utils/src/SurfaceGeometryPass.cpp | 89 ++--- .../render-utils/src/ToneMappingEffect.cpp | 17 +- .../render-utils/src/VelocityBufferPass.cpp | 21 +- libraries/render-utils/src/ZoneRenderer.cpp | 52 ++- libraries/render-utils/src/ZoneRenderer.h | 9 - libraries/render-utils/src/animdebugdraw.slf | 6 +- libraries/render-utils/src/animdebugdraw.slv | 4 +- .../src/debug_deferred_buffer.slf | 22 +- .../src/debug_deferred_buffer.slv | 4 +- libraries/render-utils/src/deferred_light.slv | 6 +- .../src/deferred_light_limited.slv | 4 +- .../render-utils/src/deferred_light_point.slv | 10 +- .../render-utils/src/deferred_light_spot.slv | 8 +- .../src/directional_ambient_light.slf | 5 +- .../src/directional_ambient_light_shadow.slf | 7 +- .../src/directional_skybox_light.slf | 5 +- .../src/directional_skybox_light_shadow.slf | 7 +- .../render-utils/src/drawWorkloadProxy.slv | 8 +- .../render-utils/src/drawWorkloadView.slf | 3 +- .../render-utils/src/drawWorkloadView.slv | 19 +- libraries/render-utils/src/forward_model.slf | 25 +- .../src/forward_model_normal_map.slf | 26 +- .../src/forward_model_translucent.slf | 21 +- .../render-utils/src/forward_model_unlit.slf | 9 +- libraries/render-utils/src/forward_simple.slf | 16 +- .../src/forward_simple_textured.slf | 16 +- .../forward_simple_textured_transparent.slf | 16 +- .../src/forward_simple_textured_unlit.slf | 12 +- .../src/forward_simple_transparent.slf | 14 +- libraries/render-utils/src/fxaa.slf | 10 +- libraries/render-utils/src/fxaa.slv | 2 +- libraries/render-utils/src/fxaa_blend.slf | 10 +- libraries/render-utils/src/glowLine.slf | 8 +- libraries/render-utils/src/glowLine.slv | 20 +- libraries/render-utils/src/grid.slf | 14 +- libraries/render-utils/src/hmd_ui.slf | 9 +- libraries/render-utils/src/hmd_ui.slv | 6 +- .../src/lightClusters_drawClusterContent.slf | 6 +- .../src/lightClusters_drawClusterContent.slv | 4 +- .../lightClusters_drawClusterFromDepth.slf | 6 +- .../lightClusters_drawClusterFromDepth.slv | 4 +- .../src/lightClusters_drawGrid.slf | 6 +- .../src/lightClusters_drawGrid.slv | 4 +- .../src/local_lights_drawOutline.slf | 5 +- .../render-utils/src/local_lights_shading.slf | 6 +- libraries/render-utils/src/model.slf | 15 +- libraries/render-utils/src/model.slv | 18 +- libraries/render-utils/src/model_fade.slf | 14 +- libraries/render-utils/src/model_fade.slv | 20 +- libraries/render-utils/src/model_lightmap.slf | 15 +- libraries/render-utils/src/model_lightmap.slv | 14 +- .../render-utils/src/model_lightmap_fade.slf | 14 +- .../render-utils/src/model_lightmap_fade.slv | 16 +- .../src/model_lightmap_normal_map.slf | 16 +- .../src/model_lightmap_normal_map.slv | 17 +- .../src/model_lightmap_normal_map_fade.slf | 18 +- .../src/model_lightmap_normal_map_fade.slv | 20 +- .../render-utils/src/model_normal_map.slf | 16 +- .../render-utils/src/model_normal_map.slv | 19 +- .../src/model_normal_map_fade.slf | 20 +- .../src/model_normal_map_fade.slv | 22 +- libraries/render-utils/src/model_shadow.slf | 2 +- .../render-utils/src/model_shadow_fade.slf | 7 +- .../render-utils/src/model_shadow_fade.slv | 5 +- .../render-utils/src/model_translucent.slf | 28 +- .../render-utils/src/model_translucent.slv | 20 +- .../src/model_translucent_fade.slf | 20 +- .../src/model_translucent_normal_map.slf | 22 +- .../src/model_translucent_normal_map.slv | 22 +- .../src/model_translucent_normal_map_fade.slf | 23 +- .../src/model_translucent_unlit.slf | 12 +- .../src/model_translucent_unlit_fade.slf | 14 +- libraries/render-utils/src/model_unlit.slf | 11 +- .../render-utils/src/model_unlit_fade.slf | 15 +- libraries/render-utils/src/nop.slf | 2 + .../src/render-utils/ShaderConstants.h | 238 +++++++++++ libraries/render-utils/src/sdf_text3D.slf | 11 +- libraries/render-utils/src/sdf_text3D.slv | 6 +- .../src/sdf_text3D_transparent.slf | 11 +- libraries/render-utils/src/simple.slf | 16 +- libraries/render-utils/src/simple.slv | 14 +- libraries/render-utils/src/simple_fade.slf | 18 +- libraries/render-utils/src/simple_fade.slv | 16 +- .../src/simple_opaque_web_browser.slf | 12 +- .../render-utils/src/simple_textured.slf | 14 +- .../render-utils/src/simple_textured_fade.slf | 14 +- .../src/simple_textured_unlit.slf | 12 +- .../src/simple_textured_unlit_fade.slf | 12 +- .../render-utils/src/simple_transparent.slf | 16 +- .../src/simple_transparent_textured.slf | 12 +- .../src/simple_transparent_textured_fade.slf | 18 +- .../src/simple_transparent_textured_unlit.slf | 12 +- ...simple_transparent_textured_unlit_fade.slf | 14 +- .../src/simple_transparent_web_browser.slf | 12 +- libraries/render-utils/src/skin_model.slv | 16 +- libraries/render-utils/src/skin_model_dq.slv | 18 +- .../render-utils/src/skin_model_fade.slv | 18 +- .../render-utils/src/skin_model_fade_dq.slv | 18 +- .../src/skin_model_normal_map.slv | 18 +- .../src/skin_model_normal_map_dq.slv | 19 +- .../src/skin_model_normal_map_fade.slv | 20 +- .../src/skin_model_normal_map_fade_dq.slv | 20 +- .../render-utils/src/skin_model_shadow_dq.slv | 2 +- .../src/skin_model_shadow_fade.slv | 4 +- .../src/skin_model_shadow_fade_dq.slv | 8 +- libraries/render-utils/src/ssao.slh | 8 +- .../render-utils/src/ssao_debugOcclusion.slf | 6 +- .../src/ssao_makeHorizontalBlur.slf | 4 +- .../render-utils/src/ssao_makeOcclusion.slf | 4 +- .../render-utils/src/ssao_makePyramid.slf | 6 +- .../src/ssao_makeVerticalBlur.slf | 4 +- .../render-utils/src/standardDrawTexture.slf | 14 +- .../src/standardTransformPNTC.slv | 10 +- .../render-utils/src/stencil_drawMask.slf | 4 +- .../subsurfaceScattering_drawScattering.slf | 9 +- .../src/subsurfaceScattering_makeLUT.slf | 6 +- .../src/subsurfaceScattering_makeProfile.slf | 6 +- ...surfaceScattering_makeSpecularBeckmann.slf | 6 +- .../src/surfaceGeometry_copyDepth.slf | 6 +- .../surfaceGeometry_downsampleDepthNormal.slf | 13 +- .../src/surfaceGeometry_makeCurvature.slf | 15 +- .../src/surfaceGeometry_makeLinearDepth.slf | 9 +- libraries/render-utils/src/taa.slf | 4 +- libraries/render-utils/src/taa.slh | 16 +- libraries/render-utils/src/taa_blend.slf | 4 +- libraries/render-utils/src/text/Font.cpp | 24 +- libraries/render-utils/src/text/Font.h | 4 - libraries/render-utils/src/toneMapping.slf | 12 +- .../src/velocityBuffer_cameraMotion.slf | 8 +- .../render-utils/src/zone_drawAmbient.slf | 4 +- .../render-utils/src/zone_drawKeyLight.slf | 4 +- .../render-utils/src/zone_drawSkybox.slf | 10 +- libraries/render/src/render/BlurTask.cpp | 26 -- libraries/render/src/render/BlurTask.slh | 8 +- .../render/src/render/DrawSceneOctree.cpp | 48 +-- libraries/render/src/render/DrawSceneOctree.h | 10 - libraries/render/src/render/DrawStatus.cpp | 42 +- libraries/render/src/render/DrawStatus.h | 8 - libraries/render/src/render/DrawTask.cpp | 14 +- libraries/render/src/render/DrawTask.h | 2 - libraries/render/src/render/ResampleTask.cpp | 12 +- libraries/render/src/render/ShapePipeline.cpp | 98 ++--- libraries/render/src/render/ShapePipeline.h | 77 ++-- .../src/render/blurGaussianDepthAwareH.slf | 6 +- .../src/render/blurGaussianDepthAwareV.slf | 6 +- libraries/render/src/render/blurGaussianH.slf | 6 +- libraries/render/src/render/blurGaussianV.slf | 6 +- .../render/src/render/drawCellBounds.slf | 6 +- .../render/src/render/drawCellBounds.slv | 6 +- .../render/src/render/drawItemBounds.slf | 6 +- .../render/src/render/drawItemBounds.slv | 15 +- .../render/src/render/drawItemStatus.slf | 8 +- .../render/src/render/drawItemStatus.slv | 15 +- .../render/src/render/drawLODReticle.slf | 4 +- libraries/shaders/CMakeLists.txt | 16 + .../{Shaders.cpp.in => ShaderEnums.cpp.in} | 4 +- libraries/shaders/ShaderEnums.h.in | 9 + libraries/shaders/Shaders.h.in | 14 - libraries/shaders/src/shaders/Shaders.cpp | 95 +++++ libraries/shaders/src/shaders/Shaders.h | 34 ++ .../shaders/src/shaders/ShadersCommon.cpp | 16 - .../shared/src/shared/GlobalAppProperties.cpp | 1 - libraries/test-utils/src/test-utils/Utils.cpp | 40 ++ libraries/test-utils/src/test-utils/Utils.h | 17 + plugins/openvr/src/OpenVrDisplayPlugin.cpp | 117 +++--- tests-manual/gpu-textures/src/TestHelpers.cpp | 11 - tests-manual/gpu-textures/src/TestHelpers.h | 1 - .../gpu-textures/src/TestTextures.cpp | 6 +- tests-manual/gpu/src/TestHelpers.cpp | 11 - tests-manual/gpu/src/TestHelpers.h | 1 - tests-manual/render-perf/CMakeLists.txt | 3 +- tests-manual/render-perf/src/main.cpp | 370 ++++++++---------- .../render-texture-load/CMakeLists.txt | 2 +- tests-manual/render-texture-load/src/main.cpp | 13 +- tests-manual/render-utils/src/main.cpp | 7 - tests-manual/shaders/CMakeLists.txt | 27 -- tests-manual/shaders/src/main.cpp | 222 ----------- tests/gpu/src/ShaderLoadTest.cpp | 33 +- tests/gpu/src/ShaderLoadTest.h | 5 +- tests/gpu/src/TextureTest.cpp | 26 +- tests/shaders/src/ShaderTests.cpp | 199 +++++++--- tools/CMakeLists.txt | 3 + tools/shreflect/CMakeLists.txt | 10 + tools/shreflect/src/main.cpp | 196 ++++++++++ 322 files changed, 4581 insertions(+), 4305 deletions(-) create mode 100644 cmake/externals/json/CMakeLists.txt create mode 100644 cmake/macros/TargetJson.cmake create mode 100644 cmake/modules/FindJSON.cmake create mode 100644 libraries/display-plugins/src/display-plugins/InterleavedSrgbToLinear.slf create mode 100644 libraries/display-plugins/src/display-plugins/SrgbToLinear.slf create mode 100644 libraries/entities-renderer/src/entities-renderer/ShaderConstants.h create mode 100644 libraries/gpu/src/gpu/ShaderConstants.h rename libraries/{render-utils/src => graphics/src/graphics}/MaterialTextures.slh (90%) create mode 100644 libraries/graphics/src/graphics/ShaderConstants.h delete mode 100644 libraries/procedural/src/procedural/ProceduralCommon.slf create mode 100644 libraries/procedural/src/procedural/ProceduralCommon.slh create mode 100644 libraries/procedural/src/procedural/ShaderConstants.h create mode 100644 libraries/procedural/src/procedural/proceduralSkybox.slf create mode 100644 libraries/render-utils/src/ShadingModel.slh create mode 100644 libraries/render-utils/src/render-utils/ShaderConstants.h rename libraries/shaders/{Shaders.cpp.in => ShaderEnums.cpp.in} (65%) create mode 100644 libraries/shaders/ShaderEnums.h.in delete mode 100644 libraries/shaders/Shaders.h.in create mode 100644 libraries/shaders/src/shaders/Shaders.cpp create mode 100644 libraries/shaders/src/shaders/Shaders.h delete mode 100644 libraries/shaders/src/shaders/ShadersCommon.cpp create mode 100644 libraries/test-utils/src/test-utils/Utils.cpp create mode 100644 libraries/test-utils/src/test-utils/Utils.h delete mode 100644 tests-manual/shaders/CMakeLists.txt delete mode 100644 tests-manual/shaders/src/main.cpp create mode 100644 tools/shreflect/CMakeLists.txt create mode 100644 tools/shreflect/src/main.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 54505717d4..2a01b18a57 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,6 +15,7 @@ include("cmake/compiler.cmake") if (BUILD_SCRIBE_ONLY) add_subdirectory(tools/scribe) + add_subdirectory(tools/shader_reflect) return() endif() diff --git a/android/app/build.gradle b/android/app/build.gradle index d5058a7f40..54405a8746 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -24,6 +24,7 @@ android { '-DANDROID_STL=c++_shared', '-DQT_CMAKE_PREFIX_PATH=' + HIFI_ANDROID_PRECOMPILED + '/qt/lib/cmake', '-DNATIVE_SCRIBE=' + HIFI_ANDROID_PRECOMPILED + '/scribe' + EXEC_SUFFIX, + '-DNATIVE_SHREFLECT=' + HIFI_ANDROID_PRECOMPILED + '/shreflect' + EXEC_SUFFIX, '-DHIFI_ANDROID_PRECOMPILED=' + HIFI_ANDROID_PRECOMPILED, '-DRELEASE_NUMBER=' + RELEASE_NUMBER, '-DRELEASE_TYPE=' + RELEASE_TYPE, diff --git a/android/build.gradle b/android/build.gradle index bc39c30472..b85aba79a1 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -164,18 +164,29 @@ def packages = [ def scribeLocalFile='scribe' + EXEC_SUFFIX - def scribeFile='scribe_linux_x86_64' def scribeChecksum='ca4b904f52f4f993c29175ba96798fa6' def scribeVersion='u_iTrJDaE95i2abTPXOpPZckGBIim53G' + +def shreflectLocalFile='shreflect' + EXEC_SUFFIX +def shreflectFile='shreflect_linux_x86_64' +def shreflectChecksum='d6094a8580066c0b6f4e80b5adfb1d98' +def shreflectVersion='jnrpudh6fptIg6T2.Z6fgKP2ultAdKmE' + if (Os.isFamily(Os.FAMILY_MAC)) { scribeFile = 'scribe_osx_x86_64' scribeChecksum='72db9d32d4e1e50add755570ac5eb749' scribeVersion='DAW0DmnjCRib4MD8x93bgc2Z2MpPojZC' + shreflectFile='shreflect_osx_x86_64' + shreflectChecksum='d613ef0703c21371fee93fd2e54b964f' + shreflectVersion='.rYNzjSFq6WtWDnE5KIKRIAGyJtr__ad' } else if (Os.isFamily(Os.FAMILY_WINDOWS)) { scribeFile = 'scribe_win32_x86_64.exe' scribeChecksum='678e43d290c90fda670c6fefe038a06d' scribeVersion='PuullrA_bPlO9kXZRt8rLe536X1UI.m7' + shreflectFile='shreflect_win32_x86_64.exe' + shreflectChecksum='6f4a77b8cceb3f1bbc655132c3665060' + shreflectVersion='iIyCyza1nelkbI7ihybF59bBlwrfAC3D' } def options = [ @@ -450,11 +461,27 @@ task fixScribePermissions(type: Exec, dependsOn: verifyScribe) { commandLine 'chmod', 'a+x', HIFI_ANDROID_PRECOMPILED + '/' + scribeLocalFile } -task setupScribe(dependsOn: verifyScribe) { } +task downloadShreflect(type: Download) { + src baseUrl + shreflectFile + '?versionId=' + shreflectVersion + dest new File(baseFolder, shreflectLocalFile) + onlyIfNewer true +} + +task verifyShreflect(type: Verify, dependsOn: downloadShreflect) { + src new File(baseFolder, shreflectLocalFile); + checksum shreflectChecksum +} + +task fixShreflectPermissions(type: Exec, dependsOn: verifyShreflect) { + commandLine 'chmod', 'a+x', HIFI_ANDROID_PRECOMPILED + '/' + shreflectLocalFile +} + +task setupScribe(dependsOn: [verifyScribe, verifyShreflect]) { } // On Windows, we don't need to set the executable bit, but on OSX and Unix we do if (!Os.isFamily(Os.FAMILY_WINDOWS)) { setupScribe.dependsOn fixScribePermissions + setupScribe.dependsOn fixShreflectPermissions } task extractGvrBinaries(dependsOn: extractDependencies) { diff --git a/cmake/compiler.cmake b/cmake/compiler.cmake index de9f8a22fa..6ff6fce1d8 100644 --- a/cmake/compiler.cmake +++ b/cmake/compiler.cmake @@ -1,10 +1,12 @@ set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG") +set(CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +if (NOT "${CMAKE_SIZEOF_VOID_P}" EQUAL "8") + message( FATAL_ERROR "Only 64 bit builds supported." ) +endif() if (WIN32) - if (NOT "${CMAKE_SIZEOF_VOID_P}" EQUAL "8") - message( FATAL_ERROR "Only 64 bit builds supported." ) - endif() - add_definitions(-DNOMINMAX -D_CRT_SECURE_NO_WARNINGS) if (NOT WINDOW_SDK_PATH) @@ -52,32 +54,27 @@ endif() if (ANDROID) # assume that the toolchain selected for android has C++11 support - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14") +elseif(APPLE) + set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LANGUAGE_STANDARD "c++14") + set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LIBRARY "libc++") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --stdlib=libc++") + if (CMAKE_GENERATOR STREQUAL "Xcode") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g") + set(CMAKE_XCODE_ATTRIBUTE_GCC_GENERATE_DEBUGGING_SYMBOLS[variant=Release] "YES") + set(CMAKE_XCODE_ATTRIBUTE_DEBUG_INFORMATION_FORMAT[variant=Release] "dwarf-with-dsym") + set(CMAKE_XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=Release] "YES") + endif() elseif ((NOT MSVC12) AND (NOT MSVC14)) include(CheckCXXCompilerFlag) - CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11) - CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X) - if (COMPILER_SUPPORTS_CXX11) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - elseif(COMPILER_SUPPORTS_CXX0X) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") + CHECK_CXX_COMPILER_FLAG("-std=c++14" COMPILER_SUPPORTS_CXX14) + if (COMPILER_SUPPORTS_CXX14) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14") else() message(FATAL_ERROR "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.") endif() endif () -if (CMAKE_GENERATOR STREQUAL "Xcode") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g") - set(CMAKE_XCODE_ATTRIBUTE_GCC_GENERATE_DEBUGGING_SYMBOLS[variant=Release] "YES") - set(CMAKE_XCODE_ATTRIBUTE_DEBUG_INFORMATION_FORMAT[variant=Release] "dwarf-with-dsym") - set(CMAKE_XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=Release] "YES") -endif() - -if (APPLE) - set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LANGUAGE_STANDARD "c++11") - set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LIBRARY "libc++") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --stdlib=libc++") -endif () if (NOT ANDROID_LIB_DIR) set(ANDROID_LIB_DIR $ENV{ANDROID_LIB_DIR}) @@ -110,4 +107,4 @@ if (APPLE) # set that as the SDK to use set(CMAKE_OSX_SYSROOT ${_OSX_DESIRED_SDK_PATH}/MacOSX${OSX_SDK}.sdk) endif () -endif () \ No newline at end of file +endif () diff --git a/cmake/externals/json/CMakeLists.txt b/cmake/externals/json/CMakeLists.txt new file mode 100644 index 0000000000..91bdb09fc8 --- /dev/null +++ b/cmake/externals/json/CMakeLists.txt @@ -0,0 +1,22 @@ +set(EXTERNAL_NAME json) + +include(ExternalProject) +ExternalProject_Add( + ${EXTERNAL_NAME} + URL https://hifi-public.s3.amazonaws.com/dependencies/json_3.1.2.zip + URL_MD5 94dbf6ea25a7569ddc0ab6e20862cf16 + BINARY_DIR ${EXTERNAL_PROJECT_PREFIX}/build + CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH= ${EXTERNAL_ARGS} + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + INSTALL_COMMAND "" + LOG_DOWNLOAD 1 +) + +# Hide this external target (for ide users) +set_target_properties(${EXTERNAL_NAME} PROPERTIES FOLDER "hidden/externals") + +ExternalProject_Get_Property(${EXTERNAL_NAME} SOURCE_DIR) + +string(TOUPPER ${EXTERNAL_NAME} EXTERNAL_NAME_UPPER) +set(${EXTERNAL_NAME_UPPER}_INCLUDE_DIRS ${SOURCE_DIR} CACHE PATH "List of json include directories") diff --git a/cmake/macros/AutoScribeShader.cmake b/cmake/macros/AutoScribeShader.cmake index 7d1b5395b9..03eaa2842f 100755 --- a/cmake/macros/AutoScribeShader.cmake +++ b/cmake/macros/AutoScribeShader.cmake @@ -86,23 +86,26 @@ macro(AUTOSCRIBE_APPEND_SHADER_SOURCES) endmacro() macro(AUTOSCRIBE_SHADER_LIB) - set(GLOBAL_SHADER_SOURCES "") - set(HIFI_LIBRARIES_SHADER_INCLUDE_FILES "") + unset(HIFI_LIBRARIES_SHADER_INCLUDE_FILES) set(SRC_FOLDER "${CMAKE_SOURCE_DIR}/libraries/${TARGET_NAME}/src") + file(GLOB_RECURSE SHADER_INCLUDE_FILES ${SRC_FOLDER}/*.slh) file(GLOB_RECURSE SHADER_VERTEX_FILES ${SRC_FOLDER}/*.slv) file(GLOB_RECURSE SHADER_FRAGMENT_FILES ${SRC_FOLDER}/*.slf) file(GLOB_RECURSE SHADER_GEOMETRY_FILES ${SRC_FOLDER}/*.slg) file(GLOB_RECURSE SHADER_COMPUTE_FILES ${SRC_FOLDER}/*.slc) + unset(SHADER_SOURCE_FILES) list(APPEND SHADER_SOURCE_FILES ${SHADER_VERTEX_FILES}) list(APPEND SHADER_SOURCE_FILES ${SHADER_FRAGMENT_FILES}) list(APPEND SHADER_SOURCE_FILES ${SHADER_GEOMETRY_FILES}) list(APPEND SHADER_SOURCE_FILES ${SHADER_COMPUTE_FILES}) - list(APPEND GLOBAL_SHADER_SOURCES ${SHADER_SOURCE_FILES}) - list(APPEND GLOBAL_SHADER_SOURCES ${SHADER_INCLUDE_FILES}) - AUTOSCRIBE_APPEND_SHADER_SOURCES(${GLOBAL_SHADER_SOURCES}) + unset(LOCAL_SHADER_SOURCES) + list(APPEND LOCAL_SHADER_SOURCES ${SHADER_SOURCE_FILES}) + list(APPEND LOCAL_SHADER_SOURCES ${SHADER_INCLUDE_FILES}) + + AUTOSCRIBE_APPEND_SHADER_SOURCES(${LOCAL_SHADER_SOURCES}) file(RELATIVE_PATH RELATIVE_LIBRARY_DIR_PATH ${CMAKE_CURRENT_SOURCE_DIR} "${HIFI_LIBRARY_DIR}") foreach(HIFI_LIBRARY ${ARGN}) @@ -157,6 +160,8 @@ macro(PROCESS_SHADER_FILE) file(TO_CMAKE_PATH "${AUTOSCRIBE_SHADER_RETURN}" AUTOSCRIBE_GENERATED_FILE) set_property(SOURCE ${AUTOSCRIBE_GENERATED_FILE} PROPERTY SKIP_AUTOMOC ON) source_group("Compiled/${SHADER_LIB}" FILES ${AUTOSCRIBE_GENERATED_FILE}) + set(REFLECTED_SHADER "${AUTOSCRIBE_GENERATED_FILE}.json") + source_group("Reflected/${SHADER_LIB}" FILES ${REFLECTED_SHADER}) list(APPEND COMPILED_SHADERS ${AUTOSCRIBE_GENERATED_FILE}) get_filename_component(ENUM_NAME ${SHADER} NAME_WE) string(CONCAT SHADER_ENUMS "${SHADER_ENUMS}" "${ENUM_NAME} = ${SHADER_COUNT},\n") @@ -239,27 +244,48 @@ macro(AUTOSCRIBE_SHADER_FINISH) string(CONCAT SHADER_PROGRAMS_ARRAY "${SHADER_PROGRAMS_ARRAY}" " ${SHADER_PROGRAM},\n") endforeach() + set(SHREFLECT_COMMAND shreflect) + set(SHREFLECT_DEPENDENCY shreflect) + if (ANDROID) + set(SHREFLECT_COMMAND ${NATIVE_SHREFLECT}) + unset(SHREFLECT_DEPENDENCY) + endif() + set(SHADER_COUNT 0) foreach(COMPILED_SHADER ${COMPILED_SHADERS}) + set(REFLECTED_SHADER "${COMPILED_SHADER}.json") + list(APPEND COMPILED_SHADER_REFLECTIONS ${REFLECTED_SHADER}) string(CONCAT SHADER_QRC "${SHADER_QRC}" "${COMPILED_SHADER}\n") + string(CONCAT SHADER_QRC "${SHADER_QRC}" "${REFLECTED_SHADER}\n") MATH(EXPR SHADER_COUNT "${SHADER_COUNT}+1") + add_custom_command( + OUTPUT ${REFLECTED_SHADER} + COMMAND ${SHREFLECT_COMMAND} ${COMPILED_SHADER} + DEPENDS ${SHREFLECT_DEPENDENCY} ${COMPILED_SHADER} + ) endforeach() + + # Custom targets required to force generation of the shaders via scribe + add_custom_target(compiled_shaders SOURCES ${COMPILED_SHADERS}) + add_custom_target(reflected_shaders SOURCES ${COMPILED_SHADER_REFLECTIONS}) + set_target_properties(compiled_shaders PROPERTIES FOLDER "Shaders") + set_target_properties(reflected_shaders PROPERTIES FOLDER "Shaders") configure_file( - Shaders.cpp.in - ${CMAKE_CURRENT_BINARY_DIR}/shaders/Shaders.cpp + ShaderEnums.cpp.in + ${CMAKE_CURRENT_BINARY_DIR}/shaders/ShaderEnums.cpp ) configure_file( - Shaders.h.in - ${CMAKE_CURRENT_BINARY_DIR}/shaders/Shaders.h + ShaderEnums.h.in + ${CMAKE_CURRENT_BINARY_DIR}/shaders/ShaderEnums.h ) configure_file( shaders.qrc.in ${CMAKE_CURRENT_BINARY_DIR}/shaders.qrc ) - set(AUTOSCRIBE_SHADER_LIB_SRC "${CMAKE_CURRENT_BINARY_DIR}/shaders/Shaders.h;${CMAKE_CURRENT_BINARY_DIR}/shaders/Shaders.cpp") + set(AUTOSCRIBE_SHADER_LIB_SRC "${CMAKE_CURRENT_BINARY_DIR}/shaders/ShaderEnums.h;${CMAKE_CURRENT_BINARY_DIR}/shaders/ShaderEnums.cpp") + list(APPEND AUTOSCRIBE_SHADER_LIB_SRC ${COMPILED_SHADERS}) set(QT_RESOURCES_FILE ${CMAKE_CURRENT_BINARY_DIR}/shaders.qrc) get_property(GLOBAL_SHADER_SOURCES GLOBAL PROPERTY GLOBAL_SHADER_SOURCES) list(REMOVE_DUPLICATES GLOBAL_SHADER_SOURCES) - #add_custom_target(shader-sources SOURCES ${GLOBAL_SHADER_SOURCES} ${COMPILED_SHADERS} "${CMAKE_BINARY_DIR}/shaders/Shaders.h") endmacro() diff --git a/cmake/macros/TargetJson.cmake b/cmake/macros/TargetJson.cmake new file mode 100644 index 0000000000..057024cd0a --- /dev/null +++ b/cmake/macros/TargetJson.cmake @@ -0,0 +1,13 @@ +# +# Created by Bradley Austin Davis on 2018/07/22 +# Copyright 2013-2018 High Fidelity, Inc. +# +# Distributed under the Apache License, Version 2.0. +# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +# +macro(TARGET_JSON) + add_dependency_external_projects(json) + find_package(JSON REQUIRED) + message("JSON_INCLUDE_DIRS ${JSON_INCLUDE_DIRS}") + target_include_directories(${TARGET_NAME} PUBLIC ${JSON_INCLUDE_DIRS}) +endmacro() \ No newline at end of file diff --git a/cmake/modules/FindJSON.cmake b/cmake/modules/FindJSON.cmake new file mode 100644 index 0000000000..d5011bd5dd --- /dev/null +++ b/cmake/modules/FindJSON.cmake @@ -0,0 +1,19 @@ +# +# Created by Bradley Austin Davis on 2018/07/22 +# Copyright 2013-2018 High Fidelity, Inc. +# +# Distributed under the Apache License, Version 2.0. +# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +# + +# setup hints for JSON search +include("${MACRO_DIR}/HifiLibrarySearchHints.cmake") +hifi_library_search_hints("json") + +# locate header +find_path(JSON_INCLUDE_DIRS "json/json.hpp" HINTS ${JSON_SEARCH_DIRS}) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(JSON DEFAULT_MSG JSON_INCLUDE_DIRS) + +mark_as_advanced(JSON_INCLUDE_DIRS JSON_SEARCH_DIRS) \ No newline at end of file diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index b859dc4b66..49b449aa39 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2703,8 +2703,6 @@ void Application::initializeGL() { // contexts _glWidget->makeCurrent(); gpu::Context::init(); - qApp->setProperty(hifi::properties::gl::MAKE_PROGRAM_CALLBACK, - QVariant::fromValue((void*)(&gpu::gl::GLBackend::makeProgram))); _glWidget->makeCurrent(); _gpuContext = std::make_shared(); diff --git a/interface/src/workload/GameWorkloadRenderer.cpp b/interface/src/workload/GameWorkloadRenderer.cpp index c0aaad8100..ae0e0abbeb 100644 --- a/interface/src/workload/GameWorkloadRenderer.cpp +++ b/interface/src/workload/GameWorkloadRenderer.cpp @@ -146,11 +146,6 @@ void GameWorkloadRenderItem::setAllViews(const workload::Views& views) { const gpu::PipelinePointer GameWorkloadRenderItem::getProxiesPipeline() { if (!_drawAllProxiesPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::drawWorkloadProxy); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding("workloadProxiesBuffer", 0)); - gpu::Shader::makeProgram(*program, slotBindings); - auto state = std::make_shared(); state->setDepthTest(true, true, gpu::LESS_EQUAL); /* state->setBlendFunction(true, @@ -168,12 +163,6 @@ const gpu::PipelinePointer GameWorkloadRenderItem::getProxiesPipeline() { const gpu::PipelinePointer GameWorkloadRenderItem::getViewsPipeline() { if (!_drawAllViewsPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::drawWorkloadView); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding("workloadViewsBuffer", 1)); - slotBindings.insert(gpu::Shader::Binding("drawMeshBuffer", 0)); - gpu::Shader::makeProgram(*program, slotBindings); - auto state = std::make_shared(); state->setDepthTest(true, true, gpu::LESS_EQUAL); /* state->setBlendFunction(true, @@ -184,6 +173,7 @@ const gpu::PipelinePointer GameWorkloadRenderItem::getViewsPipeline() { state->setCullMode(gpu::State::CULL_NONE); _drawAllViewsPipeline = gpu::Pipeline::create(program, state); } + return _drawAllViewsPipeline; } diff --git a/libraries/display-plugins/src/display-plugins/InterleavedSrgbToLinear.slf b/libraries/display-plugins/src/display-plugins/InterleavedSrgbToLinear.slf new file mode 100644 index 0000000000..db94594fe9 --- /dev/null +++ b/libraries/display-plugins/src/display-plugins/InterleavedSrgbToLinear.slf @@ -0,0 +1,21 @@ +struct TextureData { + ivec2 textureSize; +}; + +layout(std140, location=0) uniform textureDataBuffer { + TextureData textureData; +}; + +layout(binding=0) uniform sampler2D colorMap; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 outFragColor; + +void main(void) { + ivec2 texCoord = ivec2(floor(varTexCoord0 * textureData.textureSize)); + texCoord.x /= 2; + int row = int(floor(gl_FragCoord.y)); + if (row % 2 > 0) { + texCoord.x += (textureData.textureSize.x / 2); + } + outFragColor = vec4(pow(texelFetch(colorMap, texCoord, 0).rgb, vec3(2.2)), 1.0); +} diff --git a/libraries/display-plugins/src/display-plugins/OpenGLDisplayPlugin.cpp b/libraries/display-plugins/src/display-plugins/OpenGLDisplayPlugin.cpp index b9328e01c3..580bea254a 100644 --- a/libraries/display-plugins/src/display-plugins/OpenGLDisplayPlugin.cpp +++ b/libraries/display-plugins/src/display-plugins/OpenGLDisplayPlugin.cpp @@ -44,33 +44,6 @@ #include "CompositorHelper.h" #include "Logging.h" -const char* SRGB_TO_LINEAR_FRAG = R"SCRIBE( - -// OpenGLDisplayPlugin_present.frag - -uniform sampler2D colorMap; - -in vec2 varTexCoord0; - -out vec4 outFragColor; - -float sRGBFloatToLinear(float value) { - const float SRGB_ELBOW = 0.04045; - - return (value <= SRGB_ELBOW) ? value / 12.92 : pow((value + 0.055) / 1.055, 2.4); -} - -vec3 colorToLinearRGB(vec3 srgb) { - return vec3(sRGBFloatToLinear(srgb.r), sRGBFloatToLinear(srgb.g), sRGBFloatToLinear(srgb.b)); -} - -void main(void) { - outFragColor.a = 1.0; - outFragColor.rgb = colorToLinearRGB(texture(colorMap, varTexCoord0).rgb); -} - -)SCRIBE"; - extern QThread* RENDER_THREAD; class PresentThread : public QThread, public Dependency { @@ -391,10 +364,7 @@ void OpenGLDisplayPlugin::customizeContext() { if (!_presentPipeline) { { - auto vs = gpu::Shader::createVertex(shader::gpu::vertex::DrawUnitQuadTexcoord); - auto ps = gpu::Shader::createPixel(shader::gpu::fragment::DrawTexture); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - gpu::Shader::makeProgram(*program); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::gpu::program::drawTexture); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setDepthTest(gpu::State::DepthTest(false)); state->setScissorEnable(true); @@ -402,10 +372,7 @@ void OpenGLDisplayPlugin::customizeContext() { } { - auto vs = gpu::Shader::createVertex(shader::gpu::vertex::DrawUnitQuadTexcoord); - auto ps = gpu::Shader::createPixel(std::string(SRGB_TO_LINEAR_FRAG)); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - gpu::Shader::makeProgram(*program); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::display_plugins::program::SrgbToLinear); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setDepthTest(gpu::State::DepthTest(false)); state->setScissorEnable(true); @@ -416,7 +383,6 @@ void OpenGLDisplayPlugin::customizeContext() { auto vs = gpu::Shader::createVertex(shader::gpu::vertex::DrawUnitQuadTexcoord); auto ps = gpu::Shader::createPixel(shader::gpu::fragment::DrawTexture); gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - gpu::Shader::makeProgram(*program); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setDepthTest(gpu::State::DepthTest(false)); state->setBlendFunction(true, @@ -429,7 +395,6 @@ void OpenGLDisplayPlugin::customizeContext() { auto vs = gpu::Shader::createVertex(shader::gpu::vertex::DrawUnitQuadTexcoord); auto ps = gpu::Shader::createPixel(shader::gpu::fragment::DrawTextureMirroredX); gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - gpu::Shader::makeProgram(*program); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setDepthTest(gpu::State::DepthTest(false)); state->setBlendFunction(true, @@ -442,7 +407,6 @@ void OpenGLDisplayPlugin::customizeContext() { auto vs = gpu::Shader::createVertex(shader::gpu::vertex::DrawTransformUnitQuad); auto ps = gpu::Shader::createPixel(shader::gpu::fragment::DrawTexture); gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - gpu::Shader::makeProgram(*program); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setDepthTest(gpu::State::DepthTest(false)); state->setBlendFunction(true, diff --git a/libraries/display-plugins/src/display-plugins/SrgbToLinear.slf b/libraries/display-plugins/src/display-plugins/SrgbToLinear.slf new file mode 100644 index 0000000000..c2bcfb5cb3 --- /dev/null +++ b/libraries/display-plugins/src/display-plugins/SrgbToLinear.slf @@ -0,0 +1,22 @@ +// OpenGLDisplayPlugin_present.frag + +layout(binding = 0) uniform sampler2D colorMap; + +layout(location = 0) in vec2 varTexCoord0; + +layout(location = 0) out vec4 outFragColor; + +float sRGBFloatToLinear(float value) { + const float SRGB_ELBOW = 0.04045; + + return (value <= SRGB_ELBOW) ? value / 12.92 : pow((value + 0.055) / 1.055, 2.4); +} + +vec3 colorToLinearRGB(vec3 srgb) { + return vec3(sRGBFloatToLinear(srgb.r), sRGBFloatToLinear(srgb.g), sRGBFloatToLinear(srgb.b)); +} + +void main(void) { + outFragColor.a = 1.0; + outFragColor.rgb = colorToLinearRGB(texture(colorMap, varTexCoord0).rgb); +} diff --git a/libraries/display-plugins/src/display-plugins/hmd/HmdDisplayPlugin.cpp b/libraries/display-plugins/src/display-plugins/hmd/HmdDisplayPlugin.cpp index 9966fb4357..d76b211ede 100644 --- a/libraries/display-plugins/src/display-plugins/hmd/HmdDisplayPlugin.cpp +++ b/libraries/display-plugins/src/display-plugins/hmd/HmdDisplayPlugin.cpp @@ -408,9 +408,6 @@ void HmdDisplayPlugin::HUDRenderer::build() { void HmdDisplayPlugin::HUDRenderer::updatePipeline() { if (!pipeline) { auto program = gpu::Shader::createProgram(shader::render_utils::program::hmd_ui); - gpu::Shader::makeProgram(*program, gpu::Shader::BindingSet()); - uniformsLocation = program->getUniformBuffers().findLocation("hudBuffer"); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setDepthTest(gpu::State::DepthTest(true, true, gpu::LESS_EQUAL)); state->setBlendFunction(true, @@ -433,9 +430,8 @@ std::function HmdDis batch.setInputBuffer(gpu::Stream::POSITION, posView); batch.setInputBuffer(gpu::Stream::TEXCOORD, uvView); batch.setIndexBuffer(gpu::UINT16, indices, 0); - uniformsBuffer->setSubData(0, uniforms); - batch.setUniformBuffer(uniformsLocation, uniformsBuffer); + batch.setUniformBuffer(0, uniformsBuffer); auto compositorHelper = DependencyManager::get(); glm::mat4 modelTransform = compositorHelper->getUiTransform(); diff --git a/libraries/display-plugins/src/display-plugins/hmd/HmdDisplayPlugin.h b/libraries/display-plugins/src/display-plugins/hmd/HmdDisplayPlugin.h index fb10084b09..ea11832e94 100644 --- a/libraries/display-plugins/src/display-plugins/hmd/HmdDisplayPlugin.h +++ b/libraries/display-plugins/src/display-plugins/hmd/HmdDisplayPlugin.h @@ -102,7 +102,6 @@ private: gpu::BufferPointer indices; uint32_t indexCount { 0 }; gpu::PipelinePointer pipeline; - int32_t uniformsLocation { -1 }; gpu::BufferPointer uniformsBuffer; diff --git a/libraries/display-plugins/src/display-plugins/stereo/InterleavedStereoDisplayPlugin.cpp b/libraries/display-plugins/src/display-plugins/stereo/InterleavedStereoDisplayPlugin.cpp index fe3f54a9a8..0ae0f9b1b6 100644 --- a/libraries/display-plugins/src/display-plugins/stereo/InterleavedStereoDisplayPlugin.cpp +++ b/libraries/display-plugins/src/display-plugins/stereo/InterleavedStereoDisplayPlugin.cpp @@ -13,43 +13,12 @@ #include #include -static const char* INTERLEAVED_SRGB_TO_LINEAR_FRAG = R"SCRIBE( - -struct TextureData { - ivec2 textureSize; -}; - -layout(std140) uniform textureDataBuffer { - TextureData textureData; -}; - -uniform sampler2D colorMap; - -in vec2 varTexCoord0; - -out vec4 outFragColor; - -void main(void) { - ivec2 texCoord = ivec2(floor(varTexCoord0 * textureData.textureSize)); - texCoord.x /= 2; - int row = int(floor(gl_FragCoord.y)); - if (row % 2 > 0) { - texCoord.x += (textureData.textureSize.x / 2); - } - outFragColor = vec4(pow(texelFetch(colorMap, texCoord, 0).rgb, vec3(2.2)), 1.0); -} - -)SCRIBE"; - const QString InterleavedStereoDisplayPlugin::NAME("3D TV - Interleaved"); void InterleavedStereoDisplayPlugin::customizeContext() { StereoDisplayPlugin::customizeContext(); if (!_interleavedPresentPipeline) { - auto vs = gpu::Shader::createVertex(shader::gpu::vertex::DrawUnitQuadTexcoord); - auto ps = gpu::Shader::createPixel(std::string(INTERLEAVED_SRGB_TO_LINEAR_FRAG)); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - gpu::Shader::makeProgram(*program); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::display_plugins::program::InterleavedSrgbToLinear); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setDepthTest(gpu::State::DepthTest(false)); _interleavedPresentPipeline = gpu::Pipeline::create(program, state); diff --git a/libraries/entities-renderer/src/RenderableParticleEffectEntityItem.cpp b/libraries/entities-renderer/src/RenderableParticleEffectEntityItem.cpp index f5118b3570..18c4921836 100644 --- a/libraries/entities-renderer/src/RenderableParticleEffectEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderableParticleEffectEntityItem.cpp @@ -22,8 +22,6 @@ using namespace render::entities; static uint8_t CUSTOM_PIPELINE_NUMBER = 0; static gpu::Stream::FormatPointer _vertexFormat; static std::weak_ptr _texturedPipeline; -// FIXME: This is interfering with the uniform buffers in DeferredLightingEffect.cpp, so use 12 to avoid collisions -static int32_t PARTICLE_UNIFORM_SLOT { 12 }; static ShapePipelinePointer shapePipelineFactory(const ShapePlumber& plumber, const ShapeKey& key, gpu::Batch& batch) { auto texturedPipeline = _texturedPipeline.lock(); @@ -37,12 +35,6 @@ static ShapePipelinePointer shapePipelineFactory(const ShapePlumber& plumber, co auto program = gpu::Shader::createProgram(shader::entities_renderer::program::textured_particle); _texturedPipeline = texturedPipeline = gpu::Pipeline::create(program, state); - - batch.runLambda([program] { - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("particleBuffer"), PARTICLE_UNIFORM_SLOT)); - gpu::Shader::makeProgram(*program, slotBindings); - }); } return std::make_shared(texturedPipeline, nullptr, nullptr, nullptr); @@ -342,7 +334,7 @@ void ParticleEffectEntityRenderer::doRender(RenderArgs* args) { transform.setRotation(_renderTransform.getRotation()); }); batch.setModelTransform(transform); - batch.setUniformBuffer(PARTICLE_UNIFORM_SLOT, _uniformBuffer); + batch.setUniformBuffer(0, _uniformBuffer); batch.setInputFormat(_vertexFormat); batch.setInputBuffer(0, _particleBuffer, 0, sizeof(GpuParticle)); diff --git a/libraries/entities-renderer/src/RenderablePolyLineEntityItem.cpp b/libraries/entities-renderer/src/RenderablePolyLineEntityItem.cpp index fac2fd5841..25e8e859aa 100644 --- a/libraries/entities-renderer/src/RenderablePolyLineEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderablePolyLineEntityItem.cpp @@ -49,21 +49,6 @@ static render::ShapePipelinePointer shapePipelineFactory(const render::ShapePlum auto fadePS = gpu::Shader::createPixel(std::string(paintStroke_fade_frag)); gpu::ShaderPointer fadeProgram = gpu::Shader::createProgram(fadeVS, fadePS); #endif - batch.runLambda([program -#ifdef POLYLINE_ENTITY_USE_FADE_EFFECT - , fadeProgram -#endif - ] { - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("originalTexture"), PAINTSTROKE_TEXTURE_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("polyLineBuffer"), PAINTSTROKE_UNIFORM_SLOT)); - gpu::Shader::makeProgram(*program, slotBindings); -#ifdef POLYLINE_ENTITY_USE_FADE_EFFECT - slotBindings.insert(gpu::Shader::Binding(std::string("fadeMaskMap"), PAINTSTROKE_TEXTURE_SLOT + 1)); - slotBindings.insert(gpu::Shader::Binding(std::string("fadeParametersBuffer"), PAINTSTROKE_UNIFORM_SLOT + 1)); - gpu::Shader::makeProgram(*fadeProgram, slotBindings); -#endif - }); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setDepthTest(true, true, gpu::LESS_EQUAL); PrepareStencil::testMask(*state); diff --git a/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp b/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp index 0157db4cb0..c11ccb70a0 100644 --- a/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderablePolyVoxEntityItem.cpp @@ -25,6 +25,10 @@ #include #include #include +#include +#include + +#include "entities-renderer/ShaderConstants.h" #include @@ -1556,7 +1560,6 @@ scriptable::ScriptableModelBase RenderablePolyVoxEntityItem::getScriptableModel( using namespace render; using namespace render::entities; -static const int MATERIAL_GPU_SLOT { 3 }; static uint8_t CUSTOM_PIPELINE_NUMBER; static gpu::PipelinePointer _pipelines[2]; static gpu::PipelinePointer _wireframePipelines[2]; @@ -1567,15 +1570,6 @@ ShapePipelinePointer shapePipelineFactory(const ShapePlumber& plumber, const Sha using namespace shader::entities_renderer::program; int programsIds[2] = { polyvox, polyvox_fade }; - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("materialBuffer"), MATERIAL_GPU_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("xMap"), 0)); - slotBindings.insert(gpu::Shader::Binding(std::string("yMap"), 1)); - slotBindings.insert(gpu::Shader::Binding(std::string("zMap"), 2)); -#ifdef POLYVOX_ENTITY_USE_FADE_EFFECT - slotBindings.insert(gpu::Shader::Binding(std::string("fadeMaskMap"), 3)); -#endif - auto state = std::make_shared(); state->setCullMode(gpu::State::CULL_BACK); state->setDepthTest(true, true, gpu::LESS_EQUAL); @@ -1590,11 +1584,6 @@ ShapePipelinePointer shapePipelineFactory(const ShapePlumber& plumber, const Sha // Two sets of pipelines: normal and fading for (auto i = 0; i < 2; i++) { gpu::ShaderPointer program = gpu::Shader::createProgram(programsIds[i]); - - batch.runLambda([program, slotBindings] { - gpu::Shader::makeProgram(*program, slotBindings); - }); - _pipelines[i] = gpu::Pipeline::create(program, state); _wireframePipelines[i] = gpu::Pipeline::create(program, wireframeState); } @@ -1729,8 +1718,7 @@ void PolyVoxEntityRenderer::doRender(RenderArgs* args) { } } - int voxelVolumeSizeLocation = args->_shapePipeline->pipeline->getProgram()->getUniforms().findLocation("voxelVolumeSize"); - batch._glUniform3f(voxelVolumeSizeLocation, _lastVoxelVolumeSize.x, _lastVoxelVolumeSize.y, _lastVoxelVolumeSize.z); + batch._glUniform3f(entities_renderer::slot::uniform::PolyvoxVoxelSize, _lastVoxelVolumeSize.x, _lastVoxelVolumeSize.y, _lastVoxelVolumeSize.z); batch.drawIndexed(gpu::TRIANGLES, (gpu::uint32)_mesh->getNumIndices(), 0); } diff --git a/libraries/entities-renderer/src/RenderableShapeEntityItem.cpp b/libraries/entities-renderer/src/RenderableShapeEntityItem.cpp index b73ceb3269..a1b0eaf9e6 100644 --- a/libraries/entities-renderer/src/RenderableShapeEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderableShapeEntityItem.cpp @@ -32,9 +32,9 @@ static const float SPHERE_ENTITY_SCALE = 0.5f; ShapeEntityRenderer::ShapeEntityRenderer(const EntityItemPointer& entity) : Parent(entity) { - _procedural._vertexSource = gpu::Shader::getVertexShaderSource(shader::render_utils::vertex::simple).getCode(); + _procedural._vertexSource = gpu::Shader::getVertexShaderSource(shader::render_utils::vertex::simple); // FIXME: Setup proper uniform slots and use correct pipelines for forward rendering - _procedural._opaquefragmentSource = gpu::Shader::getFragmentShaderSource(shader::render_utils::fragment::simple).getCode(); + _procedural._opaquefragmentSource = gpu::Shader::getFragmentShaderSource(shader::render_utils::fragment::simple); // FIXME: Transparent procedural entities only seem to work if they use the opaque pipelines //_procedural._transparentfragmentSource = simple_transparent_frag::getSource(); _procedural._transparentfragmentSource = _procedural._opaquefragmentSource; diff --git a/libraries/entities-renderer/src/entities-renderer/ShaderConstants.h b/libraries/entities-renderer/src/entities-renderer/ShaderConstants.h new file mode 100644 index 0000000000..58b0bf5688 --- /dev/null +++ b/libraries/entities-renderer/src/entities-renderer/ShaderConstants.h @@ -0,0 +1,61 @@ +// + +// <@if not ENTITIES_SHADER_CONSTANTS_H@> +// <@def ENTITIES_SHADER_CONSTANTS_H@> + +// Hack comment to absorb the extra '//' scribe prepends + +#ifndef ENTITIES_SHADER_CONSTANTS_H +#define ENTITIES_SHADER_CONSTANTS_H + +// Polyvox +#define ENTITIES_UNIFORM_POLYVOX_VOXEL_SIZE 0 +#define ENTITIES_TEXTURE_POLYVOX_XMAP 0 +#define ENTITIES_TEXTURE_POLYVOX_YMAP 1 +#define ENTITIES_TEXTURE_POLYVOX_ZMAP 2 + + + +// +// Hack Comment + +#endif // ENTITIES_SHADER_CONSTANTS_H + +// <@if 1@> +// Trigger Scribe include +// <@endif@> + +// <@endif@> + +// Hack Comment diff --git a/libraries/entities-renderer/src/paintStroke.slf b/libraries/entities-renderer/src/paintStroke.slf index 738561eccc..718e4608b0 100644 --- a/libraries/entities-renderer/src/paintStroke.slf +++ b/libraries/entities-renderer/src/paintStroke.slf @@ -16,18 +16,18 @@ // the albedo texture -uniform sampler2D originalTexture; +layout(binding=0) uniform sampler2D originalTexture; // the interpolated normal -in vec3 interpolatedNormal; -in vec2 varTexcoord; -in vec4 varColor; +layout(location=0) in vec3 interpolatedNormal; +layout(location=1) in vec2 varTexcoord; +layout(location=2) in vec4 varColor; struct PolyLineUniforms { vec3 color; }; -uniform polyLineBuffer { +layout(binding=0) uniform polyLineBuffer { PolyLineUniforms polyline; }; diff --git a/libraries/entities-renderer/src/paintStroke.slv b/libraries/entities-renderer/src/paintStroke.slv index 0cf9596cce..5e7d9f0ae3 100644 --- a/libraries/entities-renderer/src/paintStroke.slv +++ b/libraries/entities-renderer/src/paintStroke.slv @@ -18,12 +18,12 @@ <$declareStandardTransform()$> // the interpolated normal -out vec3 interpolatedNormal; +layout(location=0) out vec3 interpolatedNormal; //the diffuse texture -out vec2 varTexcoord; +layout(location=1) out vec2 varTexcoord; -out vec4 varColor; +layout(location=2) out vec4 varColor; void main(void) { diff --git a/libraries/entities-renderer/src/paintStroke_fade.slf b/libraries/entities-renderer/src/paintStroke_fade.slf index cc037aeac4..8739c9bb9b 100644 --- a/libraries/entities-renderer/src/paintStroke_fade.slf +++ b/libraries/entities-renderer/src/paintStroke_fade.slf @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// paintStroke_fade.slf +// paintStroke_fade.frag // fragment shader // // Created by Olivier Prat on 19/07/17. @@ -18,19 +18,19 @@ <$declareFadeFragment()$> // the albedo texture -uniform sampler2D originalTexture; +layout(binding=0) uniform sampler2D originalTexture; // the interpolated normal -in vec3 interpolatedNormal; -in vec2 varTexcoord; -in vec4 varColor; -in vec4 _worldPosition; +layout(location=0) in vec3 interpolatedNormal; +layout(location=1) in vec2 varTexcoord; +layout(location=2) in vec4 varColor; +layout(location=3) in vec4 _worldPosition; struct PolyLineUniforms { vec3 color; }; -uniform polyLineBuffer { +layout(binding=0) uniform polyLineBuffer { PolyLineUniforms polyline; }; diff --git a/libraries/entities-renderer/src/paintStroke_fade.slv b/libraries/entities-renderer/src/paintStroke_fade.slv index b6075caaf8..f6fcb18c98 100644 --- a/libraries/entities-renderer/src/paintStroke_fade.slv +++ b/libraries/entities-renderer/src/paintStroke_fade.slv @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// paintStroke_fade.slv +// paintStroke_fade.vert // vertex shader // // Created by Olivier Prat on 19/07/17. @@ -18,13 +18,13 @@ <$declareStandardTransform()$> // the interpolated normal -out vec3 interpolatedNormal; +layout(location=0) out vec3 interpolatedNormal; //the diffuse texture -out vec2 varTexcoord; +layout(location=1) out vec2 varTexcoord; -out vec4 varColor; -out vec4 _worldPosition; +layout(location=2) out vec4 varColor; +layout(location=3) out vec4 _worldPosition; void main(void) { diff --git a/libraries/entities-renderer/src/polyvox.slf b/libraries/entities-renderer/src/polyvox.slf index 50034db48c..ba2fd7031b 100644 --- a/libraries/entities-renderer/src/polyvox.slf +++ b/libraries/entities-renderer/src/polyvox.slf @@ -13,15 +13,17 @@ <@include graphics/Material.slh@> <@include DeferredBufferWrite.slh@> +<@include render-utils/ShaderConstants.h@> +<@include entities-renderer/ShaderConstants.h@> -in vec3 _normal; -in vec4 _position; -in vec4 _worldPosition; +layout(location=RENDER_UTILS_ATTR_NORMAL_MS) in vec3 _normal; +layout(location=RENDER_UTILS_ATTR_POSITION_MS) in vec4 _position; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _worldPosition; -uniform sampler2D xMap; -uniform sampler2D yMap; -uniform sampler2D zMap; -uniform vec3 voxelVolumeSize; +layout(binding=ENTITIES_TEXTURE_POLYVOX_XMAP) uniform sampler2D xMap; +layout(binding=ENTITIES_TEXTURE_POLYVOX_YMAP) uniform sampler2D yMap; +layout(binding=ENTITIES_TEXTURE_POLYVOX_ZMAP) uniform sampler2D zMap; +layout(location=ENTITIES_UNIFORM_POLYVOX_VOXEL_SIZE) uniform vec3 voxelVolumeSize; void main(void) { vec3 worldNormal = cross(dFdy(_worldPosition.xyz), dFdx(_worldPosition.xyz)); diff --git a/libraries/entities-renderer/src/polyvox.slv b/libraries/entities-renderer/src/polyvox.slv index eb8d264a1b..d17974c994 100644 --- a/libraries/entities-renderer/src/polyvox.slv +++ b/libraries/entities-renderer/src/polyvox.slv @@ -11,14 +11,14 @@ // <@include gpu/Inputs.slh@> - <@include gpu/Transform.slh@> +<@include render-utils/ShaderConstants.h@> <$declareStandardTransform()$> -out vec4 _position; -out vec4 _worldPosition; -out vec3 _normal; +layout(location=RENDER_UTILS_ATTR_POSITION_MS) out vec4 _position; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _worldPosition; +layout(location=RENDER_UTILS_ATTR_NORMAL_MS) out vec3 _normal; void main(void) { // standard transform diff --git a/libraries/entities-renderer/src/polyvox_fade.slf b/libraries/entities-renderer/src/polyvox_fade.slf index 4c179a15b6..2247e472ea 100644 --- a/libraries/entities-renderer/src/polyvox_fade.slf +++ b/libraries/entities-renderer/src/polyvox_fade.slf @@ -13,18 +13,21 @@ <@include graphics/Material.slh@> <@include DeferredBufferWrite.slh@> +<@include render-utils/ShaderConstants.h@> +<@include entities-renderer/ShaderConstants.h@> <@include Fade.slh@> -in vec3 _normal; -in vec4 _position; -in vec4 _worldPosition; -in vec4 _worldFadePosition; +layout(location=RENDER_UTILS_ATTR_NORMAL_MS) in vec3 _normal; +layout(location=RENDER_UTILS_ATTR_POSITION_MS) in vec4 _position; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _worldPosition; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _worldFadePosition; -uniform sampler2D xMap; -uniform sampler2D yMap; -uniform sampler2D zMap; -uniform vec3 voxelVolumeSize; +layout(binding=ENTITIES_TEXTURE_POLYVOX_XMAP) uniform sampler2D xMap; +layout(binding=ENTITIES_TEXTURE_POLYVOX_YMAP) uniform sampler2D yMap; +layout(binding=ENTITIES_TEXTURE_POLYVOX_ZMAP) uniform sampler2D zMap; + +layout(location=ENTITIES_UNIFORM_POLYVOX_VOXEL_SIZE) uniform vec3 voxelVolumeSize; // Declare after all samplers to prevent sampler location mix up with voxel shading (sampler locations are hardcoded in RenderablePolyVoxEntityItem) <$declareFadeFragment()$> diff --git a/libraries/entities-renderer/src/polyvox_fade.slv b/libraries/entities-renderer/src/polyvox_fade.slv index 506b5d16e7..97b98f5840 100644 --- a/libraries/entities-renderer/src/polyvox_fade.slv +++ b/libraries/entities-renderer/src/polyvox_fade.slv @@ -12,15 +12,15 @@ // <@include gpu/Inputs.slh@> - <@include gpu/Transform.slh@> +<@include render-utils/ShaderConstants.h@> <$declareStandardTransform()$> -out vec4 _position; -out vec4 _worldPosition; -out vec4 _worldFadePosition; -out vec3 _normal; +layout(location=RENDER_UTILS_ATTR_POSITION_MS) out vec4 _position; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _worldPosition; +layout(location=RENDER_UTILS_ATTR_NORMAL_MS) out vec3 _normal; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _worldFadePosition; void main(void) { // standard transform diff --git a/libraries/entities-renderer/src/textured_particle.slf b/libraries/entities-renderer/src/textured_particle.slf index e139c7cc01..7a0cedf011 100644 --- a/libraries/entities-renderer/src/textured_particle.slf +++ b/libraries/entities-renderer/src/textured_particle.slf @@ -1,7 +1,8 @@ <@include gpu/Config.slh@> <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> -// fragment shader +// +// textured_particle.frag // // Copyright 2015 High Fidelity, Inc. // @@ -9,12 +10,12 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -uniform sampler2D colorMap; +layout(binding=0) uniform sampler2D colorMap; -in vec4 varColor; -in vec2 varTexcoord; +layout(location=0) in vec4 varColor; +layout(location=1) in vec2 varTexcoord; -out vec4 outFragColor; +layout(location=0) out vec4 outFragColor; void main(void) { outFragColor = texture(colorMap, varTexcoord.xy) * varColor; diff --git a/libraries/entities-renderer/src/textured_particle.slv b/libraries/entities-renderer/src/textured_particle.slv index 22254c0ab0..60bca6e9bd 100644 --- a/libraries/entities-renderer/src/textured_particle.slv +++ b/libraries/entities-renderer/src/textured_particle.slv @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// particle vertex shader +// texture_particle.vert // // Copyright 2015 High Fidelity, Inc. // @@ -43,15 +43,15 @@ struct ParticleUniforms { vec2 spare; }; -layout(std140) uniform particleBuffer { +layout(std140, binding=0) uniform particleBuffer { ParticleUniforms particle; }; layout(location=0) in vec3 inPosition; layout(location=2) in vec2 inColor; // This is actual Lifetime + Seed -out vec4 varColor; -out vec2 varTexcoord; +layout(location=0) out vec4 varColor; +layout(location=1) out vec2 varTexcoord; float bezierInterpolate(float y1, float y2, float y3, float u) { // https://en.wikipedia.org/wiki/Bezier_curve diff --git a/libraries/gl/src/gl/GLShaders.cpp b/libraries/gl/src/gl/GLShaders.cpp index 9bfe214fcf..f4a7dc1fa2 100644 --- a/libraries/gl/src/gl/GLShaders.cpp +++ b/libraries/gl/src/gl/GLShaders.cpp @@ -13,32 +13,165 @@ using namespace gl; void Uniform::load(GLuint glprogram, int index) { + this->index = index; const GLint NAME_LENGTH = 256; GLchar glname[NAME_LENGTH]; GLint length = 0; glGetActiveUniform(glprogram, index, NAME_LENGTH, &length, &size, &type, glname); + // Length does NOT include the null terminator + // https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glGetActiveUniform.xhtml name = std::string(glname, length); - location = glGetUniformLocation(glprogram, glname); + binding = glGetUniformLocation(glprogram, glname); } -Uniforms gl::loadUniforms(GLuint glprogram) { +bool isTextureType(GLenum type) { + switch (type) { +#ifndef USE_GLES + case GL_SAMPLER_1D: + case GL_SAMPLER_1D_ARRAY: + case GL_SAMPLER_1D_SHADOW: + case GL_SAMPLER_1D_ARRAY_SHADOW: +#endif + case GL_SAMPLER_2D: + case GL_SAMPLER_3D: + case GL_SAMPLER_CUBE: + case GL_SAMPLER_2D_ARRAY: + case GL_SAMPLER_CUBE_MAP_ARRAY: + case GL_SAMPLER_2D_SHADOW: + case GL_SAMPLER_2D_ARRAY_SHADOW: + case GL_SAMPLER_BUFFER: + return true; + default: + break; + } + return false; +} + +Uniforms Uniform::load(GLuint glprogram, const std::function& filter) { + Uniforms result; GLint uniformsCount = 0; glGetProgramiv(glprogram, GL_ACTIVE_UNIFORMS, &uniformsCount); - - Uniforms result; - result.resize(uniformsCount); + result.reserve(uniformsCount); for (int i = 0; i < uniformsCount; i++) { - result[i].load(glprogram, i); + result.emplace_back(glprogram, i); + } + result.erase(std::remove_if(result.begin(), result.end(), filter), result.end()); + return result; +} + + +Uniforms Uniform::loadTextures(GLuint glprogram) { + return load(glprogram, [](const Uniform& uniform) -> bool { + if (std::string::npos != uniform.name.find('.')) { + return true; + } + if (std::string::npos != uniform.name.find('[')) { + return true; + } + if (!isTextureType(uniform.type)) { + return true; + } + return false; + }); +} + +Uniforms Uniform::load(GLuint glprogram) { + return load(glprogram, [](const Uniform& uniform) -> bool { + if (std::string::npos != uniform.name.find('.')) { + return true; + } + if (std::string::npos != uniform.name.find('[')) { + return true; + } + if (isTextureType(uniform.type)) { + return true; + } + return false; + }); +} + +Uniforms Uniform::load(GLuint glprogram, const std::vector& indices) { + Uniforms result; + result.reserve(indices.size()); + for (const auto& i : indices) { + if (i == GL_INVALID_INDEX) { + continue; + } + result.emplace_back(glprogram, i); + } + return result; +} + +Uniforms Uniform::load(GLuint glprogram, const std::vector& cnames) { + GLsizei count = static_cast(cnames.size()); + std::vector indices; + indices.resize(count); + glGetUniformIndices(glprogram, count, cnames.data(), indices.data()); + return load(glprogram, indices); +} + +void UniformBlock::load(GLuint glprogram, int index) { + this->index = index; + GLint length = 0; + + // Length DOES include the null terminator + // https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glGetActiveUniformBlock.xhtml + glGetActiveUniformBlockiv(glprogram, index, GL_UNIFORM_BLOCK_NAME_LENGTH, &length); + if (length > 1) { + std::vector nameBuffer; + nameBuffer.resize(length); + glGetActiveUniformBlockName(glprogram, index, length, nullptr, nameBuffer.data()); + name = std::string(nameBuffer.data(), length - 1); + } + glGetActiveUniformBlockiv(glprogram, index, GL_UNIFORM_BLOCK_BINDING, &binding); + glGetActiveUniformBlockiv(glprogram, index, GL_UNIFORM_BLOCK_DATA_SIZE, &size); +} + +UniformBlocks UniformBlock::load(GLuint glprogram) { + GLint buffersCount = -1; + glGetProgramiv(glprogram, GL_ACTIVE_UNIFORM_BLOCKS, &buffersCount); + + // fast exit + if (buffersCount <= 0) { + return {}; + } + + UniformBlocks uniformBlocks; + for (int i = 0; i < buffersCount; ++i) { + uniformBlocks.emplace_back(glprogram, i); + } + return uniformBlocks; +} + +void Input::load(GLuint glprogram, int index) { + const GLint NAME_LENGTH = 256; + GLchar name[NAME_LENGTH]; + GLint length = 0; + // Length does NOT include the null terminator + // https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glGetActiveAttrib.xhtml + glGetActiveAttrib(glprogram, index, NAME_LENGTH, &length, &size, &type, name); + if (length > 0) { + this->name = std::string(name, length); + } + binding = glGetAttribLocation(glprogram, name); +} + +Inputs Input::load(GLuint glprogram) { + Inputs result; + GLint count; + glGetProgramiv(glprogram, GL_ACTIVE_ATTRIBUTES, &count); + for (int i = 0; i < count; ++i) { + result.emplace_back(glprogram, i); } return result; } #ifdef SEPARATE_PROGRAM bool gl::compileShader(GLenum shaderDomain, - const std::string& shaderSource, - GLuint& shaderObject, - GLuint& programObject, - std::string& message) { + const std::string& shaderSource, + GLuint& shaderObject, + GLuint& programObject, + std::string& message) { return compileShader(shaderDomain, std::vector{ shaderSource }, shaderObject, programObject, message); } #else @@ -49,15 +182,15 @@ bool gl::compileShader(GLenum shaderDomain, const std::string& shaderSource, GLu #ifdef SEPARATE_PROGRAM bool gl::compileShader(GLenum shaderDomain, - const std::string& shaderSource, - GLuint& shaderObject, - GLuint& programObject, - std::string& message) { + const std::string& shaderSource, + GLuint& shaderObject, + GLuint& programObject, + std::string& message) { #else bool gl::compileShader(GLenum shaderDomain, - const std::vector& shaderSources, - GLuint& shaderObject, - std::string& message) { + const std::vector& shaderSources, + GLuint& shaderObject, + std::string& message) { #endif if (shaderSources.empty()) { qCDebug(glLogging) << "GLShader::compileShader - no GLSL shader source code ? so failed to create"; @@ -101,17 +234,18 @@ bool gl::compileShader(GLenum shaderDomain, std::ofstream filestream; filestream.open("debugshader.glsl"); if (filestream.is_open()) { - filestream << srcstr[0]; - filestream << srcstr[1]; - filestream.close(); + for (const auto& str : cstrs) { + filestream << str; + } + filestream.close(); } */ /* filestream.open("debugshader.glsl.info.txt"); if (filestream.is_open()) { - filestream << std::string(temp); - filestream.close(); + filestream << std::string(temp); + filestream.close(); } */ @@ -193,7 +327,33 @@ bool gl::compileShader(GLenum shaderDomain, return true; } -GLuint gl::compileProgram(const std::vector& glshaders, std::string& message, CachedShader& cachedShader) { +void gl::getProgramInfoLog(GLuint glprogram, std::string& message) { + std::string result; + GLint infoLength = 0; + glGetProgramiv(glprogram, GL_INFO_LOG_LENGTH, &infoLength); + if (infoLength > 0) { + char* temp = new char[infoLength]; + glGetProgramInfoLog(glprogram, infoLength, NULL, temp); + message = std::string(temp); + delete[] temp; + } else { + message.clear(); + } +} + +void gl::getProgramBinary(GLuint glprogram, CachedShader& cachedShader) { + GLint binaryLength = 0; + glGetProgramiv(glprogram, GL_PROGRAM_BINARY_LENGTH, &binaryLength); + if (binaryLength > 0) { + cachedShader.binary.resize(binaryLength); + glGetProgramBinary(glprogram, binaryLength, NULL, &cachedShader.format, cachedShader.binary.data()); + } else { + cachedShader.binary.clear(); + cachedShader.format = 0; + } +} + +GLuint gl::buildProgram(const std::vector& glshaders) { // A brand new program: GLuint glprogram = glCreateProgram(); if (!glprogram) { @@ -201,80 +361,55 @@ GLuint gl::compileProgram(const std::vector& glshaders, std::string& mes return 0; } - bool binaryLoaded = false; - - if (glshaders.empty() && cachedShader) { - glProgramBinary(glprogram, cachedShader.format, cachedShader.binary.data(), (GLsizei)cachedShader.binary.size()); - binaryLoaded = true; - } else { - // glProgramParameteri(glprogram, GL_PROGRAM_, GL_TRUE); - // Create the program from the sub shaders - for (auto so : glshaders) { - glAttachShader(glprogram, so); - } - - // Link! - glLinkProgram(glprogram); - } - - GLint linked = 0; - glGetProgramiv(glprogram, GL_LINK_STATUS, &linked); - - GLint infoLength = 0; - glGetProgramiv(glprogram, GL_INFO_LOG_LENGTH, &infoLength); - - if ((infoLength > 0) || !linked) { - char* temp = new char[infoLength]; - glGetProgramInfoLog(glprogram, infoLength, NULL, temp); - - message = std::string(temp); - - if (!linked) { - /* - // save the source code to a temp file so we can debug easily - std::ofstream filestream; - filestream.open("debugshader.glsl"); - if (filestream.is_open()) { - filestream << shaderSource->source; - filestream.close(); - } - */ - - qCDebug(glLogging) << "GLShader::compileProgram - failed to LINK the gl program object :"; - qCDebug(glLogging) << temp; - - delete[] temp; - - /* - filestream.open("debugshader.glsl.info.txt"); - if (filestream.is_open()) { - filestream << std::string(temp); - filestream.close(); - } - */ - - glDeleteProgram(glprogram); - return 0; - } else { - qCDebug(glLogging) << "GLShader::compileProgram - success:"; - qCDebug(glLogging) << temp; - delete[] temp; - } - } - - // If linked get the binaries - if (linked && !binaryLoaded) { - GLint binaryLength = 0; - glGetProgramiv(glprogram, GL_PROGRAM_BINARY_LENGTH, &binaryLength); - if (binaryLength > 0) { - cachedShader.binary.resize(binaryLength); - glGetProgramBinary(glprogram, binaryLength, NULL, &cachedShader.format, cachedShader.binary.data()); - } + // glProgramParameteri(glprogram, GL_PROGRAM_, GL_TRUE); + // Create the program from the sub shaders + for (auto so : glshaders) { + glAttachShader(glprogram, so); } return glprogram; } + +GLuint gl::buildProgram(const CachedShader& cachedShader) { + // A brand new program: + GLuint glprogram = glCreateProgram(); + if (!glprogram) { + qCDebug(glLogging) << "GLShader::compileProgram - failed to create the gl program object"; + return 0; + } + glProgramBinary(glprogram, cachedShader.format, cachedShader.binary.data(), (GLsizei)cachedShader.binary.size()); + GLint linked = 0; + glGetProgramiv(glprogram, GL_LINK_STATUS, &linked); + if (!linked) { + glDeleteProgram(glprogram); + return 0; + } + + return glprogram; +} + + +bool gl::linkProgram(GLuint glprogram, std::string& message) { + glLinkProgram(glprogram); + + GLint linked = 0; + glGetProgramiv(glprogram, GL_LINK_STATUS, &linked); + ::gl::getProgramInfoLog(glprogram, message); + if (!linked) { + qCDebug(glLogging) << "GLShader::compileProgram - failed to LINK the gl program object :"; + qCDebug(glLogging) << message.c_str(); + return false; + } + + if (!message.empty()) { + qCDebug(glLogging) << "GLShader::compileProgram - success:"; + qCDebug(glLogging) << message.c_str(); + } + + return true; +} + const QString& getShaderCacheFile() { static const QString SHADER_CACHE_FOLDER{ "shaders" }; static const QString SHADER_CACHE_FILE_NAME{ "cache.json" }; @@ -287,6 +422,7 @@ static const char* SHADER_JSON_SOURCE_KEY = "source"; static const char* SHADER_JSON_DATA_KEY = "data"; void gl::loadShaderCache(ShaderCache& cache) { +#if !defined(DISABLE_QML) QString shaderCacheFile = getShaderCacheFile(); if (QFileInfo(shaderCacheFile).exists()) { QString json = FileUtils::readFile(shaderCacheFile); @@ -302,6 +438,7 @@ void gl::loadShaderCache(ShaderCache& cache) { cachedShader.source = programObject[SHADER_JSON_SOURCE_KEY].toString().toStdString(); } } +#endif } void gl::saveShaderCache(const ShaderCache& cache) { diff --git a/libraries/gl/src/gl/GLShaders.h b/libraries/gl/src/gl/GLShaders.h index e6c11b4eb3..7666bba823 100644 --- a/libraries/gl/src/gl/GLShaders.h +++ b/libraries/gl/src/gl/GLShaders.h @@ -12,50 +12,108 @@ #include "Config.h" -#include +#include #include #include +#include +#include namespace gl { - struct Uniform { - std::string name; - GLint size{ -1 }; - GLenum type{ GL_FLOAT }; - GLint location{ -1 }; - void load(GLuint glprogram, int index); - }; +struct ShaderBinding { + int index; + std::string name; + GLint size{ -1 }; + GLint binding{ -1 }; +}; - using Uniforms = std::vector; +struct Uniform : public ShaderBinding { + Uniform(){}; + Uniform(GLint program, int index) { load(program, index); }; + using Vector = std::vector; + GLenum type{ GL_FLOAT }; - Uniforms loadUniforms(GLuint glprogram); + void load(GLuint glprogram, int index); + // Incredibly slow on mac, DO NOT USE + static Vector load(GLuint glprogram, const std::function& filter); + static Vector loadTextures(GLuint glprogram); + static Vector load(GLuint glprogram); + static Vector load(GLuint glprogram, const std::vector& indices); + static Vector load(GLuint glprogram, const std::vector& names); - struct CachedShader { - GLenum format{ 0 }; - std::string source; - std::vector binary; - inline operator bool() const { - return format != 0 && !binary.empty(); + template + static Vector loadByName(GLuint glprogram, const C& names) { + std::vector cnames; + cnames.reserve(names.size()); + for (const auto& name : names) { + cnames.push_back(name.c_str()); } - }; + return load(glprogram, cnames); + } +}; - using ShaderCache = std::unordered_map; +using Uniforms = Uniform::Vector; - std::string getShaderHash(const std::string& shaderSource); - void loadShaderCache(ShaderCache& cache); - void saveShaderCache(const ShaderCache& cache); +struct UniformBlock : public ShaderBinding { + UniformBlock(){}; + UniformBlock(GLint program, int index) { load(program, index); }; + using Vector = std::vector; + void load(GLuint glprogram, int index); + static Vector load(GLuint glprogram); +}; + +using UniformBlocks = UniformBlock::Vector; + +struct Input : public ShaderBinding { + Input(){}; + Input(GLint program, int index) { load(program, index); }; + using Vector = std::vector; + GLenum type{ GL_FLOAT }; + + void load(GLuint glprogram, int index); + static Vector load(GLuint glprogram); +}; + +using Inputs = Input::Vector; + +struct CachedShader { + GLenum format{ 0 }; + std::string source; + std::vector binary; + inline operator bool() const { return format != 0 && !binary.empty(); } +}; + +using ShaderCache = std::unordered_map; + +std::string getShaderHash(const std::string& shaderSource); +void loadShaderCache(ShaderCache& cache); +void saveShaderCache(const ShaderCache& cache); #ifdef SEPARATE_PROGRAM - bool compileShader(GLenum shaderDomain, const std::string& shaderSource, GLuint &shaderObject, GLuint &programObject, std::string& message); - bool compileShader(GLenum shaderDomain, const std::vector& shaderSources, GLuint &shaderObject, GLuint &programObject, std::string& message); +bool compileShader(GLenum shaderDomain, + const std::string& shaderSource, + GLuint& shaderObject, + GLuint& programObject, + std::string& message); +bool compileShader(GLenum shaderDomain, + const std::vector& shaderSources, + GLuint& shaderObject, + GLuint& programObject, + std::string& message); #else - bool compileShader(GLenum shaderDomain, const std::string& shaderSource, GLuint &shaderObject, std::string& message); - bool compileShader(GLenum shaderDomain, const std::vector& shaderSources, GLuint &shaderObject, std::string& message); +bool compileShader(GLenum shaderDomain, const std::string& shaderSource, GLuint& shaderObject, std::string& message); +bool compileShader(GLenum shaderDomain, + const std::vector& shaderSources, + GLuint& shaderObject, + std::string& message); #endif - GLuint compileProgram(const std::vector& glshaders, std::string& message, CachedShader& binary); - -} +GLuint buildProgram(const std::vector& glshaders); +GLuint buildProgram(const CachedShader& binary); +bool linkProgram(GLuint glprogram, std::string& message); +void getProgramInfoLog(GLuint glprogram, std::string& message); +void getProgramBinary(GLuint glprogram, CachedShader& cachedShader); +} // namespace gl #endif diff --git a/libraries/gpu-gl-common/src/gpu/gl/GLBackend.cpp b/libraries/gpu-gl-common/src/gpu/gl/GLBackend.cpp index 2321342eb4..2d26b4b347 100644 --- a/libraries/gpu-gl-common/src/gpu/gl/GLBackend.cpp +++ b/libraries/gpu-gl-common/src/gpu/gl/GLBackend.cpp @@ -100,11 +100,35 @@ GLBackend::CommandCall GLBackend::_commandCalls[Batch::NUM_COMMANDS] = (&::gpu::gl::GLBackend::do_popProfileRange), }; +#define GL_GET_INTEGER(NAME) glGetIntegerv(GL_##NAME, &const_cast(NAME)); + +GLint GLBackend::MAX_TEXTURE_IMAGE_UNITS{ 0 }; +GLint GLBackend::MAX_UNIFORM_BUFFER_BINDINGS{ 0 }; +GLint GLBackend::MAX_COMBINED_UNIFORM_BLOCKS{ 0 }; +GLint GLBackend::MAX_COMBINED_TEXTURE_IMAGE_UNITS{ 0 }; +GLint GLBackend::MAX_UNIFORM_BLOCK_SIZE{ 0 }; +GLint GLBackend::UNIFORM_BUFFER_OFFSET_ALIGNMENT{ 1 }; +GLint GLBackend::MAX_UNIFORM_LOCATIONS{ 0 }; + void GLBackend::init() { static std::once_flag once; std::call_once(once, [] { + + QString vendor{ (const char*)glGetString(GL_VENDOR) }; QString renderer{ (const char*)glGetString(GL_RENDERER) }; + + // Textures + GL_GET_INTEGER(MAX_TEXTURE_IMAGE_UNITS); + GL_GET_INTEGER(MAX_COMBINED_TEXTURE_IMAGE_UNITS); + + // Uniform blocks + GL_GET_INTEGER(MAX_UNIFORM_BUFFER_BINDINGS); + GL_GET_INTEGER(MAX_COMBINED_UNIFORM_BLOCKS); + GL_GET_INTEGER(MAX_UNIFORM_BLOCK_SIZE); + GL_GET_INTEGER(UNIFORM_BUFFER_OFFSET_ALIGNMENT); + GL_GET_INTEGER(MAX_UNIFORM_LOCATIONS); + qCDebug(gpugllogging) << "GL Version: " << QString((const char*) glGetString(GL_VERSION)); qCDebug(gpugllogging) << "GL Shader Language Version: " << QString((const char*) glGetString(GL_SHADING_LANGUAGE_VERSION)); qCDebug(gpugllogging) << "GL Vendor: " << vendor; @@ -115,15 +139,26 @@ void GLBackend::init() { qCDebug(gpugllogging) << "\tcard:" << gpu->getName(); qCDebug(gpugllogging) << "\tdriver:" << gpu->getDriver(); qCDebug(gpugllogging) << "\tdedicated memory:" << gpu->getMemory() << "MB"; + qCDebug(gpugllogging) << "Limits:"; + qCDebug(gpugllogging) << "\tmax textures:" << MAX_TEXTURE_IMAGE_UNITS; + qCDebug(gpugllogging) << "\tmax texture binding:" << MAX_COMBINED_TEXTURE_IMAGE_UNITS; + qCDebug(gpugllogging) << "\tmax uniforms:" << MAX_UNIFORM_BUFFER_BINDINGS; + qCDebug(gpugllogging) << "\tmax uniform binding:" << MAX_COMBINED_UNIFORM_BLOCKS; + qCDebug(gpugllogging) << "\tmax uniform size:" << MAX_UNIFORM_BLOCK_SIZE; + qCDebug(gpugllogging) << "\tuniform alignment:" << UNIFORM_BUFFER_OFFSET_ALIGNMENT; #if !defined(USE_GLES) qCDebug(gpugllogging, "V-Sync is %s\n", (::gl::getSwapInterval() > 0 ? "ON" : "OFF")); #endif }); } +GLBackend::GLBackend(bool syncCache) { + _pipeline._cameraCorrectionBuffer._buffer->flush(); + initShaderBinaryCache(); +} + GLBackend::GLBackend() { _pipeline._cameraCorrectionBuffer._buffer->flush(); - glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &_uboAlignment); initShaderBinaryCache(); } @@ -386,17 +421,11 @@ void GLBackend::do_popProfileRange(const Batch& batch, size_t paramOffset) { } } + // TODO: As long as we have gl calls explicitely issued from interface // code, we need to be able to record and batch these calls. THe long // term strategy is to get rid of any GL calls in favor of the HIFI GPU API -// As long as we don;t use several versions of shaders we can avoid this more complex code path -#ifdef GPU_STEREO_CAMERA_BUFFER -#define GET_UNIFORM_LOCATION(shaderUniformLoc) ((_pipeline._programShader) ? _pipeline._programShader->getUniformLocation(shaderUniformLoc, (GLShader::Version) isStereo()) : -1) -#else -#define GET_UNIFORM_LOCATION(shaderUniformLoc) shaderUniformLoc -#endif - void GLBackend::do_glUniform1i(const Batch& batch, size_t paramOffset) { if (_pipeline._program == 0) { // We should call updatePipeline() to bind the program but we are not doing that @@ -405,8 +434,9 @@ void GLBackend::do_glUniform1i(const Batch& batch, size_t paramOffset) { } updatePipeline(); + GLint location = getRealUniformLocation(batch._params[paramOffset + 1]._int); glUniform1i( - GET_UNIFORM_LOCATION(batch._params[paramOffset + 1]._int), + location, batch._params[paramOffset + 0]._int); (void)CHECK_GL_ERROR(); } @@ -419,8 +449,9 @@ void GLBackend::do_glUniform1f(const Batch& batch, size_t paramOffset) { } updatePipeline(); + GLint location = getRealUniformLocation(batch._params[paramOffset + 1]._int); glUniform1f( - GET_UNIFORM_LOCATION(batch._params[paramOffset + 1]._int), + location, batch._params[paramOffset + 0]._float); (void)CHECK_GL_ERROR(); } @@ -432,8 +463,9 @@ void GLBackend::do_glUniform2f(const Batch& batch, size_t paramOffset) { return; } updatePipeline(); + GLint location = getRealUniformLocation(batch._params[paramOffset + 2]._int); glUniform2f( - GET_UNIFORM_LOCATION(batch._params[paramOffset + 2]._int), + location, batch._params[paramOffset + 1]._float, batch._params[paramOffset + 0]._float); (void)CHECK_GL_ERROR(); @@ -446,8 +478,9 @@ void GLBackend::do_glUniform3f(const Batch& batch, size_t paramOffset) { return; } updatePipeline(); + GLint location = getRealUniformLocation(batch._params[paramOffset + 3]._int); glUniform3f( - GET_UNIFORM_LOCATION(batch._params[paramOffset + 3]._int), + location, batch._params[paramOffset + 2]._float, batch._params[paramOffset + 1]._float, batch._params[paramOffset + 0]._float); @@ -461,8 +494,9 @@ void GLBackend::do_glUniform4f(const Batch& batch, size_t paramOffset) { return; } updatePipeline(); + GLint location = getRealUniformLocation(batch._params[paramOffset + 4]._int); glUniform4f( - GET_UNIFORM_LOCATION(batch._params[paramOffset + 4]._int), + location, batch._params[paramOffset + 3]._float, batch._params[paramOffset + 2]._float, batch._params[paramOffset + 1]._float, @@ -477,8 +511,9 @@ void GLBackend::do_glUniform3fv(const Batch& batch, size_t paramOffset) { return; } updatePipeline(); + GLint location = getRealUniformLocation(batch._params[paramOffset + 2]._int); glUniform3fv( - GET_UNIFORM_LOCATION(batch._params[paramOffset + 2]._int), + location, batch._params[paramOffset + 1]._uint, (const GLfloat*)batch.readData(batch._params[paramOffset + 0]._uint)); @@ -493,7 +528,7 @@ void GLBackend::do_glUniform4fv(const Batch& batch, size_t paramOffset) { } updatePipeline(); - GLint location = GET_UNIFORM_LOCATION(batch._params[paramOffset + 2]._int); + GLint location = getRealUniformLocation(batch._params[paramOffset + 2]._int); GLsizei count = batch._params[paramOffset + 1]._uint; const GLfloat* value = (const GLfloat*)batch.readData(batch._params[paramOffset + 0]._uint); glUniform4fv(location, count, value); @@ -508,8 +543,9 @@ void GLBackend::do_glUniform4iv(const Batch& batch, size_t paramOffset) { return; } updatePipeline(); + GLint location = getRealUniformLocation(batch._params[paramOffset + 2]._int); glUniform4iv( - GET_UNIFORM_LOCATION(batch._params[paramOffset + 2]._int), + location, batch._params[paramOffset + 1]._uint, (const GLint*)batch.readData(batch._params[paramOffset + 0]._uint)); @@ -524,8 +560,9 @@ void GLBackend::do_glUniformMatrix3fv(const Batch& batch, size_t paramOffset) { } updatePipeline(); + GLint location = getRealUniformLocation(batch._params[paramOffset + 3]._int); glUniformMatrix3fv( - GET_UNIFORM_LOCATION(batch._params[paramOffset + 3]._int), + location, batch._params[paramOffset + 2]._uint, batch._params[paramOffset + 1]._uint, (const GLfloat*)batch.readData(batch._params[paramOffset + 0]._uint)); @@ -540,8 +577,9 @@ void GLBackend::do_glUniformMatrix4fv(const Batch& batch, size_t paramOffset) { } updatePipeline(); + GLint location = getRealUniformLocation(batch._params[paramOffset + 3]._int); glUniformMatrix4fv( - GET_UNIFORM_LOCATION(batch._params[paramOffset + 3]._int), + location, batch._params[paramOffset + 2]._uint, batch._params[paramOffset + 1]._uint, (const GLfloat*)batch.readData(batch._params[paramOffset + 0]._uint)); diff --git a/libraries/gpu-gl-common/src/gpu/gl/GLBackend.h b/libraries/gpu-gl-common/src/gpu/gl/GLBackend.h index 6faccb1527..ff3e94fd16 100644 --- a/libraries/gpu-gl-common/src/gpu/gl/GLBackend.h +++ b/libraries/gpu-gl-common/src/gpu/gl/GLBackend.h @@ -68,7 +68,30 @@ protected: explicit GLBackend(bool syncCache); GLBackend(); public: - static bool makeProgram(Shader& shader, const Shader::BindingSet& slotBindings, const Shader::CompilationHandler& handler); + +#if defined(USE_GLES) + // https://www.khronos.org/registry/OpenGL-Refpages/es3/html/glGet.xhtml + static const GLint MIN_REQUIRED_TEXTURE_IMAGE_UNITS = 16; + static const GLint MIN_REQUIRED_COMBINED_UNIFORM_BLOCKS = 60; + static const GLint MIN_REQUIRED_COMBINED_TEXTURE_IMAGE_UNITS = 48; + static const GLint MIN_REQUIRED_UNIFORM_BUFFER_BINDINGS = 72; + static const GLint MIN_REQUIRED_UNIFORM_LOCATIONS = 1024; +#else + // https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glGet.xhtml + static const GLint MIN_REQUIRED_TEXTURE_IMAGE_UNITS = 16; + static const GLint MIN_REQUIRED_COMBINED_UNIFORM_BLOCKS = 70; + static const GLint MIN_REQUIRED_COMBINED_TEXTURE_IMAGE_UNITS = 48; + static const GLint MIN_REQUIRED_UNIFORM_BUFFER_BINDINGS = 36; + static const GLint MIN_REQUIRED_UNIFORM_LOCATIONS = 1024; +#endif + + static GLint MAX_TEXTURE_IMAGE_UNITS; + static GLint MAX_UNIFORM_BUFFER_BINDINGS; + static GLint MAX_COMBINED_UNIFORM_BLOCKS; + static GLint MAX_COMBINED_TEXTURE_IMAGE_UNITS; + static GLint MAX_UNIFORM_BLOCK_SIZE; + static GLint MAX_UNIFORM_LOCATIONS; + static GLint UNIFORM_BUFFER_OFFSET_ALIGNMENT; virtual ~GLBackend(); @@ -107,7 +130,6 @@ public: // Texture Tables offers 2 dedicated slot (taken from the ubo slots) static const int MAX_NUM_RESOURCE_TABLE_TEXTURES = 2; - static const int RESOURCE_TABLE_TEXTURE_SLOT_OFFSET = TRANSFORM_CAMERA_SLOT + 1; size_t getMaxNumResourceTextureTables() const { return MAX_NUM_RESOURCE_TABLE_TEXTURES; } @@ -238,6 +260,7 @@ public: bool isTextureManagementSparseEnabled() const override { return (_textureManagement._sparseCapable && Texture::getEnableSparseTextures()); } protected: + virtual GLint getRealUniformLocation(GLint location) const { return location; } void recycle() const override; @@ -247,7 +270,6 @@ protected: static const size_t INVALID_OFFSET = (size_t)-1; bool _inRenderTransferPass { false }; - int32_t _uboAlignment { 0 }; int _currentDraw { -1 }; std::list profileRanges; @@ -394,10 +416,21 @@ protected: virtual void transferTransformState(const Batch& batch) const = 0; struct UniformStageState { - std::array _buffers; + struct BufferState { + BufferPointer buffer; + GLintptr offset{ 0 }; + GLsizeiptr size{ 0 }; + BufferState(const BufferPointer& buffer = nullptr, GLintptr offset = 0, GLsizeiptr size = 0); + bool operator ==(BufferState& other) const { + return offset == other.offset && size == other.size && buffer == other.buffer; + } + }; + std::array _buffers; //Buffers _buffers { }; } _uniform; + // Helper function that provides common code + void bindUniformBuffer(uint32_t slot, const BufferPointer& buffer, GLintptr offset = 0, GLsizeiptr size = 0); void releaseUniformBuffer(uint32_t slot); void resetUniformStage(); @@ -410,6 +443,7 @@ protected: // do_setResourceTextureTable (in non-bindless mode) void bindResourceTexture(uint32_t slot, const TexturePointer& texture); + // update resource cache and do the gl unbind call with the current gpu::Texture cached at slot s void releaseResourceTexture(uint32_t slot); @@ -436,7 +470,7 @@ protected: PipelinePointer _pipeline; GLuint _program { 0 }; - GLint _cameraCorrectionLocation { -1 }; + bool _cameraCorrection { false }; GLShader* _programShader { nullptr }; bool _invalidProgram { false }; @@ -457,6 +491,7 @@ protected: } _pipeline; // Backend dependant compilation of the shader + virtual void postLinkProgram(ShaderObject& programObject, const Shader& program) const {} virtual GLShader* compileBackendProgram(const Shader& program, const Shader::CompilationHandler& handler); virtual GLShader* compileBackendShader(const Shader& shader, const Shader::CompilationHandler& handler); virtual std::string getBackendShaderHeader() const = 0; @@ -467,7 +502,6 @@ protected: // The program string returned can be used as a key for a cache of shader binaries // The shader strings can be reliably sent to the low level `compileShader` functions virtual std::string getShaderSource(const Shader& shader, int version) final; - virtual void makeProgramBindings(ShaderObject& shaderObject); class ElementResource { public: gpu::Element _element; @@ -475,15 +509,6 @@ protected: ElementResource(Element&& elem, uint16 resource) : _element(elem), _resource(resource) {} }; ElementResource getFormatFromGLUniform(GLenum gltype); - static const GLint UNUSED_SLOT {-1}; - static bool isUnusedSlot(GLint binding) { return (binding == UNUSED_SLOT); } - virtual int makeUniformSlots(const ShaderObject& program, const Shader::BindingSet& slotBindings, - Shader::SlotSet& uniforms, Shader::SlotSet& textures, Shader::SlotSet& samplers); - virtual int makeUniformBlockSlots(const ShaderObject& program, const Shader::BindingSet& slotBindings, Shader::SlotSet& buffers); - virtual int makeResourceBufferSlots(const ShaderObject& program, const Shader::BindingSet& slotBindings, Shader::SlotSet& resourceBuffers) = 0; - virtual int makeInputSlots(const ShaderObject& program, const Shader::BindingSet& slotBindings, Shader::SlotSet& inputs); - virtual int makeOutputSlots(const ShaderObject& program, const Shader::BindingSet& slotBindings, Shader::SlotSet& outputs); - // Synchronize the state cache of this Backend with the actual real state of the GL Context void syncOutputStateCache(); diff --git a/libraries/gpu-gl-common/src/gpu/gl/GLBackendPipeline.cpp b/libraries/gpu-gl-common/src/gpu/gl/GLBackendPipeline.cpp index adea3292e1..d3d2bc0938 100644 --- a/libraries/gpu-gl-common/src/gpu/gl/GLBackendPipeline.cpp +++ b/libraries/gpu-gl-common/src/gpu/gl/GLBackendPipeline.cpp @@ -10,6 +10,7 @@ // #include "GLBackend.h" #include +#include #include "GLShared.h" #include "GLPipeline.h" @@ -36,7 +37,7 @@ void GLBackend::do_setPipeline(const Batch& batch, size_t paramOffset) { _pipeline._pipeline.reset(); _pipeline._program = 0; - _pipeline._cameraCorrectionLocation = -1; + _pipeline._cameraCorrection = false; _pipeline._programShader = nullptr; _pipeline._invalidProgram = true; @@ -62,7 +63,7 @@ void GLBackend::do_setPipeline(const Batch& batch, size_t paramOffset) { _pipeline._program = glprogram; _pipeline._programShader = pipelineObject->_program; _pipeline._invalidProgram = true; - _pipeline._cameraCorrectionLocation = pipelineObject->_cameraCorrection; + _pipeline._cameraCorrection = pipelineObject->_cameraCorrection; } // Now for the state @@ -78,16 +79,13 @@ void GLBackend::do_setPipeline(const Batch& batch, size_t paramOffset) { // THis should be done on Pipeline::update... if (_pipeline._invalidProgram) { glUseProgram(_pipeline._program); - if (_pipeline._cameraCorrectionLocation != -1) { - gl::GLBuffer* cameraCorrectionBuffer = nullptr; - if (_transform._viewCorrectionEnabled) { - cameraCorrectionBuffer = syncGPUObject(*_pipeline._cameraCorrectionBuffer._buffer); - } else { - cameraCorrectionBuffer = syncGPUObject(*_pipeline._cameraCorrectionBufferIdentity._buffer); - } + if (_pipeline._cameraCorrection) { // Invalidate uniform buffer cache slot - _uniform._buffers[_pipeline._cameraCorrectionLocation].reset(); - glBindBufferRange(GL_UNIFORM_BUFFER, _pipeline._cameraCorrectionLocation, cameraCorrectionBuffer->_id, 0, sizeof(CameraCorrection)); + _uniform._buffers[gpu::slot::buffer::CameraCorrection] = {}; + auto& cameraCorrectionBuffer = _transform._viewCorrectionEnabled ? + _pipeline._cameraCorrectionBuffer._buffer : + _pipeline._cameraCorrectionBufferIdentity._buffer; + bindUniformBuffer(gpu::slot::buffer::CameraCorrection, cameraCorrectionBuffer, 0, sizeof(CameraCorrection)); } (void)CHECK_GL_ERROR(); _pipeline._invalidProgram = false; @@ -138,15 +136,18 @@ void GLBackend::resetPipelineStage() { glUseProgram(0); } +GLBackend::UniformStageState::BufferState::BufferState(const BufferPointer& buffer, GLintptr offset, GLsizeiptr size) + : buffer(buffer), offset(offset), size(size) {} + void GLBackend::releaseUniformBuffer(uint32_t slot) { auto& buf = _uniform._buffers[slot]; - if (buf) { - auto* object = Backend::getGPUObject(*buf); + if (buf.buffer) { + auto* object = Backend::getGPUObject(*buf.buffer); if (object) { glBindBufferBase(GL_UNIFORM_BUFFER, slot, 0); // RELEASE (void)CHECK_GL_ERROR(); } - buf.reset(); + buf = UniformStageState::BufferState(); } } @@ -156,6 +157,33 @@ void GLBackend::resetUniformStage() { } } +void GLBackend::bindUniformBuffer(uint32_t slot, const BufferPointer& buffer, GLintptr offset, GLsizeiptr size) { + if (!buffer) { + releaseUniformBuffer(slot); + return; + } + + UniformStageState::BufferState bufferState{ buffer, offset, size }; + + // check cache before thinking + if (_uniform._buffers[slot] == bufferState) { + return; + } + + // Sync BufferObject + auto* object = syncGPUObject(*bufferState.buffer); + if (object) { + glBindBufferRange(GL_UNIFORM_BUFFER, slot, object->_buffer, bufferState.offset, bufferState.size); + + _uniform._buffers[slot] = bufferState; + (void)CHECK_GL_ERROR(); + } else { + releaseUniformBuffer(slot); + return; + } + +} + void GLBackend::do_setUniformBuffer(const Batch& batch, size_t paramOffset) { GLuint slot = batch._params[paramOffset + 3]._uint; if (slot > (GLuint)MAX_NUM_UNIFORM_BUFFERS) { @@ -163,31 +191,12 @@ void GLBackend::do_setUniformBuffer(const Batch& batch, size_t paramOffset) { << " which doesn't exist. MaxNumUniformBuffers = " << getMaxNumUniformBuffers(); return; } + BufferPointer uniformBuffer = batch._buffers.get(batch._params[paramOffset + 2]._uint); GLintptr rangeStart = batch._params[paramOffset + 1]._uint; GLsizeiptr rangeSize = batch._params[paramOffset + 0]._uint; - if (!uniformBuffer) { - releaseUniformBuffer(slot); - return; - } - - // check cache before thinking - if (_uniform._buffers[slot] == uniformBuffer) { - return; - } - - // Sync BufferObject - auto* object = syncGPUObject(*uniformBuffer); - if (object) { - glBindBufferRange(GL_UNIFORM_BUFFER, slot, object->_buffer, rangeStart, rangeSize); - - _uniform._buffers[slot] = uniformBuffer; - (void)CHECK_GL_ERROR(); - } else { - releaseUniformBuffer(slot); - return; - } + bindUniformBuffer(slot, uniformBuffer, rangeStart, rangeSize); } void GLBackend::releaseResourceTexture(uint32_t slot) { diff --git a/libraries/gpu-gl-common/src/gpu/gl/GLBackendShader.cpp b/libraries/gpu-gl-common/src/gpu/gl/GLBackendShader.cpp index af6a0df297..7379417574 100644 --- a/libraries/gpu-gl-common/src/gpu/gl/GLBackendShader.cpp +++ b/libraries/gpu-gl-common/src/gpu/gl/GLBackendShader.cpp @@ -13,7 +13,6 @@ using namespace gpu; using namespace gpu::gl; using CachedShader = ::gl::CachedShader; - // Shader domain static const size_t NUM_SHADER_DOMAINS = 3; static_assert(Shader::Type::NUM_DOMAINS == NUM_SHADER_DOMAINS, "GL shader domains must equal defined GPU shader domains"); @@ -178,24 +177,22 @@ GLShader* GLBackend::compileBackendProgram(const Shader& program, const Shader:: } } - GLuint glprogram = 0; - // If we have a cached binary program, try to load it instead of compiling the individual shaders if (cachedBinary) { - glprogram = ::gl::compileProgram({}, compilationLogs[version].message, cachedBinary); + glprogram = ::gl::buildProgram(cachedBinary); if (0 != glprogram) { ++gpuBinaryShadersLoaded; - } - } - - // If we have no program, then either no cached binary, or the binary failed to load (perhaps a GPU driver update invalidated the cache) - if (0 == glprogram) { - cachedBinary = CachedShader(); - { + } else { + cachedBinary = CachedShader(); std::unique_lock shaderCacheLock{ _shaderBinaryCache._mutex }; _shaderBinaryCache._binaries.erase(hash); } + } + + // If we have no program, then either no cached binary, or the binary failed to load + // (perhaps a GPU driver update invalidated the cache) + if (0 == glprogram) { // Let's go through every shaders and make sure they are ready to go std::vector shaderGLObjects; shaderGLObjects.reserve(program.getShaders().size()); @@ -212,8 +209,16 @@ GLShader* GLBackend::compileBackendProgram(const Shader& program, const Shader:: } } - glprogram = ::gl::compileProgram(shaderGLObjects, compilationLogs[version].message, cachedBinary); - if (cachedBinary) { + glprogram = ::gl::buildProgram(shaderGLObjects); + + if (!::gl::linkProgram(glprogram, compilationLogs[version].message)) { + glDeleteProgram(glprogram); + glprogram = 0; + return nullptr; + } + + if (!cachedBinary) { + ::gl::getProgramBinary(glprogram, cachedBinary); cachedBinary.source = programSource; std::unique_lock shaderCacheLock{ _shaderBinaryCache._mutex }; _shaderBinaryCache._binaries[hash] = cachedBinary; @@ -228,7 +233,7 @@ GLShader* GLBackend::compileBackendProgram(const Shader& program, const Shader:: compilationLogs[version].compiled = true; programObject.glprogram = glprogram; - makeProgramBindings(programObject); + postLinkProgram(programObject, program); } // Compilation feedback program.setCompilationLogs(compilationLogs); @@ -236,7 +241,6 @@ GLShader* GLBackend::compileBackendProgram(const Shader& program, const Shader:: // So far so good, the program versions have all been created successfully GLShader* object = new GLShader(this->shared_from_this()); object->_shaderObjects = programObjects; - return object; } @@ -405,197 +409,8 @@ GLBackend::ElementResource GLBackend::getFormatFromGLUniform(GLenum gltype) { //{GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE uimage2DMS}, //{GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY uimage2DMSArray}, //{GL_UNSIGNED_INT_ATOMIC_COUNTER atomic_uint} - - }; -int GLBackend::makeUniformSlots(const ShaderObject& shaderProgram, const Shader::BindingSet& slotBindings, - Shader::SlotSet& uniforms, Shader::SlotSet& textures, Shader::SlotSet& samplers) { - auto& glprogram = shaderProgram.glprogram; - - for (const auto& uniform : shaderProgram.uniforms) { - const auto& type = uniform.type; - const auto& location = uniform.location; - const auto& size = uniform.size; - const auto& name = uniform.name; - const GLint INVALID_UNIFORM_LOCATION = -1; - - // Try to make sense of the gltype - auto elementResource = getFormatFromGLUniform(type); - - // The uniform as a standard var type - if (location != INVALID_UNIFORM_LOCATION) { - auto sname = uniform.name; - // Let's make sure the name doesn't contains an array element - auto foundBracket = sname.find_first_of('['); - if (foundBracket != std::string::npos) { - // std::string arrayname = sname.substr(0, foundBracket); - - if (sname[foundBracket + 1] == '0') { - sname = sname.substr(0, foundBracket); - } else { - // skip this uniform since it's not the first element of an array - continue; - } - } - - if (elementResource._resource == Resource::BUFFER) { - uniforms.insert(Shader::Slot(sname, location, elementResource._element, elementResource._resource)); - } else { - // For texture/Sampler, the location is the actual binding value - GLint binding = -1; - glGetUniformiv(glprogram, location, &binding); - - auto requestedBinding = slotBindings.find(std::string(sname)); - if (requestedBinding != slotBindings.end()) { - if (binding != (*requestedBinding)._location) { - binding = (*requestedBinding)._location; - for (auto i = 0; i < size; i++) { - // If we are working with an array of textures, reserve for each elemet - glProgramUniform1i(glprogram, location+i, binding+i); - } - } - } - - textures.insert(Shader::Slot(name, binding, elementResource._element, elementResource._resource)); - samplers.insert(Shader::Slot(name, binding, elementResource._element, elementResource._resource)); - } - } - } - - return static_cast(shaderProgram.uniforms.size()); -} - -int GLBackend::makeUniformBlockSlots(const ShaderObject& shaderProgram, const Shader::BindingSet& slotBindings, Shader::SlotSet& buffers) { - const auto& glprogram = shaderProgram.glprogram; - GLint buffersCount = 0; - - glGetProgramiv(glprogram, GL_ACTIVE_UNIFORM_BLOCKS, &buffersCount); - - // fast exit - if (buffersCount == 0) { - return 0; - } - - GLint maxNumUniformBufferSlots = 0; - glGetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS, &maxNumUniformBufferSlots); - std::vector uniformBufferSlotMap(maxNumUniformBufferSlots, -1); - - struct UniformBlockInfo { - using Vector = std::vector; - const GLuint index{ 0 }; - const std::string name; - GLint binding{ -1 }; - GLint size{ 0 }; - - static std::string getName(GLuint glprogram, GLuint i) { - static const GLint NAME_LENGTH = 256; - GLint length = 0; - GLchar nameBuffer[NAME_LENGTH]; - glGetActiveUniformBlockiv(glprogram, i, GL_UNIFORM_BLOCK_NAME_LENGTH, &length); - glGetActiveUniformBlockName(glprogram, i, NAME_LENGTH, &length, nameBuffer); - return std::string(nameBuffer); - } - - UniformBlockInfo(GLuint glprogram, GLuint i) : index(i), name(getName(glprogram, i)) { - glGetActiveUniformBlockiv(glprogram, index, GL_UNIFORM_BLOCK_BINDING, &binding); - glGetActiveUniformBlockiv(glprogram, index, GL_UNIFORM_BLOCK_DATA_SIZE, &size); - } - }; - - UniformBlockInfo::Vector uniformBlocks; - uniformBlocks.reserve(buffersCount); - for (int i = 0; i < buffersCount; i++) { - uniformBlocks.push_back(UniformBlockInfo(glprogram, i)); - } - - for (auto& info : uniformBlocks) { - auto requestedBinding = slotBindings.find(info.name); - if (requestedBinding != slotBindings.end()) { - info.binding = (*requestedBinding)._location; - glUniformBlockBinding(glprogram, info.index, info.binding); - uniformBufferSlotMap[info.binding] = info.index; - } - } - - for (auto& info : uniformBlocks) { - if (slotBindings.count(info.name)) { - continue; - } - - // If the binding is 0, or the binding maps to an already used binding - if (info.binding == 0 || !isUnusedSlot(uniformBufferSlotMap[info.binding])) { - // If no binding was assigned then just do it finding a free slot - auto slotIt = std::find_if(uniformBufferSlotMap.begin(), uniformBufferSlotMap.end(), GLBackend::isUnusedSlot); - if (slotIt != uniformBufferSlotMap.end()) { - info.binding = slotIt - uniformBufferSlotMap.begin(); - glUniformBlockBinding(glprogram, info.index, info.binding); - } else { - // This should neve happen, an active ubo cannot find an available slot among the max available?! - info.binding = -1; - } - } - - uniformBufferSlotMap[info.binding] = info.index; - } - - for (auto& info : uniformBlocks) { - static const Element element(SCALAR, gpu::UINT32, gpu::UNIFORM_BUFFER); - buffers.insert(Shader::Slot(info.name, info.binding, element, Resource::BUFFER, info.size)); - } - return buffersCount; -} - -int GLBackend::makeInputSlots(const ShaderObject& shaderProgram, const Shader::BindingSet& slotBindings, Shader::SlotSet& inputs) { - const auto& glprogram = shaderProgram.glprogram; - GLint inputsCount = 0; - - glGetProgramiv(glprogram, GL_ACTIVE_ATTRIBUTES, &inputsCount); - - for (int i = 0; i < inputsCount; i++) { - const GLint NAME_LENGTH = 256; - GLchar name[NAME_LENGTH]; - GLint length = 0; - GLint size = 0; - GLenum type = 0; - glGetActiveAttrib(glprogram, i, NAME_LENGTH, &length, &size, &type, name); - - GLint binding = glGetAttribLocation(glprogram, name); - - auto elementResource = getFormatFromGLUniform(type); - inputs.insert(Shader::Slot(name, binding, elementResource._element, -1)); - } - - return inputsCount; -} - -int GLBackend::makeOutputSlots(const ShaderObject& shaderProgram, const Shader::BindingSet& slotBindings, Shader::SlotSet& outputs) { - /* GLint outputsCount = 0; - - glGetProgramiv(glprogram, GL_ACTIVE_, &outputsCount); - - for (int i = 0; i < inputsCount; i++) { - const GLint NAME_LENGTH = 256; - GLchar name[NAME_LENGTH]; - GLint length = 0; - GLint size = 0; - GLenum type = 0; - glGetActiveAttrib(glprogram, i, NAME_LENGTH, &length, &size, &type, name); - - auto element = getFormatFromGLUniform(type); - outputs.insert(Shader::Slot(name, i, element)); - } - */ - return 0; //inputsCount; -} - -void GLBackend::makeProgramBindings(ShaderObject& shaderObject) { - if (!shaderObject.glprogram) { - return; - } -} - - void GLBackend::initShaderBinaryCache() { GLint numBinFormats = 0; glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS, &numBinFormats); diff --git a/libraries/gpu-gl-common/src/gpu/gl/GLBackendTransform.cpp b/libraries/gpu-gl-common/src/gpu/gl/GLBackendTransform.cpp index ed356acf68..2c2a4e254c 100644 --- a/libraries/gpu-gl-common/src/gpu/gl/GLBackendTransform.cpp +++ b/libraries/gpu-gl-common/src/gpu/gl/GLBackendTransform.cpp @@ -168,9 +168,8 @@ void GLBackend::TransformStageState::update(size_t commandIndex, const StereoSta void GLBackend::TransformStageState::bindCurrentCamera(int eye) const { if (_currentCameraOffset != INVALID_OFFSET) { - static_assert(TRANSFORM_CAMERA_SLOT >= MAX_NUM_UNIFORM_BUFFERS, "TransformCamera may overlap pipeline uniform buffer slots. Invalidate uniform buffer slot cache for safety (call _uniform._buffers[TRANSFORM_CAMERA_SLOT].reset())."); - glBindBufferRange(GL_UNIFORM_BUFFER, TRANSFORM_CAMERA_SLOT, _cameraBuffer, _currentCameraOffset + eye * _cameraUboSize, - sizeof(CameraBufferElement)); + static_assert(slot::buffer::Buffer::CameraTransform >= MAX_NUM_UNIFORM_BUFFERS, "TransformCamera may overlap pipeline uniform buffer slots. Invalidate uniform buffer slot cache for safety (call _uniform._buffers[TRANSFORM_CAMERA_SLOT].reset())."); + glBindBufferRange(GL_UNIFORM_BUFFER, slot::buffer::Buffer::CameraTransform, _cameraBuffer, _currentCameraOffset + eye * _cameraUboSize, sizeof(CameraBufferElement)); } } diff --git a/libraries/gpu-gl-common/src/gpu/gl/GLPipeline.cpp b/libraries/gpu-gl-common/src/gpu/gl/GLPipeline.cpp index ebf1a55232..1b479dceb8 100644 --- a/libraries/gpu-gl-common/src/gpu/gl/GLPipeline.cpp +++ b/libraries/gpu-gl-common/src/gpu/gl/GLPipeline.cpp @@ -10,6 +10,7 @@ #include "GLShader.h" #include "GLState.h" +#include "GLBackend.h" using namespace gpu; using namespace gpu::gl; @@ -51,7 +52,7 @@ GLPipeline* GLPipeline::sync(GLBackend& backend, const Pipeline& pipeline) { // Special case for view correction matrices, any pipeline that declares the correction buffer // uniform will automatically have it provided without any client code necessary. // Required for stable lighting in the HMD. - object->_cameraCorrection = shader->getUniformBuffers().findLocation("cameraCorrectionBuffer"); + object->_cameraCorrection = shader->getUniformBuffers().isValid(gpu::slot::buffer::CameraCorrection); object->_program = programObject; object->_state = stateObject; diff --git a/libraries/gpu-gl-common/src/gpu/gl/GLPipeline.h b/libraries/gpu-gl-common/src/gpu/gl/GLPipeline.h index a298f149d9..a102e33b14 100644 --- a/libraries/gpu-gl-common/src/gpu/gl/GLPipeline.h +++ b/libraries/gpu-gl-common/src/gpu/gl/GLPipeline.h @@ -20,7 +20,7 @@ public: GLState* _state { nullptr }; // Bit of a hack, any pipeline can need the camera correction buffer at execution time, so // we store whether a given pipeline has declared the uniform buffer for it. - int32 _cameraCorrection { -1 }; + bool _cameraCorrection{ false }; }; } } diff --git a/libraries/gpu-gl-common/src/gpu/gl/GLShader.cpp b/libraries/gpu-gl-common/src/gpu/gl/GLShader.cpp index 0a527185ef..44d2bd6ca0 100644 --- a/libraries/gpu-gl-common/src/gpu/gl/GLShader.cpp +++ b/libraries/gpu-gl-common/src/gpu/gl/GLShader.cpp @@ -56,52 +56,5 @@ GLShader* GLShader::sync(GLBackend& backend, const Shader& shader, const Shader: return object; } -bool GLShader::makeProgram(GLBackend& backend, Shader& shader, const Shader::BindingSet& slotBindings, const Shader::CompilationHandler& handler) { - - // First make sure the Shader has been compiled - GLShader* object = sync(backend, shader, handler); - if (!object) { - return false; - } - - // Apply bindings to all program versions and generate list of slots from default version - for (int version = 0; version < GLShader::NumVersions; version++) { - auto& shaderObject = object->_shaderObjects[version]; - if (shaderObject.glprogram) { - shaderObject.uniforms = ::gl::loadUniforms(shaderObject.glprogram); - Shader::SlotSet buffers; - backend.makeUniformBlockSlots(shaderObject, slotBindings, buffers); - - Shader::SlotSet uniforms; - Shader::SlotSet textures; - Shader::SlotSet samplers; - backend.makeUniformSlots(shaderObject, slotBindings, uniforms, textures, samplers); - - Shader::SlotSet resourceBuffers; - backend.makeResourceBufferSlots(shaderObject, slotBindings, resourceBuffers); - - Shader::SlotSet inputs; - backend.makeInputSlots(shaderObject, slotBindings, inputs); - - Shader::SlotSet outputs; - backend.makeOutputSlots(shaderObject, slotBindings, outputs); - - // Define the public slots only from the default version - if (version == 0) { - shader.defineSlots(uniforms, buffers, resourceBuffers, textures, samplers, inputs, outputs); - } // else - { - GLShader::UniformMapping mapping; - for (auto srcUniform : shader.getUniforms()) { - mapping[srcUniform._location] = uniforms.findLocation(srcUniform._name); - } - object->_uniformMappings.push_back(mapping); - } - } - } - - return true; -} - diff --git a/libraries/gpu-gl-common/src/gpu/gl/GLShader.h b/libraries/gpu-gl-common/src/gpu/gl/GLShader.h index 0ba77e50c6..8e3eafcb0f 100644 --- a/libraries/gpu-gl-common/src/gpu/gl/GLShader.h +++ b/libraries/gpu-gl-common/src/gpu/gl/GLShader.h @@ -14,18 +14,18 @@ namespace gpu { namespace gl { struct ShaderObject { - using Uniforms = ::gl::Uniforms; GLuint glshader { 0 }; GLuint glprogram { 0 }; - GLint transformCameraSlot { -1 }; - GLint transformObjectSlot { -1 }; - Uniforms uniforms; + +#if defined(Q_OS_MAC) + using LocationMap = std::unordered_map ; + LocationMap uniformRemap; +#endif }; class GLShader : public GPUObject { public: static GLShader* sync(GLBackend& backend, const Shader& shader, const Shader::CompilationHandler& handler = nullptr); - static bool makeProgram(GLBackend& backend, Shader& shader, const Shader::BindingSet& slotBindings, const Shader::CompilationHandler& handler); enum Version { Mono = 0, @@ -44,22 +44,11 @@ public: ~GLShader(); ShaderObjects _shaderObjects; - UniformMappingVersions _uniformMappings; GLuint getProgram(Version version = Mono) const { return _shaderObjects[version].glprogram; } - GLint getUniformLocation(GLint srcLoc, Version version = Mono) const { - // This check protect against potential invalid src location for this shader, if unknown then return -1. - const auto& mapping = _uniformMappings[version]; - auto found = mapping.find(srcLoc); - if (found == mapping.end()) { - return -1; - } - return found->second; - } - const std::weak_ptr _backend; }; diff --git a/libraries/gpu-gl-common/src/gpu/gl/GLTextureTransfer.cpp b/libraries/gpu-gl-common/src/gpu/gl/GLTextureTransfer.cpp index 07cb5fa15f..eaee054b7d 100644 --- a/libraries/gpu-gl-common/src/gpu/gl/GLTextureTransfer.cpp +++ b/libraries/gpu-gl-common/src/gpu/gl/GLTextureTransfer.cpp @@ -129,9 +129,10 @@ void GLBackend::killTextureManagementStage() { } std::vector GLTextureTransferEngine::getAllTextures() { - std::remove_if(_registeredTextures.begin(), _registeredTextures.end(), [&](const std::weak_ptr& weak) -> bool { - return weak.expired(); + auto expiredBegin = std::remove_if(_registeredTextures.begin(), _registeredTextures.end(), [&](const std::weak_ptr& weak) -> bool { + return weak.expired(); }); + _registeredTextures.erase(expiredBegin, _registeredTextures.end()); std::vector result; result.reserve(_registeredTextures.size()); diff --git a/libraries/gpu-gl/src/gpu/gl/GLDesktopBackend.cpp b/libraries/gpu-gl/src/gpu/gl/GLDesktopBackend.cpp index 72a76f8f90..be8b8cb082 100644 --- a/libraries/gpu-gl/src/gpu/gl/GLDesktopBackend.cpp +++ b/libraries/gpu-gl/src/gpu/gl/GLDesktopBackend.cpp @@ -57,7 +57,3 @@ GLBackend& getBackend() { } return *INSTANCE; } - -bool GLBackend::makeProgram(Shader& shader, const Shader::BindingSet& slotBindings, const Shader::CompilationHandler& handler) { - return GLShader::makeProgram(getBackend(), shader, slotBindings, handler); -} diff --git a/libraries/gpu-gl/src/gpu/gl41/GL41Backend.h b/libraries/gpu-gl/src/gpu/gl41/GL41Backend.h index e840b9fe78..1adb62c2d0 100644 --- a/libraries/gpu-gl/src/gpu/gl41/GL41Backend.h +++ b/libraries/gpu-gl/src/gpu/gl41/GL41Backend.h @@ -35,7 +35,6 @@ class GL41Backend : public GLBackend { friend class Context; public: - static const GLint TRANSFORM_OBJECT_SLOT { 31 }; static const GLint RESOURCE_TRANSFER_TEX_UNIT { 32 }; static const GLint RESOURCE_TRANSFER_EXTRA_TEX_UNIT { 33 }; static const GLint RESOURCE_BUFFER_TEXBUF_TEX_UNIT { 34 }; @@ -172,9 +171,9 @@ protected: void do_blit(const Batch& batch, size_t paramOffset) override; std::string getBackendShaderHeader() const override; - void makeProgramBindings(ShaderObject& shaderObject) override; - int makeResourceBufferSlots(const ShaderObject& shaderProgram, const Shader::BindingSet& slotBindings,Shader::SlotSet& resourceBuffers) override; + void postLinkProgram(ShaderObject& programObject, const Shader& program) const override; + GLint getRealUniformLocation(GLint location) const override; }; } } diff --git a/libraries/gpu-gl/src/gpu/gl41/GL41BackendShader.cpp b/libraries/gpu-gl/src/gpu/gl41/GL41BackendShader.cpp index 0fa1b1bf42..798da06b01 100644 --- a/libraries/gpu-gl/src/gpu/gl41/GL41BackendShader.cpp +++ b/libraries/gpu-gl/src/gpu/gl41/GL41BackendShader.cpp @@ -22,90 +22,98 @@ std::string GL41Backend::getBackendShaderHeader() const { return header; } -int GL41Backend::makeResourceBufferSlots(const ShaderObject& shaderProgram, const Shader::BindingSet& slotBindings,Shader::SlotSet& resourceBuffers) { - GLint ssboCount = 0; - const auto& glprogram = shaderProgram.glprogram; - for (const auto& uniform : shaderProgram.uniforms) { - const auto& name = uniform.name; - const auto& type = uniform.type; - const auto& location = uniform.location; - const GLint INVALID_UNIFORM_LOCATION = -1; +template +std::vector toCNames(const C& container, F lambda) { + std::vector result; + result.reserve(container.size()); + std::transform(container.begin(), container.end(), std::back_inserter(result), lambda); + return result; +} - // Try to make sense of the gltype - auto elementResource = getFormatFromGLUniform(type); - - // The uniform as a standard var type - if (location != INVALID_UNIFORM_LOCATION) { - - if (elementResource._resource == Resource::BUFFER) { - if (elementResource._element.getSemantic() == gpu::RESOURCE_BUFFER) { - // Let's make sure the name doesn't contains an array element - std::string sname(name); - auto foundBracket = sname.find_first_of('['); - if (foundBracket != std::string::npos) { - // std::string arrayname = sname.substr(0, foundBracket); +#if defined(Q_OS_MAC) +ShaderObject::LocationMap buildRemap(GLuint glprogram, const gpu::Shader::SlotSet& slotSet) { + static const GLint INVALID_INDEX = -1; + ShaderObject::LocationMap result; + const auto expectedNames = slotSet.getNames(); + const auto count = expectedNames.size(); + std::vector indices; + indices.resize(count); + glGetUniformIndices(glprogram, (GLsizei)count, + toCNames(expectedNames, [](const std::string& name) { return name.c_str(); }).data(), + (GLuint*)indices.data()); - if (sname[foundBracket + 1] == '0') { - sname = sname.substr(0, foundBracket); - } else { - // skip this uniform since it's not the first element of an array - continue; - } - } + const auto expectedLocationsByName = slotSet.getLocationsByName(); + for (size_t i = 0; i < count; ++i) { + const auto& index = indices[i]; + const auto& name = expectedNames[i]; + const auto& expectedLocation = expectedLocationsByName.at(name); + if (INVALID_INDEX == index) { + result[expectedLocation] = gpu::Shader::INVALID_LOCATION; + continue; + } - // For texture/Sampler, the location is the actual binding value - GLint binding = -1; - glGetUniformiv(glprogram, location, &binding); + ::gl::Uniform uniformInfo(glprogram, index); + if (expectedLocation != uniformInfo.binding) { + result[expectedLocation] = uniformInfo.binding; + } + } + return result; +} +#endif - if (binding == GL41Backend::TRANSFORM_OBJECT_SLOT) { - continue; - } - - auto requestedBinding = slotBindings.find(std::string(sname)); - if (requestedBinding != slotBindings.end()) { - GLint requestedLoc = (*requestedBinding)._location + GL41Backend::RESOURCE_BUFFER_SLOT0_TEX_UNIT; - if (binding != requestedLoc) { - binding = requestedLoc; - } - } else { - binding += GL41Backend::RESOURCE_BUFFER_SLOT0_TEX_UNIT; - } - glProgramUniform1i(glprogram, location, binding); - - ssboCount++; - resourceBuffers.insert(Shader::Slot(name, binding, elementResource._element, elementResource._resource)); - } +void GL41Backend::postLinkProgram(ShaderObject& programObject, const Shader& program) const { + const auto& glprogram = programObject.glprogram; + // For the UBOs, use glUniformBlockBinding to fixup the locations based on the reflection + { + const auto expectedUbos = program.getUniformBuffers().getLocationsByName(); + auto ubos = ::gl::UniformBlock::load(glprogram); + for (const auto& ubo : ubos) { + const auto& name = ubo.name; + if (0 == expectedUbos.count(name)) { + continue; + } + const auto& targetLocation = expectedUbos.at(name); + if (ubo.binding != targetLocation) { + glUniformBlockBinding(glprogram, ubo.index, targetLocation); } } } - return ssboCount; + // For the Textures, us glUniform1i to fixup the active texture slots based on the reflection + { + const auto expectedTextures = program.getTextures().getLocationsByName(); + const auto textureUniforms = ::gl::Uniform::loadByName(glprogram, program.getTextures().getNames()); + for (const auto& texture : textureUniforms) { + const auto& targetBinding = expectedTextures.at(texture.name); + glProgramUniform1i(glprogram, texture.binding, targetBinding); + } + } + + // For the resource buffers + { + const auto expectedTextures = program.getTextures().getLocationsByName(); + const auto textureUniforms = ::gl::Uniform::loadByName(glprogram, program.getTextures().getNames()); + for (const auto& texture : textureUniforms) { + const auto& targetBinding = expectedTextures.at(texture.name); + glProgramUniform1i(glprogram, texture.binding, targetBinding); + } + } + +#if defined(Q_OS_MAC) + // For the uniforms, we need to create a remapping layer + programObject.uniformRemap = buildRemap(glprogram, program.getUniforms()); +#endif } -void GL41Backend::makeProgramBindings(ShaderObject& shaderObject) { - if (!shaderObject.glprogram) { - return; + +GLint GL41Backend::getRealUniformLocation(GLint location) const { + GLint result = location; +#if defined(Q_OS_MAC) + auto& shader = _pipeline._programShader->_shaderObjects[(GLShader::Version)isStereo()]; + auto itr = shader.uniformRemap.find(location); + if (itr != shader.uniformRemap.end()) { + result = itr->second; } - GLuint glprogram = shaderObject.glprogram; - GLint loc = -1; - - GLBackend::makeProgramBindings(shaderObject); - - // now assign the ubo binding, then DON't relink! - - //Check for gpu specific uniform slotBindings - loc = glGetUniformLocation(glprogram, "transformObjectBuffer"); - if (loc >= 0) { - glProgramUniform1i(glprogram, loc, GL41Backend::TRANSFORM_OBJECT_SLOT); - shaderObject.transformObjectSlot = GL41Backend::TRANSFORM_OBJECT_SLOT; - } - - loc = glGetUniformBlockIndex(glprogram, "transformCameraBuffer"); - if (loc >= 0) { - glUniformBlockBinding(glprogram, loc, gpu::TRANSFORM_CAMERA_SLOT); - shaderObject.transformCameraSlot = gpu::TRANSFORM_CAMERA_SLOT; - } - - (void)CHECK_GL_ERROR(); +#endif + return result; } - diff --git a/libraries/gpu-gl/src/gpu/gl41/GL41BackendTransform.cpp b/libraries/gpu-gl/src/gpu/gl41/GL41BackendTransform.cpp index 41a3c5cf25..b11707eba2 100644 --- a/libraries/gpu-gl/src/gpu/gl41/GL41BackendTransform.cpp +++ b/libraries/gpu-gl/src/gpu/gl41/GL41BackendTransform.cpp @@ -20,7 +20,7 @@ void GL41Backend::initTransform() { glGenTextures(1, &_transform._objectBufferTexture); size_t cameraSize = sizeof(TransformStageState::CameraBufferElement); while (_transform._cameraUboSize < cameraSize) { - _transform._cameraUboSize += _uboAlignment; + _transform._cameraUboSize += UNIFORM_BUFFER_OFFSET_ALIGNMENT; } } @@ -58,7 +58,7 @@ void GL41Backend::transferTransformState(const Batch& batch) const { glBindBuffer(GL_ARRAY_BUFFER, 0); } - glActiveTexture(GL_TEXTURE0 + GL41Backend::TRANSFORM_OBJECT_SLOT); + glActiveTexture(GL_TEXTURE0 + slot::texture::ObjectTransforms); glBindTexture(GL_TEXTURE_BUFFER, _transform._objectBufferTexture); if (!batch._objects.empty()) { glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, _transform._objectBuffer); diff --git a/libraries/gpu-gl/src/gpu/gl45/GL45Backend.cpp b/libraries/gpu-gl/src/gpu/gl45/GL45Backend.cpp index c119e27d5b..8f8e158334 100644 --- a/libraries/gpu-gl/src/gpu/gl45/GL45Backend.cpp +++ b/libraries/gpu-gl/src/gpu/gl45/GL45Backend.cpp @@ -18,8 +18,24 @@ Q_LOGGING_CATEGORY(gpugl45logging, "hifi.gpu.gl45") using namespace gpu; using namespace gpu::gl45; +GLint GL45Backend::MAX_COMBINED_SHADER_STORAGE_BLOCKS{ 0 }; + +static void staticInit() { + static std::once_flag once; + std::call_once(once, [&] { + glGetIntegerv(GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS, &GL45Backend::MAX_COMBINED_SHADER_STORAGE_BLOCKS); + }); +} const std::string GL45Backend::GL45_VERSION { "GL45" }; +GL45Backend::GL45Backend(bool syncCache) : Parent(syncCache) { + staticInit(); +} + +GL45Backend::GL45Backend() : Parent() { + staticInit(); +} + void GL45Backend::recycle() const { Parent::recycle(); } diff --git a/libraries/gpu-gl/src/gpu/gl45/GL45Backend.h b/libraries/gpu-gl/src/gpu/gl45/GL45Backend.h index cb7ddce930..8694e15d97 100644 --- a/libraries/gpu-gl/src/gpu/gl45/GL45Backend.h +++ b/libraries/gpu-gl/src/gpu/gl45/GL45Backend.h @@ -33,18 +33,13 @@ class GL45Backend : public GLBackend { friend class Context; public: + static GLint MAX_COMBINED_SHADER_STORAGE_BLOCKS; #if GPU_BINDLESS_TEXTURES virtual bool supportsBindless() const override { return true; } #endif -#ifdef GPU_SSBO_TRANSFORM_OBJECT - static const GLint TRANSFORM_OBJECT_SLOT { 14 }; // SSBO binding slot -#else - static const GLint TRANSFORM_OBJECT_SLOT { 31 }; // TBO binding slot -#endif - - explicit GL45Backend(bool syncCache) : Parent(syncCache) {} - GL45Backend() : Parent() {} + explicit GL45Backend(bool syncCache); + GL45Backend(); virtual ~GL45Backend() { // call resetStages here rather than in ~GLBackend dtor because it will call releaseResourceBuffer // which is pure virtual from GLBackend's dtor. @@ -273,8 +268,6 @@ protected: // Shader Stage std::string getBackendShaderHeader() const override; - void makeProgramBindings(ShaderObject& shaderObject) override; - int makeResourceBufferSlots(const ShaderObject& shaderProgram, const Shader::BindingSet& slotBindings,Shader::SlotSet& resourceBuffers) override; // Texture Management Stage void initTextureManagementStage() override; diff --git a/libraries/gpu-gl/src/gpu/gl45/GL45BackendShader.cpp b/libraries/gpu-gl/src/gpu/gl45/GL45BackendShader.cpp index f1f388d501..6cc0d226d6 100644 --- a/libraries/gpu-gl/src/gpu/gl45/GL45BackendShader.cpp +++ b/libraries/gpu-gl/src/gpu/gl45/GL45BackendShader.cpp @@ -26,152 +26,3 @@ std::string GL45Backend::getBackendShaderHeader() const { ); return header; } - -int GL45Backend::makeResourceBufferSlots(const ShaderObject& shaderProgram, const Shader::BindingSet& slotBindings,Shader::SlotSet& resourceBuffers) { - const auto& glprogram = shaderProgram.glprogram; - GLint buffersCount = 0; - glGetProgramInterfaceiv(glprogram, GL_SHADER_STORAGE_BLOCK, GL_ACTIVE_RESOURCES, &buffersCount); - - // fast exit - if (buffersCount == 0) { - return 0; - } - - GLint maxNumResourceBufferSlots = 0; - glGetIntegerv(GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS, &maxNumResourceBufferSlots); - std::vector resourceBufferSlotMap(maxNumResourceBufferSlots, -1); - - struct ResourceBlockInfo { - using Vector = std::vector; - const GLuint index{ 0 }; - const std::string name; - GLint binding{ -1 }; - GLint size{ 0 }; - - static std::string getName(GLuint glprogram, GLuint i) { - static const GLint NAME_LENGTH = 256; - GLint length = 0; - GLchar nameBuffer[NAME_LENGTH]; - glGetProgramResourceName(glprogram, GL_SHADER_STORAGE_BLOCK, i, NAME_LENGTH, &length, nameBuffer); - return std::string(nameBuffer); - } - - ResourceBlockInfo(GLuint glprogram, GLuint i) : index(i), name(getName(glprogram, i)) { - GLenum props[2] = { GL_BUFFER_BINDING, GL_BUFFER_DATA_SIZE}; - glGetProgramResourceiv(glprogram, GL_SHADER_STORAGE_BLOCK, i, 2, props, 2, nullptr, &binding); - } - }; - - ResourceBlockInfo::Vector resourceBlocks; - resourceBlocks.reserve(buffersCount); - for (int i = 0; i < buffersCount; i++) { - resourceBlocks.push_back(ResourceBlockInfo(glprogram, i)); - } - - for (auto& info : resourceBlocks) { - auto requestedBinding = slotBindings.find(info.name); - if (requestedBinding != slotBindings.end()) { - info.binding = (*requestedBinding)._location; - glShaderStorageBlockBinding(glprogram, info.index, info.binding); - resourceBufferSlotMap[info.binding] = info.index; - } - } - - for (auto& info : resourceBlocks) { - if (slotBindings.count(info.name)) { - continue; - } - - // If the binding is -1, or the binding maps to an already used binding - if (info.binding == -1 || !isUnusedSlot(resourceBufferSlotMap[info.binding])) { - // If no binding was assigned then just do it finding a free slot - auto slotIt = std::find_if(resourceBufferSlotMap.begin(), resourceBufferSlotMap.end(), GLBackend::isUnusedSlot); - if (slotIt != resourceBufferSlotMap.end()) { - info.binding = slotIt - resourceBufferSlotMap.begin(); - glShaderStorageBlockBinding(glprogram, info.index, info.binding); - } else { - // This should never happen, an active ssbo cannot find an available slot among the max available?! - info.binding = -1; - } - } - - resourceBufferSlotMap[info.binding] = info.index; - } - - for (auto& info : resourceBlocks) { - static const Element element(SCALAR, gpu::UINT32, gpu::RESOURCE_BUFFER); - resourceBuffers.insert(Shader::Slot(info.name, info.binding, element, Resource::BUFFER, info.size)); - } - return buffersCount; -/* - GLint ssboCount = 0; - glGetProgramInterfaceiv(glprogram, GL_SHADER_STORAGE_BLOCK, GL_ACTIVE_RESOURCES, &ssboCount); - if (ssboCount > 0) { - GLint maxNameLength = 0; - glGetProgramInterfaceiv(glprogram, GL_SHADER_STORAGE_BLOCK, GL_MAX_NAME_LENGTH, &maxNameLength); - std::vector nameBytes(maxNameLength); - - for (GLint b = 0; b < ssboCount; b++) { - GLint length; - glGetProgramResourceName(glprogram, GL_SHADER_STORAGE_BLOCK, b, maxNameLength, &length, nameBytes.data()); - std::string bufferName(nameBytes.data()); - - GLenum props = GL_BUFFER_BINDING; - GLint binding = -1; - glGetProgramResourceiv(glprogram, GL_SHADER_STORAGE_BLOCK, b, 1, &props, 1, nullptr, &binding); - - auto requestedBinding = slotBindings.find(std::string(bufferName)); - if (requestedBinding != slotBindings.end()) { - if (binding != (*requestedBinding)._location) { - binding = (*requestedBinding)._location; - glShaderStorageBlockBinding(glprogram, b, binding); - } - } - - static const Element element(SCALAR, gpu::UINT32, gpu::RESOURCE_BUFFER); - resourceBuffers.insert(Shader::Slot(bufferName, binding, element, -1)); - } - } - return ssboCount;*/ -} - -void GL45Backend::makeProgramBindings(ShaderObject& shaderObject) { - if (!shaderObject.glprogram) { - return; - } - GLuint glprogram = shaderObject.glprogram; - GLint loc = -1; - - GLBackend::makeProgramBindings(shaderObject); - - // now assign the ubo binding, then DON't relink! - - //Check for gpu specific uniform slotBindings -#ifdef GPU_SSBO_TRANSFORM_OBJECT - loc = glGetProgramResourceIndex(glprogram, GL_SHADER_STORAGE_BLOCK, "transformObjectBuffer"); - if (loc >= 0) { - glShaderStorageBlockBinding(glprogram, loc, GL45Backend::TRANSFORM_OBJECT_SLOT); - shaderObject.transformObjectSlot = GL45Backend::TRANSFORM_OBJECT_SLOT; - } -#else - loc = glGetUniformLocation(glprogram, "transformObjectBuffer"); - if (loc >= 0) { - glProgramUniform1i(glprogram, loc, GL45Backend::TRANSFORM_OBJECT_SLOT); - shaderObject.transformObjectSlot = GL45Backend::TRANSFORM_OBJECT_SLOT; - } -#endif - - loc = glGetUniformBlockIndex(glprogram, "transformCameraBuffer"); - if (loc >= 0) { - glUniformBlockBinding(glprogram, loc, gpu::TRANSFORM_CAMERA_SLOT); - shaderObject.transformCameraSlot = gpu::TRANSFORM_CAMERA_SLOT; - } - - loc = glGetUniformBlockIndex(glprogram, "gpu_resourceTextureTable0"); - if (loc >= 0) { - glUniformBlockBinding(glprogram, loc, RESOURCE_TABLE_TEXTURE_SLOT_OFFSET); - } - - (void)CHECK_GL_ERROR(); -} - diff --git a/libraries/gpu-gl/src/gpu/gl45/GL45BackendTransform.cpp b/libraries/gpu-gl/src/gpu/gl45/GL45BackendTransform.cpp index ae323612c4..f389c5f62c 100644 --- a/libraries/gpu-gl/src/gpu/gl45/GL45BackendTransform.cpp +++ b/libraries/gpu-gl/src/gpu/gl45/GL45BackendTransform.cpp @@ -25,7 +25,7 @@ void GL45Backend::initTransform() { #endif size_t cameraSize = sizeof(TransformStageState::CameraBufferElement); while (_transform._cameraUboSize < cameraSize) { - _transform._cameraUboSize += _uboAlignment; + _transform._cameraUboSize += UNIFORM_BUFFER_OFFSET_ALIGNMENT; } } @@ -57,9 +57,9 @@ void GL45Backend::transferTransformState(const Batch& batch) const { } #ifdef GPU_SSBO_TRANSFORM_OBJECT - glBindBufferBase(GL_SHADER_STORAGE_BUFFER, GL45Backend::TRANSFORM_OBJECT_SLOT, _transform._objectBuffer); + glBindBufferBase(GL_SHADER_STORAGE_BUFFER, slot::storage::ObjectTransforms, _transform._objectBuffer); #else - glActiveTexture(GL_TEXTURE0 + GL45Backend::TRANSFORM_OBJECT_SLOT); + glActiveTexture(GL_TEXTURE0 + slot::texture::ObjectTransforms); glBindTexture(GL_TEXTURE_BUFFER, _transform._objectBufferTexture); glTextureBuffer(_transform._objectBufferTexture, GL_RGBA32F, _transform._objectBuffer); #endif diff --git a/libraries/gpu-gles/src/gpu/gl/GLESBackend.cpp b/libraries/gpu-gles/src/gpu/gl/GLESBackend.cpp index 2e2c988e77..df963ee40c 100644 --- a/libraries/gpu-gles/src/gpu/gl/GLESBackend.cpp +++ b/libraries/gpu-gles/src/gpu/gl/GLESBackend.cpp @@ -50,7 +50,3 @@ GLBackend& getBackend() { } return *INSTANCE; } - -bool GLBackend::makeProgram(Shader& shader, const Shader::BindingSet& slotBindings, const Shader::CompilationHandler& handler) { - return GLShader::makeProgram(getBackend(), shader, slotBindings, handler); -} diff --git a/libraries/gpu-gles/src/gpu/gles/GLESBackend.h b/libraries/gpu-gles/src/gpu/gles/GLESBackend.h index 9656d29ac5..785f4c3ef9 100644 --- a/libraries/gpu-gles/src/gpu/gles/GLESBackend.h +++ b/libraries/gpu-gles/src/gpu/gles/GLESBackend.h @@ -163,9 +163,6 @@ protected: void do_blit(const Batch& batch, size_t paramOffset) override; std::string getBackendShaderHeader() const override; - void makeProgramBindings(ShaderObject& shaderObject) override; - int makeResourceBufferSlots(const ShaderObject& shaderObject, const Shader::BindingSet& slotBindings,Shader::SlotSet& resourceBuffers) override; - }; } } @@ -173,4 +170,4 @@ protected: Q_DECLARE_LOGGING_CATEGORY(gpugleslogging) -#endif \ No newline at end of file +#endif diff --git a/libraries/gpu-gles/src/gpu/gles/GLESBackendShader.cpp b/libraries/gpu-gles/src/gpu/gles/GLESBackendShader.cpp index 34caa97696..ee8408c533 100644 --- a/libraries/gpu-gles/src/gpu/gles/GLESBackendShader.cpp +++ b/libraries/gpu-gles/src/gpu/gles/GLESBackendShader.cpp @@ -24,93 +24,3 @@ std::string GLESBackend::getBackendShaderHeader() const { )SHADER"); return header; } - -int GLESBackend::makeResourceBufferSlots(const ShaderObject& shaderObject, const Shader::BindingSet& slotBindings,Shader::SlotSet& resourceBuffers) { - GLint ssboCount = 0; - GLint uniformsCount = 0; - const auto& glprogram = shaderObject.glprogram; - - for (const auto& uniform : shaderObject.uniforms) { - const auto& type = uniform.type; - const auto& location = uniform.location; - const auto& name = uniform.name; - const GLint INVALID_UNIFORM_LOCATION = -1; - - // Try to make sense of the gltype - auto elementResource = getFormatFromGLUniform(type); - - // The uniform as a standard var type - if (location != INVALID_UNIFORM_LOCATION) { - - if (elementResource._resource == Resource::BUFFER) { - if (elementResource._element.getSemantic() == gpu::RESOURCE_BUFFER) { - // Let's make sure the name doesn't contains an array element - std::string sname(name); - auto foundBracket = sname.find_first_of('['); - if (foundBracket != std::string::npos) { - // std::string arrayname = sname.substr(0, foundBracket); - - if (sname[foundBracket + 1] == '0') { - sname = sname.substr(0, foundBracket); - } else { - // skip this uniform since it's not the first element of an array - continue; - } - } - - // For texture/Sampler, the location is the actual binding value - GLint binding = -1; - glGetUniformiv(glprogram, location, &binding); - - if (binding == GLESBackend::TRANSFORM_OBJECT_SLOT) { - continue; - } - - auto requestedBinding = slotBindings.find(std::string(sname)); - if (requestedBinding != slotBindings.end()) { - GLint requestedLoc = (*requestedBinding)._location + GLESBackend::RESOURCE_BUFFER_SLOT0_TEX_UNIT; - if (binding != requestedLoc) { - binding = requestedLoc; - } - } else { - binding += GLESBackend::RESOURCE_BUFFER_SLOT0_TEX_UNIT; - } - glProgramUniform1i(glprogram, location, binding); - - ssboCount++; - resourceBuffers.insert(Shader::Slot(name, binding, elementResource._element, elementResource._resource)); - } - } - } - } - - return ssboCount; -} - -void GLESBackend::makeProgramBindings(ShaderObject& shaderObject) { - if (!shaderObject.glprogram) { - return; - } - GLuint glprogram = shaderObject.glprogram; - GLint loc = -1; - - GLBackend::makeProgramBindings(shaderObject); - - // now assign the ubo binding, then DON't relink! - - //Check for gpu specific uniform slotBindings - loc = glGetUniformLocation(glprogram, "transformObjectBuffer"); - if (loc >= 0) { - glProgramUniform1i(glprogram, loc, GLESBackend::TRANSFORM_OBJECT_SLOT); - shaderObject.transformObjectSlot = GLESBackend::TRANSFORM_OBJECT_SLOT; - } - - loc = glGetUniformBlockIndex(glprogram, "transformCameraBuffer"); - if (loc >= 0) { - glUniformBlockBinding(glprogram, loc, gpu::TRANSFORM_CAMERA_SLOT); - shaderObject.transformCameraSlot = gpu::TRANSFORM_CAMERA_SLOT; - } - - (void)CHECK_GL_ERROR(); -} - diff --git a/libraries/gpu-gles/src/gpu/gles/GLESBackendTransform.cpp b/libraries/gpu-gles/src/gpu/gles/GLESBackendTransform.cpp index 7d33ca822d..661eb0de99 100644 --- a/libraries/gpu-gles/src/gpu/gles/GLESBackendTransform.cpp +++ b/libraries/gpu-gles/src/gpu/gles/GLESBackendTransform.cpp @@ -19,8 +19,10 @@ void GLESBackend::initTransform() { glGenBuffers(1, &_transform._drawCallInfoBuffer); glGenTextures(1, &_transform._objectBufferTexture); size_t cameraSize = sizeof(TransformStageState::CameraBufferElement); - while (_transform._cameraUboSize < cameraSize) { - _transform._cameraUboSize += _uboAlignment; + if (UNIFORM_BUFFER_OFFSET_ALIGNMENT > 0) { + while (_transform._cameraUboSize < cameraSize) { + _transform._cameraUboSize += UNIFORM_BUFFER_OFFSET_ALIGNMENT; + } } } diff --git a/libraries/gpu/src/gpu/Batch.h b/libraries/gpu/src/gpu/Batch.h index 836d7ca5ff..bcbfe0616d 100644 --- a/libraries/gpu/src/gpu/Batch.h +++ b/libraries/gpu/src/gpu/Batch.h @@ -24,15 +24,12 @@ #include "Stream.h" #include "Texture.h" #include "Transform.h" +#include "ShaderConstants.h" class QDebug; #define BATCH_PREALLOCATE_MIN 128 namespace gpu { -enum ReservedSlot { - TRANSFORM_CAMERA_SLOT = 15, -}; - // The named batch data provides a mechanism for accumulating data into buffers over the course // of many independent calls. For instance, two objects in the scene might both want to render // a simple box, but are otherwise unaware of each other. The common code that they call to render @@ -170,10 +167,10 @@ public: void resetViewTransform() { setViewTransform(Transform(), false); } void setViewTransform(const Transform& view, bool camera = true); void setProjectionTransform(const Mat4& proj); - void setProjectionJitter(float jx = 0.0f, float jy = 0.0f); - // Very simple 1 level stack management of jitter. - void pushProjectionJitter(float jx = 0.0f, float jy = 0.0f); - void popProjectionJitter(); + void setProjectionJitter(float jx = 0.0f, float jy = 0.0f); + // Very simple 1 level stack management of jitter. + void pushProjectionJitter(float jx = 0.0f, float jy = 0.0f); + void popProjectionJitter(); // Viewport is xy = low left corner in framebuffer, zw = width height of the viewport, expressed in pixels void setViewportTransform(const Vec4i& viewport); void setDepthRangeTransform(float nearDepth, float farDepth); @@ -299,9 +296,9 @@ public: COMMAND_setModelTransform, COMMAND_setViewTransform, - COMMAND_setProjectionTransform, - COMMAND_setProjectionJitter, - COMMAND_setViewportTransform, + COMMAND_setProjectionTransform, + COMMAND_setProjectionJitter, + COMMAND_setViewportTransform, COMMAND_setDepthRangeTransform, COMMAND_setPipeline, @@ -504,7 +501,7 @@ public: NamedBatchDataMap _namedData; - glm::vec2 _projectionJitter{ 0.0f, 0.0f }; + glm::vec2 _projectionJitter{ 0.0f, 0.0f }; bool _enableStereo{ true }; bool _enableSkybox { false }; diff --git a/libraries/gpu/src/gpu/Context.cpp b/libraries/gpu/src/gpu/Context.cpp index bb6b27626a..5783b7f59e 100644 --- a/libraries/gpu/src/gpu/Context.cpp +++ b/libraries/gpu/src/gpu/Context.cpp @@ -34,7 +34,6 @@ void ContextStats::evalDelta(const ContextStats& begin, const ContextStats& end) Context::CreateBackend Context::_createBackendCallback = nullptr; -Context::MakeProgram Context::_makeProgramCallback = nullptr; std::once_flag Context::_initialized; Context::Context() { @@ -139,20 +138,6 @@ void Context::executeFrame(const FramePointer& frame) const { _frameStats.evalDelta(beginStats, endStats); } -bool Context::makeProgram(Shader& shader, const Shader::BindingSet& bindings, const Shader::CompilationHandler& handler) { - PROFILE_RANGE_EX(app, "makeProgram", 0xff4040c0, shader.getID()); - // If we're running in another DLL context, we need to fetch the program callback out of the application - // FIXME find a way to do this without reliance on Qt app properties - if (!_makeProgramCallback) { - void* rawCallback = qApp->property(hifi::properties::gl::MAKE_PROGRAM_CALLBACK).value(); - _makeProgramCallback = reinterpret_cast(rawCallback); - } - if (shader.isProgram() && _makeProgramCallback) { - return _makeProgramCallback(shader, bindings, handler); - } - return false; -} - void Context::enableStereo(bool enable) { _stereo._enable = enable; } diff --git a/libraries/gpu/src/gpu/Context.h b/libraries/gpu/src/gpu/Context.h index 4560ea5526..011f980957 100644 --- a/libraries/gpu/src/gpu/Context.h +++ b/libraries/gpu/src/gpu/Context.h @@ -115,7 +115,7 @@ public: static ContextMetricSize textureResourceIdealGPUMemSize; protected: - virtual bool isStereo() { + virtual bool isStereo() const { return _stereo.isStereo(); } @@ -140,14 +140,12 @@ class Context { public: using Size = Resource::Size; typedef BackendPointer (*CreateBackend)(); - typedef bool (*MakeProgram)(Shader& shader, const Shader::BindingSet& bindings, const Shader::CompilationHandler& handler); // This one call must happen before any context is created or used (Shader::MakeProgram) in order to setup the Backend and any singleton data needed template static void init() { std::call_once(_initialized, [] { _createBackendCallback = T::createBackend; - _makeProgramCallback = T::makeProgram; T::init(); }); } @@ -261,14 +259,7 @@ protected: // Sampled at the end of every frame, the stats of all the counters mutable ContextStats _frameStats; - // This function can only be called by "static Shader::makeProgram()" - // makeProgramShader(...) make a program shader ready to be used in a Batch. - // It compiles the sub shaders, link them and defines the Slots and their bindings. - // If the shader passed is not a program, nothing happens. - static bool makeProgram(Shader& shader, const Shader::BindingSet& bindings, const Shader::CompilationHandler& handler); - static CreateBackend _createBackendCallback; - static MakeProgram _makeProgramCallback; static std::once_flag _initialized; friend class Shader; diff --git a/libraries/gpu/src/gpu/DrawColor.slf b/libraries/gpu/src/gpu/DrawColor.slf index c24d69d29f..2540d56d69 100644 --- a/libraries/gpu/src/gpu/DrawColor.slf +++ b/libraries/gpu/src/gpu/DrawColor.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// DrawColor.frag +// // Draw with color uniform // // Created by Olivier Prat on 25/10/2017 @@ -10,9 +12,12 @@ // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -uniform vec4 color; -out vec4 outFragColor; +<@include gpu/ShaderConstants.h@> + +layout(location=GPU_UNIFORM_COLOR) uniform vec4 color; + +layout(location=0) out vec4 outFragColor; void main(void) { outFragColor = color; diff --git a/libraries/gpu/src/gpu/DrawColoredTexture.slf b/libraries/gpu/src/gpu/DrawColoredTexture.slf index 2a7f6aae36..632bf18391 100755 --- a/libraries/gpu/src/gpu/DrawColoredTexture.slf +++ b/libraries/gpu/src/gpu/DrawColoredTexture.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// DrawColoredTexture.frag +// // Draw texture 0 fetched at texcoord.xy, Blend with color uniform // // Created by Sam Gateau on 7/12/2015 @@ -11,12 +13,13 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +<@include gpu/ShaderConstants.h@> -uniform sampler2D colorMap; -uniform vec4 color; +layout(binding=0) uniform sampler2D colorMap; +layout(location=GPU_UNIFORM_COLOR) uniform vec4 color; -in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 outFragColor; void main(void) { outFragColor = texture(colorMap, varTexCoord0) * color; diff --git a/libraries/gpu/src/gpu/DrawTexcoordRectTransformUnitQuad.slv b/libraries/gpu/src/gpu/DrawTexcoordRectTransformUnitQuad.slv index 1f788051bc..d401fc40c2 100755 --- a/libraries/gpu/src/gpu/DrawTexcoordRectTransformUnitQuad.slv +++ b/libraries/gpu/src/gpu/DrawTexcoordRectTransformUnitQuad.slv @@ -1,6 +1,9 @@ <@include gpu/Config.slh@> <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> +// +// DrawTexcoordRectTransformUnitQuad.vert + // // Draw and transform the unit quad [-1,-1 -> 1,1] // Transform the normalized texcoords [0, 1] to be in the range [texcoordRect.xy, texcoordRect.xy + texcoordRect.zw] @@ -14,12 +17,13 @@ // <@include gpu/Transform.slh@> +<@include gpu/ShaderConstants.h@> <$declareStandardTransform()$> -uniform vec4 texcoordRect; +layout(location=GPU_UNIFORM_TEXCOORD_RECT) uniform vec4 texcoordRect; -out vec2 varTexCoord0; +layout(location=0) out vec2 varTexCoord0; void main(void) { const vec4 UNIT_QUAD[4] = vec4[4]( diff --git a/libraries/gpu/src/gpu/DrawTexture.slf b/libraries/gpu/src/gpu/DrawTexture.slf index 64389f02b3..4298729b8b 100755 --- a/libraries/gpu/src/gpu/DrawTexture.slf +++ b/libraries/gpu/src/gpu/DrawTexture.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// DrawTexture.frag +// // Draw texture 0 fetched at texcoord.xy // // Created by Sam Gateau on 6/22/2015 @@ -12,10 +14,10 @@ // -uniform sampler2D colorMap; +layout(binding=0) uniform sampler2D colorMap; -in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 outFragColor; void main(void) { outFragColor = texture(colorMap, varTexCoord0); diff --git a/libraries/gpu/src/gpu/DrawTextureMirroredX.slf b/libraries/gpu/src/gpu/DrawTextureMirroredX.slf index aef4033496..ab6333f08d 100644 --- a/libraries/gpu/src/gpu/DrawTextureMirroredX.slf +++ b/libraries/gpu/src/gpu/DrawTextureMirroredX.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// DrawTextureMirroredX.frag +// // Draw texture 0 fetched at (1.0 - texcoord.x, texcoord.y) // // Created by Sam Gondelman on 10/24/2017 @@ -12,10 +14,10 @@ // -uniform sampler2D colorMap; +layout(binding=0) uniform sampler2D colorMap; -in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 outFragColor; void main(void) { outFragColor = texture(colorMap, vec2(1.0 - varTexCoord0.x, varTexCoord0.y)); diff --git a/libraries/gpu/src/gpu/DrawTextureOpaque.slf b/libraries/gpu/src/gpu/DrawTextureOpaque.slf index 14d2072ff3..d98daa1c9a 100755 --- a/libraries/gpu/src/gpu/DrawTextureOpaque.slf +++ b/libraries/gpu/src/gpu/DrawTextureOpaque.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// DrawTextureOpaque.frag +// // Draw texture 0 fetched at texcoord.xy // Alpha is 1 // @@ -12,11 +14,13 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +<@include gpu/ShaderConstants.h@> -uniform sampler2D colorMap; +layout(binding=0) uniform sampler2D colorMap; -in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=GPU_ATTR_TEXCOORD0) in vec2 varTexCoord0; + +layout(location=0) out vec4 outFragColor; void main(void) { outFragColor = vec4(texture(colorMap, varTexCoord0).xyz, 1.0); diff --git a/libraries/gpu/src/gpu/DrawTransformUnitQuad.slv b/libraries/gpu/src/gpu/DrawTransformUnitQuad.slv index 845cf0326d..eed3c92245 100755 --- a/libraries/gpu/src/gpu/DrawTransformUnitQuad.slv +++ b/libraries/gpu/src/gpu/DrawTransformUnitQuad.slv @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// DrawTransformUnitQuad.vert +// // Draw and transform the unit quad [-1,-1 -> 1,1] // Simply draw a Triangle_strip of 2 triangles, no input buffers or index buffer needed // @@ -16,7 +18,7 @@ <$declareStandardTransform()$> -out vec2 varTexCoord0; +layout(location=0) out vec2 varTexCoord0; void main(void) { const vec4 UNIT_QUAD[4] = vec4[4]( diff --git a/libraries/gpu/src/gpu/DrawTransformVertexPosition.slv b/libraries/gpu/src/gpu/DrawTransformVertexPosition.slv index cf66a615f5..39771403d1 100644 --- a/libraries/gpu/src/gpu/DrawTransformVertexPosition.slv +++ b/libraries/gpu/src/gpu/DrawTransformVertexPosition.slv @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// DrawTransformVertexPosition.vert +// // Draw and transform the fed vertex position with the standard MVP stack // Output the clip position // @@ -16,9 +18,9 @@ <$declareStandardTransform()$> -layout(location = 0) in vec4 inPosition; +layout(location=0) in vec4 inPosition; -out vec3 varWorldPos; +layout(location=0) out vec3 varWorldPos; void main(void) { // standard transform diff --git a/libraries/gpu/src/gpu/DrawUnitQuadTexcoord.slv b/libraries/gpu/src/gpu/DrawUnitQuadTexcoord.slv index 289d8f96b1..0378cd30e3 100644 --- a/libraries/gpu/src/gpu/DrawUnitQuadTexcoord.slv +++ b/libraries/gpu/src/gpu/DrawUnitQuadTexcoord.slv @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// DrawUnitQuadTexcoord.vert +// // Draw the unit quad [-1,-1 -> 1,1] amd pass along the unit texcoords [0, 0 -> 1, 1]. Not transform used. // Simply draw a Triangle_strip of 2 triangles, no input buffers or index buffer needed // @@ -11,7 +13,7 @@ // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -out vec2 varTexCoord0; +layout(location=0) out vec2 varTexCoord0; void main(void) { const float depth = 1.0; diff --git a/libraries/gpu/src/gpu/DrawVertexPosition.slv b/libraries/gpu/src/gpu/DrawVertexPosition.slv index b12280d577..e9961750ba 100644 --- a/libraries/gpu/src/gpu/DrawVertexPosition.slv +++ b/libraries/gpu/src/gpu/DrawVertexPosition.slv @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// DrawVertexPosition.vert +// // Draw the fed vertex position, pass straight as clip pos // Output the clip position // @@ -12,7 +14,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -layout(location = 0) in vec4 inPosition; +layout(location=0) in vec4 inPosition; void main(void) { gl_Position = inPosition; diff --git a/libraries/gpu/src/gpu/DrawViewportQuadTransformTexcoord.slv b/libraries/gpu/src/gpu/DrawViewportQuadTransformTexcoord.slv index 554728417b..ae252f73d2 100755 --- a/libraries/gpu/src/gpu/DrawViewportQuadTransformTexcoord.slv +++ b/libraries/gpu/src/gpu/DrawViewportQuadTransformTexcoord.slv @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// DrawViewportQuatTransformTexcoord.vert +// // Draw the unit quad [-1,-1 -> 1,1] filling in // Simply draw a Triangle_strip of 2 triangles, no input buffers or index buffer needed // @@ -16,7 +18,7 @@ <$declareStandardTransform()$> -out vec2 varTexCoord0; +layout(location=0) out vec2 varTexCoord0; void main(void) { const vec4 UNIT_QUAD[4] = vec4[4]( diff --git a/libraries/gpu/src/gpu/DrawWhite.slf b/libraries/gpu/src/gpu/DrawWhite.slf index bdecc0c5c5..1cdc047655 100644 --- a/libraries/gpu/src/gpu/DrawWhite.slf +++ b/libraries/gpu/src/gpu/DrawWhite.slf @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// Draw white +// DrawWhite.frag // // Created by Sam Gateau on 5/30/2017 // Copyright 2017 High Fidelity, Inc. @@ -11,7 +11,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -out vec4 outFragColor; +layout(location=0) out vec4 outFragColor; void main(void) { outFragColor = vec4(1.0); diff --git a/libraries/gpu/src/gpu/Inputs.slh b/libraries/gpu/src/gpu/Inputs.slh index 109762136e..a121b46ed8 100644 --- a/libraries/gpu/src/gpu/Inputs.slh +++ b/libraries/gpu/src/gpu/Inputs.slh @@ -10,15 +10,18 @@ !> <@if not GPU_INPUTS_SLH@> <@def GPU_INPUTS_SLH@> -layout(location = 0) in vec4 inPosition; -layout(location = 1) in vec4 inNormal; -layout(location = 2) in vec4 inColor; -layout(location = 3) in vec4 inTexCoord0; -layout(location = 4) in vec4 inTangent; -layout(location = 5) in ivec4 inSkinClusterIndex; -layout(location = 6) in vec4 inSkinClusterWeight; -layout(location = 7) in vec4 inTexCoord1; -layout(location = 8) in vec4 inTexCoord2; -layout(location = 9) in vec4 inTexCoord3; -layout(location = 10) in vec4 inTexCoord4; + +<@include gpu/ShaderConstants.h@> + +layout(location=GPU_ATTR_POSITION) in vec4 inPosition; +layout(location=GPU_ATTR_NORMAL) in vec4 inNormal; +layout(location=GPU_ATTR_COLOR) in vec4 inColor; +layout(location=GPU_ATTR_TEXCOORD0) in vec4 inTexCoord0; +layout(location=GPU_ATTR_TANGENT) in vec4 inTangent; +layout(location=GPU_ATTR_SKIN_CLUSTER_INDEX) in ivec4 inSkinClusterIndex; +layout(location=GPU_ATTR_SKIN_CLUSTER_WEIGHT) in vec4 inSkinClusterWeight; +layout(location=GPU_ATTR_TEXCOORD1) in vec4 inTexCoord1; +layout(location=GPU_ATTR_TEXCOORD2) in vec4 inTexCoord2; +layout(location=GPU_ATTR_TEXCOORD3) in vec4 inTexCoord3; +layout(location=GPU_ATTR_TEXCOORD4) in vec4 inTexCoord4; <@endif@> diff --git a/libraries/gpu/src/gpu/Shader.cpp b/libraries/gpu/src/gpu/Shader.cpp index ca1613bd0b..1166e86cd1 100755 --- a/libraries/gpu/src/gpu/Shader.cpp +++ b/libraries/gpu/src/gpu/Shader.cpp @@ -12,6 +12,10 @@ #include "Shader.h" #include #include +#include + +#include +#include #include @@ -51,6 +55,14 @@ Shader::~Shader() { } +void populateSlotSet(Shader::SlotSet& slotSet, const Shader::LocationMap& map) { + for (const auto& entry : map) { + const auto& name = entry.first; + const auto& location = entry.second; + slotSet.insert({ name, location, Element() }); + } +} + Shader::Pointer Shader::createOrReuseDomainShader(Type type, const Source& source) { auto found = _domainShaderMaps[type].find(source); if (found != _domainShaderMaps[type].end()) { @@ -60,6 +72,28 @@ Shader::Pointer Shader::createOrReuseDomainShader(Type type, const Source& sourc } } auto shader = Pointer(new Shader(type, source)); + const auto& reflection = source.getReflection(); + if (0 != reflection.count(BindingType::INPUT)) { + populateSlotSet(shader->_inputs, reflection.find(BindingType::INPUT)->second); + } + if (0 != reflection.count(BindingType::OUTPUT)) { + populateSlotSet(shader->_outputs, reflection.find(BindingType::OUTPUT)->second); + } + if (0 != reflection.count(BindingType::UNIFORM_BUFFER)) { + populateSlotSet(shader->_uniformBuffers, reflection.find(BindingType::UNIFORM_BUFFER)->second); + } + if (0 != reflection.count(BindingType::STORAGE_BUFFER)) { + populateSlotSet(shader->_resourceBuffers, reflection.find(BindingType::STORAGE_BUFFER)->second); + } + if (0 != reflection.count(BindingType::TEXTURE)) { + populateSlotSet(shader->_textures, reflection.find(BindingType::TEXTURE)->second); + } + if (0 != reflection.count(BindingType::SAMPLER)) { + populateSlotSet(shader->_samplers, reflection.find(BindingType::SAMPLER)->second); + } + if (0 != reflection.count(BindingType::PUSH_CONSTANT)) { + populateSlotSet(shader->_uniforms, reflection.find(BindingType::PUSH_CONSTANT)->second); + } _domainShaderMaps[type].emplace(source, std::weak_ptr(shader)); return shader; } @@ -103,27 +137,32 @@ ShaderPointer Shader::createOrReuseProgramShader(Type type, const Pointer& verte // Program is a new one, let's create it auto program = Pointer(new Shader(type, vertexShader, geometryShader, pixelShader)); + + // Combine the slots from the sub-shaders + for (const auto& shader : program->_shaders) { + const auto& reflection = shader->_source.getReflection(); + if (0 != reflection.count(BindingType::UNIFORM_BUFFER)) { + populateSlotSet(program->_uniformBuffers, reflection.find(BindingType::UNIFORM_BUFFER)->second); + } + if (0 != reflection.count(BindingType::STORAGE_BUFFER)) { + populateSlotSet(program->_resourceBuffers, reflection.find(BindingType::STORAGE_BUFFER)->second); + } + if (0 != reflection.count(BindingType::TEXTURE)) { + populateSlotSet(program->_textures, reflection.find(BindingType::TEXTURE)->second); + } + if (0 != reflection.count(BindingType::SAMPLER)) { + populateSlotSet(program->_samplers, reflection.find(BindingType::SAMPLER)->second); + } + if (0 != reflection.count(BindingType::PUSH_CONSTANT)) { + populateSlotSet(program->_uniforms, reflection.find(BindingType::PUSH_CONSTANT)->second); + } + + } + _programMap.emplace(key, std::weak_ptr(program)); return program; } -void Shader::defineSlots(const SlotSet& uniforms, const SlotSet& uniformBuffers, const SlotSet& resourceBuffers, const SlotSet& textures, const SlotSet& samplers, const SlotSet& inputs, const SlotSet& outputs) { - _uniforms = uniforms; - _uniformBuffers = uniformBuffers; - _resourceBuffers = resourceBuffers; - _textures = textures; - _samplers = samplers; - _inputs = inputs; - _outputs = outputs; -} - -bool Shader::makeProgram(Shader& shader, const Shader::BindingSet& bindings, const CompilationHandler& handler) { - if (shader.isProgram()) { - return Context::makeProgram(shader, bindings, handler); - } - return false; -} - void Shader::setCompilationLogs(const CompilationLogs& logs) const { _compilationLogs.clear(); for (const auto& log : logs) { @@ -135,11 +174,6 @@ void Shader::incrementCompilationAttempt() const { _numCompilationAttempts++; } - -Shader::Source Shader::getShaderSource(Type type, int shaderId) { - return shader::loadShaderSource(shaderId); -} - Shader::Pointer Shader::createVertex(const Source& source) { return createOrReuseDomainShader(VERTEX, source); } @@ -148,26 +182,68 @@ Shader::Pointer Shader::createPixel(const Source& source) { return createOrReuseDomainShader(FRAGMENT, source); } -Shader::Pointer Shader::createVertex(int id) { - return createVertex(getShaderSource(VERTEX, id)); +Shader::Pointer Shader::createVertex(uint32_t id) { + return createVertex(getShaderSource(id)); } -Shader::Pointer Shader::createPixel(int id) { - return createPixel(getShaderSource(FRAGMENT, id)); +Shader::Pointer Shader::createPixel(uint32_t id) { + return createPixel(getShaderSource(id)); } Shader::Pointer Shader::createProgram(const Pointer& vertexShader, const Pointer& pixelShader) { return createOrReuseProgramShader(PROGRAM, vertexShader, nullptr, pixelShader); } -Shader::Pointer Shader::createProgram(int programId) { - int vertexId = (programId >> 16) & 0xFFFF; - int fragmentId = programId & 0xFFFF; - auto vertexShader = createVertex(vertexId); - auto fragmentShader = createPixel(fragmentId); +Shader::Pointer Shader::createProgram(uint32_t programId) { + auto vertexShader = createVertex(shader::getVertexId(programId)); + auto fragmentShader = createPixel(shader::getFragmentId(programId)); return createOrReuseProgramShader(PROGRAM, vertexShader, nullptr, fragmentShader); } -//Shader::Pointer Shader::createProgram(const Pointer& vertexShader, const Pointer& geometryShader, const Pointer& pixelShader) { -// return createOrReuseProgramShader(PROGRAM, vertexShader, geometryShader, pixelShader); -//} +Shader::Pointer Shader::createProgram(const Pointer& vertexShader, const Pointer& geometryShader, const Pointer& pixelShader) { + return createOrReuseProgramShader(PROGRAM, vertexShader, geometryShader, pixelShader); +} + +void updateBindingsFromJsonObject(Shader::LocationMap& inOutSet, const QJsonObject& json) { + for (const auto& key : json.keys()) { + inOutSet[key.toStdString()] = json[key].toInt(); + } +} + +Shader::ReflectionMap getShaderReflection(const std::string& reflectionJson) { + if (reflectionJson.empty() && reflectionJson != std::string("null")) { + return {}; + } + + auto doc = QJsonDocument::fromJson(reflectionJson.c_str()); + if (doc.isNull()) { + qWarning() << "Invalid shader reflection JSON" << reflectionJson.c_str(); + return {}; + } + + Shader::ReflectionMap result; + auto json = doc.object(); + if (json.contains("inputs")) { + updateBindingsFromJsonObject(result[Shader::BindingType::INPUT], json["inputs"].toObject()); + } + if (json.contains("outputs")) { + updateBindingsFromJsonObject(result[Shader::BindingType::OUTPUT], json["outputs"].toObject()); + } + if (json.contains("uniformBuffers")) { + updateBindingsFromJsonObject(result[Shader::BindingType::UNIFORM_BUFFER], json["uniformBuffers"].toObject()); + } + if (json.contains("textures")) { + updateBindingsFromJsonObject(result[Shader::BindingType::TEXTURE], json["textures"].toObject()); + } + if (json.contains("uniforms")) { + updateBindingsFromJsonObject(result[Shader::BindingType::PUSH_CONSTANT], json["uniforms"].toObject()); + } + return result; +} + +Shader::Source Shader::getShaderSource(uint32_t id) { + auto source = shader::loadShaderSource(id); + auto reflectionJson = shader::loadShaderReflection(id); + auto reflection = getShaderReflection(reflectionJson); + return { source, reflection }; +} diff --git a/libraries/gpu/src/gpu/Shader.h b/libraries/gpu/src/gpu/Shader.h index 64a2fc3f4f..d713433bd6 100755 --- a/libraries/gpu/src/gpu/Shader.h +++ b/libraries/gpu/src/gpu/Shader.h @@ -15,10 +15,12 @@ #include #include #include +#include +#include #include #include #include - + namespace gpu { class Shader { @@ -26,7 +28,8 @@ public: // unique identifier of a shader using ID = uint32_t; - enum Type { + enum Type + { VERTEX = 0, PIXEL, FRAGMENT = PIXEL, @@ -36,67 +39,102 @@ public: PROGRAM, }; - typedef std::shared_ptr< Shader > Pointer; - typedef std::vector< Pointer > Shaders; + typedef std::shared_ptr Pointer; + typedef std::vector Shaders; + // Needs to match values in shaders/Shaders.h + enum class BindingType + { + INVALID = -1, + INPUT = 0, + OUTPUT, + TEXTURE, + SAMPLER, + UNIFORM_BUFFER, + STORAGE_BUFFER, + PUSH_CONSTANT, // Equivalent to uniforms in GL + SPECIALIZATION_CONSTANT, + }; + using LocationMap = std::unordered_map; + using ReflectionMap = std::map; class Source { public: - enum Language { + enum Language + { + INVALID = -1, GLSL = 0, + SPIRV = 1, + MSL = 2, + HLSL = 3, }; Source() {} - Source(const std::string& code, Language lang = GLSL) : _code(code), _lang(lang) {} - Source(const Source& source) : _code(source._code), _lang(source._lang) {} + Source(const std::string& code, const ReflectionMap& reflection, Language lang = GLSL) : + _code(code), _reflection(reflection), _lang(lang) {} + Source(const Source& source) : _code(source._code), _reflection(source._reflection), _lang(source._lang) {} virtual ~Source() {} - + virtual const std::string& getCode() const { return _code; } + virtual const ReflectionMap& getReflection() const { return _reflection; } class Less { public: - bool operator() (const Source& x, const Source& y) const { if (x._lang == y._lang) { return x._code < y._code; } else { return (x._lang < y._lang); } } + bool operator()(const Source& x, const Source& y) const { + if (x._lang == y._lang) { + return x._code < y._code; + } else { + return (x._lang < y._lang); + } + } }; protected: std::string _code; - Language _lang = GLSL; + ReflectionMap _reflection; + Language _lang; }; - static Source getShaderSource(Type type, int shaderId); - static Source getVertexShaderSource(int shaderId) { return getShaderSource(VERTEX, shaderId); } - static Source getFragmentShaderSource(int shaderId) { return getShaderSource(FRAGMENT, shaderId); } - struct CompilationLog { std::string message; bool compiled{ false }; CompilationLog() {} - CompilationLog(const CompilationLog& src) : - message(src.message), - compiled(src.compiled) {} + CompilationLog(const CompilationLog& src) : message(src.message), compiled(src.compiled) {} }; using CompilationLogs = std::vector; static const int32 INVALID_LOCATION = -1; + template + class Less { + public: + bool operator()(const T& x, const T& y) const { return x._name < y._name; } + }; + class Slot { public: - std::string _name; - int32 _location{INVALID_LOCATION}; + int32 _location{ INVALID_LOCATION }; Element _element; - uint16 _resourceType{Resource::BUFFER}; - uint32 _size { 0 }; - - Slot(const Slot& s) : _name(s._name), _location(s._location), _element(s._element), _resourceType(s._resourceType), _size(s._size) {} - Slot(Slot&& s) : _name(s._name), _location(s._location), _element(s._element), _resourceType(s._resourceType), _size(s._size) {} - Slot(const std::string& name, int32 location, const Element& element, uint16 resourceType = Resource::BUFFER, uint32 size = 0) : - _name(name), _location(location), _element(element), _resourceType(resourceType), _size(size) {} + uint16 _resourceType{ Resource::BUFFER }; + uint32 _size{ 0 }; + + Slot(const Slot& s) : + _name(s._name), _location(s._location), _element(s._element), _resourceType(s._resourceType), _size(s._size) {} + Slot(Slot&& s) : + _name(s._name), _location(s._location), _element(s._element), _resourceType(s._resourceType), _size(s._size) {} + Slot(const std::string& name, + int32 location, + const Element& element, + uint16 resourceType = Resource::BUFFER, + uint32 size = 0) : + _name(name), + _location(location), _element(element), _resourceType(resourceType), _size(size) {} Slot(const std::string& name) : _name(name) {} - Slot& operator= (const Slot& s) { + Slot& operator=(const Slot& s) { _name = s._name; _location = s._location; _element = s._element; @@ -106,49 +144,61 @@ public: } }; - class Binding { - public: - std::string _name; - int32 _location; - Binding(const std::string& name, int32 loc = INVALID_LOCATION) : _name(name), _location(loc) {} - }; + class SlotSet : protected std::set> { + using Parent = std::set>; - template class Less { public: - bool operator() (const T& x, const T& y) const { return x._name < y._name; } - }; - - class SlotSet : public std::set> { - public: - Slot findSlot(const std::string& name) const { - auto key = Slot(name); - auto found = static_cast>*>(this)->find(key); - if (found != end()) { - return (*found); + void insert(const Parent::value_type& value) { + Parent::insert(value); + if (value._location != INVALID_LOCATION) { + _validSlots.insert(value._location); } - return key; } - int32 findLocation(const std::string& name) const { - return findSlot(name)._location; - } - protected: - }; - - typedef std::set> BindingSet; + using Parent::begin; + using Parent::empty; + using Parent::end; + using Parent::size; + + using LocationMap = std::unordered_map; + using NameVector = std::vector; + + NameVector getNames() const { + NameVector result; + for (const auto& entry : *this) { + result.push_back(entry._name); + } + return result; + } + + LocationMap getLocationsByName() const { + LocationMap result; + for (const auto& entry : *this) { + result.insert({ entry._name, entry._location }); + } + return result; + } + + bool isValid(int32 slot) const { return 0 != _validSlots.count(slot); } + + protected: + std::unordered_set _validSlots; + }; + + static Source getShaderSource(uint32_t id); + static Source getVertexShaderSource(uint32_t id) { return getShaderSource(id); } + static Source getFragmentShaderSource(uint32_t id) { return getShaderSource(id); } static Pointer createVertex(const Source& source); static Pointer createPixel(const Source& source); - //static Pointer createGeometry(const Source& source); - static Pointer createVertex(int shaderId); - static Pointer createPixel(int shaderId); - static Pointer createGeometry(int shaderId); + static Pointer createGeometry(const Source& source); + static Pointer createVertex(uint32_t shaderId); + static Pointer createPixel(uint32_t shaderId); + static Pointer createGeometry(uint32_t shaderId); - static Pointer createProgram(int programId); + static Pointer createProgram(uint32_t programId); static Pointer createProgram(const Pointer& vertexShader, const Pointer& pixelShader); - //static Pointer createProgram(int vertexId, int fragmentId); - //static Pointer createProgram(const Pointer& vertexShader, const Pointer& geometryShader, const Pointer& pixelShader); - + static Pointer createProgram(const Pointer& vertexShader, const Pointer& geometryShader, const Pointer& pixelShader); ~Shader(); @@ -168,22 +218,6 @@ public: const SlotSet& getResourceBuffers() const { return _resourceBuffers; } const SlotSet& getTextures() const { return _textures; } const SlotSet& getSamplers() const { return _samplers; } - - const SlotSet& getInputs() const { return _inputs; } - const SlotSet& getOutputs() const { return _outputs; } - - // Define the list of uniforms, inputs and outputs for the shader - // This call is intendend to build the list of exposed slots in order - // to correctly bind resource to the shader. - // These can be build "manually" from knowledge of the atual shader code - // or automatically by calling "makeShader()", this is the preferred way - void defineSlots(const SlotSet& uniforms, - const SlotSet& uniformBuffers, - const SlotSet& resourceBuffers, - const SlotSet& textures, - const SlotSet& samplers, - const SlotSet& inputs, - const SlotSet& outputs); // Compilation Handler can be passed while compiling a shader (in the makeProgram call) to be able to give the hand to // the caller thread if the comilation fails and to prvide a different version of the source for it @@ -192,22 +226,7 @@ public: // @param2 the compilation log containing the error message // @param3 a new string ready to be filled with the new version of the source that could be proposed from the handler functor // @return boolean true if the backend should keep trying to compile the shader with the new source returned or false to stop and fail that shader compilation - using CompilationHandler = std::function; - - // makeProgram(...) make a program shader ready to be used in a Batch. - // It compiles the sub shaders, link them and defines the Slots and their bindings. - // If the shader passed is not a program, nothing happens. - // - // It is possible to provide a set of slot bindings (from the name of the slot to a unit number) allowing - // to make sure slots with the same semantics can be always bound on the same location from shader to shader. - // For example, the "diffuseMap" can always be bound to texture unit #1 for different shaders by specifying a Binding("diffuseMap", 1) - // - // As of now (03/2015), the call to makeProgram is in fact calling gpu::Context::makeProgram and does rely - // on the underneath gpu::Context::Backend available. Since we only support glsl, this means that it relies - // on a gl Context and the driver to compile the glsl shader. - // Hoppefully in a few years the shader compilation will be completely abstracted in a separate shader compiler library - // independant of the graphics api in use underneath (looking at you opengl & vulkan). - static bool makeProgram(Shader& shader, const Shader::BindingSet& bindings = Shader::BindingSet(), const CompilationHandler& handler = nullptr); + using CompilationHandler = std::function; // Check the compilation state bool compilationHasFailed() const { return _compilationHasFailed; } @@ -219,16 +238,14 @@ public: void setCompilationLogs(const CompilationLogs& logs) const; void incrementCompilationAttempt() const; - - const GPUObjectPointer gpuObject {}; + const GPUObjectPointer gpuObject{}; protected: Shader(Type type, const Source& source); Shader(Type type, const Pointer& vertex, const Pointer& geometry, const Pointer& pixel); - Shader(const Shader& shader); // deep copy of the sysmem shader - Shader& operator=(const Shader& shader); // deep copy of the sysmem texture - + Shader(const Shader& shader); // deep copy of the sysmem shader + Shader& operator=(const Shader& shader); // deep copy of the sysmem texture // Source contains the actual source code or nothing if the shader is a program Source _source; @@ -257,32 +274,29 @@ protected: mutable CompilationLogs _compilationLogs; // Whether or not the shader compilation failed - bool _compilationHasFailed { false }; + bool _compilationHasFailed{ false }; - - // Global maps of the shaders + // Global maps of the shaders // Unique shader ID static std::atomic _nextShaderID; - using ShaderMap = std::map, Source::Less>; + using ShaderMap = std::map, Source::Less>; using DomainShaderMaps = std::array; static DomainShaderMaps _domainShaderMaps; static ShaderPointer createOrReuseDomainShader(Type type, const Source& source); - using ProgramMapKey = glm::uvec3; // The IDs of the shaders in a program make its key + using ProgramMapKey = glm::uvec3; // The IDs of the shaders in a program make its key class ProgramKeyLess { public: - bool operator() (const ProgramMapKey& l, const ProgramMapKey& r) const { + bool operator()(const ProgramMapKey& l, const ProgramMapKey& r) const { if (l.x == r.x) { if (l.y == r.y) { return (l.z < r.z); - } - else { + } else { return (l.y < r.y); } - } - else { + } else { return (l.x < r.x); } } @@ -290,13 +304,15 @@ protected: using ProgramMap = std::map, ProgramKeyLess>; static ProgramMap _programMap; - static ShaderPointer createOrReuseProgramShader(Type type, const Pointer& vertexShader, const Pointer& geometryShader, const Pointer& pixelShader); + static ShaderPointer createOrReuseProgramShader(Type type, + const Pointer& vertexShader, + const Pointer& geometryShader, + const Pointer& pixelShader); }; typedef Shader::Pointer ShaderPointer; -typedef std::vector< ShaderPointer > Shaders; - -}; +typedef std::vector Shaders; +}; // namespace gpu #endif diff --git a/libraries/gpu/src/gpu/ShaderConstants.h b/libraries/gpu/src/gpu/ShaderConstants.h new file mode 100644 index 0000000000..dd9b350a4e --- /dev/null +++ b/libraries/gpu/src/gpu/ShaderConstants.h @@ -0,0 +1,126 @@ +// + +// <@if not GPU_SHADER_CONSTANTS_H@> +// <@def GPU_SHADER_CONSTANTS_H@> + +// Hack comment to absorb the extra '//' scribe prepends + +#ifndef GPU_SHADER_CONSTANTS_H +#define GPU_SHADER_CONSTANTS_H + +#define GPU_BUFFER_TRANSFORM_CAMERA 15 +#define GPU_BUFFER_TEXTURE_TABLE0 16 +#define GPU_BUFFER_TEXTURE_TABLE1 17 +#define GPU_BUFFER_CAMERA_CORRECTION 18 + +#define GPU_TEXTURE_TRANSFORM_OBJECT 31 + +#define GPU_STORAGE_TRANSFORM_OBJECT 7 + +#define GPU_ATTR_POSITION 0 +#define GPU_ATTR_NORMAL 1 +#define GPU_ATTR_COLOR 2 +#define GPU_ATTR_TEXCOORD0 3 +#define GPU_ATTR_TANGENT 4 +#define GPU_ATTR_SKIN_CLUSTER_INDEX 5 +#define GPU_ATTR_SKIN_CLUSTER_WEIGHT 6 +#define GPU_ATTR_TEXCOORD1 7 +#define GPU_ATTR_TEXCOORD2 8 +#define GPU_ATTR_TEXCOORD3 9 +#define GPU_ATTR_TEXCOORD4 10 +#define GPU_ATTR_STEREO_SIDE 14 +#define GPU_ATTR_DRAW_CALL_INFO 15 + +#define GPU_UNIFORM_COLOR 101 +#define GPU_UNIFORM_TEXCOORD_RECT 102 +#define GPU_UNIFORM_EXTRA0 110 +#define GPU_UNIFORM_EXTRA1 111 +#define GPU_UNIFORM_EXTRA2 112 +#define GPU_UNIFORM_EXTRA3 113 +#define GPU_UNIFORM_EXTRA4 114 +#define GPU_UNIFORM_EXTRA5 115 +#define GPU_UNIFORM_EXTRA6 116 +#define GPU_UNIFORM_EXTRA7 117 +#define GPU_UNIFORM_EXTRA8 118 +#define GPU_UNIFORM_EXTRA9 119 + +// + +// Hack Comment +#endif // GPU_SHADER_CONSTANTS_H + +// <@if 1@> +// Trigger Scribe include +// <@endif@> + +// <@endif@> + +// Hack Comment diff --git a/libraries/gpu/src/gpu/Transform.slh b/libraries/gpu/src/gpu/Transform.slh index 864a106350..fd389e1d50 100644 --- a/libraries/gpu/src/gpu/Transform.slh +++ b/libraries/gpu/src/gpu/Transform.slh @@ -10,12 +10,13 @@ <@if not GPU_TRANSFORM_STATE_SLH@> <@def GPU_TRANSFORM_STATE_SLH@> +<@include gpu/ShaderConstants.h@> <@func declareStandardCameraTransform()@> <@include gpu/TransformCamera_shared.slh@> #define TransformCamera _TransformCamera -layout(std140) uniform transformCameraBuffer { +layout(std140, binding=GPU_BUFFER_TRANSFORM_CAMERA) uniform transformCameraBuffer { #ifdef GPU_TRANSFORM_IS_STEREO #ifdef GPU_TRANSFORM_STEREO_CAMERA TransformCamera _camera[2]; @@ -31,10 +32,10 @@ layout(std140) uniform transformCameraBuffer { #ifdef GPU_TRANSFORM_IS_STEREO #ifdef GPU_TRANSFORM_STEREO_CAMERA #ifdef GPU_TRANSFORM_STEREO_CAMERA_ATTRIBUTED -layout(location=14) in int _inStereoSide; +layout(location=GPU_ATTR_STEREO_SIDE) in int _inStereoSide; #endif -flat out int _stereoSide; +layout(location=GPU_ATTR_STEREO_SIDE) flat out int _stereoSide; // In stereo drawcall mode Instances are drawn twice (left then right) hence the true InstanceID is the gl_InstanceID / 2 int gpu_InstanceID() { @@ -59,7 +60,7 @@ int gpu_InstanceID() { #ifdef GPU_PIXEL_SHADER #ifdef GPU_TRANSFORM_STEREO_CAMERA -flat in int _stereoSide; +layout(location=GPU_ATTR_STEREO_SIDE) flat in int _stereoSide; #endif #endif @@ -116,10 +117,10 @@ struct TransformObject { mat4 _modelInverse; }; -layout(location=15) in ivec2 _drawCallInfo; +layout(location=GPU_ATTR_DRAW_CALL_INFO) in ivec2 _drawCallInfo; #if defined(GPU_SSBO_TRANSFORM_OBJECT) -layout(std140) buffer transformObjectBuffer { +layout(std140, binding=GPU_STORAGE_TRANSFORM_OBJECT) buffer transformObjectBuffer { TransformObject _object[]; }; TransformObject getTransformObject() { @@ -127,7 +128,7 @@ TransformObject getTransformObject() { return transformObject; } #else -uniform samplerBuffer transformObjectBuffer; +layout(binding=GPU_TEXTURE_TRANSFORM_OBJECT) uniform samplerBuffer transformObjectBuffer; TransformObject getTransformObject() { int offset = 8 * _drawCallInfo.x; diff --git a/libraries/gpu/src/gpu/null/NullBackend.h b/libraries/gpu/src/gpu/null/NullBackend.h index 57b8fbafbc..e227b631c7 100644 --- a/libraries/gpu/src/gpu/null/NullBackend.h +++ b/libraries/gpu/src/gpu/null/NullBackend.h @@ -28,7 +28,6 @@ class Backend : public gpu::Backend { friend class gpu::Context; static void init() {} static gpu::Backend* createBackend() { return new Backend(); } - static bool makeProgram(Shader& shader, const Shader::BindingSet& slotBindings, const Shader::CompilationHandler& handler) { return true; } protected: explicit Backend(bool syncCache) : Parent() { } diff --git a/libraries/graphics/src/graphics/Light.slh b/libraries/graphics/src/graphics/Light.slh index 53b840f5fb..d22da44c66 100644 --- a/libraries/graphics/src/graphics/Light.slh +++ b/libraries/graphics/src/graphics/Light.slh @@ -11,6 +11,7 @@ <@if not MODEL_LIGHT_SLH@> <@def MODEL_LIGHT_SLH@> +<@include graphics/ShaderConstants.h@> <@include graphics/LightVolume.shared.slh@> <@include graphics/LightIrradiance.shared.slh@> @@ -50,7 +51,7 @@ float getLightAmbientMapNumMips(LightAmbient l) { return l._ambient.y; } <@if N@> -uniform lightBuffer { +layout(binding=GRAPHICS_BUFFER_LIGHT) uniform lightBuffer { Light lightArray[<$N$>]; }; Light getLight(int index) { @@ -58,7 +59,7 @@ Light getLight(int index) { } <@else@> -uniform keyLightBuffer { +layout(binding=GRAPHICS_BUFFER_KEY_LIGHT) uniform keyLightBuffer { Light light; }; Light getKeyLight() { @@ -78,7 +79,7 @@ Light getKeyLight() { <@if N@> -uniform lightAmbientBuffer { +layout(binding=GRAPHICS_BUFFER_AMBIENT_LIGHT) uniform lightAmbientBuffer { LightAmbient lightAmbientArray[<$N$>]; }; @@ -87,7 +88,7 @@ LightAmbient getLightAmbient(int index) { } <@else@> -uniform lightAmbientBuffer { +layout(binding=GRAPHICS_BUFFER_AMBIENT_LIGHT) uniform lightAmbientBuffer { LightAmbient lightAmbient; }; diff --git a/libraries/graphics/src/graphics/Material.slh b/libraries/graphics/src/graphics/Material.slh index dd2985b4da..fe273ed2a9 100644 --- a/libraries/graphics/src/graphics/Material.slh +++ b/libraries/graphics/src/graphics/Material.slh @@ -11,6 +11,8 @@ <@if not MODEL_MATERIAL_SLH@> <@def MODEL_MATERIAL_SLH@> +<@include graphics/ShaderConstants.h@> + // The material values (at least the material key) must be precisely bitwise accurate // to what is provided by the uniform buffer, or the material key has the wrong bits @@ -21,7 +23,7 @@ struct Material { vec4 _scatteringSpare2Key; }; -uniform materialBuffer { +layout(binding=GRAPHICS_BUFFER_MATERIAL) uniform materialBuffer { Material _mat; }; diff --git a/libraries/render-utils/src/MaterialTextures.slh b/libraries/graphics/src/graphics/MaterialTextures.slh similarity index 90% rename from libraries/render-utils/src/MaterialTextures.slh rename to libraries/graphics/src/graphics/MaterialTextures.slh index 0b83fd1334..e19b429684 100644 --- a/libraries/render-utils/src/MaterialTextures.slh +++ b/libraries/graphics/src/graphics/MaterialTextures.slh @@ -11,6 +11,8 @@ <@if not MODEL_MATERIAL_TEXTURES_SLH@> <@def MODEL_MATERIAL_TEXTURES_SLH@> +<@include graphics/ShaderConstants.h@> + <@func declareMaterialTexMapArrayBuffer()@> const int MAX_TEXCOORDS = 2; @@ -22,7 +24,7 @@ struct TexMapArray { vec4 _lightmapParams; }; -uniform texMapArrayBuffer { +layout(binding=GRAPHICS_BUFFER_TEXMAPARRAY) uniform texMapArrayBuffer { TexMapArray _texMapArray; }; @@ -123,21 +125,21 @@ float fetchScatteringMap(vec2 uv) { #else <@if withAlbedo@> -uniform sampler2D albedoMap; +layout(binding=GRAPHICS_TEXTURE_MATERIAL_ALBEDO) uniform sampler2D albedoMap; vec4 fetchAlbedoMap(vec2 uv) { return texture(albedoMap, uv, TAA_TEXTURE_LOD_BIAS); } <@endif@> <@if withRoughness@> -uniform sampler2D roughnessMap; +layout(binding=GRAPHICS_TEXTURE_MATERIAL_ROUGHNESS) uniform sampler2D roughnessMap; float fetchRoughnessMap(vec2 uv) { return (texture(roughnessMap, uv, TAA_TEXTURE_LOD_BIAS).r); } <@endif@> <@if withNormal@> -uniform sampler2D normalMap; +layout(binding=GRAPHICS_TEXTURE_MATERIAL_NORMAL) uniform sampler2D normalMap; vec3 fetchNormalMap(vec2 uv) { // unpack normal, swizzle to get into hifi tangent space with Y axis pointing out vec2 t = 2.0 * (texture(normalMap, uv, TAA_TEXTURE_LOD_BIAS).rg - vec2(0.5, 0.5)); @@ -147,28 +149,28 @@ vec3 fetchNormalMap(vec2 uv) { <@endif@> <@if withMetallic@> -uniform sampler2D metallicMap; +layout(binding=GRAPHICS_TEXTURE_MATERIAL_METALLIC) uniform sampler2D metallicMap; float fetchMetallicMap(vec2 uv) { return (texture(metallicMap, uv, TAA_TEXTURE_LOD_BIAS).r); } <@endif@> <@if withEmissive@> -uniform sampler2D emissiveMap; +layout(binding=GRAPHICS_TEXTURE_MATERIAL_EMISSIVE_LIGHTMAP) uniform sampler2D emissiveMap; vec3 fetchEmissiveMap(vec2 uv) { return texture(emissiveMap, uv, TAA_TEXTURE_LOD_BIAS).rgb; } <@endif@> <@if withOcclusion@> -uniform sampler2D occlusionMap; +layout(binding=GRAPHICS_TEXTURE_MATERIAL_OCCLUSION) uniform sampler2D occlusionMap; float fetchOcclusionMap(vec2 uv) { return texture(occlusionMap, uv).r; } <@endif@> <@if withScattering@> -uniform sampler2D scatteringMap; +layout(binding=GRAPHICS_TEXTURE_MATERIAL_SCATTERING) uniform sampler2D scatteringMap; float fetchScatteringMap(vec2 uv) { float scattering = texture(scatteringMap, uv, TAA_TEXTURE_LOD_BIAS).r; // boolean scattering for now return max(((scattering - 0.1) / 0.9), 0.0); @@ -217,10 +219,10 @@ float fetchScatteringMap(vec2 uv) { <$declareMaterialTexMapArrayBuffer()$> -uniform sampler2D emissiveMap; +layout(binding=GRAPHICS_TEXTURE_MATERIAL_EMISSIVE_LIGHTMAP) uniform sampler2D emissiveMap; vec3 fetchLightmapMap(vec2 uv) { - vec2 emissiveParams = getTexMapArray()._lightmapParams.xy; - return (vec3(emissiveParams.x) + emissiveParams.y * texture(emissiveMap, uv).rgb); + vec2 lightmapParams = getTexMapArray()._lightmapParams.xy; + return (vec3(lightmapParams.x) + lightmapParams.y * texture(emissiveMap, uv).rgb); } <@endfunc@> diff --git a/libraries/graphics/src/graphics/ShaderConstants.h b/libraries/graphics/src/graphics/ShaderConstants.h new file mode 100644 index 0000000000..c902185d4f --- /dev/null +++ b/libraries/graphics/src/graphics/ShaderConstants.h @@ -0,0 +1,78 @@ +// + +// <@if not GRAPHICS_SHADER_CONSTANTS_H@> +// <@def GRAPHICS_SHADER_CONSTANTS_H@> + +// Hack comment to absorb the extra '//' scribe prepends + +#ifndef GRAPHICS_SHADER_CONSTANTS_H +#define GRAPHICS_SHADER_CONSTANTS_H + +#define GRAPHICS_BUFFER_SKINNING 0 +#define GRAPHICS_BUFFER_MATERIAL 1 +#define GRAPHICS_BUFFER_TEXMAPARRAY 2 +#define GRAPHICS_BUFFER_KEY_LIGHT 4 +#define GRAPHICS_BUFFER_LIGHT 5 +#define GRAPHICS_BUFFER_AMBIENT_LIGHT 6 + +#define GRAPHICS_TEXTURE_MATERIAL_ALBEDO 0 +#define GRAPHICS_TEXTURE_MATERIAL_NORMAL 1 +#define GRAPHICS_TEXTURE_MATERIAL_METALLIC 2 +#define GRAPHICS_TEXTURE_MATERIAL_EMISSIVE_LIGHTMAP 3 +#define GRAPHICS_TEXTURE_MATERIAL_ROUGHNESS 4 +#define GRAPHICS_TEXTURE_MATERIAL_OCCLUSION 5 +#define GRAPHICS_TEXTURE_MATERIAL_SCATTERING 6 + +// Make sure these match the ones in render-utils/ShaderConstants.h +#define GRAPHICS_TEXTURE_SKYBOX 11 +#define GRAPHICS_BUFFER_SKYBOX_PARAMS 5 + +// +// Hack Comment + +#endif // GRAPHICS_SHADER_CONSTANTS_H + +// <@if 1@> +// Trigger Scribe include +// <@endif@> + +// <@endif@> + +// Hack Comment diff --git a/libraries/graphics/src/graphics/Skybox.cpp b/libraries/graphics/src/graphics/Skybox.cpp index 6c044444f0..532b5f1706 100755 --- a/libraries/graphics/src/graphics/Skybox.cpp +++ b/libraries/graphics/src/graphics/Skybox.cpp @@ -14,8 +14,8 @@ #include #include #include - #include +#include "ShaderConstants.h" using namespace graphics; @@ -64,17 +64,12 @@ void Skybox::clear() { _empty = true; } -void Skybox::prepare(gpu::Batch& batch, int textureSlot, int bufferSlot) const { - if (bufferSlot > -1) { - batch.setUniformBuffer(bufferSlot, _schemaBuffer); - } - - if (textureSlot > -1) { - gpu::TexturePointer skymap = getCubemap(); - // FIXME: skymap->isDefined may not be threadsafe - if (skymap && skymap->isDefined()) { - batch.setResourceTexture(textureSlot, skymap); - } +void Skybox::prepare(gpu::Batch& batch) const { + batch.setUniformBuffer(graphics::slot::buffer::SkyboxParams, _schemaBuffer); + gpu::TexturePointer skymap = getCubemap(); + // FIXME: skymap->isDefined may not be threadsafe + if (skymap && skymap->isDefined()) { + batch.setResourceTexture(graphics::slot::texture::Skybox, skymap); } } @@ -91,16 +86,6 @@ void Skybox::render(gpu::Batch& batch, const ViewFrustum& viewFrustum, const Sky std::call_once(once, [&] { { auto skyShader = gpu::Shader::createProgram(shader::graphics::program::skybox); - - batch.runLambda([skyShader] { - gpu::Shader::BindingSet bindings; - bindings.insert(gpu::Shader::Binding(std::string("cubeMap"), SKYBOX_SKYMAP_SLOT)); - bindings.insert(gpu::Shader::Binding(std::string("skyboxBuffer"), SKYBOX_CONSTANTS_SLOT)); - if (!gpu::Shader::makeProgram(*skyShader, bindings)) { - - } - }); - auto skyState = std::make_shared(); // Must match PrepareStencil::STENCIL_BACKGROUND const int8_t STENCIL_BACKGROUND = 0; @@ -130,5 +115,5 @@ void Skybox::render(gpu::Batch& batch, const ViewFrustum& viewFrustum, const Sky skybox.prepare(batch); batch.draw(gpu::TRIANGLE_STRIP, 4); - batch.setResourceTexture(SKYBOX_SKYMAP_SLOT, nullptr); + batch.setResourceTexture(graphics::slot::texture::Skybox, nullptr); } diff --git a/libraries/graphics/src/graphics/Skybox.h b/libraries/graphics/src/graphics/Skybox.h index a739b9a745..50189f4c51 100755 --- a/libraries/graphics/src/graphics/Skybox.h +++ b/libraries/graphics/src/graphics/Skybox.h @@ -43,7 +43,7 @@ public: virtual bool empty() { return _empty; } virtual void clear(); - void prepare(gpu::Batch& batch, int textureSlot = SKYBOX_SKYMAP_SLOT, int bufferSlot = SKYBOX_CONSTANTS_SLOT) const; + void prepare(gpu::Batch& batch) const; virtual void render(gpu::Batch& batch, const ViewFrustum& frustum) const; static void render(gpu::Batch& batch, const ViewFrustum& frustum, const Skybox& skybox); @@ -51,9 +51,6 @@ public: const UniformBufferView& getSchemaBuffer() const { return _schemaBuffer; } protected: - static const int SKYBOX_SKYMAP_SLOT { 0 }; - static const int SKYBOX_CONSTANTS_SLOT { 0 }; - class Schema { public: glm::vec3 color { 0.0f, 0.0f, 0.0f }; diff --git a/libraries/graphics/src/graphics/skybox.slf b/libraries/graphics/src/graphics/skybox.slf index 153e73b9ef..2b81a433f1 100755 --- a/libraries/graphics/src/graphics/skybox.slf +++ b/libraries/graphics/src/graphics/skybox.slf @@ -10,42 +10,22 @@ // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +<@include graphics/ShaderConstants.h@> -uniform samplerCube cubeMap; +layout(binding=GRAPHICS_TEXTURE_SKYBOX) uniform samplerCube cubeMap; struct Skybox { vec4 color; }; -uniform skyboxBuffer { +layout(binding=GRAPHICS_BUFFER_SKYBOX_PARAMS) uniform skyboxBuffer { Skybox skybox; }; -in vec3 _normal; -out vec4 _fragColor; +layout(location=0) in vec3 _normal; +layout(location=0) out vec4 _fragColor; -//PROCEDURAL_COMMON_BLOCK - -#line 1001 -//PROCEDURAL_BLOCK - -#line 2033 void main(void) { - -#ifdef PROCEDURAL - - vec3 color = getSkyboxColor(); - // Protect from NaNs and negative values - color = mix(color, vec3(0), isnan(color)); - color = max(color, vec3(0)); - // Procedural Shaders are expected to be Gamma corrected so let's bring back the RGB in linear space for the rest of the pipeline - color = pow(color, vec3(2.2)); - _fragColor = vec4(color, 0.0); - - // FIXME: scribe does not yet scrub out else statements - return; - -#else vec3 coord = normalize(_normal); vec3 color = skybox.color.rgb; @@ -57,7 +37,4 @@ void main(void) { } } _fragColor = vec4(color, 0.0); - -#endif - } diff --git a/libraries/graphics/src/graphics/skybox.slv b/libraries/graphics/src/graphics/skybox.slv index 6fd9532fa1..4b14872df2 100755 --- a/libraries/graphics/src/graphics/skybox.slv +++ b/libraries/graphics/src/graphics/skybox.slv @@ -15,7 +15,7 @@ <$declareStandardTransform()$> -out vec3 _normal; +layout(location=0) out vec3 _normal; void main(void) { const float depth = 0.0; diff --git a/libraries/procedural/src/procedural/Logging.h b/libraries/procedural/src/procedural/Logging.h index 3684d7c78f..77a25c305d 100644 --- a/libraries/procedural/src/procedural/Logging.h +++ b/libraries/procedural/src/procedural/Logging.h @@ -11,6 +11,6 @@ #include -Q_DECLARE_LOGGING_CATEGORY(procedural) +Q_DECLARE_LOGGING_CATEGORY(proceduralLog) #endif // hifi_octree_Logging_h diff --git a/libraries/procedural/src/procedural/Procedural.cpp b/libraries/procedural/src/procedural/Procedural.cpp index 8f0c9ab4f0..644212864e 100644 --- a/libraries/procedural/src/procedural/Procedural.cpp +++ b/libraries/procedural/src/procedural/Procedural.cpp @@ -22,10 +22,10 @@ #include #include +#include "ShaderConstants.h" #include "Logging.h" -Q_LOGGING_CATEGORY(procedural, "hifi.gpu.procedural") - +Q_LOGGING_CATEGORY(proceduralLog, "hifi.gpu.procedural") // Userdata parsing constants static const QString PROCEDURAL_USER_DATA_KEY = "ProceduralEntity"; @@ -36,20 +36,9 @@ static const QString CHANNELS_KEY = "channels"; // Shader replace strings static const std::string PROCEDURAL_BLOCK = "//PROCEDURAL_BLOCK"; -static const std::string PROCEDURAL_COMMON_BLOCK = "//PROCEDURAL_COMMON_BLOCK"; static const std::string PROCEDURAL_VERSION = "//PROCEDURAL_VERSION"; -static const std::string STANDARD_UNIFORM_NAMES[Procedural::NUM_STANDARD_UNIFORMS] = { - "iDate", - "iGlobalTime", - "iFrameCount", - "iWorldScale", - "iWorldPosition", - "iWorldOrientation", - "iChannelResolution" -}; - -bool operator ==(const ProceduralData& a, const ProceduralData& b) { +bool operator==(const ProceduralData& a, const ProceduralData& b) { return ( (a.version == b.version) && (a.shaderUrl == b.shaderUrl) && @@ -57,7 +46,6 @@ bool operator ==(const ProceduralData& a, const ProceduralData& b) { (a.channels == b.channels)); } - QJsonValue ProceduralData::getProceduralData(const QString& proceduralJson) { if (proceduralJson.isEmpty()) { return QJsonValue(); @@ -99,7 +87,7 @@ void ProceduralData::parse(const QJsonObject& proceduralData) { auto rawShaderUrl = proceduralData[URL_KEY].toString(); shaderUrl = DependencyManager::get()->normalizeURL(rawShaderUrl); - + // Empty shader URL isn't valid if (shaderUrl.isEmpty()) { return; @@ -119,10 +107,8 @@ void ProceduralData::parse(const QJsonObject& proceduralData) { Procedural::Procedural() { _transparentState->setCullMode(gpu::State::CULL_NONE); _transparentState->setDepthTest(true, true, gpu::LESS_EQUAL); - _transparentState->setBlendFunction(true, - gpu::State::SRC_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::INV_SRC_ALPHA, - gpu::State::FACTOR_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::ONE); - + _transparentState->setBlendFunction(true, gpu::State::SRC_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::INV_SRC_ALPHA, + gpu::State::FACTOR_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::ONE); } void Procedural::setProceduralData(const ProceduralData& proceduralData) { @@ -168,13 +154,13 @@ void Procedural::setProceduralData(const ProceduralData& proceduralData) { } if (!shaderUrl.isValid()) { - qCWarning(procedural) << "Invalid shader URL: " << shaderUrl; + qCWarning(proceduralLog) << "Invalid shader URL: " << shaderUrl; return; } if (shaderUrl.isLocalFile()) { if (!QFileInfo(shaderUrl.toLocalFile()).exists()) { - qCWarning(procedural) << "Invalid shader URL, missing local file: " << shaderUrl; + qCWarning(proceduralLog) << "Invalid shader URL, missing local file: " << shaderUrl; return; } _shaderPath = shaderUrl.toLocalFile(); @@ -222,29 +208,27 @@ bool Procedural::isReady() const { } std::string Procedural::replaceProceduralBlock(const std::string& fragmentSource) { - std::string fragmentShaderSource = fragmentSource; - static const auto proceduralCommonSource = gpu::Shader::getFragmentShaderSource(shader::procedural::fragment::ProceduralCommon); - size_t replaceIndex = fragmentShaderSource.find(PROCEDURAL_COMMON_BLOCK); - if (replaceIndex != std::string::npos) { - fragmentShaderSource.replace(replaceIndex, PROCEDURAL_COMMON_BLOCK.size(), proceduralCommonSource.getCode()); - } - - replaceIndex = fragmentShaderSource.find(PROCEDURAL_VERSION); + std::string result = fragmentSource; + auto replaceIndex = result.find(PROCEDURAL_VERSION); if (replaceIndex != std::string::npos) { if (_data.version == 1) { - fragmentShaderSource.replace(replaceIndex, PROCEDURAL_VERSION.size(), "#define PROCEDURAL_V1 1"); + result.replace(replaceIndex, PROCEDURAL_VERSION.size(), "#define PROCEDURAL_V1 1"); } else if (_data.version == 2) { - fragmentShaderSource.replace(replaceIndex, PROCEDURAL_VERSION.size(), "#define PROCEDURAL_V2 1"); + result.replace(replaceIndex, PROCEDURAL_VERSION.size(), "#define PROCEDURAL_V2 1"); } } - replaceIndex = fragmentShaderSource.find(PROCEDURAL_BLOCK); + replaceIndex = result.find(PROCEDURAL_BLOCK); if (replaceIndex != std::string::npos) { - fragmentShaderSource.replace(replaceIndex, PROCEDURAL_BLOCK.size(), _shaderSource.toLocal8Bit().data()); + result.replace(replaceIndex, PROCEDURAL_BLOCK.size(), _shaderSource.toLocal8Bit().data()); } - return fragmentShaderSource; + return result; } -void Procedural::prepare(gpu::Batch& batch, const glm::vec3& position, const glm::vec3& size, const glm::quat& orientation, const glm::vec4& color) { +void Procedural::prepare(gpu::Batch& batch, + const glm::vec3& position, + const glm::vec3& size, + const glm::quat& orientation, + const glm::vec4& color) { _entityDimensions = size; _entityPosition = position; _entityOrientation = glm::mat3_cast(orientation); @@ -267,31 +251,31 @@ void Procedural::prepare(gpu::Batch& batch, const glm::vec3& position, const glm } // Build the fragment shader - std::string opaqueShaderSource = replaceProceduralBlock(_opaquefragmentSource); - std::string transparentShaderSource = replaceProceduralBlock(_transparentfragmentSource); + std::string opaqueShaderSource = replaceProceduralBlock(_opaquefragmentSource.getCode()); + auto opaqueReflection = _opaquefragmentSource.getReflection(); + auto& opaqueUniforms = opaqueReflection[gpu::Shader::BindingType::PUSH_CONSTANT]; + std::string transparentShaderSource = replaceProceduralBlock(_transparentfragmentSource.getCode()); + auto transparentReflection = _transparentfragmentSource.getReflection(); + auto& transparentUniforms = transparentReflection[gpu::Shader::BindingType::PUSH_CONSTANT]; + + // Set any userdata specified uniforms + int customSlot = procedural::slot::uniform::Custom; + for (const auto& key : _data.uniforms.keys()) { + std::string uniformName = key.toLocal8Bit().data(); + opaqueUniforms[uniformName] = customSlot; + transparentUniforms[uniformName] = customSlot; + ++customSlot; + } // Leave this here for debugging // qCDebug(procedural) << "FragmentShader:\n" << fragmentShaderSource.c_str(); - gpu::Shader::BindingSet slotBindings; - - slotBindings.insert(gpu::Shader::Binding(std::string("iChannel0"), 0)); - slotBindings.insert(gpu::Shader::Binding(std::string("iChannel1"), 1)); - slotBindings.insert(gpu::Shader::Binding(std::string("iChannel2"), 2)); - slotBindings.insert(gpu::Shader::Binding(std::string("iChannel3"), 3)); - // TODO: THis is a simple fix, we need a cleaner way to provide the "hosting" program for procedural custom shaders to be defined together with the required bindings. - const int PROCEDURAL_PROGRAM_LIGHTING_MODEL_SLOT = 3; - slotBindings.insert(gpu::Shader::Binding(std::string("lightingModelBuffer"), PROCEDURAL_PROGRAM_LIGHTING_MODEL_SLOT)); - - _opaqueFragmentShader = gpu::Shader::createPixel(opaqueShaderSource); + _opaqueFragmentShader = gpu::Shader::createPixel({ opaqueShaderSource, opaqueReflection }); _opaqueShader = gpu::Shader::createProgram(_vertexShader, _opaqueFragmentShader); - gpu::Shader::makeProgram(*_opaqueShader, slotBindings); - if (!transparentShaderSource.empty() && transparentShaderSource != opaqueShaderSource) { - _transparentFragmentShader = gpu::Shader::createPixel(transparentShaderSource); + _transparentFragmentShader = gpu::Shader::createPixel({ transparentShaderSource, transparentReflection }); _transparentShader = gpu::Shader::createProgram(_vertexShader, _transparentFragmentShader); - gpu::Shader::makeProgram(*_transparentShader, slotBindings); } else { _transparentFragmentShader = _opaqueFragmentShader; _transparentShader = _opaqueShader; @@ -299,11 +283,6 @@ void Procedural::prepare(gpu::Batch& batch, const glm::vec3& position, const glm _opaquePipeline = gpu::Pipeline::create(_opaqueShader, _opaqueState); _transparentPipeline = gpu::Pipeline::create(_transparentShader, _transparentState); - for (size_t i = 0; i < NUM_STANDARD_UNIFORMS; ++i) { - const std::string& name = STANDARD_UNIFORM_NAMES[i]; - _standardOpaqueUniformSlots[i] = _opaqueShader->getUniforms().findLocation(name); - _standardTransparentUniformSlots[i] = _transparentShader->getUniforms().findLocation(name); - } _start = usecTimestampNow(); _frameCount = 0; } @@ -347,19 +326,22 @@ void Procedural::prepare(gpu::Batch& batch, const glm::vec3& position, const glm void Procedural::setupUniforms(bool transparent) { _uniforms.clear(); - // Set any userdata specified uniforms - foreach(QString key, _data.uniforms.keys()) { - std::string uniformName = key.toLocal8Bit().data(); - int32_t slot = (transparent ? _transparentShader : _opaqueShader)->getUniforms().findLocation(uniformName); - if (gpu::Shader::INVALID_LOCATION == slot) { + auto& pipeline = transparent ? _transparentShader : _opaqueShader; + const auto& uniformSlots = pipeline->getUniforms(); + auto customUniformCount = _data.uniforms.keys().size(); + + // Set any userdata specified uniforms + for (int i = 0; i < customUniformCount; ++i) { + int slot = procedural::slot::uniform::Custom + i; + if (!uniformSlots.isValid(slot)) { continue; } + QString key = _data.uniforms.keys().at(i); + std::string uniformName = key.toLocal8Bit().data(); QJsonValue value = _data.uniforms[key]; if (value.isDouble()) { float v = value.toDouble(); - _uniforms.push_back([=](gpu::Batch& batch) { - batch._glUniform1f(slot, v); - }); + _uniforms.push_back([=](gpu::Batch& batch) { batch._glUniform1f(slot, v); }); } else if (value.isArray()) { auto valueArray = value.toArray(); switch (valueArray.size()) { @@ -368,17 +350,13 @@ void Procedural::setupUniforms(bool transparent) { case 1: { float v = valueArray[0].toDouble(); - _uniforms.push_back([=](gpu::Batch& batch) { - batch._glUniform1f(slot, v); - }); + _uniforms.push_back([=](gpu::Batch& batch) { batch._glUniform1f(slot, v); }); break; } case 2: { glm::vec2 v{ valueArray[0].toDouble(), valueArray[1].toDouble() }; - _uniforms.push_back([=](gpu::Batch& batch) { - batch._glUniform2f(slot, v.x, v.y); - }); + _uniforms.push_back([=](gpu::Batch& batch) { batch._glUniform2f(slot, v.x, v.y); }); break; } @@ -388,9 +366,7 @@ void Procedural::setupUniforms(bool transparent) { valueArray[1].toDouble(), valueArray[2].toDouble(), }; - _uniforms.push_back([=](gpu::Batch& batch) { - batch._glUniform3f(slot, v.x, v.y, v.z); - }); + _uniforms.push_back([=](gpu::Batch& batch) { batch._glUniform3f(slot, v.x, v.y, v.z); }); break; } @@ -402,26 +378,22 @@ void Procedural::setupUniforms(bool transparent) { valueArray[2].toDouble(), valueArray[3].toDouble(), }; - _uniforms.push_back([=](gpu::Batch& batch) { - batch._glUniform4f(slot, v.x, v.y, v.z, v.w); - }); + _uniforms.push_back([=](gpu::Batch& batch) { batch._glUniform4f(slot, v.x, v.y, v.z, v.w); }); break; } } } } - auto uniformSlots = transparent ? _standardTransparentUniformSlots : _standardOpaqueUniformSlots; - - if (gpu::Shader::INVALID_LOCATION != uniformSlots[TIME]) { + if (uniformSlots.isValid(procedural::slot::uniform::Time)) { _uniforms.push_back([=](gpu::Batch& batch) { // Minimize floating point error by doing an integer division to milliseconds, before the floating point division to seconds float time = (float)((usecTimestampNow() - _start) / USECS_PER_MSEC) / MSECS_PER_SECOND; - batch._glUniform(uniformSlots[TIME], time); + batch._glUniform(procedural::slot::uniform::Time, time); }); } - if (gpu::Shader::INVALID_LOCATION != uniformSlots[DATE]) { + if (uniformSlots.isValid(procedural::slot::uniform::Date)) { _uniforms.push_back([=](gpu::Batch& batch) { QDateTime now = QDateTime::currentDateTimeUtc(); QDate date = now.date(); @@ -434,41 +406,37 @@ void Procedural::setupUniforms(bool transparent) { v.z = date.day(); float fractSeconds = (time.msec() / 1000.0f); v.w = (time.hour() * 3600) + (time.minute() * 60) + time.second() + fractSeconds; - batch._glUniform(uniformSlots[DATE], v); + batch._glUniform(procedural::slot::uniform::Date, v); }); } - if (gpu::Shader::INVALID_LOCATION != uniformSlots[FRAME_COUNT]) { - _uniforms.push_back([=](gpu::Batch& batch) { - batch._glUniform(uniformSlots[FRAME_COUNT], ++_frameCount); - }); + if (uniformSlots.isValid(procedural::slot::uniform::FrameCount)) { + _uniforms.push_back([=](gpu::Batch& batch) { batch._glUniform(procedural::slot::uniform::FrameCount, ++_frameCount); }); } - if (gpu::Shader::INVALID_LOCATION != uniformSlots[SCALE]) { + if (uniformSlots.isValid(procedural::slot::uniform::Scale)) { // FIXME move into the 'set once' section, since this doesn't change over time - _uniforms.push_back([=](gpu::Batch& batch) { - batch._glUniform(uniformSlots[SCALE], _entityDimensions); - }); + _uniforms.push_back([=](gpu::Batch& batch) { batch._glUniform(procedural::slot::uniform::Scale, _entityDimensions); }); } - if (gpu::Shader::INVALID_LOCATION != uniformSlots[ORIENTATION]) { + if (uniformSlots.isValid(procedural::slot::uniform::Orientation)) { // FIXME move into the 'set once' section, since this doesn't change over time - _uniforms.push_back([=](gpu::Batch& batch) { - batch._glUniform(uniformSlots[ORIENTATION], _entityOrientation); - }); + _uniforms.push_back( + [=](gpu::Batch& batch) { batch._glUniform(procedural::slot::uniform::Orientation, _entityOrientation); }); } - if (gpu::Shader::INVALID_LOCATION != uniformSlots[POSITION]) { + if (uniformSlots.isValid(procedural::slot::uniform::Position)) { // FIXME move into the 'set once' section, since this doesn't change over time - _uniforms.push_back([=](gpu::Batch& batch) { - batch._glUniform(uniformSlots[POSITION], _entityPosition); - }); + _uniforms.push_back( + [=](gpu::Batch& batch) { batch._glUniform(procedural::slot::uniform::Orientation, _entityPosition); }); } } void Procedural::setupChannels(bool shouldCreate, bool transparent) { - auto uniformSlots = transparent ? _standardTransparentUniformSlots : _standardOpaqueUniformSlots; - if (gpu::Shader::INVALID_LOCATION != uniformSlots[CHANNEL_RESOLUTION]) { + auto& pipeline = transparent ? _transparentShader : _opaqueShader; + const auto& uniformSlots = pipeline->getUniforms(); + + if (uniformSlots.isValid(procedural::slot::uniform::ChannelResolution)) { if (!shouldCreate) { // Instead of modifying the last element, just remove and recreate it. _uniforms.pop_back(); @@ -480,7 +448,8 @@ void Procedural::setupChannels(bool shouldCreate, bool transparent) { channelSizes[i] = vec3(_channels[i]->getWidth(), _channels[i]->getHeight(), 1.0); } } - batch._glUniform3fv(uniformSlots[CHANNEL_RESOLUTION], MAX_PROCEDURAL_TEXTURE_CHANNELS, &channelSizes[0].x); + batch._glUniform3fv(procedural::slot::uniform::ChannelResolution, MAX_PROCEDURAL_TEXTURE_CHANNELS, + &channelSizes[0].x); }); } } diff --git a/libraries/procedural/src/procedural/Procedural.h b/libraries/procedural/src/procedural/Procedural.h index 1d3b0b3b5a..973b323f60 100644 --- a/libraries/procedural/src/procedural/Procedural.h +++ b/libraries/procedural/src/procedural/Procedural.h @@ -64,23 +64,13 @@ public: void setIsFading(bool isFading) { _isFading = isFading; } void setDoesFade(bool doesFade) { _doesFade = doesFade; } - std::string _vertexSource; - std::string _opaquefragmentSource; - std::string _transparentfragmentSource; + gpu::Shader::Source _vertexSource; + gpu::Shader::Source _opaquefragmentSource; + gpu::Shader::Source _transparentfragmentSource; gpu::StatePointer _opaqueState { std::make_shared() }; gpu::StatePointer _transparentState { std::make_shared() }; - enum StandardUniforms { - DATE, - TIME, - FRAME_COUNT, - SCALE, - POSITION, - ORIENTATION, - CHANNEL_RESOLUTION, - NUM_STANDARD_UNIFORMS - }; protected: // Procedural metadata @@ -102,8 +92,6 @@ protected: // Rendering objects UniformLambdas _uniforms; - int32_t _standardOpaqueUniformSlots[NUM_STANDARD_UNIFORMS]; - int32_t _standardTransparentUniformSlots[NUM_STANDARD_UNIFORMS]; NetworkTexturePointer _channels[MAX_PROCEDURAL_TEXTURE_CHANNELS]; gpu::PipelinePointer _opaquePipeline; gpu::PipelinePointer _transparentPipeline; diff --git a/libraries/procedural/src/procedural/ProceduralCommon.slf b/libraries/procedural/src/procedural/ProceduralCommon.slf deleted file mode 100644 index de226e6dae..0000000000 --- a/libraries/procedural/src/procedural/ProceduralCommon.slf +++ /dev/null @@ -1,52 +0,0 @@ -<@include gpu/Config.slh@> -// Generated on <$_SCRIBE_DATE$> -// -// Created by Bradley Austin Davis on 2015/09/05 -// Copyright 2013-2015 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -<@include gpu/Transform.slh@> -<@include gpu/Noise.slh@> - -<$declareStandardCameraTransform()$> - -#define PROCEDURAL 1 - -//PROCEDURAL_VERSION - -#ifdef PROCEDURAL_V1 - -// shader playback time (in seconds) -uniform float iGlobalTime; -// the dimensions of the object being rendered -uniform vec3 iWorldScale; - -#else - -// Unimplemented uniforms -// Resolution doesn't make sense in the VR context -const vec3 iResolution = vec3(1.0); -// Mouse functions not enabled currently -const vec4 iMouse = vec4(0.0); -// No support for audio input -const float iSampleRate = 1.0; -// No support for video input -const vec4 iChannelTime = vec4(0.0); - - -uniform float iGlobalTime; // shader playback time (in seconds) -uniform vec4 iDate; -uniform int iFrameCount; -uniform vec3 iWorldPosition; // the position of the object being rendered -uniform vec3 iWorldScale; // the dimensions of the object being rendered -uniform mat3 iWorldOrientation; // the orientation of the object being rendered -uniform vec3 iChannelResolution[4]; -uniform sampler2D iChannel0; -uniform sampler2D iChannel1; -uniform sampler2D iChannel2; -uniform sampler2D iChannel3; - -#endif \ No newline at end of file diff --git a/libraries/procedural/src/procedural/ProceduralCommon.slh b/libraries/procedural/src/procedural/ProceduralCommon.slh new file mode 100644 index 0000000000..c36f2da1d3 --- /dev/null +++ b/libraries/procedural/src/procedural/ProceduralCommon.slh @@ -0,0 +1,56 @@ +<@include gpu/Config.slh@> +// Generated on <$_SCRIBE_DATE$> +// +// Created by Bradley Austin Davis on 2015/09/05 +// Copyright 2013-2015 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +<@include gpu/Transform.slh@> +<@include gpu/Noise.slh@> +<@include procedural/ShaderConstants.h@> + +<$declareStandardCameraTransform()$> + +#define PROCEDURAL 1 + +//PROCEDURAL_VERSION + +#ifdef PROCEDURAL_V1 + +// shader playback time (in seconds) +layout(location=PROCEDURAL_UNIFORM_TIME) uniform float iGlobalTime; +// the dimensions of the object being rendered +layout(location=PROCEDURAL_UNIFORM_SCALE) uniform vec3 iWorldScale; + +#else + +// Unimplemented uniforms +// Resolution doesn't make sense in the VR context +const vec3 iResolution = vec3(1.0); +// Mouse functions not enabled currently +const vec4 iMouse = vec4(0.0); +// No support for audio input +const float iSampleRate = 1.0; +// No support for video input +const vec4 iChannelTime = vec4(0.0); + + +layout(location=PROCEDURAL_UNIFORM_TIME) uniform float iGlobalTime; // shader playback time (in seconds) +layout(location=PROCEDURAL_UNIFORM_DATE) uniform vec4 iDate; +layout(location=PROCEDURAL_UNIFORM_FRAME_COUNT) uniform int iFrameCount; +layout(location=PROCEDURAL_UNIFORM_POSITION) uniform vec3 iWorldPosition; // the position of the object being rendered +layout(location=PROCEDURAL_UNIFORM_SCALE) uniform vec3 iWorldScale; // the dimensions of the object being rendered +layout(location=PROCEDURAL_UNIFORM_ORIENTATION) uniform mat3 iWorldOrientation; // the orientation of the object being rendered +layout(location=PROCEDURAL_UNIFORM_CHANNEL_RESOLUTION) uniform vec3 iChannelResolution[4]; +layout(binding=PROCEDURAL_TEXTURE_CHANNEL0) uniform sampler2D iChannel0; +layout(binding=PROCEDURAL_TEXTURE_CHANNEL1) uniform sampler2D iChannel1; +layout(binding=PROCEDURAL_TEXTURE_CHANNEL2) uniform sampler2D iChannel2; +layout(binding=PROCEDURAL_TEXTURE_CHANNEL3) uniform sampler2D iChannel3; + +#endif + +// hack comment for extra whitespace + diff --git a/libraries/procedural/src/procedural/ProceduralSkybox.cpp b/libraries/procedural/src/procedural/ProceduralSkybox.cpp index 26a90e1894..0addb57fcf 100644 --- a/libraries/procedural/src/procedural/ProceduralSkybox.cpp +++ b/libraries/procedural/src/procedural/ProceduralSkybox.cpp @@ -18,8 +18,8 @@ #include ProceduralSkybox::ProceduralSkybox() : graphics::Skybox() { - _procedural._vertexSource = gpu::Shader::getVertexShaderSource(shader::graphics::vertex::skybox).getCode(); - _procedural._opaquefragmentSource = gpu::Shader::getFragmentShaderSource(shader::graphics::fragment::skybox).getCode(); + _procedural._vertexSource = gpu::Shader::createVertex(shader::graphics::vertex::skybox)->getSource(); + _procedural._opaquefragmentSource = gpu::Shader::createPixel(shader::procedural::fragment::proceduralSkybox)->getSource(); // Adjust the pipeline state for background using the stencil test _procedural.setDoesFade(false); // Must match PrepareStencil::STENCIL_BACKGROUND @@ -60,9 +60,7 @@ void ProceduralSkybox::render(gpu::Batch& batch, const ViewFrustum& viewFrustum, auto& procedural = skybox._procedural; procedural.prepare(batch, glm::vec3(0), glm::vec3(1), glm::quat()); - auto textureSlot = procedural.getOpaqueShader()->getTextures().findLocation("cubeMap"); - auto bufferSlot = procedural.getOpaqueShader()->getUniformBuffers().findLocation("skyboxBuffer"); - skybox.prepare(batch, textureSlot, bufferSlot); + skybox.prepare(batch); batch.draw(gpu::TRIANGLE_STRIP, 4); } diff --git a/libraries/procedural/src/procedural/ShaderConstants.h b/libraries/procedural/src/procedural/ShaderConstants.h new file mode 100644 index 0000000000..1995996c97 --- /dev/null +++ b/libraries/procedural/src/procedural/ShaderConstants.h @@ -0,0 +1,72 @@ +// + +// <@if not PROCEDURAL_SHADER_CONSTANTS_H@> +// <@def PROCEDURAL_SHADER_CONSTANTS_H@> + +// Hack comment to absorb the extra '//' scribe prepends + +#ifndef PROCEDURAL_SHADER_CONSTANTS_H +#define PROCEDURAL_SHADER_CONSTANTS_H + +// Polyvox +#define PROCEDURAL_UNIFORM_TIME 200 +#define PROCEDURAL_UNIFORM_DATE 201 +#define PROCEDURAL_UNIFORM_FRAME_COUNT 202 +#define PROCEDURAL_UNIFORM_POSITION 203 +#define PROCEDURAL_UNIFORM_SCALE 204 +#define PROCEDURAL_UNIFORM_ORIENTATION 205 +// Additional space because orientation will take up 3-4 locations, being a matrix +#define PROCEDURAL_UNIFORM_CHANNEL_RESOLUTION 209 +#define PROCEDURAL_UNIFORM_CUSTOM 220 + +#define PROCEDURAL_TEXTURE_CHANNEL0 0 +#define PROCEDURAL_TEXTURE_CHANNEL1 1 +#define PROCEDURAL_TEXTURE_CHANNEL2 2 +#define PROCEDURAL_TEXTURE_CHANNEL3 3 + +// +// Hack Comment + +#endif // PROCEDURAL_SHADER_CONSTANTS_H + +// <@if 1@> +// Trigger Scribe include +// <@endif@> + +// <@endif@> + +// Hack Comment diff --git a/libraries/procedural/src/procedural/proceduralSkybox.slf b/libraries/procedural/src/procedural/proceduralSkybox.slf new file mode 100644 index 0000000000..9960698ff0 --- /dev/null +++ b/libraries/procedural/src/procedural/proceduralSkybox.slf @@ -0,0 +1,45 @@ +<@include gpu/Config.slh@> +<$VERSION_HEADER$> +// Generated on <$_SCRIBE_DATE$> +// proceduralSkybox.frag +// fragment shader +// +// Created by Sam Gateau on 5/5/2015. +// Copyright 2015 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// +<@include graphics/ShaderConstants.h@> + +layout(binding=GRAPHICS_TEXTURE_SKYBOX) uniform samplerCube cubeMap; + +struct Skybox { + vec4 color; +}; + +layout(binding=GRAPHICS_BUFFER_SKYBOX_PARAMS) uniform skyboxBuffer { + Skybox skybox; +}; + +layout(location=0) in vec3 _normal; +layout(location=0) out vec4 _fragColor; + +<@include procedural/ProceduralCommon.slh@> + +#line 1001 +//PROCEDURAL_BLOCK + +#line 2033 +void main(void) { + vec3 color = getSkyboxColor(); + // Protect from NaNs and negative values + color = mix(color, vec3(0), isnan(color)); + color = max(color, vec3(0)); + // Procedural Shaders are expected to be Gamma corrected so let's bring back the RGB in linear space for the rest of the pipeline + color = pow(color, vec3(2.2)); + _fragColor = vec4(color, 0.0); + + // FIXME: scribe does not yet scrub out else statements + return; +} diff --git a/libraries/render-utils/src/AmbientOcclusionEffect.cpp b/libraries/render-utils/src/AmbientOcclusionEffect.cpp index aca71636ff..ced1570f37 100644 --- a/libraries/render-utils/src/AmbientOcclusionEffect.cpp +++ b/libraries/render-utils/src/AmbientOcclusionEffect.cpp @@ -19,9 +19,11 @@ #include #include #include +#include #include "RenderUtilsLogging.h" +#include "render-utils/ShaderConstants.h" #include "DeferredLightingEffect.h" #include "TextureCache.h" #include "FramebufferCache.h" @@ -162,12 +164,6 @@ public: } }; -const int AmbientOcclusionEffect_FrameTransformSlot = 0; -const int AmbientOcclusionEffect_ParamsSlot = 1; -const int AmbientOcclusionEffect_CameraCorrectionSlot = 2; -const int AmbientOcclusionEffect_LinearDepthMapSlot = 0; -const int AmbientOcclusionEffect_OcclusionMapSlot = 0; - AmbientOcclusionEffect::AmbientOcclusionEffect() { } @@ -258,15 +254,6 @@ void AmbientOcclusionEffect::configure(const Config& config) { const gpu::PipelinePointer& AmbientOcclusionEffect::getOcclusionPipeline() { if (!_occlusionPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::ssao_makeOcclusion); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), AmbientOcclusionEffect_FrameTransformSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("ambientOcclusionParamsBuffer"), AmbientOcclusionEffect_ParamsSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("cameraCorrectionBuffer"), AmbientOcclusionEffect_CameraCorrectionSlot)); - - slotBindings.insert(gpu::Shader::Binding(std::string("pyramidMap"), AmbientOcclusionEffect_LinearDepthMapSlot)); - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setColorWriteMask(true, true, true, false); @@ -281,14 +268,6 @@ const gpu::PipelinePointer& AmbientOcclusionEffect::getOcclusionPipeline() { const gpu::PipelinePointer& AmbientOcclusionEffect::getHBlurPipeline() { if (!_hBlurPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::ssao_makeHorizontalBlur); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("ambientOcclusionFrameTransformBuffer"), AmbientOcclusionEffect_FrameTransformSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("cameraCorrectionBuffer"), AmbientOcclusionEffect_CameraCorrectionSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("ambientOcclusionParamsBuffer"), AmbientOcclusionEffect_ParamsSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("occlusionMap"), AmbientOcclusionEffect_OcclusionMapSlot)); - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setColorWriteMask(true, true, true, false); @@ -302,15 +281,6 @@ const gpu::PipelinePointer& AmbientOcclusionEffect::getHBlurPipeline() { const gpu::PipelinePointer& AmbientOcclusionEffect::getVBlurPipeline() { if (!_vBlurPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::ssao_makeVerticalBlur); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("ambientOcclusionFrameTransformBuffer"), AmbientOcclusionEffect_FrameTransformSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("cameraCorrectionBuffer"), AmbientOcclusionEffect_CameraCorrectionSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("ambientOcclusionParamsBuffer"), AmbientOcclusionEffect_ParamsSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("occlusionMap"), AmbientOcclusionEffect_OcclusionMapSlot)); - - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); // Vertical blur write just the final result Occlusion value in the alpha channel @@ -388,8 +358,8 @@ void AmbientOcclusionEffect::run(const render::RenderContextPointer& renderConte model.setScale(glm::vec3(sWidth, tHeight, 1.0f)); batch.setModelTransform(model); - batch.setUniformBuffer(AmbientOcclusionEffect_FrameTransformSlot, frameTransform->getFrameTransformBuffer()); - batch.setUniformBuffer(AmbientOcclusionEffect_ParamsSlot, _parametersBuffer); + batch.setUniformBuffer(render_utils::slot::buffer::DeferredFrameTransform, frameTransform->getFrameTransformBuffer()); + batch.setUniformBuffer(render_utils::slot::buffer::SsaoParams, _parametersBuffer); // We need this with the mips levels @@ -399,7 +369,7 @@ void AmbientOcclusionEffect::run(const render::RenderContextPointer& renderConte batch.setFramebuffer(occlusionFBO); batch.clearColorFramebuffer(gpu::Framebuffer::BUFFER_COLOR0, glm::vec4(1.0f)); batch.setPipeline(occlusionPipeline); - batch.setResourceTexture(AmbientOcclusionEffect_LinearDepthMapSlot, _framebuffer->getLinearDepthTexture()); + batch.setResourceTexture(render_utils::slot::texture::SsaoPyramid, _framebuffer->getLinearDepthTexture()); batch.draw(gpu::TRIANGLE_STRIP, 4); @@ -407,19 +377,19 @@ void AmbientOcclusionEffect::run(const render::RenderContextPointer& renderConte // Blur 1st pass batch.setFramebuffer(occlusionBlurredFBO); batch.setPipeline(firstHBlurPipeline); - batch.setResourceTexture(AmbientOcclusionEffect_OcclusionMapSlot, occlusionFBO->getRenderBuffer(0)); + batch.setResourceTexture(render_utils::slot::texture::SsaoOcclusion, occlusionFBO->getRenderBuffer(0)); batch.draw(gpu::TRIANGLE_STRIP, 4); // Blur 2nd pass batch.setFramebuffer(occlusionFBO); batch.setPipeline(lastVBlurPipeline); - batch.setResourceTexture(AmbientOcclusionEffect_OcclusionMapSlot, occlusionBlurredFBO->getRenderBuffer(0)); + batch.setResourceTexture(render_utils::slot::texture::SsaoOcclusion, occlusionBlurredFBO->getRenderBuffer(0)); batch.draw(gpu::TRIANGLE_STRIP, 4); } - batch.setResourceTexture(AmbientOcclusionEffect_LinearDepthMapSlot, nullptr); - batch.setResourceTexture(AmbientOcclusionEffect_OcclusionMapSlot, nullptr); + batch.setResourceTexture(render_utils::slot::texture::SsaoPyramid, nullptr); + batch.setResourceTexture(render_utils::slot::texture::SsaoOcclusion, nullptr); _gpuTimer->end(batch); }); @@ -447,14 +417,6 @@ void DebugAmbientOcclusion::configure(const Config& config) { const gpu::PipelinePointer& DebugAmbientOcclusion::getDebugPipeline() { if (!_debugPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::ssao_debugOcclusion); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), AmbientOcclusionEffect_FrameTransformSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("ambientOcclusionParamsBuffer"), AmbientOcclusionEffect_ParamsSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("debugAmbientOcclusionBuffer"), 2)); - slotBindings.insert(gpu::Shader::Binding(std::string("pyramidMap"), AmbientOcclusionEffect_LinearDepthMapSlot)); - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setColorWriteMask(true, true, true, false); @@ -517,16 +479,16 @@ void DebugAmbientOcclusion::run(const render::RenderContextPointer& renderContex model.setScale(glm::vec3(sWidth, tHeight, 1.0f)); batch.setModelTransform(model); - batch.setUniformBuffer(AmbientOcclusionEffect_FrameTransformSlot, frameTransform->getFrameTransformBuffer()); - batch.setUniformBuffer(AmbientOcclusionEffect_ParamsSlot, ambientOcclusionUniforms); + batch.setUniformBuffer(render_utils::slot::buffer::DeferredFrameTransform, frameTransform->getFrameTransformBuffer()); + batch.setUniformBuffer(render_utils::slot::buffer::SsaoParams, ambientOcclusionUniforms); batch.setUniformBuffer(2, _parametersBuffer); batch.setPipeline(debugPipeline); - batch.setResourceTexture(AmbientOcclusionEffect_LinearDepthMapSlot, linearDepthTexture); + batch.setResourceTexture(render_utils::slot::texture::SsaoPyramid, linearDepthTexture); batch.draw(gpu::TRIANGLE_STRIP, 4); - batch.setResourceTexture(AmbientOcclusionEffect_LinearDepthMapSlot, nullptr); + batch.setResourceTexture(render_utils::slot::texture::SsaoPyramid, nullptr); }); } diff --git a/libraries/render-utils/src/AntialiasingEffect.cpp b/libraries/render-utils/src/AntialiasingEffect.cpp index 52105f1390..2b17ba3c01 100644 --- a/libraries/render-utils/src/AntialiasingEffect.cpp +++ b/libraries/render-utils/src/AntialiasingEffect.cpp @@ -17,7 +17,9 @@ #include #include #include +#include +#include "render-utils/ShaderConstants.h" #include "StencilMaskPass.h" #include "TextureCache.h" #include "DependencyManager.h" @@ -25,6 +27,18 @@ #include "GeometryCache.h" #include "FramebufferCache.h" + +namespace ru { + using render_utils::slot::uniform::Uniform; + using render_utils::slot::texture::Texture; + using render_utils::slot::buffer::Buffer; +} + +namespace gr { + using graphics::slot::texture::Texture; + using graphics::slot::buffer::Buffer; +} + #define ANTIALIASING_USE_TAA 1 #if !ANTIALIASING_USE_TAA @@ -66,11 +80,6 @@ const gpu::PipelinePointer& Antialiasing::getAntialiasingPipeline(RenderArgs* ar auto ps = fxaa_frag::getShader(); gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("colorTexture"), 0)); - - gpu::Shader::makeProgram(*program, slotBindings); - _texcoordOffsetLoc = program->getUniforms().findLocation("texcoordOffset"); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); @@ -90,14 +99,7 @@ const gpu::PipelinePointer& Antialiasing::getBlendPipeline() { auto vs = fxaa_vert::getShader(); auto ps = fxaa_blend_frag::getShader(); gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("colorTexture"), 0)); - - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); - state->setDepthTest(false, false, gpu::LESS_EQUAL); PrepareStencil::testNoAA(*state); @@ -172,17 +174,6 @@ void Antialiasing::run(const render::RenderContextPointer& renderContext, const } #else -const int AntialiasingPass_ParamsSlot = 0; -const int AntialiasingPass_FrameTransformSlot = 1; - -const int AntialiasingPass_HistoryMapSlot = 0; -const int AntialiasingPass_SourceMapSlot = 1; -const int AntialiasingPass_VelocityMapSlot = 2; -const int AntialiasingPass_DepthMapSlot = 3; - -const int AntialiasingPass_NextMapSlot = 4; - - Antialiasing::Antialiasing(bool isSharpenEnabled) : _isSharpenEnabled{ isSharpenEnabled } { } @@ -197,30 +188,12 @@ const gpu::PipelinePointer& Antialiasing::getAntialiasingPipeline(const render:: if (!_antialiasingPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::taa); - - gpu::Shader::BindingSet slotBindings; - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); PrepareStencil::testNoAA(*state); // Good to go add the brand new pipeline _antialiasingPipeline = gpu::Pipeline::create(program, state); - - gpu::doInBatch("SurfaceGeometryPass::CurvaturePipeline", renderContext->args->_context, [program](gpu::Batch& batch) { - batch.runLambda([program]() { - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("taaParamsBuffer"), AntialiasingPass_ParamsSlot)); - - slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), AntialiasingPass_FrameTransformSlot)); - - slotBindings.insert(gpu::Shader::Binding(std::string("historyMap"), AntialiasingPass_HistoryMapSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("sourceMap"), AntialiasingPass_SourceMapSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("velocityMap"), AntialiasingPass_VelocityMapSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("depthMap"), AntialiasingPass_DepthMapSlot)); - gpu::Shader::makeProgram(*program, slotBindings); - }); - }); } return _antialiasingPipeline; @@ -229,20 +202,10 @@ const gpu::PipelinePointer& Antialiasing::getAntialiasingPipeline(const render:: const gpu::PipelinePointer& Antialiasing::getBlendPipeline() { if (!_blendPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::fxaa_blend); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("colorTexture"), AntialiasingPass_NextMapSlot)); - - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); PrepareStencil::testNoAA(*state); - - // Good to go add the brand new pipeline _blendPipeline = gpu::Pipeline::create(program, state); - _sharpenLoc = program->getUniforms().findLocation("sharpenIntensity"); - } return _blendPipeline; } @@ -250,20 +213,6 @@ const gpu::PipelinePointer& Antialiasing::getBlendPipeline() { const gpu::PipelinePointer& Antialiasing::getDebugBlendPipeline() { if (!_debugBlendPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::taa_blend); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("taaParamsBuffer"), AntialiasingPass_ParamsSlot)); - - slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), AntialiasingPass_FrameTransformSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("nextMap"), AntialiasingPass_NextMapSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("historyMap"), AntialiasingPass_HistoryMapSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("sourceMap"), AntialiasingPass_SourceMapSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("velocityMap"), AntialiasingPass_VelocityMapSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("depthMap"), AntialiasingPass_DepthMapSlot)); - - - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); PrepareStencil::testNoAA(*state); @@ -340,41 +289,43 @@ void Antialiasing::run(const render::RenderContextPointer& renderContext, const // TAA step getAntialiasingPipeline(renderContext); - batch.setResourceFramebufferSwapChainTexture(AntialiasingPass_HistoryMapSlot, _antialiasingBuffers, 0); - batch.setResourceTexture(AntialiasingPass_SourceMapSlot, sourceBuffer->getRenderBuffer(0)); - batch.setResourceTexture(AntialiasingPass_VelocityMapSlot, velocityBuffer->getVelocityTexture()); + batch.setResourceFramebufferSwapChainTexture(ru::Texture::TaaHistory, _antialiasingBuffers, 0); + batch.setResourceTexture(ru::Texture::TaaSource, sourceBuffer->getRenderBuffer(0)); + batch.setResourceTexture(ru::Texture::TaaVelocity, velocityBuffer->getVelocityTexture()); // This is only used during debug - batch.setResourceTexture(AntialiasingPass_DepthMapSlot, linearDepthBuffer->getLinearDepthTexture()); + batch.setResourceTexture(ru::Texture::TaaDepth, linearDepthBuffer->getLinearDepthTexture()); - batch.setUniformBuffer(AntialiasingPass_ParamsSlot, _params); - batch.setUniformBuffer(AntialiasingPass_FrameTransformSlot, deferredFrameTransform->getFrameTransformBuffer()); + batch.setUniformBuffer(ru::Buffer::TaaParams, _params); + batch.setUniformBuffer(ru::Buffer::DeferredFrameTransform, deferredFrameTransform->getFrameTransformBuffer()); batch.setFramebufferSwapChain(_antialiasingBuffers, 1); batch.setPipeline(getAntialiasingPipeline(renderContext)); batch.draw(gpu::TRIANGLE_STRIP, 4); // Blend step - batch.setResourceTexture(AntialiasingPass_SourceMapSlot, nullptr); + batch.setResourceTexture(ru::Texture::TaaSource, nullptr); batch.setFramebuffer(sourceBuffer); if (_params->isDebug()) { batch.setPipeline(getDebugBlendPipeline()); + batch.setResourceFramebufferSwapChainTexture(ru::Texture::TaaNext, _antialiasingBuffers, 1); } else { batch.setPipeline(getBlendPipeline()); + // Must match the bindg point in the fxaa_blend.slf shader + batch.setResourceFramebufferSwapChainTexture(0, _antialiasingBuffers, 1); // Disable sharpen if FXAA - batch._glUniform1f(_sharpenLoc, _sharpen * _params.get().regionInfo.z); + batch._glUniform1f(ru::Uniform::TaaSharpenIntensity, _sharpen * _params.get().regionInfo.z); } - batch.setResourceFramebufferSwapChainTexture(AntialiasingPass_NextMapSlot, _antialiasingBuffers, 1); batch.draw(gpu::TRIANGLE_STRIP, 4); batch.advance(_antialiasingBuffers); - batch.setUniformBuffer(AntialiasingPass_ParamsSlot, nullptr); - batch.setUniformBuffer(AntialiasingPass_FrameTransformSlot, nullptr); + batch.setUniformBuffer(ru::Buffer::TaaParams, nullptr); + batch.setUniformBuffer(ru::Buffer::DeferredFrameTransform, nullptr); - batch.setResourceTexture(AntialiasingPass_DepthMapSlot, nullptr); - batch.setResourceTexture(AntialiasingPass_HistoryMapSlot, nullptr); - batch.setResourceTexture(AntialiasingPass_VelocityMapSlot, nullptr); - batch.setResourceTexture(AntialiasingPass_NextMapSlot, nullptr); + batch.setResourceTexture(ru::Texture::TaaDepth, nullptr); + batch.setResourceTexture(ru::Texture::TaaHistory, nullptr); + batch.setResourceTexture(ru::Texture::TaaVelocity, nullptr); + batch.setResourceTexture(ru::Texture::TaaNext, nullptr); }); } @@ -504,5 +455,4 @@ void JitterSample::run(const render::RenderContextPointer& renderContext, Output } } - #endif diff --git a/libraries/render-utils/src/AntialiasingEffect.h b/libraries/render-utils/src/AntialiasingEffect.h index ffce84495e..61da352154 100644 --- a/libraries/render-utils/src/AntialiasingEffect.h +++ b/libraries/render-utils/src/AntialiasingEffect.h @@ -193,7 +193,6 @@ private: TAAParamsBuffer _params; float _sharpen{ 0.15f }; - int _sharpenLoc{ -1 }; bool _isSharpenEnabled{ true }; }; diff --git a/libraries/render-utils/src/BloomApply.slf b/libraries/render-utils/src/BloomApply.slf index 28415643a0..576a71c7c4 100644 --- a/libraries/render-utils/src/BloomApply.slf +++ b/libraries/render-utils/src/BloomApply.slf @@ -1,6 +1,6 @@ <@include gpu/Config.slh@> <$VERSION_HEADER$> -// BloomApply.slf +// BloomApply.frag // Mix the three gaussian blur textures. // // Created by Olivier Prat on 10/09/2017 @@ -11,16 +11,16 @@ // <@include BloomApply.shared.slh@> -uniform sampler2D blurMap0; -uniform sampler2D blurMap1; -uniform sampler2D blurMap2; +layout(binding=0) uniform sampler2D blurMap0; +layout(binding=1) uniform sampler2D blurMap1; +layout(binding=2) uniform sampler2D blurMap2; -layout(std140) uniform parametersBuffer { +layout(std140, location=0) uniform parametersBuffer { Parameters parameters; }; -in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 outFragColor; void main(void) { vec4 blur0 = texture(blurMap0, varTexCoord0); diff --git a/libraries/render-utils/src/BloomEffect.cpp b/libraries/render-utils/src/BloomEffect.cpp index 604919ad2d..2a9a9b3850 100644 --- a/libraries/render-utils/src/BloomEffect.cpp +++ b/libraries/render-utils/src/BloomEffect.cpp @@ -16,6 +16,7 @@ #include #include +#include "render-utils/ShaderConstants.h" #define BLOOM_BLUR_LEVEL_COUNT 3 @@ -59,17 +60,8 @@ void BloomThreshold::run(const render::RenderContextPointer& renderContext, cons _parameters.edit()._deltaUV = { 1.0f / bufferSize.x, 1.0f / bufferSize.y }; } - static const int COLOR_MAP_SLOT = 0; - static const int PARAMETERS_SLOT = 1; - if (!_pipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::bloomThreshold); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding("colorMap", COLOR_MAP_SLOT)); - slotBindings.insert(gpu::Shader::Binding("parametersBuffer", PARAMETERS_SLOT)); - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); _pipeline = gpu::Pipeline::create(program, state); } @@ -86,8 +78,8 @@ void BloomThreshold::run(const render::RenderContextPointer& renderContext, cons batch.setPipeline(_pipeline); batch.setFramebuffer(_outputBuffer); - batch.setResourceTexture(COLOR_MAP_SLOT, inputBuffer); - batch.setUniformBuffer(PARAMETERS_SLOT, _parameters); + batch.setResourceTexture(render_utils::slot::texture::BloomColor, inputBuffer); + batch.setUniformBuffer(render_utils::slot::buffer::BloomParams, _parameters); batch.draw(gpu::TRIANGLE_STRIP, 4); }); @@ -121,14 +113,6 @@ void BloomApply::run(const render::RenderContextPointer& renderContext, const In if (!_pipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::bloomApply); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding("blurMap0", BLUR0_SLOT)); - slotBindings.insert(gpu::Shader::Binding("blurMap1", BLUR1_SLOT)); - slotBindings.insert(gpu::Shader::Binding("blurMap2", BLUR2_SLOT)); - slotBindings.insert(gpu::Shader::Binding("parametersBuffer", PARAMETERS_SLOT)); - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setDepthTest(gpu::State::DepthTest(false, false)); _pipeline = gpu::Pipeline::create(program, state); @@ -155,7 +139,7 @@ void BloomApply::run(const render::RenderContextPointer& renderContext, const In batch.setResourceTexture(BLUR0_SLOT, blur0FB->getRenderBuffer(0)); batch.setResourceTexture(BLUR1_SLOT, blur1FB->getRenderBuffer(0)); batch.setResourceTexture(BLUR2_SLOT, blur2FB->getRenderBuffer(0)); - batch.setUniformBuffer(PARAMETERS_SLOT, _parameters); + batch.setUniformBuffer(PARAMETERS_SLOT, _parameters); batch.draw(gpu::TRIANGLE_STRIP, 4); }); } @@ -173,9 +157,6 @@ void BloomDraw::run(const render::RenderContextPointer& renderContext, const Inp if (!_pipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::gpu::program::drawTransformUnitQuadTextureOpaque); - gpu::Shader::BindingSet slotBindings; - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setDepthTest(gpu::State::DepthTest(false, false)); state->setBlendFunction(true, gpu::State::ONE, gpu::State::BLEND_OP_ADD, gpu::State::ONE, @@ -229,11 +210,6 @@ void DebugBloom::run(const render::RenderContextPointer& renderContext, const In if (!_pipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::gpu::program::drawTextureOpaqueTexcoordRect); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("texcoordRect"), TEXCOORD_RECT_SLOT)); - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setDepthTest(gpu::State::DepthTest(false)); _pipeline = gpu::Pipeline::create(program, state); @@ -307,7 +283,7 @@ float BloomConfig::getIntensity() const { void BloomConfig::setSize(float value) { std::string blurName{ "BloomBlurN" }; auto sigma = 0.5f+value*3.5f; - auto task = static_cast(_task); + auto task = static_cast(_task); for (auto i = 0; i < BLOOM_BLUR_LEVEL_COUNT; i++) { blurName.back() = '0' + i; @@ -317,9 +293,9 @@ void BloomConfig::setSize(float value) { auto gaussianBlurParams = gaussianBlur.getParameters(); gaussianBlurParams->setFilterGaussianTaps(9, sigma); } - auto blurJobIt = task->getJob("BloomApply"); - assert(blurJobIt != task->_jobs.end()); - blurJobIt->getConfiguration()->setProperty("sigma", sigma); + auto blurJobIt = task->getJob("BloomApply"); + assert(blurJobIt != task->_jobs.end()); + blurJobIt->getConfiguration()->setProperty("sigma", sigma); } Bloom::Bloom() { diff --git a/libraries/render-utils/src/BloomThreshold.slf b/libraries/render-utils/src/BloomThreshold.slf index 6eb75fba6e..2756e7aa01 100644 --- a/libraries/render-utils/src/BloomThreshold.slf +++ b/libraries/render-utils/src/BloomThreshold.slf @@ -1,6 +1,6 @@ <@include gpu/Config.slh@> <$VERSION_HEADER$> -// BloomThreshold.slf +// BloomThreshold.frag // Perform a soft threshold on an input texture and downsample to half size in one go. // // Created by Olivier Prat on 09/26/2017 @@ -10,14 +10,15 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // <@include BloomThreshold.shared.slh@> +<@include render-utils/ShaderConstants.h@> -uniform sampler2D colorMap; -layout(std140) uniform parametersBuffer { +layout(binding=RENDER_UTILS_TEXTURE_BLOOM_COLOR) uniform sampler2D colorMap; +layout(std140, location=RENDER_UTILS_BUFFER_BLOOM_PARAMS) uniform parametersBuffer { Parameters parameters; }; -in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 outFragColor; void main(void) { vec2 startUv = varTexCoord0; diff --git a/libraries/render-utils/src/CauterizedMeshPartPayload.cpp b/libraries/render-utils/src/CauterizedMeshPartPayload.cpp index a4dc56e696..a310c10136 100644 --- a/libraries/render-utils/src/CauterizedMeshPartPayload.cpp +++ b/libraries/render-utils/src/CauterizedMeshPartPayload.cpp @@ -12,6 +12,7 @@ #include "CauterizedMeshPartPayload.h" #include +#include #include "CauterizedModel.h" @@ -58,7 +59,7 @@ void CauterizedMeshPartPayload::bindTransform(gpu::Batch& batch, RenderArgs::Ren bool useCauterizedMesh = (renderMode != RenderArgs::RenderMode::SHADOW_RENDER_MODE && renderMode != RenderArgs::RenderMode::SECONDARY_CAMERA_RENDER_MODE) && _enableCauterization; if (useCauterizedMesh) { if (_cauterizedClusterBuffer) { - batch.setUniformBuffer(ShapePipeline::Slot::BUFFER::SKINNING, _cauterizedClusterBuffer); + batch.setUniformBuffer(graphics::slot::buffer::Skinning, _cauterizedClusterBuffer); } batch.setModelTransform(_cauterizedTransform); } else { diff --git a/libraries/render-utils/src/DebugDeferredBuffer.cpp b/libraries/render-utils/src/DebugDeferredBuffer.cpp index 4844c821e5..e7268f2799 100644 --- a/libraries/render-utils/src/DebugDeferredBuffer.cpp +++ b/libraries/render-utils/src/DebugDeferredBuffer.cpp @@ -19,6 +19,7 @@ #include #include #include +#include "render-utils/ShaderConstants.h" #include "GeometryCache.h" #include "TextureCache.h" @@ -37,6 +38,7 @@ void DebugDeferredBufferConfig::setMode(int newMode) { emit dirty(); } +#if 0 enum TextureSlot { Albedo = 0, Normal, @@ -61,29 +63,30 @@ enum ParamSlot { ShadowTransform, DebugParametersBuffer }; +#endif -static const std::string DEFAULT_ALBEDO_SHADER { +static const std::string DEFAULT_ALBEDO_SHADER{ "vec4 getFragmentColor() {" " DeferredFragment frag = unpackDeferredFragmentNoPosition(uv);" " return vec4(pow(frag.albedo, vec3(1.0 / 2.2)), 1.0);" " }" }; -static const std::string DEFAULT_METALLIC_SHADER { +static const std::string DEFAULT_METALLIC_SHADER{ "vec4 getFragmentColor() {" " DeferredFragment frag = unpackDeferredFragmentNoPosition(uv);" " return vec4(vec3(pow(frag.metallic, 1.0 / 2.2)), 1.0);" " }" }; -static const std::string DEFAULT_ROUGHNESS_SHADER { +static const std::string DEFAULT_ROUGHNESS_SHADER{ "vec4 getFragmentColor() {" " DeferredFragment frag = unpackDeferredFragmentNoPosition(uv);" " return vec4(vec3(pow(frag.roughness, 1.0 / 2.2)), 1.0);" - // " return vec4(vec3(pow(colorRamp(frag.roughness), vec3(1.0 / 2.2))), 1.0);" + // " return vec4(vec3(pow(colorRamp(frag.roughness), vec3(1.0 / 2.2))), 1.0);" " }" }; -static const std::string DEFAULT_NORMAL_SHADER { +static const std::string DEFAULT_NORMAL_SHADER{ "vec4 getFragmentColor() {" " DeferredFragment frag = unpackDeferredFragmentNoPosition(uv);" " return vec4(vec3(0.5) + (frag.normal * 0.5), 1.0);" @@ -92,8 +95,8 @@ static const std::string DEFAULT_NORMAL_SHADER { static const std::string DEFAULT_OCCLUSION_SHADER{ "vec4 getFragmentColor() {" - // " DeferredFragment frag = unpackDeferredFragmentNoPosition(uv);" - // " return vec4(vec3(pow(frag.obscurance, 1.0 / 2.2)), 1.0);" + // " DeferredFragment frag = unpackDeferredFragmentNoPosition(uv);" + // " return vec4(vec3(pow(frag.obscurance, 1.0 / 2.2)), 1.0);" " return vec4(vec3(pow(texture(specularMap, uv).a, 1.0 / 2.2)), 1.0);" " }" }; @@ -101,7 +104,8 @@ static const std::string DEFAULT_OCCLUSION_SHADER{ static const std::string DEFAULT_EMISSIVE_SHADER{ "vec4 getFragmentColor() {" " DeferredFragment frag = unpackDeferredFragmentNoPosition(uv);" - " return (frag.mode == FRAG_MODE_SHADED ? vec4(pow(texture(specularMap, uv).rgb, vec3(1.0 / 2.2)), 1.0) : vec4(vec3(0.0), 1.0));" + " return (frag.mode == FRAG_MODE_SHADED ? vec4(pow(texture(specularMap, uv).rgb, vec3(1.0 / 2.2)), 1.0) : " + "vec4(vec3(0.0), 1.0));" " }" }; @@ -115,7 +119,8 @@ static const std::string DEFAULT_UNLIT_SHADER{ static const std::string DEFAULT_LIGHTMAP_SHADER{ "vec4 getFragmentColor() {" " DeferredFragment frag = unpackDeferredFragmentNoPosition(uv);" - " return (frag.mode == FRAG_MODE_LIGHTMAPPED ? vec4(pow(texture(specularMap, uv).rgb, vec3(1.0 / 2.2)), 1.0) : vec4(vec3(0.0), 1.0));" + " return (frag.mode == FRAG_MODE_LIGHTMAPPED ? vec4(pow(texture(specularMap, uv).rgb, vec3(1.0 / 2.2)), 1.0) : " + "vec4(vec3(0.0), 1.0));" " }" }; @@ -126,13 +131,13 @@ static const std::string DEFAULT_SCATTERING_SHADER{ " }" }; -static const std::string DEFAULT_DEPTH_SHADER { +static const std::string DEFAULT_DEPTH_SHADER{ "vec4 getFragmentColor() {" " return vec4(vec3(texture(depthMap, uv).x), 1.0);" " }" }; -static const std::string DEFAULT_LIGHTING_SHADER { +static const std::string DEFAULT_LIGHTING_SHADER{ "vec4 getFragmentColor() {" " return vec4(pow(texture(lightingMap, uv).xyz, vec3(1.0 / 2.2)), 1.0);" " }" @@ -171,7 +176,7 @@ static const std::string DEFAULT_SHADOW_CASCADE_SHADER{ "}" }; -static const std::string DEFAULT_LINEAR_DEPTH_SHADER { +static const std::string DEFAULT_LINEAR_DEPTH_SHADER{ "vec4 getFragmentColor() {" " return vec4(vec3(1.0 - texture(linearDepthMap, uv).x * 0.01), 1.0);" "}" @@ -192,7 +197,7 @@ static const std::string DEFAULT_HALF_NORMAL_SHADER{ static const std::string DEFAULT_CURVATURE_SHADER{ "vec4 getFragmentColor() {" " return vec4(pow(vec3(texture(curvatureMap, uv).a), vec3(1.0 / 2.2)), 1.0);" - // " return vec4(pow(vec3(texture(curvatureMap, uv).xyz), vec3(1.0 / 2.2)), 1.0);" + // " return vec4(pow(vec3(texture(curvatureMap, uv).xyz), vec3(1.0 / 2.2)), 1.0);" //" return vec4(vec3(1.0 - textureLod(pyramidMap, uv, 3).x * 0.01), 1.0);" " }" }; @@ -200,7 +205,7 @@ static const std::string DEFAULT_CURVATURE_SHADER{ static const std::string DEFAULT_NORMAL_CURVATURE_SHADER{ "vec4 getFragmentColor() {" //" return vec4(pow(vec3(texture(curvatureMap, uv).a), vec3(1.0 / 2.2)), 1.0);" - " return vec4(vec3(texture(curvatureMap, uv).xyz), 1.0);" + " return vec4(vec3(texture(curvatureMap, uv).xyz), 1.0);" //" return vec4(vec3(1.0 - textureLod(pyramidMap, uv, 3).x * 0.01), 1.0);" " }" }; @@ -236,7 +241,7 @@ static const std::string DEFAULT_CURVATURE_OCCLUSION_SHADER{ static const std::string DEFAULT_DEBUG_SCATTERING_SHADER{ "vec4 getFragmentColor() {" " return vec4(pow(vec3(texture(scatteringMap, uv).xyz), vec3(1.0 / 2.2)), 1.0);" - // " return vec4(vec3(texture(scatteringMap, uv).xyz), 1.0);" + // " return vec4(vec3(texture(scatteringMap, uv).xyz), 1.0);" " }" }; @@ -259,7 +264,7 @@ static const std::string DEFAULT_VELOCITY_SHADER{ " }" }; -static const std::string DEFAULT_CUSTOM_SHADER { +static const std::string DEFAULT_CUSTOM_SHADER{ "vec4 getFragmentColor() {" " return vec4(1.0, 0.0, 0.0, 1.0);" " }" @@ -270,12 +275,11 @@ static std::string getFileContent(std::string fileName, std::string defaultConte if (customFile.open(QIODevice::ReadOnly)) { return customFile.readAll().toStdString(); } - qWarning() << "DebugDeferredBuffer::getFileContent(): Could not open" - << QString::fromStdString(fileName); + qWarning() << "DebugDeferredBuffer::getFileContent(): Could not open" << QString::fromStdString(fileName); return defaultContent; } -#include // TODO REMOVE: Temporary until UI +#include // TODO REMOVE: Temporary until UI DebugDeferredBuffer::DebugDeferredBuffer() { // TODO REMOVE: Temporary until UI static const auto DESKTOP_PATH = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); @@ -361,60 +365,35 @@ bool DebugDeferredBuffer::pipelineNeedsUpdate(Mode mode, std::string customFile) if (mode != CustomMode) { return !_pipelines[mode]; } - + auto it = _customPipelines.find(customFile); if (it != _customPipelines.end() && it->second.pipeline) { auto& info = it->second.info; - + auto lastModified = info.lastModified(); info.refresh(); return lastModified != info.lastModified(); } - + return true; } const gpu::PipelinePointer& DebugDeferredBuffer::getPipeline(Mode mode, std::string customFile) { if (pipelineNeedsUpdate(mode, customFile)) { - static const std::string FRAGMENT_SHADER { gpu::Shader::getFragmentShaderSource(shader::render_utils::fragment::debug_deferred_buffer).getCode() }; - static const std::string SOURCE_PLACEHOLDER { "//SOURCE_PLACEHOLDER" }; - static const auto SOURCE_PLACEHOLDER_INDEX = FRAGMENT_SHADER.find(SOURCE_PLACEHOLDER); - Q_ASSERT_X(SOURCE_PLACEHOLDER_INDEX != std::string::npos, Q_FUNC_INFO, - "Could not find source placeholder"); - - auto bakedFragmentShader = FRAGMENT_SHADER; - bakedFragmentShader.replace(SOURCE_PLACEHOLDER_INDEX, SOURCE_PLACEHOLDER.size(), - getShaderSourceCode(mode, customFile)); - - const auto vs = gpu::Shader::createVertex(shader::render_utils::vertex::debug_deferred_buffer); - const auto ps = gpu::Shader::createPixel(bakedFragmentShader); - const auto program = gpu::Shader::createProgram(vs, ps); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding("cameraCorrectionBuffer", CameraCorrection)); - slotBindings.insert(gpu::Shader::Binding("deferredFrameTransformBuffer", DeferredFrameTransform)); - slotBindings.insert(gpu::Shader::Binding("shadowTransformBuffer", ShadowTransform)); - slotBindings.insert(gpu::Shader::Binding("parametersBuffer", DebugParametersBuffer)); + static const auto FRAGMENT_SHADER_SOURCE = + gpu::Shader::createPixel(shader::render_utils::fragment::debug_deferred_buffer)->getSource(); + static const std::string SOURCE_PLACEHOLDER{ "//SOURCE_PLACEHOLDER" }; + static const auto SOURCE_PLACEHOLDER_INDEX = FRAGMENT_SHADER_SOURCE.getCode().find(SOURCE_PLACEHOLDER); + Q_ASSERT_X(SOURCE_PLACEHOLDER_INDEX != std::string::npos, Q_FUNC_INFO, "Could not find source placeholder"); - slotBindings.insert(gpu::Shader::Binding("albedoMap", Albedo)); - slotBindings.insert(gpu::Shader::Binding("normalMap", Normal)); - slotBindings.insert(gpu::Shader::Binding("specularMap", Specular)); - slotBindings.insert(gpu::Shader::Binding("depthMap", Depth)); - slotBindings.insert(gpu::Shader::Binding("obscuranceMap", AmbientOcclusion)); - slotBindings.insert(gpu::Shader::Binding("lightingMap", Lighting)); - slotBindings.insert(gpu::Shader::Binding("shadowMaps", Shadow)); - slotBindings.insert(gpu::Shader::Binding("linearDepthMap", LinearDepth)); - slotBindings.insert(gpu::Shader::Binding("halfLinearDepthMap", HalfLinearDepth)); - slotBindings.insert(gpu::Shader::Binding("halfNormalMap", HalfNormal)); - slotBindings.insert(gpu::Shader::Binding("curvatureMap", Curvature)); - slotBindings.insert(gpu::Shader::Binding("diffusedCurvatureMap", DiffusedCurvature)); - slotBindings.insert(gpu::Shader::Binding("scatteringMap", Scattering)); - slotBindings.insert(gpu::Shader::Binding("occlusionBlurredMap", AmbientOcclusionBlurred)); - slotBindings.insert(gpu::Shader::Binding("velocityMap", Velocity)); - gpu::Shader::makeProgram(*program, slotBindings); - + auto bakedFragmentShader = FRAGMENT_SHADER_SOURCE.getCode(); + bakedFragmentShader.replace(SOURCE_PLACEHOLDER_INDEX, SOURCE_PLACEHOLDER.size(), getShaderSourceCode(mode, customFile)); + + const auto vs = gpu::Shader::createVertex(shader::render_utils::vertex::debug_deferred_buffer); + const auto ps = gpu::Shader::createPixel({ bakedFragmentShader, FRAGMENT_SHADER_SOURCE.getReflection() }); + const auto program = gpu::Shader::createProgram(vs, ps); auto pipeline = gpu::Pipeline::create(program, std::make_shared()); - + // Good to go add the brand new pipeline if (mode != CustomMode) { _pipelines[mode] = pipeline; @@ -422,7 +401,7 @@ const gpu::PipelinePointer& DebugDeferredBuffer::getPipeline(Mode mode, std::str _customPipelines[customFile].pipeline = pipeline; } } - + if (mode != CustomMode) { return _pipelines[mode]; } else { @@ -443,6 +422,7 @@ void DebugDeferredBuffer::run(const RenderContextPointer& renderContext, const I return; } +#if 0 assert(renderContext->args); assert(renderContext->args->hasViewFrustum()); RenderArgs* args = renderContext->args; @@ -469,23 +449,26 @@ void DebugDeferredBuffer::run(const RenderContextPointer& renderContext, const I batch.setViewTransform(viewMat, true); batch.setModelTransform(Transform()); + using Textures = render_utils::slot::texture::Texture; + using UBOs = render_utils::slot::buffer::Buffer; + // TODO REMOVE: Temporary until UI auto first = _customPipelines.begin()->first; auto pipeline = getPipeline(_mode, first); batch.setPipeline(pipeline); if (deferredFramebuffer) { - batch.setResourceTexture(Albedo, deferredFramebuffer->getDeferredColorTexture()); - batch.setResourceTexture(Normal, deferredFramebuffer->getDeferredNormalTexture()); - batch.setResourceTexture(Specular, deferredFramebuffer->getDeferredSpecularTexture()); - batch.setResourceTexture(Depth, deferredFramebuffer->getPrimaryDepthTexture()); - batch.setResourceTexture(Lighting, deferredFramebuffer->getLightingTexture()); + batch.setResourceTexture(Textures::DeferredColor, deferredFramebuffer->getDeferredColorTexture()); + batch.setResourceTexture(Textures::DeferredNormal, deferredFramebuffer->getDeferredNormalTexture()); + batch.setResourceTexture(Textures::DeferredSpecular, deferredFramebuffer->getDeferredSpecularTexture()); + batch.setResourceTexture(Textures::DeferredDepth, deferredFramebuffer->getPrimaryDepthTexture()); + batch.setResourceTexture(Textures::DeferredLighting, deferredFramebuffer->getLightingTexture()); } if (velocityFramebuffer) { - batch.setResourceTexture(Velocity, velocityFramebuffer->getVelocityTexture()); + batch.setResourceTexture(Textures::TaaVelocity, velocityFramebuffer->getVelocityTexture()); } - batch.setUniformBuffer(DebugParametersBuffer, _parameters); + batch.setUniformBuffer(UBOs:: DebugParametersBuffer, _parameters); auto lightStage = renderContext->_scene->getStage(); assert(lightStage); @@ -493,13 +476,13 @@ void DebugDeferredBuffer::run(const RenderContextPointer& renderContext, const I auto lightAndShadow = lightStage->getCurrentKeyLightAndShadow(); const auto& globalShadow = lightAndShadow.second; if (globalShadow) { - batch.setResourceTexture(Shadow, globalShadow->map); - batch.setUniformBuffer(ShadowTransform, globalShadow->getBuffer()); - batch.setUniformBuffer(DeferredFrameTransform, frameTransform->getFrameTransformBuffer()); + batch.setResourceTexture(Textures::Shadow, globalShadow->map); + batch.setUniformBuffer(UBOs::ShadowParams, globalShadow->getBuffer()); + batch.setUniformBuffer(UBOs::DeferredFrameTransform, frameTransform->getFrameTransformBuffer()); } if (linearDepthTarget) { - batch.setResourceTexture(LinearDepth, linearDepthTarget->getLinearDepthTexture()); + batch.setResourceTexture(Textures::LLinearDepth, linearDepthTarget->getLinearDepthTexture()); batch.setResourceTexture(HalfLinearDepth, linearDepthTarget->getHalfLinearDepthTexture()); batch.setResourceTexture(HalfNormal, linearDepthTarget->getHalfNormalTexture()); } @@ -508,7 +491,7 @@ void DebugDeferredBuffer::run(const RenderContextPointer& renderContext, const I batch.setResourceTexture(DiffusedCurvature, surfaceGeometryFramebuffer->getLowCurvatureTexture()); } if (ambientOcclusionFramebuffer) { - batch.setResourceTexture(AmbientOcclusion, ambientOcclusionFramebuffer->getOcclusionTexture()); + batch.setResourceTexture(Textures::SsaoOcclusion, ambientOcclusionFramebuffer->getOcclusionTexture()); batch.setResourceTexture(AmbientOcclusionBlurred, ambientOcclusionFramebuffer->getOcclusionBlurredTexture()); } const glm::vec4 color(1.0f, 1.0f, 1.0f, 1.0f); @@ -535,4 +518,5 @@ void DebugDeferredBuffer::run(const RenderContextPointer& renderContext, const I batch.setResourceTexture(Velocity, nullptr); }); +#endif } diff --git a/libraries/render-utils/src/DeferredBufferRead.slh b/libraries/render-utils/src/DeferredBufferRead.slh index f7ab0957cc..8c6c76b24a 100644 --- a/libraries/render-utils/src/DeferredBufferRead.slh +++ b/libraries/render-utils/src/DeferredBufferRead.slh @@ -11,26 +11,29 @@ <@if not DEFERRED_BUFFER_READ_SLH@> <@def DEFERRED_BUFFER_READ_SLH@> +<@include render-utils/ShaderConstants.h@> <@include DeferredBuffer.slh@> +// See DeferredShader_MapSlot in DeferredLightingEffect.cpp for constants + // the albedo texture -uniform sampler2D albedoMap; +layout(binding=RENDER_UTILS_TEXTURE_DEFERRRED_COLOR) uniform sampler2D albedoMap; // the normal texture -uniform sampler2D normalMap; +layout(binding=RENDER_UTILS_TEXTURE_DEFERRRED_NORMAL) uniform sampler2D normalMap; // the specular texture -uniform sampler2D specularMap; +layout(binding=RENDER_UTILS_TEXTURE_DEFERRRED_SPECULAR) uniform sampler2D specularMap; // the depth texture -uniform sampler2D depthMap; -uniform sampler2D linearZeyeMap; +layout(binding=RENDER_UTILS_TEXTURE_DEFERRRED_DEPTH) uniform sampler2D depthMap; +layout(binding=RENDER_UTILS_TEXTURE_DEFERRRED_LINEAR_Z_EYE) uniform sampler2D linearZeyeMap; // the obscurance texture -uniform sampler2D obscuranceMap; +layout(binding=RENDER_UTILS_TEXTURE_DEFERRED_OBSCURANCE) uniform sampler2D obscuranceMap; // the lighting texture -uniform sampler2D lightingMap; +layout(binding=RENDER_UTILS_TEXTURE_DEFERRED_LIGHTING) uniform sampler2D lightingMap; struct DeferredFragment { @@ -167,14 +170,14 @@ DeferredFragment unpackDeferredFragment(DeferredFrameTransform deferredTransform <@func declareDeferredCurvature()@> // the curvature texture -uniform sampler2D curvatureMap; +layout(binding=RENDER_UTILS_TEXTURE_DEFERRED_CURVATURE) uniform sampler2D curvatureMap; vec4 fetchCurvature(vec2 texcoord) { return texture(curvatureMap, texcoord); } // the curvature texture -uniform sampler2D diffusedCurvatureMap; +layout(binding=RENDER_UTILS_TEXTURE_DEFERRED_DIFFUSED_CURVATURE) uniform sampler2D diffusedCurvatureMap; vec4 fetchDiffusedCurvature(vec2 texcoord) { return texture(diffusedCurvatureMap, texcoord); diff --git a/libraries/render-utils/src/DeferredBufferWrite.slh b/libraries/render-utils/src/DeferredBufferWrite.slh index ae8d6fa277..769e602dc5 100644 --- a/libraries/render-utils/src/DeferredBufferWrite.slh +++ b/libraries/render-utils/src/DeferredBufferWrite.slh @@ -14,11 +14,10 @@ <@include DeferredBuffer.slh@> -layout(location = 0) out vec4 _fragColor0; -layout(location = 1) out vec4 _fragColor1; -layout(location = 2) out vec4 _fragColor2; - -layout(location = 3) out vec4 _fragColor3; +layout(location=0) out vec4 _fragColor0; // albedo / metallic +layout(location=1) out vec4 _fragColor1; // Normal +layout(location=2) out vec4 _fragColor2; // scattering / emissive / occlusion +layout(location=3) out vec4 _fragColor3; // emissive // the alpha threshold const float alphaThreshold = 0.5; diff --git a/libraries/render-utils/src/DeferredFrameTransform.h b/libraries/render-utils/src/DeferredFrameTransform.h index f8181b6b8a..f7700cb2dc 100644 --- a/libraries/render-utils/src/DeferredFrameTransform.h +++ b/libraries/render-utils/src/DeferredFrameTransform.h @@ -43,20 +43,20 @@ protected: glm::vec4 depthInfo; // Stereo info is { isStereoFrame, halfWidth } glm::vec4 stereoInfo{ 0.0 }; - // Mono proj matrix or Left and Right proj matrix going from Mono Eye space to side clip space - glm::mat4 projection[2]; - // Inverse proj matrix or Left and Right proj matrix going from Mono Eye space to side clip space - glm::mat4 invProjection[2]; - // THe mono projection for sure + // Mono proj matrix or Left and Right proj matrix going from Mono Eye space to side clip space + glm::mat4 projection[2]; + // Inverse proj matrix or Left and Right proj matrix going from Mono Eye space to side clip space + glm::mat4 invProjection[2]; + // THe mono projection for sure glm::mat4 projectionMono; // Inv View matrix from eye space (mono) to world space glm::mat4 invView; // View matrix from world space to eye space (mono) glm::mat4 view; - // Mono proj matrix or Left and Right proj matrix going from Mono Eye space to side clip space without jittering - glm::mat4 projectionUnjittered[2]; - // Inverse proj matrix or Left and Right proj matrix going from Mono Eye space to side clip space without jittering - glm::mat4 invProjectionUnjittered[2]; + // Mono proj matrix or Left and Right proj matrix going from Mono Eye space to side clip space without jittering + glm::mat4 projectionUnjittered[2]; + // Inverse proj matrix or Left and Right proj matrix going from Mono Eye space to side clip space without jittering + glm::mat4 invProjectionUnjittered[2]; FrameTransform() {} }; diff --git a/libraries/render-utils/src/DeferredLightingEffect.cpp b/libraries/render-utils/src/DeferredLightingEffect.cpp index 0d077b19d8..2995d17f03 100644 --- a/libraries/render-utils/src/DeferredLightingEffect.cpp +++ b/libraries/render-utils/src/DeferredLightingEffect.cpp @@ -10,7 +10,6 @@ // #include "DeferredLightingEffect.h" - #include #include @@ -21,54 +20,33 @@ #include #include +#include + +#include "render-utils/ShaderConstants.h" #include "StencilMaskPass.h" #include "AbstractViewStateInterface.h" #include "GeometryCache.h" #include "TextureCache.h" #include "FramebufferCache.h" +namespace ru { + using render_utils::slot::texture::Texture; + using render_utils::slot::buffer::Buffer; + using render_utils::slot::uniform::Uniform; +} + +namespace gr { + using graphics::slot::texture::Texture; + using graphics::slot::buffer::Buffer; +} + using namespace render; struct LightLocations { - int radius{ -1 }; - int keyLightBufferUnit{ -1 }; - int lightBufferUnit{ -1 }; - int ambientBufferUnit { -1 }; - int lightIndexBufferUnit { -1 }; - int texcoordFrameTransform{ -1 }; - int deferredFrameTransformBuffer{ -1 }; - int subsurfaceScatteringParametersBuffer{ -1 }; - int shadowTransformBuffer{ -1 }; -}; - -enum DeferredShader_MapSlot { - DEFERRED_BUFFER_COLOR_UNIT = 0, - DEFERRED_BUFFER_NORMAL_UNIT = 1, - DEFERRED_BUFFER_EMISSIVE_UNIT = 2, - DEFERRED_BUFFER_DEPTH_UNIT = 3, - DEFERRED_BUFFER_OBSCURANCE_UNIT = 4, - DEFERRED_BUFFER_LINEAR_DEPTH_UNIT = 5, - DEFERRED_BUFFER_CURVATURE_UNIT = 6, - DEFERRED_BUFFER_DIFFUSED_CURVATURE_UNIT = 7, - SCATTERING_LUT_UNIT = 8, - SCATTERING_SPECULAR_UNIT = 9, - SKYBOX_MAP_UNIT = render::ShapePipeline::Slot::LIGHT_AMBIENT_MAP, // unit = 10 - SHADOW_MAP_UNIT = 11, - nextAvailableUnit = SHADOW_MAP_UNIT -}; -enum DeferredShader_BufferSlot { - DEFERRED_FRAME_TRANSFORM_BUFFER_SLOT = 0, - CAMERA_CORRECTION_BUFFER_SLOT, - SCATTERING_PARAMETERS_BUFFER_SLOT, - LIGHTING_MODEL_BUFFER_SLOT = render::ShapePipeline::Slot::LIGHTING_MODEL, - KEY_LIGHT_SLOT = render::ShapePipeline::Slot::KEY_LIGHT, - LIGHT_ARRAY_SLOT = render::ShapePipeline::Slot::LIGHT_ARRAY_BUFFER, - LIGHT_AMBIENT_SLOT = render::ShapePipeline::Slot::LIGHT_AMBIENT_BUFFER, - HAZE_MODEL_BUFFER_SLOT = render::ShapePipeline::Slot::HAZE_MODEL, - LIGHT_INDEX_GPU_SLOT, - LIGHT_CLUSTER_GRID_FRUSTUM_GRID_SLOT, - LIGHT_CLUSTER_GRID_CLUSTER_GRID_SLOT, - LIGHT_CLUSTER_GRID_CLUSTER_CONTENT_SLOT, + bool shadowTransform{ false }; + void initialize(const gpu::ShaderPointer& program) { + shadowTransform = program->getUniformBuffers().isValid(ru::Buffer::ShadowParams); + } }; static void loadLightProgram(int programId, bool lightVolume, gpu::PipelinePointer& program, LightLocationsPtr& locations); @@ -93,7 +71,7 @@ void DeferredLightingEffect::init() { loadLightProgram(shader::render_utils::program::local_lights_drawOutline, true, _localLightOutline, _localLightOutlineLocations); } -void DeferredLightingEffect::setupKeyLightBatch(const RenderArgs* args, gpu::Batch& batch, int lightBufferUnit, int ambientBufferUnit, int skyboxCubemapUnit) { +void DeferredLightingEffect::setupKeyLightBatch(const RenderArgs* args, gpu::Batch& batch) { PerformanceTimer perfTimer("DLE->setupBatch()"); graphics::LightPointer keySunLight; auto lightStage = args->_scene->getStage(); @@ -107,108 +85,43 @@ void DeferredLightingEffect::setupKeyLightBatch(const RenderArgs* args, gpu::Bat } if (keySunLight) { - if (lightBufferUnit >= 0) { - batch.setUniformBuffer(lightBufferUnit, keySunLight->getLightSchemaBuffer()); - } + batch.setUniformBuffer(gr::Buffer::KeyLight, keySunLight->getLightSchemaBuffer()); } if (keyAmbiLight) { - if (ambientBufferUnit >= 0) { - batch.setUniformBuffer(ambientBufferUnit, keyAmbiLight->getAmbientSchemaBuffer()); - } + batch.setUniformBuffer(gr::Buffer::AmbientLight, keyAmbiLight->getAmbientSchemaBuffer()); - if (keyAmbiLight->getAmbientMap() && (skyboxCubemapUnit >= 0)) { - batch.setResourceTexture(skyboxCubemapUnit, keyAmbiLight->getAmbientMap()); + if (keyAmbiLight->getAmbientMap() ) { + batch.setResourceTexture(ru::Texture::Skybox, keyAmbiLight->getAmbientMap()); } } } -void DeferredLightingEffect::unsetKeyLightBatch(gpu::Batch& batch, int lightBufferUnit, int ambientBufferUnit, int skyboxCubemapUnit) { - if (lightBufferUnit >= 0) { - batch.setUniformBuffer(lightBufferUnit, nullptr); - } - if ((ambientBufferUnit >= 0)) { - batch.setUniformBuffer(ambientBufferUnit, nullptr); - } - - if ((skyboxCubemapUnit >= 0)) { - batch.setResourceTexture(skyboxCubemapUnit, nullptr); - } +void DeferredLightingEffect::unsetKeyLightBatch(gpu::Batch& batch) { + batch.setUniformBuffer(gr::Buffer::KeyLight, nullptr); + batch.setUniformBuffer(gr::Buffer::AmbientLight, nullptr); + batch.setResourceTexture(ru::Texture::Skybox, nullptr); } -void DeferredLightingEffect::setupLocalLightsBatch(gpu::Batch& batch, - int lightArrayBufferUnit, int clusterGridBufferUnit, int clusterContentBufferUnit, int frustumGridBufferUnit, - const LightClustersPointer& lightClusters) { +void DeferredLightingEffect::setupLocalLightsBatch(gpu::Batch& batch, const LightClustersPointer& lightClusters) { // Bind the global list of lights and the visible lights this frame - batch.setUniformBuffer(lightArrayBufferUnit, lightClusters->_lightStage->getLightArrayBuffer()); + batch.setUniformBuffer(gr::Buffer::Light, lightClusters->_lightStage->getLightArrayBuffer()); - batch.setUniformBuffer(frustumGridBufferUnit, lightClusters->_frustumGridBuffer); - batch.setUniformBuffer(clusterGridBufferUnit, lightClusters->_clusterGridBuffer); - batch.setUniformBuffer(clusterContentBufferUnit, lightClusters->_clusterContentBuffer); + batch.setUniformBuffer(ru::Buffer::LightClusterFrustumGrid, lightClusters->_frustumGridBuffer); + batch.setUniformBuffer(ru::Buffer::LightClusterGrid, lightClusters->_clusterGridBuffer); + batch.setUniformBuffer(ru::Buffer::LightClusterContent, lightClusters->_clusterContentBuffer); } -void DeferredLightingEffect::unsetLocalLightsBatch(gpu::Batch& batch, int lightArrayBufferUnit, int clusterGridBufferUnit, int clusterContentBufferUnit, int frustumGridBufferUnit) { - if (lightArrayBufferUnit >= 0) { - batch.setUniformBuffer(lightArrayBufferUnit, nullptr); - } - if (clusterGridBufferUnit >= 0) { - batch.setUniformBuffer(clusterGridBufferUnit, nullptr); - } - if (clusterContentBufferUnit >= 0) { - batch.setUniformBuffer(clusterContentBufferUnit, nullptr); - } - if (frustumGridBufferUnit >= 0) { - batch.setUniformBuffer(frustumGridBufferUnit, nullptr); - } +void DeferredLightingEffect::unsetLocalLightsBatch(gpu::Batch& batch) { + batch.setUniformBuffer(gr::Buffer::Light, nullptr); + batch.setUniformBuffer(ru::Buffer::LightClusterGrid, nullptr); + batch.setUniformBuffer(ru::Buffer::LightClusterContent, nullptr); + batch.setUniformBuffer(ru::Buffer::LightClusterFrustumGrid, nullptr); } static gpu::ShaderPointer makeLightProgram(int programId, LightLocationsPtr& locations) { gpu::ShaderPointer program = gpu::Shader::createProgram(programId); - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("colorMap"), DEFERRED_BUFFER_COLOR_UNIT)); - slotBindings.insert(gpu::Shader::Binding(std::string("normalMap"), DEFERRED_BUFFER_NORMAL_UNIT)); - slotBindings.insert(gpu::Shader::Binding(std::string("specularMap"), DEFERRED_BUFFER_EMISSIVE_UNIT)); - slotBindings.insert(gpu::Shader::Binding(std::string("depthMap"), DEFERRED_BUFFER_DEPTH_UNIT)); - slotBindings.insert(gpu::Shader::Binding(std::string("obscuranceMap"), DEFERRED_BUFFER_OBSCURANCE_UNIT)); - slotBindings.insert(gpu::Shader::Binding(std::string("shadowMaps"), SHADOW_MAP_UNIT)); - slotBindings.insert(gpu::Shader::Binding(std::string("skyboxMap"), SKYBOX_MAP_UNIT)); - - slotBindings.insert(gpu::Shader::Binding(std::string("linearZeyeMap"), DEFERRED_BUFFER_LINEAR_DEPTH_UNIT)); - slotBindings.insert(gpu::Shader::Binding(std::string("curvatureMap"), DEFERRED_BUFFER_CURVATURE_UNIT)); - slotBindings.insert(gpu::Shader::Binding(std::string("diffusedCurvatureMap"), DEFERRED_BUFFER_DIFFUSED_CURVATURE_UNIT)); - slotBindings.insert(gpu::Shader::Binding(std::string("scatteringLUT"), SCATTERING_LUT_UNIT)); - slotBindings.insert(gpu::Shader::Binding(std::string("scatteringSpecularBeckmann"), SCATTERING_SPECULAR_UNIT)); - - - slotBindings.insert(gpu::Shader::Binding(std::string("cameraCorrectionBuffer"), CAMERA_CORRECTION_BUFFER_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), DEFERRED_FRAME_TRANSFORM_BUFFER_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("lightingModelBuffer"), LIGHTING_MODEL_BUFFER_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("hazeBuffer"), HAZE_MODEL_BUFFER_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("subsurfaceScatteringParametersBuffer"), SCATTERING_PARAMETERS_BUFFER_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("keyLightBuffer"), KEY_LIGHT_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("lightBuffer"), LIGHT_ARRAY_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("lightAmbientBuffer"), LIGHT_AMBIENT_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("lightIndexBuffer"), LIGHT_INDEX_GPU_SLOT)); - - - slotBindings.insert(gpu::Shader::Binding(std::string("frustumGridBuffer"), LIGHT_CLUSTER_GRID_FRUSTUM_GRID_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("clusterGridBuffer"), LIGHT_CLUSTER_GRID_CLUSTER_GRID_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("clusterContentBuffer"), LIGHT_CLUSTER_GRID_CLUSTER_CONTENT_SLOT)); - - gpu::Shader::makeProgram(*program, slotBindings); - - locations->radius = program->getUniforms().findLocation("radius"); - - locations->texcoordFrameTransform = program->getUniforms().findLocation("texcoordFrameTransform"); - - locations->keyLightBufferUnit = program->getUniformBuffers().findLocation("keyLightBuffer"); - locations->lightBufferUnit = program->getUniformBuffers().findLocation("lightBuffer"); - locations->ambientBufferUnit = program->getUniformBuffers().findLocation("lightAmbientBuffer"); - locations->lightIndexBufferUnit = program->getUniformBuffers().findLocation("lightIndexBuffer"); - locations->deferredFrameTransformBuffer = program->getUniformBuffers().findLocation("deferredFrameTransformBuffer"); - locations->subsurfaceScatteringParametersBuffer = program->getUniformBuffers().findLocation("subsurfaceScatteringParametersBuffer"); - locations->shadowTransformBuffer = program->getUniformBuffers().findLocation("shadowTransformBuffer"); - + locations->initialize(program); return program; } @@ -223,9 +136,8 @@ static void loadLightProgram(int programId, bool lightVolume, gpu::PipelinePoint PrepareStencil::testShape(*state); state->setCullMode(gpu::State::CULL_BACK); - // state->setCullMode(gpu::State::CULL_FRONT); - // state->setDepthTest(true, false, gpu::GREATER_EQUAL); - + //state->setCullMode(gpu::State::CULL_FRONT); + //state->setDepthTest(true, false, gpu::GREATER_EQUAL); //state->setDepthClampEnable(true); // TODO: We should use DepthClamp and avoid changing geometry for inside /outside cases // additive blending @@ -448,7 +360,7 @@ void PrepareDeferred::run(const RenderContextPointer& renderContext, const Input vec4(vec3(0), 0), 1.0, 0, true); // For the rest of the rendering, bind the lighting model - batch.setUniformBuffer(LIGHTING_MODEL_BUFFER_SLOT, lightingModel->getParametersBuffer()); + batch.setUniformBuffer(ru::Buffer::LightModel, lightingModel->getParametersBuffer()); }); @@ -487,35 +399,35 @@ void RenderDeferredSetup::run(const render::RenderContextPointer& renderContext, // Bind the G-Buffer surfaces - batch.setResourceTexture(DEFERRED_BUFFER_COLOR_UNIT, deferredFramebuffer->getDeferredColorTexture()); - batch.setResourceTexture(DEFERRED_BUFFER_NORMAL_UNIT, deferredFramebuffer->getDeferredNormalTexture()); - batch.setResourceTexture(DEFERRED_BUFFER_EMISSIVE_UNIT, deferredFramebuffer->getDeferredSpecularTexture()); - batch.setResourceTexture(DEFERRED_BUFFER_DEPTH_UNIT, deferredFramebuffer->getPrimaryDepthTexture()); + batch.setResourceTexture(ru::Texture::DeferredColor, deferredFramebuffer->getDeferredColorTexture()); + batch.setResourceTexture(ru::Texture::DeferredNormal, deferredFramebuffer->getDeferredNormalTexture()); + batch.setResourceTexture(ru::Texture::DeferredSpecular, deferredFramebuffer->getDeferredSpecularTexture()); + batch.setResourceTexture(ru::Texture::DeferredDepth, deferredFramebuffer->getPrimaryDepthTexture()); // FIXME: Different render modes should have different tasks if (args->_renderMode == RenderArgs::DEFAULT_RENDER_MODE && deferredLightingEffect->isAmbientOcclusionEnabled() && ambientOcclusionFramebuffer) { - batch.setResourceTexture(DEFERRED_BUFFER_OBSCURANCE_UNIT, ambientOcclusionFramebuffer->getOcclusionTexture()); + batch.setResourceTexture(ru::Texture::DeferredObscurance, ambientOcclusionFramebuffer->getOcclusionTexture()); } else { // need to assign the white texture if ao is off - batch.setResourceTexture(DEFERRED_BUFFER_OBSCURANCE_UNIT, textureCache->getWhiteTexture()); + batch.setResourceTexture(ru::Texture::DeferredObscurance, textureCache->getWhiteTexture()); } // The Deferred Frame Transform buffer - batch.setUniformBuffer(DEFERRED_FRAME_TRANSFORM_BUFFER_SLOT, frameTransform->getFrameTransformBuffer()); + batch.setUniformBuffer(ru::Buffer::DeferredFrameTransform, frameTransform->getFrameTransformBuffer()); // THe lighting model - batch.setUniformBuffer(LIGHTING_MODEL_BUFFER_SLOT, lightingModel->getParametersBuffer()); + batch.setUniformBuffer(ru::Buffer::LightModel, lightingModel->getParametersBuffer()); // Subsurface scattering specific if (surfaceGeometryFramebuffer) { - batch.setResourceTexture(DEFERRED_BUFFER_LINEAR_DEPTH_UNIT, surfaceGeometryFramebuffer->getLinearDepthTexture()); - batch.setResourceTexture(DEFERRED_BUFFER_CURVATURE_UNIT, surfaceGeometryFramebuffer->getCurvatureTexture()); - batch.setResourceTexture(DEFERRED_BUFFER_DIFFUSED_CURVATURE_UNIT, surfaceGeometryFramebuffer->getLowCurvatureTexture()); + batch.setResourceTexture(ru::Texture::DeferredLinearZEye, surfaceGeometryFramebuffer->getLinearDepthTexture()); + batch.setResourceTexture(ru::Texture::DeferredCurvature, surfaceGeometryFramebuffer->getCurvatureTexture()); + batch.setResourceTexture(ru::Texture::DeferredDiffusedCurvature, surfaceGeometryFramebuffer->getLowCurvatureTexture()); } if (subsurfaceScatteringResource) { - batch.setUniformBuffer(SCATTERING_PARAMETERS_BUFFER_SLOT, subsurfaceScatteringResource->getParametersBuffer()); - batch.setResourceTexture(SCATTERING_LUT_UNIT, subsurfaceScatteringResource->getScatteringTable()); - batch.setResourceTexture(SCATTERING_SPECULAR_UNIT, subsurfaceScatteringResource->getScatteringSpecular()); + batch.setUniformBuffer(ru::Buffer::SsscParams, subsurfaceScatteringResource->getParametersBuffer()); + batch.setResourceTexture(ru::Texture::SsscLut, subsurfaceScatteringResource->getScatteringTable()); + batch.setResourceTexture(ru::Texture::SsscSpecularBeckmann, subsurfaceScatteringResource->getScatteringSpecular()); } // Global directional light and ambient pass @@ -528,7 +440,7 @@ void RenderDeferredSetup::run(const render::RenderContextPointer& renderContext, // Bind the shadow buffers if (globalShadow) { - batch.setResourceTexture(SHADOW_MAP_UNIT, globalShadow->map); + batch.setResourceTexture(ru::Texture::Shadow, globalShadow->map); } auto program = deferredLightingEffect->_directionalSkyboxLight; @@ -577,10 +489,8 @@ void RenderDeferredSetup::run(const render::RenderContextPointer& renderContext, } } - if (locations->shadowTransformBuffer >= 0) { - if (globalShadow) { - batch.setUniformBuffer(locations->shadowTransformBuffer, globalShadow->getBuffer()); - } + if (locations->shadowTransform && globalShadow) { + batch.setUniformBuffer(ru::Buffer::ShadowParams, globalShadow->getBuffer()); } batch.setPipeline(program); @@ -588,22 +498,22 @@ void RenderDeferredSetup::run(const render::RenderContextPointer& renderContext, // Adjust the texcoordTransform in the case we are rendeirng a sub region(mini mirror) auto textureFrameTransform = gpu::Framebuffer::evalSubregionTexcoordTransformCoefficients(deferredFramebuffer->getFrameSize(), args->_viewport); - batch._glUniform4fv(locations->texcoordFrameTransform, 1, reinterpret_cast< const float* >(&textureFrameTransform)); + batch._glUniform4fv(ru::Uniform::TexcoordTransform, 1, reinterpret_cast< const float* >(&textureFrameTransform)); // Setup the global lighting - deferredLightingEffect->setupKeyLightBatch(args, batch, KEY_LIGHT_SLOT, LIGHT_AMBIENT_SLOT, SKYBOX_MAP_UNIT); + deferredLightingEffect->setupKeyLightBatch(args, batch); // Haze if (haze) { - batch.setUniformBuffer(HAZE_MODEL_BUFFER_SLOT, haze->getHazeParametersBuffer()); + batch.setUniformBuffer(ru::Buffer::HazeParams, haze->getHazeParametersBuffer()); } batch.draw(gpu::TRIANGLE_STRIP, 4); - deferredLightingEffect->unsetKeyLightBatch(batch, KEY_LIGHT_SLOT, LIGHT_AMBIENT_SLOT, SKYBOX_MAP_UNIT); + deferredLightingEffect->unsetKeyLightBatch(batch); for (auto i = 0; i < SHADOW_CASCADE_MAX_COUNT; i++) { - batch.setResourceTexture(SHADOW_MAP_UNIT+i, nullptr); + batch.setResourceTexture(ru::Texture::Shadow +i, nullptr); } } } @@ -655,20 +565,18 @@ void RenderDeferredLocals::run(const render::RenderContextPointer& renderContext auto& lightIndices = lightClusters->_visibleLightIndices; if (!lightIndices.empty() && lightIndices[0] > 0) { - deferredLightingEffect->setupLocalLightsBatch(batch, - LIGHT_ARRAY_SLOT, LIGHT_CLUSTER_GRID_CLUSTER_GRID_SLOT, LIGHT_CLUSTER_GRID_CLUSTER_CONTENT_SLOT, LIGHT_CLUSTER_GRID_FRUSTUM_GRID_SLOT, - lightClusters); + deferredLightingEffect->setupLocalLightsBatch(batch, lightClusters); // Local light pipeline batch.setPipeline(deferredLightingEffect->_localLight); - batch._glUniform4fv(deferredLightingEffect->_localLightLocations->texcoordFrameTransform, 1, reinterpret_cast(&textureFrameTransform)); + batch._glUniform4fv(ru::Uniform::TexcoordTransform, 1, reinterpret_cast(&textureFrameTransform)); batch.draw(gpu::TRIANGLE_STRIP, 4); // Draw outline as well ? if (lightingModel->isShowLightContourEnabled()) { batch.setPipeline(deferredLightingEffect->_localLightOutline); - batch._glUniform4fv(deferredLightingEffect->_localLightOutlineLocations->texcoordFrameTransform, 1, reinterpret_cast(&textureFrameTransform)); + batch._glUniform4fv(ru::Uniform::TexcoordTransform, 1, reinterpret_cast(&textureFrameTransform)); batch.draw(gpu::TRIANGLE_STRIP, 4); } @@ -681,25 +589,25 @@ void RenderDeferredCleanup::run(const render::RenderContextPointer& renderContex auto& batch = (*args->_batch); { // Probably not necessary in the long run because the gpu layer would unbound this texture if used as render target - batch.setResourceTexture(DEFERRED_BUFFER_COLOR_UNIT, nullptr); - batch.setResourceTexture(DEFERRED_BUFFER_NORMAL_UNIT, nullptr); - batch.setResourceTexture(DEFERRED_BUFFER_EMISSIVE_UNIT, nullptr); - batch.setResourceTexture(DEFERRED_BUFFER_DEPTH_UNIT, nullptr); - batch.setResourceTexture(DEFERRED_BUFFER_OBSCURANCE_UNIT, nullptr); + batch.setResourceTexture(ru::Texture::DeferredColor, nullptr); + batch.setResourceTexture(ru::Texture::DeferredNormal, nullptr); + batch.setResourceTexture(ru::Texture::DeferredSpecular, nullptr); + batch.setResourceTexture(ru::Texture::DeferredDepth, nullptr); + batch.setResourceTexture(ru::Texture::DeferredObscurance, nullptr); - batch.setResourceTexture(DEFERRED_BUFFER_LINEAR_DEPTH_UNIT, nullptr); - batch.setResourceTexture(DEFERRED_BUFFER_CURVATURE_UNIT, nullptr); - batch.setResourceTexture(DEFERRED_BUFFER_DIFFUSED_CURVATURE_UNIT, nullptr); - batch.setResourceTexture(SCATTERING_LUT_UNIT, nullptr); - batch.setResourceTexture(SCATTERING_SPECULAR_UNIT, nullptr); + batch.setResourceTexture(ru::Texture::DeferredLinearZEye, nullptr); + batch.setResourceTexture(ru::Texture::DeferredCurvature, nullptr); + batch.setResourceTexture(ru::Texture::DeferredDiffusedCurvature, nullptr); + batch.setResourceTexture(ru::Texture::SsscLut, nullptr); + batch.setResourceTexture(ru::Texture::SsscSpecularBeckmann, nullptr); - batch.setUniformBuffer(SCATTERING_PARAMETERS_BUFFER_SLOT, nullptr); + batch.setUniformBuffer(ru::Buffer::SsscParams, nullptr); // batch.setUniformBuffer(LIGHTING_MODEL_BUFFER_SLOT, nullptr); - batch.setUniformBuffer(DEFERRED_FRAME_TRANSFORM_BUFFER_SLOT, nullptr); + batch.setUniformBuffer(ru::Buffer::DeferredFrameTransform, nullptr); - batch.setUniformBuffer(LIGHT_CLUSTER_GRID_FRUSTUM_GRID_SLOT, nullptr); - batch.setUniformBuffer(LIGHT_CLUSTER_GRID_CLUSTER_GRID_SLOT, nullptr); - batch.setUniformBuffer(LIGHT_CLUSTER_GRID_CLUSTER_CONTENT_SLOT, nullptr); + batch.setUniformBuffer(ru::Buffer::LightClusterFrustumGrid, nullptr); + batch.setUniformBuffer(ru::Buffer::LightClusterGrid, nullptr); + batch.setUniformBuffer(ru::Buffer::LightClusterContent, nullptr); } } diff --git a/libraries/render-utils/src/DeferredLightingEffect.h b/libraries/render-utils/src/DeferredLightingEffect.h index 5da2eb22f7..70bfb65f38 100644 --- a/libraries/render-utils/src/DeferredLightingEffect.h +++ b/libraries/render-utils/src/DeferredLightingEffect.h @@ -48,11 +48,11 @@ class DeferredLightingEffect : public Dependency { public: void init(); - void setupKeyLightBatch(const RenderArgs* args, gpu::Batch& batch, int lightBufferUnit, int ambientBufferUnit, int skyboxCubemapUnit); - void unsetKeyLightBatch(gpu::Batch& batch, int lightBufferUnit, int ambientBufferUnit, int skyboxCubemapUnit); + static void setupKeyLightBatch(const RenderArgs* args, gpu::Batch& batch); + static void unsetKeyLightBatch(gpu::Batch& batch); - void setupLocalLightsBatch(gpu::Batch& batch, int lightArrayBufferUnit, int clusterGridBufferUnit, int clusterContentBufferUnit, int frustumGridBufferUnit, const LightClustersPointer& lightClusters); - void unsetLocalLightsBatch(gpu::Batch& batch, int lightArrayBufferUnit, int clusterGridBufferUnit, int clusterContentBufferUnit, int frustumGridBufferUnit); + static void setupLocalLightsBatch(gpu::Batch& batch, const LightClustersPointer& lightClusters); + static void unsetLocalLightsBatch(gpu::Batch& batch); void setShadowMapEnabled(bool enable) { _shadowMapEnabled = enable; }; void setAmbientOcclusionEnabled(bool enable) { _ambientOcclusionEnabled = enable; } diff --git a/libraries/render-utils/src/DeferredTransform.slh b/libraries/render-utils/src/DeferredTransform.slh index 2f015b95fe..6dd92c651b 100644 --- a/libraries/render-utils/src/DeferredTransform.slh +++ b/libraries/render-utils/src/DeferredTransform.slh @@ -11,6 +11,9 @@ <@if not DEFERRED_TRANSFORM_SLH@> <@def DEFERRED_TRANSFORM_SLH@> +<@include gpu/ShaderConstants.h@> +<@include render-utils/ShaderConstants.h@> + <@func declareDeferredFrameTransform()@> struct CameraCorrection { @@ -21,7 +24,7 @@ struct CameraCorrection { mat4 _prevViewInverse; }; -uniform cameraCorrectionBuffer { +layout(binding=GPU_BUFFER_CAMERA_CORRECTION) uniform cameraCorrectionBuffer { CameraCorrection cameraCorrection; }; @@ -39,7 +42,7 @@ struct DeferredFrameTransform { mat4 _invProjectionUnJittered[2]; }; -uniform deferredFrameTransformBuffer { +layout(binding=RENDER_UTILS_BUFFER_DEFERRED_FRAME_TRANSFORM) uniform deferredFrameTransformBuffer { DeferredFrameTransform frameTransform; }; diff --git a/libraries/render-utils/src/DrawHaze.cpp b/libraries/render-utils/src/DrawHaze.cpp index 587f997887..538a916a06 100644 --- a/libraries/render-utils/src/DrawHaze.cpp +++ b/libraries/render-utils/src/DrawHaze.cpp @@ -14,11 +14,24 @@ #include #include +#include +#include "render-utils/ShaderConstants.h" + #include "StencilMaskPass.h" #include "FramebufferCache.h" #include "HazeStage.h" #include "LightStage.h" +namespace ru { + using render_utils::slot::texture::Texture; + using render_utils::slot::buffer::Buffer; +} + +namespace gr { + using graphics::slot::texture::Texture; + using graphics::slot::buffer::Buffer; +} + void HazeConfig::setHazeColor(const glm::vec3 value) { hazeColor = value; } @@ -105,12 +118,6 @@ void MakeHaze::run(const render::RenderContextPointer& renderContext, graphics:: haze = _haze; } -// Buffer slots -const int HazeEffect_ParamsSlot = 0; -const int HazeEffect_TransformBufferSlot = 1; -// Texture slots -const int HazeEffect_LinearDepthMapSlot = 0; - void DrawHaze::configure(const Config& config) { } @@ -139,19 +146,7 @@ void DrawHaze::run(const render::RenderContextPointer& renderContext, const Inpu // Mask out haze on the tablet PrepareStencil::testMask(*state); - _hazePipeline = gpu::PipelinePointer(gpu::Pipeline::create(program, state)); - gpu::doInBatch("DrawHaze::build", args->_context, [program](gpu::Batch& batch) { - batch.runLambda([program]() { - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("hazeBuffer"), HazeEffect_ParamsSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), HazeEffect_TransformBufferSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("lightingModelBuffer"), render::ShapePipeline::Slot::LIGHTING_MODEL)); - slotBindings.insert(gpu::Shader::Binding(std::string("linearDepthMap"), HazeEffect_LinearDepthMapSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("keyLightBuffer"), render::ShapePipeline::Slot::KEY_LIGHT)); - gpu::Shader::makeProgram(*program, slotBindings); - }); - }); } auto outputFramebufferSize = glm::ivec2(outputBuffer->getSize()); @@ -171,26 +166,25 @@ void DrawHaze::run(const render::RenderContextPointer& renderContext, const Inpu if (hazeStage && hazeStage->_currentFrame._hazes.size() > 0) { graphics::HazePointer hazePointer = hazeStage->getHaze(hazeStage->_currentFrame._hazes.front()); if (hazePointer) { - batch.setUniformBuffer(HazeEffect_ParamsSlot, hazePointer->getHazeParametersBuffer()); + batch.setUniformBuffer(ru::Buffer::HazeParams, hazePointer->getHazeParametersBuffer()); } else { // Something is wrong, so just quit Haze return; } } - batch.setUniformBuffer(HazeEffect_TransformBufferSlot, transformBuffer->getFrameTransformBuffer()); - batch.setUniformBuffer(render::ShapePipeline::Slot::LIGHTING_MODEL, lightingModel->getParametersBuffer()); + batch.setUniformBuffer(ru::Buffer::DeferredFrameTransform, transformBuffer->getFrameTransformBuffer()); + batch.setUniformBuffer(ru::Buffer::LightModel, lightingModel->getParametersBuffer()); + batch.setResourceTexture(ru::Texture::HazeLinearDepth, depthBuffer); + auto lightStage = args->_scene->getStage(); + if (lightStage) { + graphics::LightPointer keyLight; + keyLight = lightStage->getCurrentKeyLight(); + if (keyLight) { + batch.setUniformBuffer(gr::Buffer::KeyLight, keyLight->getLightSchemaBuffer()); + } + } - auto lightStage = args->_scene->getStage(); - if (lightStage) { - graphics::LightPointer keyLight; - keyLight = lightStage->getCurrentKeyLight(); - if (keyLight) { - batch.setUniformBuffer(render::ShapePipeline::Slot::KEY_LIGHT, keyLight->getLightSchemaBuffer()); - } - } - - batch.setResourceTexture(HazeEffect_LinearDepthMapSlot, depthBuffer); batch.draw(gpu::TRIANGLE_STRIP, 4); }); diff --git a/libraries/render-utils/src/Fade.slh b/libraries/render-utils/src/Fade.slh index a4e8fdf1f4..47347ba135 100644 --- a/libraries/render-utils/src/Fade.slh +++ b/libraries/render-utils/src/Fade.slh @@ -9,18 +9,22 @@ <@if not FADE_SLH@> <@def FADE_SLH@> -<@func declareFadeFragmentCommon()@> +<@include render-utils/ShaderConstants.h@> +<@func declareFadeFragmentCommon()@> #define CATEGORY_COUNT 5 <@include Fade_shared.slh@> <@include FadeObjectParams.shared.slh@> -layout(std140) uniform fadeParametersBuffer { +// See ShapePipeline::Slot::BUFFER in ShapePipeline.h +layout(std140, binding=RENDER_UTILS_BUFFER_FADE_PARAMS) uniform fadeParametersBuffer { FadeParameters fadeParameters[CATEGORY_COUNT]; }; -uniform sampler2D fadeMaskMap; + +// See ShapePipeline::Slot::MAP in ShapePipeline.h +layout(binding=RENDER_UTILS_TEXTURE_FADE_MASK) uniform sampler2D fadeMaskMap; vec3 getNoiseInverseSize(int category) { return fadeParameters[category]._noiseInvSizeAndLevel.xyz; @@ -113,7 +117,7 @@ void applyFade(FadeObjectParams params, vec3 position, out vec3 emissive) { <@func declareFadeFragmentUniform()@> -layout(std140) uniform fadeObjectParametersBuffer { +layout(std140, binding=RENDER_UTILS_BUFFER_FADE_OBJECT_PARAMS) uniform fadeObjectParametersBuffer { FadeObjectParams fadeObjectParams; }; @@ -125,9 +129,9 @@ layout(std140) uniform fadeObjectParametersBuffer { <@func declareFadeFragmentVertexInput()@> -in vec4 _fadeData1; -in vec4 _fadeData2; -in vec4 _fadeData3; +layout(location=RENDER_UTILS_ATTR_FADE1) in vec4 _fadeData1; +layout(location=RENDER_UTILS_ATTR_FADE2) in vec4 _fadeData2; +layout(location=RENDER_UTILS_ATTR_FADE3) in vec4 _fadeData3; <@endfunc@> @@ -150,9 +154,9 @@ in vec4 _fadeData3; <@endfunc@> <@func declareFadeVertexInstanced()@> -out vec4 _fadeData1; -out vec4 _fadeData2; -out vec4 _fadeData3; +layout(location=RENDER_UTILS_ATTR_FADE1) out vec4 _fadeData1; +layout(location=RENDER_UTILS_ATTR_FADE2) out vec4 _fadeData2; +layout(location=RENDER_UTILS_ATTR_FADE3) out vec4 _fadeData3; <@endfunc@> <@func passThroughFadeObjectParams()@> diff --git a/libraries/render-utils/src/FadeEffect.cpp b/libraries/render-utils/src/FadeEffect.cpp index 12531d4c9d..402865da4c 100644 --- a/libraries/render-utils/src/FadeEffect.cpp +++ b/libraries/render-utils/src/FadeEffect.cpp @@ -14,7 +14,7 @@ #include "render/TransitionStage.h" #include "FadeObjectParams.shared.slh" - +#include "render-utils/ShaderConstants.h" #include FadeEffect::FadeEffect() { @@ -33,16 +33,16 @@ void FadeEffect::build(render::Task::TaskConcept& task, const task::Varying& edi render::ShapePipeline::BatchSetter FadeEffect::getBatchSetter() const { return [this](const render::ShapePipeline& shapePipeline, gpu::Batch& batch, render::Args*) { - batch.setResourceTexture(render::ShapePipeline::Slot::FADE_MASK, _maskMap); - batch.setUniformBuffer(render::ShapePipeline::Slot::FADE_PARAMETERS, _configurations); + batch.setResourceTexture(render_utils::slot::texture::FadeMask, _maskMap); + batch.setUniformBuffer(render_utils::slot::buffer::FadeParameters, _configurations); }; } render::ShapePipeline::ItemSetter FadeEffect::getItemUniformSetter() const { return [](const render::ShapePipeline& shapePipeline, render::Args* args, const render::Item& item) { if (!render::TransitionStage::isIndexInvalid(item.getTransitionId())) { - auto scene = args->_scene; - auto batch = args->_batch; + const auto& scene = args->_scene; + const auto& batch = args->_batch; auto transitionStage = scene->getStage(render::TransitionStage::getName()); auto& transitionState = transitionStage->getTransition(item.getTransitionId()); @@ -67,7 +67,7 @@ render::ShapePipeline::ItemSetter FadeEffect::getItemUniformSetter() const { params.noiseOffset = glm::vec4(transitionState.noiseOffset, 0.0f); params.baseOffset = glm::vec4(transitionState.baseOffset, 0.0f); } - batch->setUniformBuffer(render::ShapePipeline::Slot::FADE_OBJECT_PARAMETERS, transitionState.paramsBuffer); + batch->setUniformBuffer(render_utils::slot::buffer::FadeObjectParameters, transitionState.paramsBuffer); } }; } diff --git a/libraries/render-utils/src/GeometryCache.cpp b/libraries/render-utils/src/GeometryCache.cpp index 60ac75619e..cbc9b40129 100644 --- a/libraries/render-utils/src/GeometryCache.cpp +++ b/libraries/render-utils/src/GeometryCache.cpp @@ -27,7 +27,9 @@ #include #include #include +#include +#include "render-utils/ShaderConstants.h" #include "TextureCache.h" #include "RenderUtilsLogging.h" #include "StencilMaskPass.h" @@ -37,6 +39,16 @@ #include "DeferredLightingEffect.h" +namespace gr { + using graphics::slot::texture::Texture; + using graphics::slot::buffer::Buffer; +} + +namespace ru { + using render_utils::slot::texture::Texture; + using render_utils::slot::buffer::Buffer; +} + #if defined(USE_GLES) static bool DISABLE_DEFERRED = true; #else @@ -804,12 +816,9 @@ render::ShapePipelinePointer GeometryCache::getShapePipeline(bool textured, bool return std::make_shared(getSimplePipeline(textured, transparent, culled, unlit, depthBias, false, true), nullptr, [](const render::ShapePipeline& pipeline, gpu::Batch& batch, render::Args* args) { - batch.setResourceTexture(render::ShapePipeline::Slot::MAP::ALBEDO, DependencyManager::get()->getWhiteTexture()); - DependencyManager::get()->setupKeyLightBatch(args, batch, - pipeline.pipeline->getProgram()->getUniformBuffers().findLocation("keyLightBuffer"), - pipeline.pipeline->getProgram()->getUniformBuffers().findLocation("lightAmbientBuffer"), - pipeline.pipeline->getProgram()->getUniformBuffers().findLocation("skyboxMap")); - } + batch.setResourceTexture(gr::Texture::MaterialAlbedo, DependencyManager::get()->getWhiteTexture()); + DependencyManager::get()->setupKeyLightBatch(args, batch); + } ); } @@ -820,7 +829,7 @@ render::ShapePipelinePointer GeometryCache::getFadingShapePipeline(bool textured auto fadeItemSetter = fadeEffect->getItemStoredSetter(); return std::make_shared(getSimplePipeline(textured, transparent, culled, unlit, depthBias, true), nullptr, [fadeBatchSetter, fadeItemSetter](const render::ShapePipeline& shapePipeline, gpu::Batch& batch, render::Args* args) { - batch.setResourceTexture(render::ShapePipeline::Slot::MAP::ALBEDO, DependencyManager::get()->getWhiteTexture()); + batch.setResourceTexture(gr::Texture::MaterialAlbedo, DependencyManager::get()->getWhiteTexture()); fadeBatchSetter(shapePipeline, batch, args); }, fadeItemSetter @@ -2027,7 +2036,6 @@ void GeometryCache::renderGlowLine(gpu::Batch& batch, const glm::vec3& p1, const } // Compile the shaders - static const uint32_t LINE_DATA_SLOT = 1; static std::once_flag once; std::call_once(once, [&] { auto state = std::make_shared(); @@ -2039,10 +2047,6 @@ void GeometryCache::renderGlowLine(gpu::Batch& batch, const glm::vec3& p1, const gpu::State::FACTOR_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::ONE); PrepareStencil::testMask(*state); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("lineData"), LINE_DATA_SLOT)); - gpu::Shader::makeProgram(*program, slotBindings); _glowLinePipeline = gpu::Pipeline::create(program, state); }); @@ -2079,7 +2083,7 @@ void GeometryCache::renderGlowLine(gpu::Batch& batch, const glm::vec3& p1, const } // The shader requires no vertices, only uniforms. - batch.setUniformBuffer(LINE_DATA_SLOT, details.uniformBuffer); + batch.setUniformBuffer(0, details.uniformBuffer); batch.draw(gpu::TRIANGLE_STRIP, NUM_VERTICES, 0); } @@ -2104,11 +2108,6 @@ void GeometryCache::useSimpleDrawPipeline(gpu::Batch& batch, bool noBlend) { auto programNoBlend = gpu::Shader::createProgram(shader::render_utils::program::standardDrawTextureNoBlend); _standardDrawPipelineNoBlend = gpu::Pipeline::create(programNoBlend, stateNoBlend); - - batch.runLambda([program, programNoBlend] { - gpu::Shader::makeProgram((*program)); - gpu::Shader::makeProgram((*programNoBlend)); - }); }); if (noBlend) { @@ -2121,9 +2120,7 @@ void GeometryCache::useSimpleDrawPipeline(gpu::Batch& batch, bool noBlend) { void GeometryCache::useGridPipeline(gpu::Batch& batch, GridBuffer gridBuffer, bool isLayered) { if (!_gridPipeline) { auto program = gpu::Shader::createProgram(shader::render_utils::program::grid); - gpu::Shader::makeProgram((*program)); - _gridSlot = program->getUniformBuffers().findLocation("gridBuffer"); - + _gridSlot = 0; auto stateLayered = std::make_shared(); stateLayered->setBlendFunction(true, gpu::State::SRC_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::INV_SRC_ALPHA); PrepareStencil::testMask(*stateLayered); @@ -2205,9 +2202,6 @@ inline bool operator==(const SimpleProgramKey& a, const SimpleProgramKey& b) { static void buildWebShader(int programId, bool blendEnable, gpu::ShaderPointer& shaderPointerOut, gpu::PipelinePointer& pipelinePointerOut) { shaderPointerOut = gpu::Shader::createProgram(programId); - - gpu::Shader::BindingSet slotBindings; - gpu::Shader::makeProgram(*shaderPointerOut, slotBindings); auto state = std::make_shared(); state->setCullMode(gpu::State::CULL_NONE); state->setDepthTest(true, true, gpu::LESS_EQUAL); @@ -2239,7 +2233,7 @@ void GeometryCache::bindSimpleProgram(gpu::Batch& batch, bool textured, bool tra // If not textured, set a default albedo map if (!textured) { - batch.setResourceTexture(render::ShapePipeline::Slot::MAP::ALBEDO, + batch.setResourceTexture(gr::Texture::MaterialAlbedo, DependencyManager::get()->getWhiteTexture()); } } @@ -2262,20 +2256,9 @@ gpu::PipelinePointer GeometryCache::getSimplePipeline(bool textured, bool transp // Use the forward pipeline for both here, otherwise transparents will be unlit auto PSTransparent = DISABLE_DEFERRED ? forward_simple_textured_transparent : forward_simple_textured_transparent; auto PSUnlit = DISABLE_DEFERRED ? forward_simple_textured_unlit : simple_textured_unlit; - _simpleShader = gpu::Shader::createProgram(PS); _transparentShader = gpu::Shader::createProgram(PSTransparent); _unlitShader = gpu::Shader::createProgram(PSUnlit); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("originalTexture"), render::ShapePipeline::Slot::MAP::ALBEDO)); - slotBindings.insert(gpu::Shader::Binding(std::string("lightingModelBuffer"), render::ShapePipeline::Slot::LIGHTING_MODEL)); - slotBindings.insert(gpu::Shader::Binding(std::string("keyLightBuffer"), render::ShapePipeline::Slot::KEY_LIGHT)); - slotBindings.insert(gpu::Shader::Binding(std::string("lightAmbientBuffer"), render::ShapePipeline::Slot::LIGHT_AMBIENT_BUFFER)); - slotBindings.insert(gpu::Shader::Binding(std::string("skyboxMap"), render::ShapePipeline::Slot::MAP::LIGHT_AMBIENT_MAP)); - gpu::Shader::makeProgram(*_simpleShader, slotBindings); - gpu::Shader::makeProgram(*_transparentShader, slotBindings); - gpu::Shader::makeProgram(*_unlitShader, slotBindings); }); } else { static std::once_flag once; @@ -2283,16 +2266,6 @@ gpu::PipelinePointer GeometryCache::getSimplePipeline(bool textured, bool transp using namespace shader::render_utils::program; _simpleFadeShader = gpu::Shader::createProgram(DISABLE_DEFERRED ? forward_simple_textured : simple_textured_fade); _unlitFadeShader = gpu::Shader::createProgram(DISABLE_DEFERRED ? forward_simple_textured_unlit : simple_textured_unlit_fade); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("originalTexture"), render::ShapePipeline::Slot::MAP::ALBEDO)); - slotBindings.insert(gpu::Shader::Binding(std::string("lightingModelBuffer"), render::ShapePipeline::Slot::LIGHTING_MODEL)); - slotBindings.insert(gpu::Shader::Binding(std::string("keyLightBuffer"), render::ShapePipeline::Slot::KEY_LIGHT)); - slotBindings.insert(gpu::Shader::Binding(std::string("lightAmbientBuffer"), render::ShapePipeline::Slot::LIGHT_AMBIENT_BUFFER)); - slotBindings.insert(gpu::Shader::Binding(std::string("skyboxMap"), render::ShapePipeline::Slot::MAP::LIGHT_AMBIENT_MAP)); - slotBindings.insert(gpu::Shader::Binding(std::string("fadeMaskMap"), render::ShapePipeline::Slot::MAP::FADE_MASK)); - gpu::Shader::makeProgram(*_simpleFadeShader, slotBindings); - gpu::Shader::makeProgram(*_unlitFadeShader, slotBindings); }); } diff --git a/libraries/render-utils/src/Haze.slf b/libraries/render-utils/src/Haze.slf index 93b66d99ed..ce5141d3c6 100644 --- a/libraries/render-utils/src/Haze.slf +++ b/libraries/render-utils/src/Haze.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// Haze.frag +// // Created by Nissim Hadar on 9/5/2107. // Copyright 2016 High Fidelity, Inc. // @@ -22,7 +24,7 @@ <@include Haze.slh@> -uniform sampler2D linearDepthMap; +layout(binding=RENDER_UTILS_TEXTURE_HAZE_LINEAR_DEPTH) uniform sampler2D linearDepthMap; vec4 unpackPositionFromZeye(vec2 texcoord) { float Zeye = -texture(linearDepthMap, texcoord).x; @@ -37,8 +39,8 @@ vec4 unpackPositionFromZeye(vec2 texcoord) { return vec4(evalEyePositionFromZeye(side, Zeye, texcoord), 1.0); } -in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 outFragColor; void main(void) { if ((isHazeEnabled() == 0.0) || (hazeParams.hazeMode & HAZE_MODE_IS_ACTIVE) != HAZE_MODE_IS_ACTIVE) { diff --git a/libraries/render-utils/src/Haze.slh b/libraries/render-utils/src/Haze.slh index 7854ad08ca..b7bcfcefcd 100644 --- a/libraries/render-utils/src/Haze.slh +++ b/libraries/render-utils/src/Haze.slh @@ -10,6 +10,8 @@ <@if not HAZE_SLH@> <@def HAZE_SLH@> +<@include render-utils/ShaderConstants.h@> + const int HAZE_MODE_IS_ACTIVE = 1 << 0; const int HAZE_MODE_IS_ALTITUDE_BASED = 1 << 1; const int HAZE_MODE_IS_KEYLIGHT_ATTENUATED = 1 << 2; @@ -36,7 +38,8 @@ struct HazeParams { float hazeKeyLightAltitudeFactor; }; -layout(std140) uniform hazeBuffer { +// See ShapePipeline::Slot::BUFFER in ShapePipeline.h +layout(std140, binding=RENDER_UTILS_BUFFER_HAZE_PARAMS) uniform hazeBuffer { HazeParams hazeParams; }; diff --git a/libraries/render-utils/src/Highlight.slf b/libraries/render-utils/src/Highlight.slf index bf65f92613..676df52235 100644 --- a/libraries/render-utils/src/Highlight.slf +++ b/libraries/render-utils/src/Highlight.slf @@ -1,4 +1,4 @@ -// Highlight.slf +// Highlight.frag // Add highlight effect based on two zbuffers : one containing the total scene z and another // with the z of only the objects to be outlined. // This is the version without the fill effect inside the silhouette. diff --git a/libraries/render-utils/src/Highlight.slh b/libraries/render-utils/src/Highlight.slh index f4d4ad0e04..56a999f508 100644 --- a/libraries/render-utils/src/Highlight.slh +++ b/libraries/render-utils/src/Highlight.slh @@ -15,12 +15,12 @@ <@include Highlight_shared.slh@> -uniform highlightParamsBuffer { +layout(binding=RENDER_UTILS_BUFFER_HIGHLIGHT_PARAMS) uniform highlightParamsBuffer { HighlightParameters params; }; -uniform sampler2D sceneDepthMap; -uniform sampler2D highlightedDepthMap; +layout(binding=RENDER_UTILS_TEXTURE_HIGHLIGHT_SCENE_DEPTH) uniform sampler2D sceneDepthMap; +layout(binding=RENDER_UTILS_TEXTURE_HIGHLIGHT_DEPTH) uniform sampler2D highlightedDepthMap; in vec2 varTexCoord0; out vec4 outFragColor; diff --git a/libraries/render-utils/src/HighlightEffect.cpp b/libraries/render-utils/src/HighlightEffect.cpp index a07d24c106..7e2e55c768 100644 --- a/libraries/render-utils/src/HighlightEffect.cpp +++ b/libraries/render-utils/src/HighlightEffect.cpp @@ -12,6 +12,7 @@ #include +#include #include #include @@ -21,10 +22,19 @@ #include "GeometryCache.h" #include "CubeProjectedPolygon.h" - - +#include "render-utils/ShaderConstants.h" using namespace render; +namespace ru { + using render_utils::slot::texture::Texture; + using render_utils::slot::buffer::Buffer; + using render_utils::slot::uniform::Uniform; +} + +namespace gr { + using graphics::slot::texture::Texture; + using graphics::slot::buffer::Buffer; +} #define OUTLINE_STENCIL_MASK 1 @@ -112,7 +122,7 @@ void DrawHighlightMask::run(const render::RenderContextPointer& renderContext, c auto& inShapes = inputs.get0(); const int BOUNDS_SLOT = 0; - const int PARAMETERS_SLOT = 1; + const int PARAMETERS_SLOT = 0; if (!_stencilMaskPipeline || !_stencilMaskFillPipeline) { gpu::StatePointer state = gpu::StatePointer(new gpu::State()); @@ -128,12 +138,6 @@ void DrawHighlightMask::run(const render::RenderContextPointer& renderContext, c fillState->setCullMode(gpu::State::CULL_FRONT); gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::highlight_aabox); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("ssbo0Buffer"), BOUNDS_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("parametersBuffer"), PARAMETERS_SLOT)); - gpu::Shader::makeProgram(*program, slotBindings); - _stencilMaskPipeline = gpu::Pipeline::create(program, state); _stencilMaskFillPipeline = gpu::Pipeline::create(program, fillState); } @@ -298,10 +302,10 @@ void DrawHighlight::run(const render::RenderContextPointer& renderContext, const batch.setModelTransform(gpu::Framebuffer::evalSubregionTexcoordTransform(framebufferSize, args->_viewport)); batch.setPipeline(pipeline); - batch.setUniformBuffer(HIGHLIGHT_PARAMS_SLOT, _configuration); - batch.setUniformBuffer(FRAME_TRANSFORM_SLOT, frameTransform->getFrameTransformBuffer()); - batch.setResourceTexture(SCENE_DEPTH_MAP_SLOT, sceneDepthBuffer->getPrimaryDepthTexture()); - batch.setResourceTexture(HIGHLIGHTED_DEPTH_MAP_SLOT, highlightedDepthTexture); + batch.setUniformBuffer(ru::Buffer::HighlightParams, _configuration); + batch.setUniformBuffer(ru::Buffer::DeferredFrameTransform, frameTransform->getFrameTransformBuffer()); + batch.setResourceTexture(ru::Texture::HighlightSceneDepth, sceneDepthBuffer->getPrimaryDepthTexture()); + batch.setResourceTexture(ru::Texture::HighlightDepth, highlightedDepthTexture); batch.draw(gpu::TRIANGLE_STRIP, 4); // Reset the framebuffer for overlay drawing @@ -319,19 +323,10 @@ const gpu::PipelinePointer& DrawHighlight::getPipeline(const render::HighlightSt state->setBlendFunction(true, gpu::State::SRC_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::INV_SRC_ALPHA); state->setStencilTest(true, 0, gpu::State::StencilTest(OUTLINE_STENCIL_MASK, 0xFF, gpu::EQUAL)); - gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::highlight); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding("highlightParamsBuffer", HIGHLIGHT_PARAMS_SLOT)); - slotBindings.insert(gpu::Shader::Binding("deferredFrameTransformBuffer", FRAME_TRANSFORM_SLOT)); - slotBindings.insert(gpu::Shader::Binding("sceneDepthMap", SCENE_DEPTH_MAP_SLOT)); - slotBindings.insert(gpu::Shader::Binding("highlightedDepthMap", HIGHLIGHTED_DEPTH_MAP_SLOT)); - gpu::Shader::makeProgram(*program, slotBindings); - + auto program = gpu::Shader::createProgram(shader::render_utils::program::highlight); _pipeline = gpu::Pipeline::create(program, state); program = gpu::Shader::createProgram(shader::render_utils::program::highlight_filled); - gpu::Shader::makeProgram(*program, slotBindings); _pipelineFilled = gpu::Pipeline::create(program, state); } return style.isFilled() ? _pipelineFilled : _pipeline; @@ -395,9 +390,9 @@ void DebugHighlight::run(const render::RenderContextPointer& renderContext, cons } void DebugHighlight::initializePipelines() { - static const std::string FRAGMENT_SHADER{ gpu::Shader::getFragmentShaderSource(shader::render_utils::fragment::debug_deferred_buffer).getCode() }; + static const auto FRAGMENT_SHADER_SOURCE = gpu::Shader::createPixel(shader::render_utils::fragment::debug_deferred_buffer)->getSource(); static const std::string SOURCE_PLACEHOLDER{ "//SOURCE_PLACEHOLDER" }; - static const auto SOURCE_PLACEHOLDER_INDEX = FRAGMENT_SHADER.find(SOURCE_PLACEHOLDER); + static const auto SOURCE_PLACEHOLDER_INDEX = FRAGMENT_SHADER_SOURCE.getCode().find(SOURCE_PLACEHOLDER); Q_ASSERT_X(SOURCE_PLACEHOLDER_INDEX != std::string::npos, Q_FUNC_INFO, "Could not find source placeholder"); @@ -417,16 +412,11 @@ void DebugHighlight::initializePipelines() { } )SHADER" }; - auto fragmentShader = FRAGMENT_SHADER; + auto fragmentShader = FRAGMENT_SHADER_SOURCE.getCode(); fragmentShader.replace(SOURCE_PLACEHOLDER_INDEX, SOURCE_PLACEHOLDER.size(), DEPTH_SHADER); - const auto ps = gpu::Shader::createPixel(fragmentShader); + const auto ps = gpu::Shader::createPixel({ fragmentShader, FRAGMENT_SHADER_SOURCE.getReflection() }); const auto program = gpu::Shader::createProgram(vs, ps); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding("depthMap", 0)); - gpu::Shader::makeProgram(*program, slotBindings); - _depthPipeline = gpu::Pipeline::create(program, state); } } diff --git a/libraries/render-utils/src/HighlightEffect.h b/libraries/render-utils/src/HighlightEffect.h index eee1c29cb7..64a97a549e 100644 --- a/libraries/render-utils/src/HighlightEffect.h +++ b/libraries/render-utils/src/HighlightEffect.h @@ -148,14 +148,6 @@ private: #include "Highlight_shared.slh" - enum { - SCENE_DEPTH_MAP_SLOT = 0, - HIGHLIGHTED_DEPTH_MAP_SLOT, - - HIGHLIGHT_PARAMS_SLOT = 0, - FRAME_TRANSFORM_SLOT, - }; - using HighlightConfigurationBuffer = gpu::StructBuffer; static const gpu::PipelinePointer& getPipeline(const render::HighlightStyle& style); diff --git a/libraries/render-utils/src/Highlight_aabox.slv b/libraries/render-utils/src/Highlight_aabox.slv index 2a87e00f94..5130d5e7ff 100644 --- a/libraries/render-utils/src/Highlight_aabox.slv +++ b/libraries/render-utils/src/Highlight_aabox.slv @@ -12,6 +12,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +<@include gpu/ShaderConstants.h@> <@include gpu/Transform.slh@> <$declareStandardTransform()$> @@ -22,7 +23,7 @@ struct ItemBound { }; #if defined(GPU_GL410) -uniform samplerBuffer ssbo0Buffer; +layout(binding=0) uniform samplerBuffer ssbo0Buffer; ItemBound getItemBound(int i) { int offset = 2 * i; ItemBound bound; @@ -31,7 +32,7 @@ ItemBound getItemBound(int i) { return bound; } #else -layout(std140) buffer ssbo0Buffer { +layout(std140, binding=0) buffer ssbo0Buffer { ItemBound bounds[]; }; ItemBound getItemBound(int i) { @@ -40,10 +41,14 @@ ItemBound getItemBound(int i) { } #endif -uniform parametersBuffer { +struct HighlightParameters { vec2 outlineWidth; }; +layout(binding=0) uniform parametersBuffer { + HighlightParameters _parameters; +}; + void main(void) { const vec3 UNIT_BOX_VERTICES[8] = vec3[8]( vec3(0.0, 1.0, 0.0), @@ -101,6 +106,6 @@ void main(void) { pos.xyz += UNIT_BOX_NORMALS[triangleIndex]; vec4 offsetPosition; <$transformModelToMonoClipPos(cam, obj, pos, offsetPosition)$> - gl_Position.xy += normalize(offsetPosition.xy-gl_Position.xy) * outlineWidth * gl_Position.w; + gl_Position.xy += normalize(offsetPosition.xy-gl_Position.xy) * _parameters.outlineWidth * gl_Position.w; <$transformStereoClipsSpace(cam, gl_Position)$> } diff --git a/libraries/render-utils/src/Highlight_filled.slf b/libraries/render-utils/src/Highlight_filled.slf index 53530746f0..8e4da681f9 100644 --- a/libraries/render-utils/src/Highlight_filled.slf +++ b/libraries/render-utils/src/Highlight_filled.slf @@ -1,4 +1,4 @@ -// Highlight_filled.slf +// Highlight_filled.frag // Add highlight effect based on two zbuffers : one containing the total scene z and another // with the z of only the objects to be outlined. // This is the version with the fill effect inside the silhouette. diff --git a/libraries/render-utils/src/LightAmbient.slh b/libraries/render-utils/src/LightAmbient.slh index b2377d1904..797595bf47 100644 --- a/libraries/render-utils/src/LightAmbient.slh +++ b/libraries/render-utils/src/LightAmbient.slh @@ -6,9 +6,10 @@ // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +<@include render-utils/ShaderConstants.h@> <@func declareSkyboxMap()@> // declareSkyboxMap -uniform samplerCube skyboxMap; +layout(binding=RENDER_UTILS_TEXTURE_SKYBOX) uniform samplerCube skyboxMap; vec4 evalSkyboxLight(vec3 direction, float lod) { // textureQueryLevels is not available until #430, so we require explicit lod diff --git a/libraries/render-utils/src/LightClusterGrid.slh b/libraries/render-utils/src/LightClusterGrid.slh index 709e8c0f70..8f57169ace 100644 --- a/libraries/render-utils/src/LightClusterGrid.slh +++ b/libraries/render-utils/src/LightClusterGrid.slh @@ -10,7 +10,7 @@ <@if not RENDER_LIGHT_CLUSTER_GRID_SLH@> <@def RENDER_LIGHT_CLUSTER_GRID_SLH@> - +<@include render-utils/ShaderConstants.h@> struct FrustumGrid { float frustumNear; @@ -24,7 +24,7 @@ struct FrustumGrid { mat4 eyeToWorldMat; }; -layout(std140) uniform frustumGridBuffer { +layout(std140, binding=RENDER_UTILS_BUFFER_LIGHT_CLUSTER_FRUSTUM_GRID) uniform frustumGridBuffer { FrustumGrid frustumGrid; }; @@ -60,11 +60,11 @@ float projection_getFar(mat4 projection) { #define GRID_FETCH_BUFFER(i) i!> <@endif@> -layout(std140) uniform clusterGridBuffer { +layout(std140, binding=RENDER_UTILS_BUFFER_LIGHT_CLUSTER_GRID) uniform clusterGridBuffer { GRID_INDEX_TYPE _clusterGridTable[GRID_NUM_ELEMENTS]; }; -layout(std140) uniform clusterContentBuffer { +layout(std140, binding=RENDER_UTILS_BUFFER_LIGHT_CLUSTER_CONTENT) uniform clusterContentBuffer { GRID_INDEX_TYPE _clusterGridContent[GRID_NUM_ELEMENTS]; }; diff --git a/libraries/render-utils/src/LightClusters.cpp b/libraries/render-utils/src/LightClusters.cpp index 87698cab44..ae484f868f 100644 --- a/libraries/render-utils/src/LightClusters.cpp +++ b/libraries/render-utils/src/LightClusters.cpp @@ -12,28 +12,22 @@ #include #include +#include #include "RenderUtilsLogging.h" +#include "render-utils/ShaderConstants.h" #include "StencilMaskPass.h" -enum LightClusterGridShader_MapSlot { - DEFERRED_BUFFER_LINEAR_DEPTH_UNIT = 0, - DEFERRED_BUFFER_COLOR_UNIT = 1, - DEFERRED_BUFFER_NORMAL_UNIT = 2, - DEFERRED_BUFFER_EMISSIVE_UNIT = 3, - DEFERRED_BUFFER_DEPTH_UNIT = 4, -}; +namespace ru { + using render_utils::slot::texture::Texture; + using render_utils::slot::buffer::Buffer; +} -enum LightClusterGridShader_BufferSlot { - DEFERRED_FRAME_TRANSFORM_BUFFER_SLOT = 0, - CAMERA_CORRECTION_BUFFER_SLOT = 1, - LIGHT_GPU_SLOT = render::ShapePipeline::Slot::LIGHT_ARRAY_BUFFER, - LIGHT_INDEX_GPU_SLOT = 7, - LIGHT_CLUSTER_GRID_FRUSTUM_GRID_SLOT = 8, - LIGHT_CLUSTER_GRID_CLUSTER_GRID_SLOT = 9, - LIGHT_CLUSTER_GRID_CLUSTER_CONTENT_SLOT = 10, -}; +namespace gr { + using graphics::slot::texture::Texture; + using graphics::slot::buffer::Buffer; +} FrustumGrid::FrustumGrid(const FrustumGrid& source) : frustumNear(source.frustumNear), @@ -595,16 +589,6 @@ void DebugLightClusters::configure(const Config& config) { const gpu::PipelinePointer DebugLightClusters::getDrawClusterGridPipeline() { if (!_drawClusterGrid) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::lightClusters_drawGrid); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("frustumGridBuffer"), LIGHT_CLUSTER_GRID_FRUSTUM_GRID_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("clusterGridBuffer"), LIGHT_CLUSTER_GRID_CLUSTER_GRID_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("clusterContentBuffer"), LIGHT_CLUSTER_GRID_CLUSTER_CONTENT_SLOT)); - - - gpu::Shader::makeProgram(*program, slotBindings); - - auto state = std::make_shared(); state->setDepthTest(true, false, gpu::LESS_EQUAL); @@ -621,19 +605,6 @@ const gpu::PipelinePointer DebugLightClusters::getDrawClusterGridPipeline() { const gpu::PipelinePointer DebugLightClusters::getDrawClusterFromDepthPipeline() { if (!_drawClusterFromDepth) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::lightClusters_drawClusterFromDepth); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("frustumGridBuffer"), LIGHT_CLUSTER_GRID_FRUSTUM_GRID_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("clusterGridBuffer"), LIGHT_CLUSTER_GRID_CLUSTER_GRID_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("clusterContentBuffer"), LIGHT_CLUSTER_GRID_CLUSTER_CONTENT_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("linearZeyeMap"), DEFERRED_BUFFER_LINEAR_DEPTH_UNIT)); - - slotBindings.insert(gpu::Shader::Binding(std::string("cameraCorrectionBuffer"), CAMERA_CORRECTION_BUFFER_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), DEFERRED_FRAME_TRANSFORM_BUFFER_SLOT)); - - gpu::Shader::makeProgram(*program, slotBindings); - - auto state = std::make_shared(); // Blend on transparent @@ -648,20 +619,6 @@ const gpu::PipelinePointer DebugLightClusters::getDrawClusterFromDepthPipeline() const gpu::PipelinePointer DebugLightClusters::getDrawClusterContentPipeline() { if (!_drawClusterContent) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::lightClusters_drawClusterContent); - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("lightBuffer"), LIGHT_GPU_SLOT)); - - slotBindings.insert(gpu::Shader::Binding(std::string("frustumGridBuffer"), LIGHT_CLUSTER_GRID_FRUSTUM_GRID_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("clusterGridBuffer"), LIGHT_CLUSTER_GRID_CLUSTER_GRID_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("clusterContentBuffer"), LIGHT_CLUSTER_GRID_CLUSTER_CONTENT_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("linearZeyeMap"), DEFERRED_BUFFER_LINEAR_DEPTH_UNIT)); - - slotBindings.insert(gpu::Shader::Binding(std::string("cameraCorrectionBuffer"), CAMERA_CORRECTION_BUFFER_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), DEFERRED_FRAME_TRANSFORM_BUFFER_SLOT)); - - gpu::Shader::makeProgram(*program, slotBindings); - - auto state = std::make_shared(); // Blend on transparent @@ -705,41 +662,42 @@ void DebugLightClusters::run(const render::RenderContextPointer& renderContext, batch.setModelTransform(Transform()); // Bind the Light CLuster data strucutre - batch.setUniformBuffer(LIGHT_GPU_SLOT, lightClusters->_lightStage->getLightArrayBuffer()); - batch.setUniformBuffer(LIGHT_CLUSTER_GRID_FRUSTUM_GRID_SLOT, lightClusters->_frustumGridBuffer); - batch.setUniformBuffer(LIGHT_CLUSTER_GRID_CLUSTER_GRID_SLOT, lightClusters->_clusterGridBuffer); - batch.setUniformBuffer(LIGHT_CLUSTER_GRID_CLUSTER_CONTENT_SLOT, lightClusters->_clusterContentBuffer); + // FIXME consolidate code with DeferredLightingEffect logic that does the same thing + batch.setUniformBuffer(gr::Buffer::Light, lightClusters->_lightStage->getLightArrayBuffer()); + batch.setUniformBuffer(ru::Buffer::LightClusterFrustumGrid, lightClusters->_frustumGridBuffer); + batch.setUniformBuffer(ru::Buffer::LightClusterGrid, lightClusters->_clusterGridBuffer); + batch.setUniformBuffer(ru::Buffer::LightClusterContent, lightClusters->_clusterContentBuffer); if (doDrawClusterFromDepth) { batch.setPipeline(getDrawClusterFromDepthPipeline()); - batch.setUniformBuffer(DEFERRED_FRAME_TRANSFORM_BUFFER_SLOT, deferredTransform->getFrameTransformBuffer()); + batch.setUniformBuffer(ru::Buffer::DeferredFrameTransform, deferredTransform->getFrameTransformBuffer()); if (linearDepthTarget) { - batch.setResourceTexture(DEFERRED_BUFFER_LINEAR_DEPTH_UNIT, linearDepthTarget->getLinearDepthTexture()); + batch.setResourceTexture(ru::Texture::DeferredLinearZEye, linearDepthTarget->getLinearDepthTexture()); } batch.draw(gpu::TRIANGLE_STRIP, 4, 0); - batch.setResourceTexture(DEFERRED_BUFFER_LINEAR_DEPTH_UNIT, nullptr); - batch.setUniformBuffer(DEFERRED_FRAME_TRANSFORM_BUFFER_SLOT, nullptr); + batch.setResourceTexture(ru::Texture::DeferredLinearZEye, nullptr); + batch.setUniformBuffer(ru::Buffer::DeferredFrameTransform, nullptr); } if (doDrawContent) { // bind the one gpu::Pipeline we need batch.setPipeline(getDrawClusterContentPipeline()); - batch.setUniformBuffer(DEFERRED_FRAME_TRANSFORM_BUFFER_SLOT, deferredTransform->getFrameTransformBuffer()); + batch.setUniformBuffer(ru::Buffer::DeferredFrameTransform, deferredTransform->getFrameTransformBuffer()); if (linearDepthTarget) { - batch.setResourceTexture(DEFERRED_BUFFER_LINEAR_DEPTH_UNIT, linearDepthTarget->getLinearDepthTexture()); + batch.setResourceTexture(ru::Texture::DeferredLinearZEye, linearDepthTarget->getLinearDepthTexture()); } batch.draw(gpu::TRIANGLE_STRIP, 4, 0); - batch.setResourceTexture(DEFERRED_BUFFER_LINEAR_DEPTH_UNIT, nullptr); - batch.setUniformBuffer(DEFERRED_FRAME_TRANSFORM_BUFFER_SLOT, nullptr); + batch.setResourceTexture(ru::Texture::DeferredLinearZEye, nullptr); + batch.setUniformBuffer(ru::Buffer::DeferredFrameTransform, nullptr); } }); @@ -756,14 +714,14 @@ void DebugLightClusters::run(const render::RenderContextPointer& renderContext, drawGridAndCleanBatch.drawInstanced(summedDims.x, gpu::LINES, 24, 0); } - drawGridAndCleanBatch.setUniformBuffer(LIGHT_GPU_SLOT, nullptr); - drawGridAndCleanBatch.setUniformBuffer(LIGHT_CLUSTER_GRID_FRUSTUM_GRID_SLOT, nullptr); - drawGridAndCleanBatch.setUniformBuffer(LIGHT_CLUSTER_GRID_CLUSTER_GRID_SLOT, nullptr); - drawGridAndCleanBatch.setUniformBuffer(LIGHT_CLUSTER_GRID_CLUSTER_CONTENT_SLOT, nullptr); + drawGridAndCleanBatch.setUniformBuffer(gr::Buffer::Light, nullptr); + drawGridAndCleanBatch.setUniformBuffer(ru::Buffer::LightClusterFrustumGrid, nullptr); + drawGridAndCleanBatch.setUniformBuffer(ru::Buffer::LightClusterGrid, nullptr); + drawGridAndCleanBatch.setUniformBuffer(ru::Buffer::LightClusterContent, nullptr); - drawGridAndCleanBatch.setResourceTexture(DEFERRED_BUFFER_COLOR_UNIT, nullptr); - drawGridAndCleanBatch.setResourceTexture(DEFERRED_BUFFER_NORMAL_UNIT, nullptr); - drawGridAndCleanBatch.setResourceTexture(DEFERRED_BUFFER_EMISSIVE_UNIT, nullptr); - drawGridAndCleanBatch.setResourceTexture(DEFERRED_BUFFER_DEPTH_UNIT, nullptr); + drawGridAndCleanBatch.setResourceTexture(ru::Texture::DeferredColor, nullptr); + drawGridAndCleanBatch.setResourceTexture(ru::Texture::DeferredNormal, nullptr); + drawGridAndCleanBatch.setResourceTexture(ru::Texture::DeferredSpecular, nullptr); + drawGridAndCleanBatch.setResourceTexture(ru::Texture::DeferredLinearZEye, nullptr); }); -} \ No newline at end of file +} diff --git a/libraries/render-utils/src/LightDirectional.slh b/libraries/render-utils/src/LightDirectional.slh index b6e1720a2c..1490a2ff25 100644 --- a/libraries/render-utils/src/LightDirectional.slh +++ b/libraries/render-utils/src/LightDirectional.slh @@ -7,7 +7,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // - +<@include ShadingModel.slh@> <@func declareLightingDirectional(supportScattering)@> diff --git a/libraries/render-utils/src/LightLocal.slh b/libraries/render-utils/src/LightLocal.slh index 06f8871e24..91f0b4fd20 100644 --- a/libraries/render-utils/src/LightLocal.slh +++ b/libraries/render-utils/src/LightLocal.slh @@ -9,17 +9,15 @@ // Everything about light <@include graphics/Light.slh@> -<$declareLightBuffer(256)$> <@include LightingModel.slh@> - - <@include LightPoint.slh@> -<$declareLightingPoint(supportScattering)$> <@include LightSpot.slh@> -<$declareLightingSpot(supportScattering)$> - <@include LightClusterGrid.slh@> +<$declareLightBuffer(256)$> +<$declareLightingPoint(supportScattering)$> +<$declareLightingSpot(supportScattering)$> + vec4 evalLocalLighting(ivec3 cluster, int numLights, vec3 fragWorldPos, SurfaceData surface, float fragMetallic, vec3 fragFresnel, vec3 fragAlbedo, float fragScattering, vec4 midNormalCurvature, vec4 lowNormalCurvature, float opacity) { @@ -145,4 +143,5 @@ vec4 evalLocalLighting(ivec3 cluster, int numLights, vec3 fragWorldPos, SurfaceD fragColor.rgb += fragDiffuse; fragColor.rgb += evalSpecularWithOpacity(fragSpecular, opacity); return fragColor; -} \ No newline at end of file +} + diff --git a/libraries/render-utils/src/LightPoint.slh b/libraries/render-utils/src/LightPoint.slh index 91a1260fcc..1a361e3717 100644 --- a/libraries/render-utils/src/LightPoint.slh +++ b/libraries/render-utils/src/LightPoint.slh @@ -7,7 +7,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // - +<@include ShadingModel.slh@> <@func declareLightingPoint(supportScattering)@> diff --git a/libraries/render-utils/src/LightSpot.slh b/libraries/render-utils/src/LightSpot.slh index 73c5bd9559..2546c0225c 100644 --- a/libraries/render-utils/src/LightSpot.slh +++ b/libraries/render-utils/src/LightSpot.slh @@ -7,7 +7,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // - +<@include ShadingModel.slh@> <@func declareLightingSpot(supportScattering)@> diff --git a/libraries/render-utils/src/LightingModel.slh b/libraries/render-utils/src/LightingModel.slh index fe2d684c32..10a2afabef 100644 --- a/libraries/render-utils/src/LightingModel.slh +++ b/libraries/render-utils/src/LightingModel.slh @@ -11,6 +11,7 @@ <@if not LIGHTING_MODEL_SLH@> <@def LIGHTING_MODEL_SLH@> +<@include render-utils/ShaderConstants.h@> <@func declareLightingModel()@> struct LightingModel { @@ -21,7 +22,8 @@ struct LightingModel { vec4 _Haze_spareyzw; }; -uniform lightingModelBuffer{ +// See DeferredShader_BufferSlot in DeferredLightingEffect.cpp +layout(binding=RENDER_UTILS_BUFFER_LIGHT_MODEL) uniform lightingModelBuffer{ LightingModel lightingModel; }; @@ -106,225 +108,4 @@ vec3 getFresnelF0(float metallic, vec3 metalF0) { } <@endif@> -<@func declareBeckmannSpecular()@> - -uniform sampler2D scatteringSpecularBeckmann; - -float fetchSpecularBeckmann(float ndoth, float roughness) { - return pow(2.0 * texture(scatteringSpecularBeckmann, vec2(ndoth, roughness)).r, 10.0); -} - -vec2 skinSpecular(SurfaceData surface, float intensity) { - vec2 result = vec2(0.0, 1.0); - if (surface.ndotl > 0.0) { - float PH = fetchSpecularBeckmann(surface.ndoth, surface.roughness); - float F = fresnelSchlickScalar(0.028, surface); - float frSpec = max(PH * F / dot(surface.halfDir, surface.halfDir), 0.0); - result.x = surface.ndotl * intensity * frSpec; - result.y -= F; - } - - return result; -} -<@endfunc@> - -<@func declareEvalPBRShading()@> - -float evalSmithInvG1(float roughness4, float ndotd) { - return ndotd + sqrt(roughness4+ndotd*ndotd*(1.0-roughness4)); -} - -SurfaceData initSurfaceData(float roughness, vec3 normal, vec3 eyeDir) { - SurfaceData surface; - surface.eyeDir = eyeDir; - surface.normal = normal; - surface.roughness = mix(0.01, 1.0, roughness); - surface.roughness2 = surface.roughness * surface.roughness; - surface.roughness4 = surface.roughness2 * surface.roughness2; - surface.ndotv = clamp(dot(normal, eyeDir), 0.0, 1.0); - surface.smithInvG1NdotV = evalSmithInvG1(surface.roughness4, surface.ndotv); - - // These values will be set when we know the light direction, in updateSurfaceDataWithLight - surface.ndoth = 0.0; - surface.ndotl = 0.0; - surface.ldoth = 0.0; - surface.lightDir = vec3(0,0,1); - surface.halfDir = vec3(0,0,1); - - return surface; -} - -void updateSurfaceDataWithLight(inout SurfaceData surface, vec3 lightDir) { - surface.lightDir = lightDir; - surface.halfDir = normalize(surface.eyeDir + lightDir); - vec3 dots; - dots.x = dot(surface.normal, surface.halfDir); - dots.y = dot(surface.normal, surface.lightDir); - dots.z = dot(surface.halfDir, surface.lightDir); - dots = clamp(dots, vec3(0), vec3(1)); - surface.ndoth = dots.x; - surface.ndotl = dots.y; - surface.ldoth = dots.z; -} - -vec3 fresnelSchlickColor(vec3 fresnelColor, SurfaceData surface) { - float base = 1.0 - surface.ldoth; - //float exponential = pow(base, 5.0); - float base2 = base * base; - float exponential = base * base2 * base2; - return vec3(exponential) + fresnelColor * (1.0 - exponential); -} - -float fresnelSchlickScalar(float fresnelScalar, SurfaceData surface) { - float base = 1.0 - surface.ldoth; - //float exponential = pow(base, 5.0); - float base2 = base * base; - float exponential = base * base2 * base2; - return (exponential) + fresnelScalar * (1.0 - exponential); -} - -float specularDistribution(SurfaceData surface) { - // See https://www.khronos.org/assets/uploads/developers/library/2017-web3d/glTF-2.0-Launch_Jun17.pdf - // for details of equations, especially page 20 - float denom = (surface.ndoth*surface.ndoth * (surface.roughness4 - 1.0) + 1.0); - denom *= denom; - // Add geometric factors G1(n,l) and G1(n,v) - float smithInvG1NdotL = evalSmithInvG1(surface.roughness4, surface.ndotl); - denom *= surface.smithInvG1NdotV * smithInvG1NdotL; - // Don't divide by PI as this is part of the light normalization factor - float power = surface.roughness4 / denom; - return power; -} - -// Frag Shading returns the diffuse amount as W and the specular rgb as xyz -vec4 evalPBRShading(float metallic, vec3 fresnel, SurfaceData surface) { - // Incident angle attenuation - float angleAttenuation = surface.ndotl; - - // Specular Lighting - vec3 fresnelColor = fresnelSchlickColor(fresnel, surface); - float power = specularDistribution(surface); - vec3 specular = fresnelColor * power * angleAttenuation; - float diffuse = (1.0 - metallic) * angleAttenuation * (1.0 - fresnelColor.x); - - // We don't divided by PI, as the "normalized" equations state we should, because we decide, as Naty Hoffman, that - // we wish to have a similar color as raw albedo on a perfectly diffuse surface perpendicularly lit - // by a white light of intensity 1. But this is an arbitrary normalization of what light intensity "means". - // (see http://blog.selfshadow.com/publications/s2013-shading-course/hoffman/s2013_pbs_physics_math_notes.pdf - // page 23 paragraph "Punctual light sources") - return vec4(specular, diffuse); -} - -// Frag Shading returns the diffuse amount as W and the specular rgb as xyz -vec4 evalPBRShadingDielectric(SurfaceData surface, float fresnel) { - // Incident angle attenuation - float angleAttenuation = surface.ndotl; - - // Specular Lighting - float fresnelScalar = fresnelSchlickScalar(fresnel, surface); - float power = specularDistribution(surface); - vec3 specular = vec3(fresnelScalar) * power * angleAttenuation; - float diffuse = angleAttenuation * (1.0 - fresnelScalar); - - // We don't divided by PI, as the "normalized" equations state we should, because we decide, as Naty Hoffman, that - // we wish to have a similar color as raw albedo on a perfectly diffuse surface perpendicularly lit - // by a white light of intensity 1. But this is an arbitrary normalization of what light intensity "means". - // (see http://blog.selfshadow.com/publications/s2013-shading-course/hoffman/s2013_pbs_physics_math_notes.pdf - // page 23 paragraph "Punctual light sources") - return vec4(specular, diffuse); -} - -vec4 evalPBRShadingMetallic(SurfaceData surface, vec3 fresnel) { - // Incident angle attenuation - float angleAttenuation = surface.ndotl; - - // Specular Lighting - vec3 fresnelColor = fresnelSchlickColor(fresnel, surface); - float power = specularDistribution(surface); - vec3 specular = fresnelColor * power * angleAttenuation; - - // We don't divided by PI, as the "normalized" equations state we should, because we decide, as Naty Hoffman, that - // we wish to have a similar color as raw albedo on a perfectly diffuse surface perpendicularly lit - // by a white light of intensity 1. But this is an arbitrary normalization of what light intensity "means". - // (see http://blog.selfshadow.com/publications/s2013-shading-course/hoffman/s2013_pbs_physics_math_notes.pdf - // page 23 paragraph "Punctual light sources") - return vec4(specular, 0.f); -} - -<@endfunc@> - - - -<$declareEvalPBRShading()$> - -void evalFragShading(out vec3 diffuse, out vec3 specular, - float metallic, vec3 fresnel, SurfaceData surface, vec3 albedo) { - vec4 shading = evalPBRShading(metallic, fresnel, surface); - diffuse = vec3(shading.w); - diffuse *= mix(vec3(1.0), albedo, isAlbedoEnabled()); - specular = shading.xyz; -} - -<$declareBeckmannSpecular()$> -<@include SubsurfaceScattering.slh@> -<$declareSubsurfaceScatteringBRDF()$> - - -void evalFragShading(out vec3 diffuse, out vec3 specular, - float metallic, vec3 fresnel, SurfaceData surface, vec3 albedo, - float scattering, vec4 midNormalCurvature, vec4 lowNormalCurvature) { - if (scattering * isScatteringEnabled() > 0.0) { - vec3 brdf = evalSkinBRDF(surface.lightDir, surface.normal, midNormalCurvature.xyz, lowNormalCurvature.xyz, lowNormalCurvature.w); - diffuse = mix(vec3(surface.ndotl), brdf, scattering); - - // Specular Lighting - vec2 specularBrdf = skinSpecular(surface, 1.0); - - diffuse *= specularBrdf.y; - specular = vec3(specularBrdf.x); - } else { - vec4 shading = evalPBRShading(metallic, fresnel, surface); - diffuse = vec3(shading.w); - specular = shading.xyz; - } - diffuse *= mix(vec3(1.0), albedo, isAlbedoEnabled()); -} - - -void evalFragShadingScattering(out vec3 diffuse, out vec3 specular, - float metallic, vec3 fresnel, SurfaceData surface, vec3 albedo, - float scattering, vec4 midNormalCurvature, vec4 lowNormalCurvature) { - vec3 brdf = evalSkinBRDF(surface.lightDir, surface.normal, midNormalCurvature.xyz, lowNormalCurvature.xyz, lowNormalCurvature.w); - float NdotL = surface.ndotl; - diffuse = mix(vec3(NdotL), brdf, scattering); - - // Specular Lighting - vec2 specularBrdf = skinSpecular(surface, 1.0); - - diffuse *= specularBrdf.y; - specular = vec3(specularBrdf.x); - diffuse *= mix(vec3(1.0), albedo, isAlbedoEnabled()); -} - -void evalFragShadingGloss(out vec3 diffuse, out vec3 specular, - float metallic, vec3 fresnel, SurfaceData surface, vec3 albedo) { - vec4 shading = evalPBRShading(metallic, fresnel, surface); - diffuse = vec3(shading.w); - diffuse *= mix(vec3(1.0), albedo, isAlbedoEnabled()); - specular = shading.xyz; -} - -vec3 evalSpecularWithOpacity(vec3 specular, float opacity) { - return specular / opacity; -} - -<@if not GETFRESNEL0@> -<@def GETFRESNEL0@> -vec3 getFresnelF0(float metallic, vec3 metalF0) { - // Enable continuous metallness value by lerping between dielectric - // and metal fresnel F0 value based on the "metallic" parameter - return mix(vec3(0.03), metalF0, metallic); -} -<@endif@> - <@endif@> diff --git a/libraries/render-utils/src/MeshPartPayload.cpp b/libraries/render-utils/src/MeshPartPayload.cpp index 7cf8bc8297..9e335c9213 100644 --- a/libraries/render-utils/src/MeshPartPayload.cpp +++ b/libraries/render-utils/src/MeshPartPayload.cpp @@ -13,7 +13,9 @@ #include #include +#include +#include "render-utils/ShaderConstants.h" #include "DeferredLightingEffect.h" #include "RenderPipelines.h" @@ -395,7 +397,7 @@ void ModelMeshPartPayload::bindMesh(gpu::Batch& batch) { void ModelMeshPartPayload::bindTransform(gpu::Batch& batch, RenderArgs::RenderMode renderMode) const { if (_clusterBuffer) { - batch.setUniformBuffer(ShapePipeline::Slot::BUFFER::SKINNING, _clusterBuffer); + batch.setUniformBuffer(graphics::slot::buffer::Skinning, _clusterBuffer); } batch.setModelTransform(_transform); } diff --git a/libraries/render-utils/src/RenderCommonTask.cpp b/libraries/render-utils/src/RenderCommonTask.cpp index c2181b7613..9aee0e57a4 100644 --- a/libraries/render-utils/src/RenderCommonTask.cpp +++ b/libraries/render-utils/src/RenderCommonTask.cpp @@ -9,10 +9,23 @@ #include "RenderCommonTask.h" #include +#include +#include "render-utils/ShaderConstants.h" #include "DeferredLightingEffect.h" #include "RenderUtilsLogging.h" +namespace ru { + using render_utils::slot::texture::Texture; + using render_utils::slot::buffer::Buffer; +} + +namespace gr { + using graphics::slot::texture::Texture; + using graphics::slot::buffer::Buffer; +} + + using namespace render; extern void initForwardPipelines(ShapePlumber& plumber); @@ -46,7 +59,7 @@ void DrawOverlay3D::run(const RenderContextPointer& renderContext, const Inputs& const auto& inItems = inputs.get0(); const auto& lightingModel = inputs.get1(); - const auto jitter = inputs.get2(); + const auto jitter = inputs.get2(); config->setNumDrawn((int)inItems.size()); emit config->numDrawnChanged(); @@ -76,11 +89,11 @@ void DrawOverlay3D::run(const RenderContextPointer& renderContext, const Inputs& args->getViewFrustum().evalViewTransform(viewMat); batch.setProjectionTransform(projMat); - batch.setProjectionJitter(jitter.x, jitter.y); - batch.setViewTransform(viewMat); + batch.setProjectionJitter(jitter.x, jitter.y); + batch.setViewTransform(viewMat); // Setup lighting model for all items; - batch.setUniformBuffer(render::ShapePipeline::Slot::LIGHTING_MODEL, lightingModel->getParametersBuffer()); + batch.setUniformBuffer(ru::Buffer::LightModel, lightingModel->getParametersBuffer()); renderShapes(renderContext, _shapePlumber, inItems, _maxDrawn); args->_batch = nullptr; diff --git a/libraries/render-utils/src/RenderDeferredTask.cpp b/libraries/render-utils/src/RenderDeferredTask.cpp index 0b05977265..ea9655d26d 100644 --- a/libraries/render-utils/src/RenderDeferredTask.cpp +++ b/libraries/render-utils/src/RenderDeferredTask.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include @@ -29,6 +30,7 @@ #include #include "RenderHifi.h" +#include "render-utils/ShaderConstants.h" #include "RenderCommonTask.h" #include "LightingModel.h" #include "StencilMaskPass.h" @@ -56,6 +58,17 @@ using namespace render; extern void initDeferredPipelines(render::ShapePlumber& plumber, const render::ShapePipeline::BatchSetter& batchSetter, const render::ShapePipeline::ItemSetter& itemSetter); +namespace ru { + using render_utils::slot::texture::Texture; + using render_utils::slot::buffer::Buffer; +} + +namespace gr { + using graphics::slot::texture::Texture; + using graphics::slot::buffer::Buffer; +} + + RenderDeferredTask::RenderDeferredTask() { } @@ -347,27 +360,18 @@ void DrawDeferred::run(const RenderContextPointer& renderContext, const Inputs& batch.setViewTransform(viewMat); // Setup lighting model for all items; - batch.setUniformBuffer(render::ShapePipeline::Slot::LIGHTING_MODEL, lightingModel->getParametersBuffer()); + batch.setUniformBuffer(ru::Buffer::LightModel, lightingModel->getParametersBuffer()); // Set the light - deferredLightingEffect->setupKeyLightBatch(args, batch, - render::ShapePipeline::Slot::KEY_LIGHT, - render::ShapePipeline::Slot::LIGHT_AMBIENT_BUFFER, - render::ShapePipeline::Slot::LIGHT_AMBIENT_MAP); - - deferredLightingEffect->setupLocalLightsBatch(batch, - render::ShapePipeline::Slot::LIGHT_ARRAY_BUFFER, - render::ShapePipeline::Slot::LIGHT_CLUSTER_GRID_CLUSTER_GRID_SLOT, - render::ShapePipeline::Slot::LIGHT_CLUSTER_GRID_CLUSTER_CONTENT_SLOT, - render::ShapePipeline::Slot::LIGHT_CLUSTER_GRID_FRUSTUM_GRID_SLOT, - lightClusters); + deferredLightingEffect->setupKeyLightBatch(args, batch); + deferredLightingEffect->setupLocalLightsBatch(batch, lightClusters); // Setup haze if current zone has haze auto hazeStage = args->_scene->getStage(); if (hazeStage && hazeStage->_currentFrame._hazes.size() > 0) { graphics::HazePointer hazePointer = hazeStage->getHaze(hazeStage->_currentFrame._hazes.front()); if (hazePointer) { - batch.setUniformBuffer(render::ShapePipeline::Slot::HAZE_MODEL, hazePointer->getHazeParametersBuffer()); + batch.setUniformBuffer(ru::Buffer::HazeParams, hazePointer->getHazeParametersBuffer()); } } @@ -385,16 +389,8 @@ void DrawDeferred::run(const RenderContextPointer& renderContext, const Inputs& args->_batch = nullptr; args->_globalShapeKey = 0; - deferredLightingEffect->unsetLocalLightsBatch(batch, - render::ShapePipeline::Slot::LIGHT_ARRAY_BUFFER, - render::ShapePipeline::Slot::LIGHT_CLUSTER_GRID_CLUSTER_GRID_SLOT, - render::ShapePipeline::Slot::LIGHT_CLUSTER_GRID_CLUSTER_CONTENT_SLOT, - render::ShapePipeline::Slot::LIGHT_CLUSTER_GRID_FRUSTUM_GRID_SLOT); - - deferredLightingEffect->unsetKeyLightBatch(batch, - render::ShapePipeline::Slot::KEY_LIGHT, - render::ShapePipeline::Slot::LIGHT_AMBIENT_BUFFER, - render::ShapePipeline::Slot::LIGHT_AMBIENT_MAP); + deferredLightingEffect->unsetLocalLightsBatch(batch); + deferredLightingEffect->unsetKeyLightBatch(batch); }); config->setNumDrawn((int)inItems.size()); @@ -429,7 +425,7 @@ void DrawStateSortDeferred::run(const RenderContextPointer& renderContext, const batch.setViewTransform(viewMat); // Setup lighting model for all items; - batch.setUniformBuffer(render::ShapePipeline::Slot::LIGHTING_MODEL, lightingModel->getParametersBuffer()); + batch.setUniformBuffer(ru::Buffer::LightModel, lightingModel->getParametersBuffer()); // From the lighting model define a global shapeKey ORED with individiual keys ShapeKey::Builder keyBuilder; diff --git a/libraries/render-utils/src/RenderForwardTask.cpp b/libraries/render-utils/src/RenderForwardTask.cpp index c6cc97f0b6..c2d39128ba 100755 --- a/libraries/render-utils/src/RenderForwardTask.cpp +++ b/libraries/render-utils/src/RenderForwardTask.cpp @@ -17,12 +17,13 @@ #include #include #include - +#include #include #include #include "RenderHifi.h" +#include "render-utils/ShaderConstants.h" #include "StencilMaskPass.h" #include "ZoneRenderer.h" #include "FadeEffect.h" @@ -33,7 +34,18 @@ #include "RenderCommonTask.h" #include "LightStage.h" +namespace ru { + using render_utils::slot::texture::Texture; + using render_utils::slot::buffer::Buffer; +} + +namespace gr { + using graphics::slot::texture::Texture; + using graphics::slot::buffer::Buffer; +} + using namespace render; + extern void initForwardPipelines(ShapePlumber& plumber); void RenderForwardTask::build(JobModel& task, const render::Varying& input, render::Varying& output) { @@ -176,14 +188,14 @@ void PrepareForward::run(const RenderContextPointer& renderContext, const Inputs } if (keySunLight) { - batch.setUniformBuffer(render::ShapePipeline::Slot::KEY_LIGHT, keySunLight->getLightSchemaBuffer()); + batch.setUniformBuffer(gr::Buffer::KeyLight, keySunLight->getLightSchemaBuffer()); } if (keyAmbiLight) { - batch.setUniformBuffer(render::ShapePipeline::Slot::LIGHT_AMBIENT_BUFFER, keyAmbiLight->getAmbientSchemaBuffer()); + batch.setUniformBuffer(gr::Buffer::AmbientLight, keyAmbiLight->getAmbientSchemaBuffer()); if (keyAmbiLight->getAmbientMap()) { - batch.setResourceTexture(render::ShapePipeline::Slot::LIGHT_AMBIENT_MAP, keyAmbiLight->getAmbientMap()); + batch.setResourceTexture(ru::Texture::Skybox, keyAmbiLight->getAmbientMap()); } } }); @@ -209,7 +221,7 @@ void DrawForward::run(const RenderContextPointer& renderContext, const Inputs& i batch.setModelTransform(Transform()); // Setup lighting model for all items; - batch.setUniformBuffer(render::ShapePipeline::Slot::LIGHTING_MODEL, lightingModel->getParametersBuffer()); + batch.setUniformBuffer(ru::Buffer::LightModel, lightingModel->getParametersBuffer()); // From the lighting model define a global shapeKey ORED with individiual keys ShapeKey::Builder keyBuilder; diff --git a/libraries/render-utils/src/RenderPipelines.cpp b/libraries/render-utils/src/RenderPipelines.cpp index f44325d353..704b1d7663 100644 --- a/libraries/render-utils/src/RenderPipelines.cpp +++ b/libraries/render-utils/src/RenderPipelines.cpp @@ -18,7 +18,9 @@ #include #include #include +#include +#include "render-utils/ShaderConstants.h" #include "StencilMaskPass.h" #include "DeferredLightingEffect.h" #include "TextureCache.h" @@ -26,6 +28,16 @@ using namespace render; using namespace std::placeholders; +namespace ru { + using render_utils::slot::texture::Texture; + using render_utils::slot::buffer::Buffer; +} + +namespace gr { + using graphics::slot::texture::Texture; + using graphics::slot::buffer::Buffer; +} + void initDeferredPipelines(ShapePlumber& plumber, const render::ShapePipeline::BatchSetter& batchSetter, const render::ShapePipeline::ItemSetter& itemSetter); void initForwardPipelines(ShapePlumber& plumber); void initZPassPipelines(ShapePlumber& plumber, gpu::StatePointer state); @@ -319,11 +331,11 @@ void addPlumberPipeline(ShapePlumber& plumber, void batchSetter(const ShapePipeline& pipeline, gpu::Batch& batch, RenderArgs* args) { // Set a default albedo map - batch.setResourceTexture(render::ShapePipeline::Slot::MAP::ALBEDO, + batch.setResourceTexture(gr::Texture::MaterialAlbedo, DependencyManager::get()->getWhiteTexture()); // Set a default material - if (pipeline.locations->materialBufferUnit >= 0) { + if (pipeline.locations->materialBufferUnit) { // Create a default schema static bool isMaterialSet = false; static graphics::Material material; @@ -336,7 +348,7 @@ void batchSetter(const ShapePipeline& pipeline, gpu::Batch& batch, RenderArgs* a } // Set a default schema - batch.setUniformBuffer(ShapePipeline::Slot::BUFFER::MATERIAL, material.getSchemaBuffer()); + batch.setUniformBuffer(gr::Buffer::Material, material.getSchemaBuffer()); } } @@ -345,11 +357,8 @@ void lightBatchSetter(const ShapePipeline& pipeline, gpu::Batch& batch, RenderAr batchSetter(pipeline, batch, args); // Set the light - if (pipeline.locations->keyLightBufferUnit >= 0) { - DependencyManager::get()->setupKeyLightBatch(args, batch, - pipeline.locations->keyLightBufferUnit, - pipeline.locations->lightAmbientBufferUnit, - pipeline.locations->lightAmbientMapUnit); + if (pipeline.locations->keyLightBufferUnit) { + DependencyManager::get()->setupKeyLightBatch(args, batch); } } @@ -394,8 +403,8 @@ void RenderPipelines::bindMaterial(const graphics::MaterialPointer& material, gp auto textureCache = DependencyManager::get(); - batch.setUniformBuffer(ShapePipeline::Slot::BUFFER::MATERIAL, material->getSchemaBuffer()); - batch.setUniformBuffer(ShapePipeline::Slot::BUFFER::TEXMAPARRAY, material->getTexMapArrayBuffer()); + batch.setUniformBuffer(gr::Buffer::Material, material->getSchemaBuffer()); + batch.setUniformBuffer(gr::Buffer::TexMapArray, material->getTexMapArrayBuffer()); const auto& materialKey = material->getKey(); const auto& textureMaps = material->getTextureMaps(); @@ -411,9 +420,9 @@ void RenderPipelines::bindMaterial(const graphics::MaterialPointer& material, gp if (materialKey.isAlbedoMap()) { auto itr = textureMaps.find(graphics::MaterialKey::ALBEDO_MAP); if (enableTextures && itr != textureMaps.end() && itr->second->isDefined()) { - drawMaterialTextures->setTexture(ShapePipeline::Slot::ALBEDO, itr->second->getTextureView()); + drawMaterialTextures->setTexture(gr::Texture::MaterialAlbedo, itr->second->getTextureView()); } else { - drawMaterialTextures->setTexture(ShapePipeline::Slot::ALBEDO, textureCache->getWhiteTexture()); + drawMaterialTextures->setTexture(gr::Texture::MaterialAlbedo, textureCache->getWhiteTexture()); } } @@ -421,9 +430,9 @@ void RenderPipelines::bindMaterial(const graphics::MaterialPointer& material, gp if (materialKey.isRoughnessMap()) { auto itr = textureMaps.find(graphics::MaterialKey::ROUGHNESS_MAP); if (enableTextures && itr != textureMaps.end() && itr->second->isDefined()) { - drawMaterialTextures->setTexture(ShapePipeline::Slot::ROUGHNESS, itr->second->getTextureView()); + drawMaterialTextures->setTexture(gr::Texture::MaterialRoughness, itr->second->getTextureView()); } else { - drawMaterialTextures->setTexture(ShapePipeline::Slot::ROUGHNESS, textureCache->getWhiteTexture()); + drawMaterialTextures->setTexture(gr::Texture::MaterialRoughness, textureCache->getWhiteTexture()); } } @@ -431,9 +440,9 @@ void RenderPipelines::bindMaterial(const graphics::MaterialPointer& material, gp if (materialKey.isNormalMap()) { auto itr = textureMaps.find(graphics::MaterialKey::NORMAL_MAP); if (enableTextures && itr != textureMaps.end() && itr->second->isDefined()) { - drawMaterialTextures->setTexture(ShapePipeline::Slot::NORMAL, itr->second->getTextureView()); + drawMaterialTextures->setTexture(gr::Texture::MaterialNormal, itr->second->getTextureView()); } else { - drawMaterialTextures->setTexture(ShapePipeline::Slot::NORMAL, textureCache->getBlueTexture()); + drawMaterialTextures->setTexture(gr::Texture::MaterialNormal, textureCache->getBlueTexture()); } } @@ -441,9 +450,9 @@ void RenderPipelines::bindMaterial(const graphics::MaterialPointer& material, gp if (materialKey.isMetallicMap()) { auto itr = textureMaps.find(graphics::MaterialKey::METALLIC_MAP); if (enableTextures && itr != textureMaps.end() && itr->second->isDefined()) { - drawMaterialTextures->setTexture(ShapePipeline::Slot::METALLIC, itr->second->getTextureView()); + drawMaterialTextures->setTexture(gr::Texture::MaterialMetallic, itr->second->getTextureView()); } else { - drawMaterialTextures->setTexture(ShapePipeline::Slot::METALLIC, textureCache->getBlackTexture()); + drawMaterialTextures->setTexture(gr::Texture::MaterialMetallic, textureCache->getBlackTexture()); } } @@ -451,9 +460,9 @@ void RenderPipelines::bindMaterial(const graphics::MaterialPointer& material, gp if (materialKey.isOcclusionMap()) { auto itr = textureMaps.find(graphics::MaterialKey::OCCLUSION_MAP); if (enableTextures && itr != textureMaps.end() && itr->second->isDefined()) { - drawMaterialTextures->setTexture(ShapePipeline::Slot::OCCLUSION, itr->second->getTextureView()); + drawMaterialTextures->setTexture(gr::Texture::MaterialOcclusion, itr->second->getTextureView()); } else { - drawMaterialTextures->setTexture(ShapePipeline::Slot::OCCLUSION, textureCache->getWhiteTexture()); + drawMaterialTextures->setTexture(gr::Texture::MaterialOcclusion, textureCache->getWhiteTexture()); } } @@ -461,9 +470,9 @@ void RenderPipelines::bindMaterial(const graphics::MaterialPointer& material, gp if (materialKey.isScatteringMap()) { auto itr = textureMaps.find(graphics::MaterialKey::SCATTERING_MAP); if (enableTextures && itr != textureMaps.end() && itr->second->isDefined()) { - drawMaterialTextures->setTexture(ShapePipeline::Slot::SCATTERING, itr->second->getTextureView()); + drawMaterialTextures->setTexture(gr::Texture::MaterialScattering, itr->second->getTextureView()); } else { - drawMaterialTextures->setTexture(ShapePipeline::Slot::SCATTERING, textureCache->getWhiteTexture()); + drawMaterialTextures->setTexture(gr::Texture::MaterialScattering, textureCache->getWhiteTexture()); } } @@ -472,16 +481,16 @@ void RenderPipelines::bindMaterial(const graphics::MaterialPointer& material, gp auto itr = textureMaps.find(graphics::MaterialKey::LIGHTMAP_MAP); if (enableTextures && itr != textureMaps.end() && itr->second->isDefined()) { - drawMaterialTextures->setTexture(ShapePipeline::Slot::EMISSIVE_LIGHTMAP, itr->second->getTextureView()); + drawMaterialTextures->setTexture(gr::Texture::MaterialEmissiveLightmap, itr->second->getTextureView()); } else { - drawMaterialTextures->setTexture(ShapePipeline::Slot::EMISSIVE_LIGHTMAP, textureCache->getGrayTexture()); + drawMaterialTextures->setTexture(gr::Texture::MaterialEmissiveLightmap, textureCache->getGrayTexture()); } } else if (materialKey.isEmissiveMap()) { auto itr = textureMaps.find(graphics::MaterialKey::EMISSIVE_MAP); if (enableTextures && itr != textureMaps.end() && itr->second->isDefined()) { - drawMaterialTextures->setTexture(ShapePipeline::Slot::EMISSIVE_LIGHTMAP, itr->second->getTextureView()); + drawMaterialTextures->setTexture(gr::Texture::MaterialEmissiveLightmap, itr->second->getTextureView()); } else { - drawMaterialTextures->setTexture(ShapePipeline::Slot::EMISSIVE_LIGHTMAP, textureCache->getBlackTexture()); + drawMaterialTextures->setTexture(gr::Texture::MaterialEmissiveLightmap, textureCache->getBlackTexture()); } } diff --git a/libraries/render-utils/src/ShadingModel.slh b/libraries/render-utils/src/ShadingModel.slh new file mode 100644 index 0000000000..6b0b7bca18 --- /dev/null +++ b/libraries/render-utils/src/ShadingModel.slh @@ -0,0 +1,237 @@ + +<@if not SHADING_MODEL_SLH@> +<@def SHADING_MODEL_SLH@> + +<@include LightingModel.slh@> + +<@func declareBeckmannSpecular()@> + +layout(binding=RENDER_UTILS_TEXTURE_SSSC_SPECULAR_BECKMANN) uniform sampler2D scatteringSpecularBeckmann; + +float fetchSpecularBeckmann(float ndoth, float roughness) { + return pow(2.0 * texture(scatteringSpecularBeckmann, vec2(ndoth, roughness)).r, 10.0); +} + +vec2 skinSpecular(SurfaceData surface, float intensity) { + vec2 result = vec2(0.0, 1.0); + if (surface.ndotl > 0.0) { + float PH = fetchSpecularBeckmann(surface.ndoth, surface.roughness); + float F = fresnelSchlickScalar(0.028, surface); + float frSpec = max(PH * F / dot(surface.halfDir, surface.halfDir), 0.0); + result.x = surface.ndotl * intensity * frSpec; + result.y -= F; + } + + return result; +} +<@endfunc@> + +<@func declareEvalPBRShading()@> + +float evalSmithInvG1(float roughness4, float ndotd) { + return ndotd + sqrt(roughness4+ndotd*ndotd*(1.0-roughness4)); +} + +SurfaceData initSurfaceData(float roughness, vec3 normal, vec3 eyeDir) { + SurfaceData surface; + surface.eyeDir = eyeDir; + surface.normal = normal; + surface.roughness = mix(0.01, 1.0, roughness); + surface.roughness2 = surface.roughness * surface.roughness; + surface.roughness4 = surface.roughness2 * surface.roughness2; + surface.ndotv = clamp(dot(normal, eyeDir), 0.0, 1.0); + surface.smithInvG1NdotV = evalSmithInvG1(surface.roughness4, surface.ndotv); + + // These values will be set when we know the light direction, in updateSurfaceDataWithLight + surface.ndoth = 0.0; + surface.ndotl = 0.0; + surface.ldoth = 0.0; + surface.lightDir = vec3(0,0,1); + surface.halfDir = vec3(0,0,1); + + return surface; +} + +void updateSurfaceDataWithLight(inout SurfaceData surface, vec3 lightDir) { + surface.lightDir = lightDir; + surface.halfDir = normalize(surface.eyeDir + lightDir); + vec3 dots; + dots.x = dot(surface.normal, surface.halfDir); + dots.y = dot(surface.normal, surface.lightDir); + dots.z = dot(surface.halfDir, surface.lightDir); + dots = clamp(dots, vec3(0), vec3(1)); + surface.ndoth = dots.x; + surface.ndotl = dots.y; + surface.ldoth = dots.z; +} + +vec3 fresnelSchlickColor(vec3 fresnelColor, SurfaceData surface) { + float base = 1.0 - surface.ldoth; + //float exponential = pow(base, 5.0); + float base2 = base * base; + float exponential = base * base2 * base2; + return vec3(exponential) + fresnelColor * (1.0 - exponential); +} + +float fresnelSchlickScalar(float fresnelScalar, SurfaceData surface) { + float base = 1.0 - surface.ldoth; + //float exponential = pow(base, 5.0); + float base2 = base * base; + float exponential = base * base2 * base2; + return (exponential) + fresnelScalar * (1.0 - exponential); +} + +float specularDistribution(SurfaceData surface) { + // See https://www.khronos.org/assets/uploads/developers/library/2017-web3d/glTF-2.0-Launch_Jun17.pdf + // for details of equations, especially page 20 + float denom = (surface.ndoth*surface.ndoth * (surface.roughness4 - 1.0) + 1.0); + denom *= denom; + // Add geometric factors G1(n,l) and G1(n,v) + float smithInvG1NdotL = evalSmithInvG1(surface.roughness4, surface.ndotl); + denom *= surface.smithInvG1NdotV * smithInvG1NdotL; + // Don't divide by PI as this is part of the light normalization factor + float power = surface.roughness4 / denom; + return power; +} + +// Frag Shading returns the diffuse amount as W and the specular rgb as xyz +vec4 evalPBRShading(float metallic, vec3 fresnel, SurfaceData surface) { + // Incident angle attenuation + float angleAttenuation = surface.ndotl; + + // Specular Lighting + vec3 fresnelColor = fresnelSchlickColor(fresnel, surface); + float power = specularDistribution(surface); + vec3 specular = fresnelColor * power * angleAttenuation; + float diffuse = (1.0 - metallic) * angleAttenuation * (1.0 - fresnelColor.x); + + // We don't divided by PI, as the "normalized" equations state we should, because we decide, as Naty Hoffman, that + // we wish to have a similar color as raw albedo on a perfectly diffuse surface perpendicularly lit + // by a white light of intensity 1. But this is an arbitrary normalization of what light intensity "means". + // (see http://blog.selfshadow.com/publications/s2013-shading-course/hoffman/s2013_pbs_physics_math_notes.pdf + // page 23 paragraph "Punctual light sources") + return vec4(specular, diffuse); +} + +// Frag Shading returns the diffuse amount as W and the specular rgb as xyz +vec4 evalPBRShadingDielectric(SurfaceData surface, float fresnel) { + // Incident angle attenuation + float angleAttenuation = surface.ndotl; + + // Specular Lighting + float fresnelScalar = fresnelSchlickScalar(fresnel, surface); + float power = specularDistribution(surface); + vec3 specular = vec3(fresnelScalar) * power * angleAttenuation; + float diffuse = angleAttenuation * (1.0 - fresnelScalar); + + // We don't divided by PI, as the "normalized" equations state we should, because we decide, as Naty Hoffman, that + // we wish to have a similar color as raw albedo on a perfectly diffuse surface perpendicularly lit + // by a white light of intensity 1. But this is an arbitrary normalization of what light intensity "means". + // (see http://blog.selfshadow.com/publications/s2013-shading-course/hoffman/s2013_pbs_physics_math_notes.pdf + // page 23 paragraph "Punctual light sources") + return vec4(specular, diffuse); +} + +vec4 evalPBRShadingMetallic(SurfaceData surface, vec3 fresnel) { + // Incident angle attenuation + float angleAttenuation = surface.ndotl; + + // Specular Lighting + vec3 fresnelColor = fresnelSchlickColor(fresnel, surface); + float power = specularDistribution(surface); + vec3 specular = fresnelColor * power * angleAttenuation; + + // We don't divided by PI, as the "normalized" equations state we should, because we decide, as Naty Hoffman, that + // we wish to have a similar color as raw albedo on a perfectly diffuse surface perpendicularly lit + // by a white light of intensity 1. But this is an arbitrary normalization of what light intensity "means". + // (see http://blog.selfshadow.com/publications/s2013-shading-course/hoffman/s2013_pbs_physics_math_notes.pdf + // page 23 paragraph "Punctual light sources") + return vec4(specular, 0.f); +} + +<@endfunc@> + + + +<$declareEvalPBRShading()$> + +void evalFragShading(out vec3 diffuse, out vec3 specular, + float metallic, vec3 fresnel, SurfaceData surface, vec3 albedo) { + vec4 shading = evalPBRShading(metallic, fresnel, surface); + diffuse = vec3(shading.w); + diffuse *= mix(vec3(1.0), albedo, isAlbedoEnabled()); + specular = shading.xyz; +} + +<$declareBeckmannSpecular()$> +<@include SubsurfaceScattering.slh@> +<$declareSubsurfaceScatteringBRDF()$> + + +void evalFragShading(out vec3 diffuse, out vec3 specular, + float metallic, vec3 fresnel, SurfaceData surface, vec3 albedo, + float scattering, vec4 midNormalCurvature, vec4 lowNormalCurvature) { + if (scattering * isScatteringEnabled() > 0.0) { + vec3 brdf = evalSkinBRDF(surface.lightDir, surface.normal, midNormalCurvature.xyz, lowNormalCurvature.xyz, lowNormalCurvature.w); + diffuse = mix(vec3(surface.ndotl), brdf, scattering); + + // Specular Lighting + vec2 specularBrdf = skinSpecular(surface, 1.0); + + diffuse *= specularBrdf.y; + specular = vec3(specularBrdf.x); + } else { + vec4 shading = evalPBRShading(metallic, fresnel, surface); + diffuse = vec3(shading.w); + specular = shading.xyz; + } + diffuse *= mix(vec3(1.0), albedo, isAlbedoEnabled()); +} + + +void evalFragShadingScattering(out vec3 diffuse, out vec3 specular, + float metallic, vec3 fresnel, SurfaceData surface, vec3 albedo, + float scattering, vec4 midNormalCurvature, vec4 lowNormalCurvature) { + vec3 brdf = evalSkinBRDF(surface.lightDir, surface.normal, midNormalCurvature.xyz, lowNormalCurvature.xyz, lowNormalCurvature.w); + float NdotL = surface.ndotl; + diffuse = mix(vec3(NdotL), brdf, scattering); + + // Specular Lighting + vec2 specularBrdf = skinSpecular(surface, 1.0); + + diffuse *= specularBrdf.y; + specular = vec3(specularBrdf.x); + diffuse *= mix(vec3(1.0), albedo, isAlbedoEnabled()); +} + +void evalFragShadingGloss(out vec3 diffuse, out vec3 specular, + float metallic, vec3 fresnel, SurfaceData surface, vec3 albedo) { + vec4 shading = evalPBRShading(metallic, fresnel, surface); + diffuse = vec3(shading.w); + diffuse *= mix(vec3(1.0), albedo, isAlbedoEnabled()); + specular = shading.xyz; +} + +vec3 evalSpecularWithOpacity(vec3 specular, float opacity) { + return specular / opacity; +} + +<@if not GETFRESNEL0@> +<@def GETFRESNEL0@> +vec3 getFresnelF0(float metallic, vec3 metalF0) { + // Enable continuous metallness value by lerping between dielectric + // and metal fresnel F0 value based on the "metallic" parameter + return mix(vec3(0.03), metalF0, metallic); +} +<@endif@> + +<@endif@> diff --git a/libraries/render-utils/src/Shadow.slh b/libraries/render-utils/src/Shadow.slh index 235ea519ab..76d08c2c22 100644 --- a/libraries/render-utils/src/Shadow.slh +++ b/libraries/render-utils/src/Shadow.slh @@ -11,13 +11,14 @@ <@if not SHADOW_SLH@> <@def SHADOW_SLH@> +<@include render-utils/ShaderConstants.h@> <@include ShadowCore.slh@> #define SHADOW_NOISE_ENABLED 0 #define SHADOW_SCREEN_SPACE_DITHER 1 // the shadow texture -uniform sampler2DArrayShadow shadowMaps; +layout(binding=RENDER_UTILS_TEXTURE_SHADOW) uniform sampler2DArrayShadow shadowMaps; // Sample the shadowMap with PCF (built-in) float fetchShadow(int cascadeIndex, vec3 shadowTexcoord) { diff --git a/libraries/render-utils/src/ShadowCore.slh b/libraries/render-utils/src/ShadowCore.slh index a787c54ca0..28ef9a4831 100644 --- a/libraries/render-utils/src/ShadowCore.slh +++ b/libraries/render-utils/src/ShadowCore.slh @@ -13,7 +13,7 @@ <@include Shadows_shared.slh@> -layout(std140) uniform shadowTransformBuffer { +layout(std140, binding=RENDER_UTILS_BUFFER_SHADOW_PARAMS) uniform shadowTransformBuffer { ShadowParameters shadow; }; diff --git a/libraries/render-utils/src/Skinning.slh b/libraries/render-utils/src/Skinning.slh index fbfe6b7185..a35948f026 100644 --- a/libraries/render-utils/src/Skinning.slh +++ b/libraries/render-utils/src/Skinning.slh @@ -11,12 +11,14 @@ <@if not SKINNING_SLH@> <@def SKINNING_SLH@> +<@include graphics/ShaderConstants.h@> + const int MAX_CLUSTERS = 128; const int INDICES_PER_VERTEX = 4; <@func declareUseDualQuaternionSkinning(USE_DUAL_QUATERNION_SKINNING)@> -layout(std140) uniform skinClusterBuffer { +layout(std140, binding=GRAPHICS_BUFFER_SKINNING) uniform skinClusterBuffer { mat4 clusterMatrices[MAX_CLUSTERS]; }; diff --git a/libraries/render-utils/src/StencilMaskPass.cpp b/libraries/render-utils/src/StencilMaskPass.cpp index 08fe1bf35a..556e305fac 100644 --- a/libraries/render-utils/src/StencilMaskPass.cpp +++ b/libraries/render-utils/src/StencilMaskPass.cpp @@ -40,8 +40,6 @@ graphics::MeshPointer PrepareStencil::getMesh() { gpu::PipelinePointer PrepareStencil::getMeshStencilPipeline() { if (!_meshStencilPipeline) { auto program = gpu::Shader::createProgram(shader::gpu::program::drawNothing); - gpu::Shader::makeProgram((*program)); - auto state = std::make_shared(); drawMask(*state); state->setColorWriteMask(0); @@ -54,8 +52,6 @@ gpu::PipelinePointer PrepareStencil::getMeshStencilPipeline() { gpu::PipelinePointer PrepareStencil::getPaintStencilPipeline() { if (!_paintStencilPipeline) { auto program = gpu::Shader::createProgram(shader::render_utils::program::stencil_drawMask); - gpu::Shader::makeProgram((*program)); - auto state = std::make_shared(); drawMask(*state); state->setColorWriteMask(0); @@ -143,4 +139,4 @@ void PrepareStencil::testMaskDrawShape(gpu::State& state) { void PrepareStencil::testMaskDrawShapeNoAA(gpu::State& state) { state.setStencilTest(true, STENCIL_SHAPE | STENCIL_NO_AA, gpu::State::StencilTest(STENCIL_MASK | STENCIL_SHAPE | STENCIL_NO_AA, STENCIL_MASK, gpu::NOT_EQUAL, gpu::State::STENCIL_OP_KEEP, gpu::State::STENCIL_OP_KEEP, gpu::State::STENCIL_OP_REPLACE)); -} \ No newline at end of file +} diff --git a/libraries/render-utils/src/SubsurfaceScattering.cpp b/libraries/render-utils/src/SubsurfaceScattering.cpp index 2c27569269..84b51d626a 100644 --- a/libraries/render-utils/src/SubsurfaceScattering.cpp +++ b/libraries/render-utils/src/SubsurfaceScattering.cpp @@ -12,29 +12,26 @@ #include #include +#include +#include + +#include "render-utils/ShaderConstants.h" #include "FramebufferCache.h" #include "DeferredLightingEffect.h" -enum ScatteringShaderBufferSlots { - ScatteringTask_FrameTransformSlot = 0, - ScatteringTask_ParamSlot, - ScatteringTask_LightSlot, -}; -enum ScatteringShaderMapSlots { - ScatteringTask_ScatteringTableSlot = 0, - ScatteringTask_CurvatureMapSlot, - ScatteringTask_DiffusedCurvatureMapSlot, - ScatteringTask_NormalMapSlot, +namespace ru { + using render_utils::slot::texture::Texture; + using render_utils::slot::buffer::Buffer; +} - ScatteringTask_AlbedoMapSlot, - ScatteringTask_LinearMapSlot, - - ScatteringTask_IBLMapSlot, +namespace gr { + using graphics::slot::texture::Texture; + using graphics::slot::buffer::Buffer; +} -}; SubsurfaceScatteringResource::SubsurfaceScatteringResource() { Parameters parameters; @@ -342,15 +339,7 @@ void diffuseScatterGPU(const gpu::TexturePointer& profileMap, gpu::TexturePointe gpu::doInBatch("SubsurfaceScattering::diffuseScatterGPU", args->_context, [=](gpu::Batch& batch) { batch.enableStereo(false); - - batch.runLambda([program] (){ - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("scatteringProfile"), 0)); - gpu::Shader::makeProgram(*program, slotBindings); - }); - batch.setViewportTransform(glm::ivec4(0, 0, width, height)); - batch.setFramebuffer(makeFramebuffer); batch.setPipeline(makePipeline); batch.setResourceTexture(0, profileMap); @@ -439,24 +428,6 @@ void DebugSubsurfaceScattering::configure(const Config& config) { gpu::PipelinePointer DebugSubsurfaceScattering::getScatteringPipeline() { if (!_scatteringPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::subsurfaceScattering_drawScattering); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), ScatteringTask_FrameTransformSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("scatteringParamsBuffer"), ScatteringTask_ParamSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("keyLightBuffer"), ScatteringTask_LightSlot)); - - slotBindings.insert(gpu::Shader::Binding(std::string("scatteringLUT"), ScatteringTask_ScatteringTableSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("curvatureMap"), ScatteringTask_CurvatureMapSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("diffusedCurvatureMap"), ScatteringTask_DiffusedCurvatureMapSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("normalMap"), ScatteringTask_NormalMapSlot)); - - slotBindings.insert(gpu::Shader::Binding(std::string("albedoMap"), ScatteringTask_AlbedoMapSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("linearDepthMap"), ScatteringTask_LinearMapSlot)); - - slotBindings.insert(gpu::Shader::Binding(std::string("skyboxMap"), ScatteringTask_IBLMapSlot)); - - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); _scatteringPipeline = gpu::Pipeline::create(program, state); @@ -539,20 +510,20 @@ void DebugSubsurfaceScattering::run(const render::RenderContextPointer& renderCo model.setScale(glm::vec3(viewportSize / (float)args->_viewport.z, viewportSize / (float)args->_viewport.w, 1.0)); batch.setModelTransform(model); - batch.setUniformBuffer(ScatteringTask_FrameTransformSlot, frameTransform->getFrameTransformBuffer()); - batch.setUniformBuffer(ScatteringTask_ParamSlot, scatteringResource->getParametersBuffer()); + batch.setUniformBuffer(ru::Buffer::DeferredFrameTransform, frameTransform->getFrameTransformBuffer()); + batch.setUniformBuffer(ru::Buffer::SsscParams, scatteringResource->getParametersBuffer()); if (light) { - batch.setUniformBuffer(ScatteringTask_LightSlot, light->getLightSchemaBuffer()); + batch.setUniformBuffer(gr::Buffer::Light, light->getLightSchemaBuffer()); } - batch.setResourceTexture(ScatteringTask_ScatteringTableSlot, scatteringTable); - batch.setResourceTexture(ScatteringTask_CurvatureMapSlot, curvatureFramebuffer->getRenderBuffer(0)); - batch.setResourceTexture(ScatteringTask_DiffusedCurvatureMapSlot, diffusedFramebuffer->getRenderBuffer(0)); - batch.setResourceTexture(ScatteringTask_NormalMapSlot, deferredFramebuffer->getDeferredNormalTexture()); - batch.setResourceTexture(ScatteringTask_AlbedoMapSlot, deferredFramebuffer->getDeferredColorTexture()); - batch.setResourceTexture(ScatteringTask_LinearMapSlot, linearDepthTexture); + batch.setResourceTexture(ru::Texture::SsscLut, scatteringTable); + batch.setResourceTexture(ru::Texture::DeferredCurvature, curvatureFramebuffer->getRenderBuffer(0)); + batch.setResourceTexture(ru::Texture::DeferredDiffusedCurvature, diffusedFramebuffer->getRenderBuffer(0)); + batch.setResourceTexture(ru::Texture::DeferredNormal, deferredFramebuffer->getDeferredNormalTexture()); + batch.setResourceTexture(ru::Texture::DeferredColor, deferredFramebuffer->getDeferredColorTexture()); + batch.setResourceTexture(ru::Texture::DeferredDepth, linearDepthTexture); - batch._glUniform2f(debugScatteringPipeline->getProgram()->getUniforms().findLocation("uniformCursorTexcoord"), _debugCursorTexcoord.x, _debugCursorTexcoord.y); + batch._glUniform2f(gpu::slot::uniform::Extra0, _debugCursorTexcoord.x, _debugCursorTexcoord.y); batch.draw(gpu::TRIANGLE_STRIP, 4); } } diff --git a/libraries/render-utils/src/SubsurfaceScattering.slh b/libraries/render-utils/src/SubsurfaceScattering.slh index 233dfd7a0c..3d37f52e4d 100644 --- a/libraries/render-utils/src/SubsurfaceScattering.slh +++ b/libraries/render-utils/src/SubsurfaceScattering.slh @@ -9,6 +9,8 @@ <@if not SUBSURFACE_SCATTERING_SLH@> <@def SUBSURFACE_SCATTERING_SLH@> +<@include render-utils/ShaderConstants.h@> + <@func declareSubsurfaceScatteringProfileSource()@> float gaussian(float v, float r) { @@ -54,7 +56,7 @@ vec3 generateProfile(vec2 uv) { <@func declareSubsurfaceScatteringProfileMap()@> -uniform sampler2D scatteringProfile; +layout(binding=RENDER_UTILS_TEXTURE_SSSC_PROFILE) uniform sampler2D scatteringProfile; vec3 scatter(float r) { return texture(scatteringProfile, vec2(r * 0.5, 0.5)).rgb; @@ -102,7 +104,7 @@ vec3 integrate(float cosTheta, float skinRadius) { <@func declareSubsurfaceScatteringResource()@> -uniform sampler2D scatteringLUT; +layout(binding=RENDER_UTILS_TEXTURE_SSSC_LUT) uniform sampler2D scatteringLUT; vec3 fetchBRDF(float LdotN, float curvature) { return texture(scatteringLUT, vec2( clamp(LdotN * 0.5 + 0.5, 0.0, 1.0), clamp(2.0 * curvature, 0.0, 1.0))).xyz; @@ -122,7 +124,7 @@ struct ScatteringParameters { vec4 debugFlags; }; -uniform subsurfaceScatteringParametersBuffer { +layout(binding=RENDER_UTILS_BUFFER_SSSC_PARAMS) uniform subsurfaceScatteringParametersBuffer { ScatteringParameters parameters; }; diff --git a/libraries/render-utils/src/SurfaceGeometryPass.cpp b/libraries/render-utils/src/SurfaceGeometryPass.cpp index fd0200b369..d32cba43db 100644 --- a/libraries/render-utils/src/SurfaceGeometryPass.cpp +++ b/libraries/render-utils/src/SurfaceGeometryPass.cpp @@ -17,19 +17,17 @@ #include "StencilMaskPass.h" -const int DepthLinearPass_FrameTransformSlot = 0; -const int DepthLinearPass_DepthMapSlot = 0; -const int DepthLinearPass_NormalMapSlot = 1; +#include "render-utils/ShaderConstants.h" + +namespace ru { + using render_utils::slot::texture::Texture; + using render_utils::slot::buffer::Buffer; +} -const int SurfaceGeometryPass_FrameTransformSlot = 0; -const int SurfaceGeometryPass_ParamsSlot = 1; -const int SurfaceGeometryPass_DepthMapSlot = 0; -const int SurfaceGeometryPass_NormalMapSlot = 1; LinearDepthFramebuffer::LinearDepthFramebuffer() { } - void LinearDepthFramebuffer::updatePrimaryDepth(const gpu::TexturePointer& depthBuffer) { //If the depth buffer or size changed, we need to delete our FBOs bool reset = false; @@ -177,21 +175,21 @@ void LinearDepthPass::run(const render::RenderContextPointer& renderContext, con batch.resetViewTransform(); batch.setModelTransform(gpu::Framebuffer::evalSubregionTexcoordTransform(_linearDepthFramebuffer->getDepthFrameSize(), depthViewport)); - batch.setUniformBuffer(DepthLinearPass_FrameTransformSlot, frameTransform->getFrameTransformBuffer()); + batch.setUniformBuffer(ru::Buffer::DeferredFrameTransform, frameTransform->getFrameTransformBuffer()); // LinearDepth batch.setFramebuffer(linearDepthFBO); batch.clearColorFramebuffer(gpu::Framebuffer::BUFFER_COLOR0, glm::vec4(clearLinearDepth, 0.0f, 0.0f, 0.0f)); batch.setPipeline(linearDepthPipeline); - batch.setResourceTexture(DepthLinearPass_DepthMapSlot, depthBuffer); + batch.setResourceTexture(ru::Texture::SurfaceGeometryDepth, depthBuffer); batch.draw(gpu::TRIANGLE_STRIP, 4); // Downsample batch.setViewportTransform(halfViewport); batch.setFramebuffer(downsampleFBO); - batch.setResourceTexture(DepthLinearPass_DepthMapSlot, linearDepthTexture); - batch.setResourceTexture(DepthLinearPass_NormalMapSlot, normalTexture); + batch.setResourceTexture(ru::Texture::SurfaceGeometryDepth, linearDepthTexture); + batch.setResourceTexture(ru::Texture::SurfaceGeometryNormal, normalTexture); batch.setPipeline(downsamplePipeline); batch.draw(gpu::TRIANGLE_STRIP, 4); @@ -217,15 +215,6 @@ const gpu::PipelinePointer& LinearDepthPass::getLinearDepthPipeline(const render // Good to go add the brand new pipeline _linearDepthPipeline = gpu::Pipeline::create(program, state); - - gpu::doInBatch("LinearDepthPass::run", renderContext->args->_context, [program](gpu::Batch& batch) { - batch.runLambda([program]() { - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), DepthLinearPass_FrameTransformSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("depthMap"), DepthLinearPass_DepthMapSlot)); - gpu::Shader::makeProgram(*program, slotBindings); - }); - }); } @@ -244,16 +233,6 @@ const gpu::PipelinePointer& LinearDepthPass::getDownsamplePipeline(const render: // Good to go add the brand new pipeline _downsamplePipeline = gpu::Pipeline::create(program, state); - - gpu::doInBatch("LinearDepthPass::run", renderContext->args->_context, [program](gpu::Batch& batch) { - batch.runLambda([program]() { - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding("deferredFrameTransformBuffer", DepthLinearPass_FrameTransformSlot)); - slotBindings.insert(gpu::Shader::Binding("linearDepthMap", DepthLinearPass_DepthMapSlot)); - slotBindings.insert(gpu::Shader::Binding("normalMap", DepthLinearPass_NormalMapSlot)); - gpu::Shader::makeProgram(*program, slotBindings); - }); - }); } return _downsamplePipeline; @@ -475,8 +454,8 @@ void SurfaceGeometryPass::run(const render::RenderContextPointer& renderContext, batch.setModelTransform(gpu::Framebuffer::evalSubregionTexcoordTransform(_surfaceGeometryFramebuffer->getSourceFrameSize(), curvatureViewport)); // Curvature pass - batch.setUniformBuffer(SurfaceGeometryPass_FrameTransformSlot, frameTransform->getFrameTransformBuffer()); - batch.setUniformBuffer(SurfaceGeometryPass_ParamsSlot, _parametersBuffer); + batch.setUniformBuffer(ru::Buffer::DeferredFrameTransform, frameTransform->getFrameTransformBuffer()); + batch.setUniformBuffer(ru::Buffer::SurfaceGeometryParams, _parametersBuffer); batch.setFramebuffer(curvatureFramebuffer); // We can avoid the clear by drawing the same clear vallue from the makeCurvature shader. same performances or no worse #ifdef USE_STENCIL_TEST @@ -484,47 +463,44 @@ void SurfaceGeometryPass::run(const render::RenderContextPointer& renderContext, batch.clearColorFramebuffer(gpu::Framebuffer::BUFFER_COLOR0, glm::vec4(0.0)); #endif batch.setPipeline(curvaturePipeline); - batch.setResourceTexture(SurfaceGeometryPass_DepthMapSlot, linearDepthTexture); - batch.setResourceTexture(SurfaceGeometryPass_NormalMapSlot, normalTexture); + batch.setResourceTexture(ru::Texture::SurfaceGeometryDepth, linearDepthTexture); + batch.setResourceTexture(ru::Texture::SurfaceGeometryNormal, normalTexture); batch.draw(gpu::TRIANGLE_STRIP, 4); - batch.setResourceTexture(SurfaceGeometryPass_DepthMapSlot, nullptr); - batch.setResourceTexture(SurfaceGeometryPass_NormalMapSlot, nullptr); - batch.setUniformBuffer(SurfaceGeometryPass_ParamsSlot, nullptr); - batch.setUniformBuffer(SurfaceGeometryPass_FrameTransformSlot, nullptr); + batch.setResourceTexture(ru::Texture::SurfaceGeometryDepth, nullptr); + batch.setResourceTexture(ru::Texture::SurfaceGeometryNormal, nullptr); + batch.setUniformBuffer(ru::Buffer::SurfaceGeometryParams, nullptr); + batch.setUniformBuffer(ru::Buffer::DeferredFrameTransform, nullptr); // Diffusion pass - const int BlurTask_ParamsSlot = 0; - const int BlurTask_SourceSlot = 0; - const int BlurTask_DepthSlot = 1; - batch.setUniformBuffer(BlurTask_ParamsSlot, _diffusePass.getParameters()->_parametersBuffer); + batch.setUniformBuffer(ru::Buffer::BlurParams, _diffusePass.getParameters()->_parametersBuffer); - batch.setResourceTexture(BlurTask_DepthSlot, linearDepthTexture); + batch.setResourceTexture(ru::Texture::BlurDepth, linearDepthTexture); batch.setFramebuffer(blurringFramebuffer); batch.setPipeline(diffuseVPipeline); - batch.setResourceTexture(BlurTask_SourceSlot, curvatureTexture); + batch.setResourceTexture(ru::Texture::BlurSource, curvatureTexture); batch.draw(gpu::TRIANGLE_STRIP, 4); batch.setFramebuffer(curvatureFramebuffer); batch.setPipeline(diffuseHPipeline); - batch.setResourceTexture(BlurTask_SourceSlot, blurringTexture); + batch.setResourceTexture(ru::Texture::BlurSource, blurringTexture); batch.draw(gpu::TRIANGLE_STRIP, 4); batch.setFramebuffer(blurringFramebuffer); batch.setPipeline(diffuseVPipeline); - batch.setResourceTexture(BlurTask_SourceSlot, curvatureTexture); + batch.setResourceTexture(ru::Texture::BlurSource, curvatureTexture); batch.draw(gpu::TRIANGLE_STRIP, 4); batch.setFramebuffer(lowCurvatureFramebuffer); batch.setPipeline(diffuseHPipeline); - batch.setResourceTexture(BlurTask_SourceSlot, blurringTexture); + batch.setResourceTexture(ru::Texture::BlurSource, blurringTexture); batch.draw(gpu::TRIANGLE_STRIP, 4); - batch.setResourceTexture(BlurTask_SourceSlot, nullptr); - batch.setResourceTexture(BlurTask_DepthSlot, nullptr); - batch.setUniformBuffer(BlurTask_ParamsSlot, nullptr); + batch.setResourceTexture(ru::Texture::BlurSource, nullptr); + batch.setResourceTexture(ru::Texture::BlurDepth, nullptr); + batch.setUniformBuffer(ru::Buffer::BlurParams, nullptr); _gpuTimer->end(batch); }); @@ -546,17 +522,6 @@ const gpu::PipelinePointer& SurfaceGeometryPass::getCurvaturePipeline(const rend #endif // Good to go add the brand new pipeline _curvaturePipeline = gpu::Pipeline::create(program, state); - - gpu::doInBatch("SurfaceGeometryPass::CurvaturePipeline", renderContext->args->_context, [program](gpu::Batch& batch) { - batch.runLambda([program]() { - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), SurfaceGeometryPass_FrameTransformSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("surfaceGeometryParamsBuffer"), SurfaceGeometryPass_ParamsSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("depthMap"), SurfaceGeometryPass_DepthMapSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("normalMap"), SurfaceGeometryPass_NormalMapSlot)); - gpu::Shader::makeProgram(*program, slotBindings); - }); - }); } return _curvaturePipeline; diff --git a/libraries/render-utils/src/ToneMappingEffect.cpp b/libraries/render-utils/src/ToneMappingEffect.cpp index 5403f3e2f8..d192266d7e 100644 --- a/libraries/render-utils/src/ToneMappingEffect.cpp +++ b/libraries/render-utils/src/ToneMappingEffect.cpp @@ -14,13 +14,11 @@ #include #include +#include "render-utils/ShaderConstants.h" #include "StencilMaskPass.h" #include "FramebufferCache.h" -const int ToneMappingEffect_ParamsSlot = 0; -const int ToneMappingEffect_LightingMapSlot = 0; - ToneMappingEffect::ToneMappingEffect() { Parameters parameters; _parametersBuffer = gpu::BufferView(std::make_shared(sizeof(Parameters), (const gpu::Byte*) ¶meters)); @@ -32,15 +30,6 @@ void ToneMappingEffect::init(RenderArgs* args) { auto blitState = std::make_shared(); blitState->setColorWriteMask(true, true, true, true); _blitLightBuffer = gpu::PipelinePointer(gpu::Pipeline::create(blitProgram, blitState)); - - gpu::doInBatch("ToneMappingEffect::toneMapping", args->_context, [blitProgram](gpu::Batch& batch) { - batch.runLambda([blitProgram]() { - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("toneMappingParamsBuffer"), ToneMappingEffect_ParamsSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("colorMap"), ToneMappingEffect_LightingMapSlot)); - gpu::Shader::makeProgram(*blitProgram, slotBindings); - }); - }); } void ToneMappingEffect::setExposure(float exposure) { @@ -82,8 +71,8 @@ void ToneMappingEffect::render(RenderArgs* args, const gpu::TexturePointer& ligh batch.setModelTransform(gpu::Framebuffer::evalSubregionTexcoordTransform(framebufferSize, args->_viewport)); batch.setPipeline(_blitLightBuffer); - batch.setUniformBuffer(ToneMappingEffect_ParamsSlot, _parametersBuffer); - batch.setResourceTexture(ToneMappingEffect_LightingMapSlot, lightingBuffer); + batch.setUniformBuffer(render_utils::slot::buffer::ToneMappingParams, _parametersBuffer); + batch.setResourceTexture(render_utils::slot::texture::ToneMappingColor, lightingBuffer); batch.draw(gpu::TRIANGLE_STRIP, 4); }); } diff --git a/libraries/render-utils/src/VelocityBufferPass.cpp b/libraries/render-utils/src/VelocityBufferPass.cpp index 1431316aed..5833089967 100644 --- a/libraries/render-utils/src/VelocityBufferPass.cpp +++ b/libraries/render-utils/src/VelocityBufferPass.cpp @@ -16,9 +16,12 @@ #include #include "StencilMaskPass.h" +#include "render-utils/ShaderConstants.h" -const int VelocityBufferPass_FrameTransformSlot = 0; -const int VelocityBufferPass_DepthMapSlot = 0; +namespace ru { + using render_utils::slot::texture::Texture; + using render_utils::slot::buffer::Buffer; +} VelocityFramebuffer::VelocityFramebuffer() { } @@ -124,13 +127,13 @@ void VelocityBufferPass::run(const render::RenderContextPointer& renderContext, batch.resetViewTransform(); batch.setModelTransform(gpu::Framebuffer::evalSubregionTexcoordTransform(_velocityFramebuffer->getDepthFrameSize(), fullViewport)); - batch.setUniformBuffer(VelocityBufferPass_FrameTransformSlot, frameTransform->getFrameTransformBuffer()); + batch.setUniformBuffer(ru::Buffer::DeferredFrameTransform, frameTransform->getFrameTransformBuffer()); // Velocity buffer camera motion batch.setFramebuffer(velocityFBO); batch.clearColorFramebuffer(gpu::Framebuffer::BUFFER_COLOR0, glm::vec4(0.0f, 0.0f, 0.0f, 0.0f)); batch.setPipeline(cameraMotionPipeline); - batch.setResourceTexture(VelocityBufferPass_DepthMapSlot, depthBuffer); + batch.setResourceTexture(ru::Texture::TaaDepth, depthBuffer); batch.draw(gpu::TRIANGLE_STRIP, 4); _gpuTimer->end(batch); @@ -153,16 +156,6 @@ const gpu::PipelinePointer& VelocityBufferPass::getCameraMotionPipeline(const re // Good to go add the brand new pipeline _cameraMotionPipeline = gpu::Pipeline::create(program, state); - - gpu::doInBatch("VelocityBufferPass::CameraMotionPipeline", renderContext->args->_context, - [program](gpu::Batch& batch) { - batch.runLambda([program]() { - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), VelocityBufferPass_FrameTransformSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("depthMap"), VelocityBufferPass_DepthMapSlot)); - gpu::Shader::makeProgram(*program, slotBindings); - }); - }); } return _cameraMotionPipeline; diff --git a/libraries/render-utils/src/ZoneRenderer.cpp b/libraries/render-utils/src/ZoneRenderer.cpp index fc0cccd9e3..3299b0c41c 100644 --- a/libraries/render-utils/src/ZoneRenderer.cpp +++ b/libraries/render-utils/src/ZoneRenderer.cpp @@ -15,10 +15,27 @@ #include #include #include +#include +#include #include "StencilMaskPass.h" #include "DeferredLightingEffect.h" + +#include "render-utils/ShaderConstants.h" +#include "StencilMaskPass.h" +#include "DeferredLightingEffect.h" + +namespace ru { + using render_utils::slot::texture::Texture; + using render_utils::slot::buffer::Buffer; +} + +namespace gr { + using graphics::slot::texture::Texture; + using graphics::slot::buffer::Buffer; +} + using namespace render; class SetupZones { @@ -72,13 +89,6 @@ void SetupZones::run(const RenderContextPointer& context, const Inputs& inputs) const gpu::PipelinePointer& DebugZoneLighting::getKeyLightPipeline() { if (!_keyLightPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::zone_drawKeyLight); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), ZONE_DEFERRED_TRANSFORM_BUFFER)); - slotBindings.insert(gpu::Shader::Binding(std::string("keyLightBuffer"), ZONE_KEYLIGHT_BUFFER)); - - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); PrepareStencil::testMask(*state); @@ -91,14 +101,6 @@ const gpu::PipelinePointer& DebugZoneLighting::getKeyLightPipeline() { const gpu::PipelinePointer& DebugZoneLighting::getAmbientPipeline() { if (!_ambientPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::zone_drawAmbient); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), ZONE_DEFERRED_TRANSFORM_BUFFER)); - slotBindings.insert(gpu::Shader::Binding(std::string("lightAmbientBuffer"), ZONE_AMBIENT_BUFFER)); - slotBindings.insert(gpu::Shader::Binding(std::string("skyboxMap"), ZONE_AMBIENT_MAP)); - - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); PrepareStencil::testMask(*state); @@ -110,14 +112,6 @@ const gpu::PipelinePointer& DebugZoneLighting::getAmbientPipeline() { const gpu::PipelinePointer& DebugZoneLighting::getBackgroundPipeline() { if (!_backgroundPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::zone_drawSkybox); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("deferredFrameTransformBuffer"), ZONE_DEFERRED_TRANSFORM_BUFFER)); - slotBindings.insert(gpu::Shader::Binding(std::string("skyboxMap"), ZONE_SKYBOX_MAP)); - slotBindings.insert(gpu::Shader::Binding(std::string("skyboxBuffer"), ZONE_SKYBOX_BUFFER)); - - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); PrepareStencil::testMask(*state); @@ -168,7 +162,7 @@ void DebugZoneLighting::run(const render::RenderContextPointer& context, const I Transform model; - batch.setUniformBuffer(ZONE_DEFERRED_TRANSFORM_BUFFER, deferredTransform->getFrameTransformBuffer()); + batch.setUniformBuffer(ru::Buffer::DeferredFrameTransform, deferredTransform->getFrameTransformBuffer()); batch.setPipeline(getKeyLightPipeline()); auto numKeys = (int) keyLightStack.size(); @@ -176,7 +170,7 @@ void DebugZoneLighting::run(const render::RenderContextPointer& context, const I model.setTranslation(glm::vec3(-4.0, -3.0 + (i * 1.0), -10.0 - (i * 3.0))); batch.setModelTransform(model); if (keyLightStack[i]) { - batch.setUniformBuffer(ZONE_KEYLIGHT_BUFFER, keyLightStack[i]->getLightSchemaBuffer()); + batch.setUniformBuffer(gr::Buffer::KeyLight, keyLightStack[i]->getLightSchemaBuffer()); batch.draw(gpu::TRIANGLE_STRIP, 4); } } @@ -187,9 +181,9 @@ void DebugZoneLighting::run(const render::RenderContextPointer& context, const I model.setTranslation(glm::vec3(0.0, -3.0 + (i * 1.0), -10.0 - (i * 3.0))); batch.setModelTransform(model); if (ambientLightStack[i]) { - batch.setUniformBuffer(ZONE_AMBIENT_BUFFER, ambientLightStack[i]->getAmbientSchemaBuffer()); + batch.setUniformBuffer(gr::Buffer::AmbientLight, ambientLightStack[i]->getAmbientSchemaBuffer()); if (ambientLightStack[i]->getAmbientMap()) { - batch.setResourceTexture(ZONE_AMBIENT_MAP, ambientLightStack[i]->getAmbientMap()); + batch.setResourceTexture(ru::Texture::Skybox, ambientLightStack[i]->getAmbientMap()); } batch.draw(gpu::TRIANGLE_STRIP, 4); } @@ -201,8 +195,8 @@ void DebugZoneLighting::run(const render::RenderContextPointer& context, const I model.setTranslation(glm::vec3(4.0, -3.0 + (i * 1.0), -10.0 - (i * 3.0))); batch.setModelTransform(model); if (skyboxStack[i]) { - batch.setResourceTexture(ZONE_SKYBOX_MAP, skyboxStack[i]->getCubemap()); - batch.setUniformBuffer(ZONE_SKYBOX_BUFFER, skyboxStack[i]->getSchemaBuffer()); + batch.setResourceTexture(ru::Texture::Skybox, skyboxStack[i]->getCubemap()); + batch.setUniformBuffer(ru::Buffer::DebugSkyboxParams, skyboxStack[i]->getSchemaBuffer()); batch.draw(gpu::TRIANGLE_STRIP, 4); } } diff --git a/libraries/render-utils/src/ZoneRenderer.h b/libraries/render-utils/src/ZoneRenderer.h index 419db4ebe2..6e85243d1a 100644 --- a/libraries/render-utils/src/ZoneRenderer.h +++ b/libraries/render-utils/src/ZoneRenderer.h @@ -69,15 +69,6 @@ public: protected: - enum Slots { - ZONE_DEFERRED_TRANSFORM_BUFFER = 0, - ZONE_KEYLIGHT_BUFFER, - ZONE_AMBIENT_BUFFER, - ZONE_AMBIENT_MAP, - ZONE_SKYBOX_BUFFER, - ZONE_SKYBOX_MAP, - }; - gpu::PipelinePointer _keyLightPipeline; gpu::PipelinePointer _ambientPipeline; gpu::PipelinePointer _backgroundPipeline; diff --git a/libraries/render-utils/src/animdebugdraw.slf b/libraries/render-utils/src/animdebugdraw.slf index 8a3aca055e..1a4b8754b3 100644 --- a/libraries/render-utils/src/animdebugdraw.slf +++ b/libraries/render-utils/src/animdebugdraw.slf @@ -10,9 +10,11 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -in vec4 _color; +<@include render-utils/ShaderConstants.h@> -out vec4 _fragColor; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; + +layout(location=0) out vec4 _fragColor; void main(void) { _fragColor = _color; diff --git a/libraries/render-utils/src/animdebugdraw.slv b/libraries/render-utils/src/animdebugdraw.slv index 3255c6783c..ec4bdc9f52 100644 --- a/libraries/render-utils/src/animdebugdraw.slv +++ b/libraries/render-utils/src/animdebugdraw.slv @@ -13,7 +13,9 @@ <@include gpu/Transform.slh@> <$declareStandardTransform()$> -out vec4 _color; +<@include render-utils/ShaderConstants.h@> + +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; void main(void) { // pass along the color diff --git a/libraries/render-utils/src/debug_deferred_buffer.slf b/libraries/render-utils/src/debug_deferred_buffer.slf index 5f974acfeb..aee04cba90 100644 --- a/libraries/render-utils/src/debug_deferred_buffer.slf +++ b/libraries/render-utils/src/debug_deferred_buffer.slf @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// debug_deferred_buffer.slf +// debug_deferred_buffer.frag // fragment shader // // Created by Clement on 12/3 @@ -16,14 +16,14 @@ <@include gpu/Color.slh@> <$declareColorWheel()$> -uniform sampler2D linearDepthMap; -uniform sampler2D halfLinearDepthMap; -uniform sampler2D halfNormalMap; -uniform sampler2D occlusionMap; -uniform sampler2D occlusionBlurredMap; -uniform sampler2D scatteringMap; -uniform sampler2D velocityMap; -uniform sampler2DArrayShadow shadowMaps; +layout(binding=RENDER_UTILS_TEXTURE_DEBUG_DEPTH) uniform sampler2D linearDepthMap; +layout(binding=RENDER_UTILS_TEXTURE_DEBUG_HALF_DEPTH) uniform sampler2D halfLinearDepthMap; +layout(binding=RENDER_UTILS_TEXTURE_DEBUG_HALF_NORMAL) uniform sampler2D halfNormalMap; +layout(binding=RENDER_UTILS_TEXTURE_DEBUG_OCCLUSION) uniform sampler2D occlusionMap; +layout(binding=RENDER_UTILS_TEXTURE_DEBUG_OCCLUSION_BLURRED) uniform sampler2D occlusionBlurredMap; +layout(binding=RENDER_UTILS_TEXTURE_DEBUG_SCATTERING) uniform sampler2D scatteringMap; +layout(binding=RENDER_UTILS_TEXTURE_DEBUG_VELOCITY) uniform sampler2D velocityMap; +layout(binding=RENDER_UTILS_TEXTURE_DEBUG_SHADOWS) uniform sampler2DArrayShadow shadowMaps; <@include ShadowCore.slh@> @@ -39,8 +39,8 @@ float curvatureAO(float k) { return 1.0f - (0.0022f * k * k) + (0.0776f * k) + 0.7369f; } -in vec2 uv; -out vec4 outFragColor; +layout(location=0) in vec2 uv; +layout(location=0) out vec4 outFragColor; //SOURCE_PLACEHOLDER diff --git a/libraries/render-utils/src/debug_deferred_buffer.slv b/libraries/render-utils/src/debug_deferred_buffer.slv index 85ff2b651d..c68f986905 100644 --- a/libraries/render-utils/src/debug_deferred_buffer.slv +++ b/libraries/render-utils/src/debug_deferred_buffer.slv @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// debug_deferred_buffer.slv +// debug_deferred_buffer.vert // vertex shader // // Created by Clement on 12/3 @@ -14,7 +14,7 @@ <@include gpu/Inputs.slh@> -out vec2 uv; +layout(location=0) out vec2 uv; void main(void) { uv = (inPosition.xy + 1.0) * 0.5; diff --git a/libraries/render-utils/src/deferred_light.slv b/libraries/render-utils/src/deferred_light.slv index 74b3749181..3b8aee6aae 100644 --- a/libraries/render-utils/src/deferred_light.slv +++ b/libraries/render-utils/src/deferred_light.slv @@ -12,9 +12,11 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -out vec2 _texCoord0; +<@include render-utils/ShaderConstants.h@> -uniform vec4 texcoordFrameTransform; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; + +layout(location=RENDER_UTILS_UNIFORM_LIGHT_TEXCOORD_TRANSFORM) uniform vec4 texcoordFrameTransform; void main(void) { const float depth = 1.0; diff --git a/libraries/render-utils/src/deferred_light_limited.slv b/libraries/render-utils/src/deferred_light_limited.slv index 36e281ab5b..790c305204 100644 --- a/libraries/render-utils/src/deferred_light_limited.slv +++ b/libraries/render-utils/src/deferred_light_limited.slv @@ -13,14 +13,14 @@ // <@include gpu/Transform.slh@> - <@include gpu/Inputs.slh@> +<@include render-utils/ShaderConstants.h@> <$declareStandardTransform()$> uniform vec4 sphereParam; -out vec4 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec4 _texCoord0; void main(void) { if (sphereParam.w != 0.0) { diff --git a/libraries/render-utils/src/deferred_light_point.slv b/libraries/render-utils/src/deferred_light_point.slv index 2b75ee3915..85707b322d 100644 --- a/libraries/render-utils/src/deferred_light_point.slv +++ b/libraries/render-utils/src/deferred_light_point.slv @@ -12,21 +12,21 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -<@include gpu/Transform.slh@> +<@include gpu/Transform.slh@> <@include gpu/Inputs.slh@> +<@include graphics/Light.slh@> +<@include render-utils/ShaderConstants.h@> <$declareStandardTransform()$> -<@include graphics/Light.slh@> - <$declareLightBuffer(256)$> -uniform lightIndexBuffer { +layout(binding=RENDER_UTILS_BUFFER_LIGHT_INDEX) uniform lightIndexBuffer { int lightIndex[256]; }; -out vec4 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec4 _texCoord0; void main(void) { diff --git a/libraries/render-utils/src/deferred_light_spot.slv b/libraries/render-utils/src/deferred_light_spot.slv index 7e3e45b3b6..637df14175 100644 --- a/libraries/render-utils/src/deferred_light_spot.slv +++ b/libraries/render-utils/src/deferred_light_spot.slv @@ -13,18 +13,18 @@ // <@include gpu/Inputs.slh@> - <@include gpu/Transform.slh@> +<@include graphics/Light.slh@> +<@include render-utils/ShaderConstants.h@> <$declareStandardTransform()$> -<@include graphics/Light.slh@> <$declareLightBuffer(256)$> -uniform lightIndexBuffer { +layout(binding=RENDER_UTILS_BUFFER_LIGHT_INDEX) uniform lightIndexBuffer { int lightIndex[256]; }; -out vec4 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec4 _texCoord0; void main(void) { vec4 coneVertex = inPosition; diff --git a/libraries/render-utils/src/directional_ambient_light.slf b/libraries/render-utils/src/directional_ambient_light.slf index d7e0dcd08c..86adc744e2 100644 --- a/libraries/render-utils/src/directional_ambient_light.slf +++ b/libraries/render-utils/src/directional_ambient_light.slf @@ -16,14 +16,15 @@ <@include DeferredBufferRead.slh@> <@include DeferredGlobalLight.slh@> +<@include render-utils/ShaderConstants.h@> <$declareEvalLightmappedColor()$> <$declareEvalAmbientSphereGlobalColor(supportScattering)$> -in vec2 _texCoord0; -out vec4 _fragColor; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=0) out vec4 _fragColor; void main(void) { DeferredFrameTransform deferredTransform = getDeferredFrameTransform(); diff --git a/libraries/render-utils/src/directional_ambient_light_shadow.slf b/libraries/render-utils/src/directional_ambient_light_shadow.slf index fda0164b4d..f54f01c4af 100644 --- a/libraries/render-utils/src/directional_ambient_light_shadow.slf +++ b/libraries/render-utils/src/directional_ambient_light_shadow.slf @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// directional_light_shadow.frag +// directional_ambient_light_shadow.frag // fragment shader // // Created by Zach Pomerantz on 1/18/2016. @@ -15,12 +15,13 @@ <@include Shadow.slh@> <@include DeferredBufferRead.slh@> <@include DeferredGlobalLight.slh@> +<@include render-utils/ShaderConstants.h@> <$declareEvalLightmappedColor()$> <$declareEvalAmbientSphereGlobalColor(isScattering)$> -in vec2 _texCoord0; -out vec4 _fragColor; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=0) out vec4 _fragColor; void main(void) { DeferredFrameTransform deferredTransform = getDeferredFrameTransform(); diff --git a/libraries/render-utils/src/directional_skybox_light.slf b/libraries/render-utils/src/directional_skybox_light.slf index 65b4b086e9..f9b7664d10 100644 --- a/libraries/render-utils/src/directional_skybox_light.slf +++ b/libraries/render-utils/src/directional_skybox_light.slf @@ -14,12 +14,13 @@ <@include DeferredBufferRead.slh@> <@include DeferredGlobalLight.slh@> +<@include render-utils/ShaderConstants.h@> <$declareEvalLightmappedColor()$> <$declareEvalSkyboxGlobalColor(isScattering)$> -in vec2 _texCoord0; -out vec4 _fragColor; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=0) out vec4 _fragColor; void main(void) { DeferredFrameTransform deferredTransform = getDeferredFrameTransform(); diff --git a/libraries/render-utils/src/directional_skybox_light_shadow.slf b/libraries/render-utils/src/directional_skybox_light_shadow.slf index e927f53a1f..34a836e5b0 100644 --- a/libraries/render-utils/src/directional_skybox_light_shadow.slf +++ b/libraries/render-utils/src/directional_skybox_light_shadow.slf @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// directional_light_shadow.frag +// directional_skybox_light_shadow.frag // fragment shader // // Created by Zach Pomerantz on 1/18/2016. @@ -15,12 +15,13 @@ <@include Shadow.slh@> <@include DeferredBufferRead.slh@> <@include DeferredGlobalLight.slh@> +<@include render-utils/ShaderConstants.h@> <$declareEvalLightmappedColor()$> <$declareEvalSkyboxGlobalColor(isScattering)$> -in vec2 _texCoord0; -out vec4 _fragColor; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=0) out vec4 _fragColor; void main(void) { DeferredFrameTransform deferredTransform = getDeferredFrameTransform(); diff --git a/libraries/render-utils/src/drawWorkloadProxy.slv b/libraries/render-utils/src/drawWorkloadProxy.slv index 64fb335fd6..ec007e1a78 100644 --- a/libraries/render-utils/src/drawWorkloadProxy.slv +++ b/libraries/render-utils/src/drawWorkloadProxy.slv @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// drawItemBounds.slv +// drawWorkloadProxy.vert // vertex shader // // Created by Sam Gateau on 6/29/2015. @@ -18,7 +18,7 @@ <@include gpu/Color.slh@> <$declareColorWheel()$> -uniform vec4 inColor; +layout(location=0) uniform vec4 inColor; struct WorkloadProxy { @@ -27,7 +27,7 @@ struct WorkloadProxy { }; #if defined(GPU_GL410) -uniform samplerBuffer workloadProxiesBuffer; +layout(binding=0) uniform samplerBuffer workloadProxiesBuffer; WorkloadProxy getWorkloadProxy(int i) { int offset = 2 * i; WorkloadProxy proxy; @@ -36,7 +36,7 @@ WorkloadProxy getWorkloadProxy(int i) { return proxy; } #else -layout(std140) buffer workloadProxiesBuffer { +layout(std140, binding=0) buffer workloadProxiesBuffer { WorkloadProxy _proxies[]; }; WorkloadProxy getWorkloadProxy(int i) { diff --git a/libraries/render-utils/src/drawWorkloadView.slf b/libraries/render-utils/src/drawWorkloadView.slf index 1304e68c7f..946b2ce6b7 100644 --- a/libraries/render-utils/src/drawWorkloadView.slf +++ b/libraries/render-utils/src/drawWorkloadView.slf @@ -1,7 +1,8 @@ <@include gpu/Config.slh@> <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> -// drawItemBounds.frag +// +// drawWorkloadView.frag // fragment shader // // Created by Sam Gateau on 6/29/15. diff --git a/libraries/render-utils/src/drawWorkloadView.slv b/libraries/render-utils/src/drawWorkloadView.slv index f5497d250c..2211bfb1ac 100644 --- a/libraries/render-utils/src/drawWorkloadView.slv +++ b/libraries/render-utils/src/drawWorkloadView.slv @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// drawItemBounds.slv +// drawWorkloadView.vert // vertex shader // // Created by Sam Gateau on 6/29/2015. @@ -18,7 +18,7 @@ <@include gpu/Color.slh@> <$declareColorWheel()$> -uniform vec4 inColor; +layout(location=0) uniform vec4 inColor; struct WorkloadView { @@ -30,16 +30,16 @@ struct WorkloadView { }; #if defined(GPU_GL410) -uniform samplerBuffer workloadViewsBuffer; +layout(binding=1) uniform samplerBuffer workloadViewsBuffer; WorkloadView getWorkloadView(int i) { int offset = 2 * i; WorkloadView view; view.origin = texelFetch(workloadViewsBuffer, offset); - view.radiuses = texelFetch(workloadViewsBuffer, offset + 1); + //view.radiuses = texelFetch(workloadViewsBuffer, offset + 1); return view; } #else -layout(std140) buffer workloadViewsBuffer { +layout(std140,binding=1) buffer workloadViewsBuffer { WorkloadView _views[]; }; WorkloadView getWorkloadView(int i) { @@ -61,11 +61,14 @@ const int NUM_VERTICES_PER_VIEW_REGION = NUM_SEGMENT_PER_VIEW_REGION * NUM_VERTI const int NUM_REGIONS_PER_VIEW = 3; const int NUM_VERTICES_PER_VIEW = NUM_VERTICES_PER_VIEW_REGION * NUM_REGIONS_PER_VIEW; - -layout(std140) uniform drawMeshBuffer { +struct DrawMesh { vec4 verts[NUM_SEGMENT_PER_VIEW_REGION]; }; +layout(std140, location=0) uniform DrawMeshBuffer { + DrawMesh _drawMeshBuffer; +}; + void main(void) { int viewID = gl_VertexID / NUM_VERTICES_PER_VIEW; int viewVertexID = gl_VertexID - viewID * NUM_VERTICES_PER_VIEW; @@ -76,7 +79,7 @@ void main(void) { int segmentID = regionVertexID / NUM_VERTICES_PER_SEGMENT; int segmentVertexID = regionVertexID - segmentID * NUM_VERTICES_PER_SEGMENT; - vec4 segment = verts[segmentID]; + vec4 segment = _drawMeshBuffer.verts[segmentID]; vec4 spriteVert = vec4(segment.y, 0.0, segment.x, 1.0); vec3 spriteTan = vec3(segment.x, 0.0, -segment.y); diff --git a/libraries/render-utils/src/forward_model.slf b/libraries/render-utils/src/forward_model.slf index ea3a66d21c..6df5343c5c 100644 --- a/libraries/render-utils/src/forward_model.slf +++ b/libraries/render-utils/src/forward_model.slf @@ -11,24 +11,27 @@ // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -<@include ForwardGlobalLight.slh@> -<$declareEvalSkyboxGlobalColor()$> - -<@include graphics/Material.slh@> <@include gpu/Transform.slh@> +<@include graphics/Material.slh@> +<@include graphics/MaterialTextures.slh@> +<@include render-utils/ShaderConstants.h@> +<@include ForwardGlobalLight.slh@> + +<$declareEvalSkyboxGlobalColor()$> + + <$declareStandardCameraTransform()$> -<@include MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO, ROUGHNESS, _SCRIBE_NULL, METALLIC, EMISSIVE, OCCLUSION)$> -in vec4 _positionES; -in vec2 _texCoord0; -in vec2 _texCoord1; -in vec3 _normalWS; -in vec3 _color; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; -layout(location = 0) out vec4 _fragColor0; +layout(location=0) out vec4 _fragColor0; void main(void) { Material mat = getMaterial(); diff --git a/libraries/render-utils/src/forward_model_normal_map.slf b/libraries/render-utils/src/forward_model_normal_map.slf index ac76e909e4..88f9df1ecf 100644 --- a/libraries/render-utils/src/forward_model_normal_map.slf +++ b/libraries/render-utils/src/forward_model_normal_map.slf @@ -12,25 +12,25 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -<@include ForwardGlobalLight.slh@> -<$declareEvalSkyboxGlobalColor()$> - -<@include graphics/Material.slh@> - <@include gpu/Transform.slh@> +<@include graphics/Material.slh@> +<@include graphics/MaterialTextures.slh@> +<@include render-utils/ShaderConstants.h@> +<@include ForwardGlobalLight.slh@> + +<$declareEvalSkyboxGlobalColor()$> <$declareStandardCameraTransform()$> -<@include MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO, ROUGHNESS, NORMAL, METALLIC, EMISSIVE, OCCLUSION)$> -in vec4 _positionES; -in vec2 _texCoord0; -in vec2 _texCoord1; -in vec3 _normalWS; -in vec3 _tangentWS; -in vec3 _color; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; -layout(location = 0) out vec4 _fragColor0; +layout(location=0) out vec4 _fragColor0; void main(void) { Material mat = getMaterial(); diff --git a/libraries/render-utils/src/forward_model_translucent.slf b/libraries/render-utils/src/forward_model_translucent.slf index 70a3233737..5b69a6cb21 100644 --- a/libraries/render-utils/src/forward_model_translucent.slf +++ b/libraries/render-utils/src/forward_model_translucent.slf @@ -12,26 +12,25 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +<@include gpu/Transform.slh@> <@include graphics/Material.slh@> - +<@include graphics/MaterialTextures.slh@> +<@include render-utils/ShaderConstants.h@> <@include ForwardGlobalLight.slh@> <$declareEvalGlobalLightingAlphaBlended()$> - -<@include gpu/Transform.slh@> <$declareStandardCameraTransform()$> -<@include MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO, ROUGHNESS, _SCRIBE_NULL, METALLIC, EMISSIVE, OCCLUSION)$> -in vec2 _texCoord0; -in vec2 _texCoord1; -in vec4 _positionES; -in vec3 _normalWS; -in vec3 _color; -in float _alpha; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) in float _alpha; -layout(location = 0) out vec4 _fragColor0; +layout(location=0) out vec4 _fragColor0; void main(void) { Material mat = getMaterial(); diff --git a/libraries/render-utils/src/forward_model_unlit.slf b/libraries/render-utils/src/forward_model_unlit.slf index e693a79e53..d01bd70815 100644 --- a/libraries/render-utils/src/forward_model_unlit.slf +++ b/libraries/render-utils/src/forward_model_unlit.slf @@ -14,14 +14,15 @@ <@include LightingModel.slh@> <@include graphics/Material.slh@> +<@include graphics/MaterialTextures.slh@> +<@include render-utils/ShaderConstants.h@> -<@include MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO)$> -in vec2 _texCoord0; -in vec3 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; -layout(location = 0) out vec4 _fragColor0; +layout(location=0) out vec4 _fragColor0; void main(void) { diff --git a/libraries/render-utils/src/forward_simple.slf b/libraries/render-utils/src/forward_simple.slf index 1ac44750a7..d4cf85d802 100644 --- a/libraries/render-utils/src/forward_simple.slf +++ b/libraries/render-utils/src/forward_simple.slf @@ -18,12 +18,12 @@ // the interpolated normal -in vec3 _normalWS; -in vec3 _normalMS; -in vec4 _color; -in vec2 _texCoord0; -in vec4 _positionMS; -in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_NORMAL_MS) in vec3 _normalMS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_POSITION_MS) in vec4 _positionMS; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; // For retro-compatibility #define _normal _normalWS @@ -31,9 +31,9 @@ in vec4 _positionES; #define _position _positionMS #define _eyePosition _positionES -layout(location = 0) out vec4 _fragColor0; +layout(location=0) out vec4 _fragColor0; -//PROCEDURAL_COMMON_BLOCK +<@include procedural/ProceduralCommon.slh@> #line 1001 //PROCEDURAL_BLOCK diff --git a/libraries/render-utils/src/forward_simple_textured.slf b/libraries/render-utils/src/forward_simple_textured.slf index 9bdf236743..0c50b0b599 100644 --- a/libraries/render-utils/src/forward_simple_textured.slf +++ b/libraries/render-utils/src/forward_simple_textured.slf @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// forward_simple_textured.slf +// forward_simple_textured.frag // fragment shader // // Created by Clément Brisset on 5/29/15. @@ -19,16 +19,18 @@ <@include gpu/Transform.slh@> <$declareStandardCameraTransform()$> +<@include render-utils/ShaderConstants.h@> + // the albedo texture -uniform sampler2D originalTexture; +layout(binding=0) uniform sampler2D originalTexture; // the interpolated normal -in vec3 _normalWS; -in vec4 _color; -in vec2 _texCoord0; -in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; -layout(location = 0) out vec4 _fragColor0; +layout(location=0) out vec4 _fragColor0; void main(void) { vec4 texel = texture(originalTexture, _texCoord0); diff --git a/libraries/render-utils/src/forward_simple_textured_transparent.slf b/libraries/render-utils/src/forward_simple_textured_transparent.slf index 167d1cb87a..d1cd21b4cb 100644 --- a/libraries/render-utils/src/forward_simple_textured_transparent.slf +++ b/libraries/render-utils/src/forward_simple_textured_transparent.slf @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// forward_simple_textured_transparent.slf +// forward_simple_textured_transparent.frag // fragment shader // // Created by Clément Brisset on 5/29/15. @@ -19,16 +19,18 @@ <@include gpu/Transform.slh@> <$declareStandardCameraTransform()$> +<@include render-utils/ShaderConstants.h@> + // the albedo texture -uniform sampler2D originalTexture; +layout(binding=0) uniform sampler2D originalTexture; // the interpolated normal -in vec3 _normalWS; -in vec4 _color; -in vec2 _texCoord0; -in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; -layout(location = 0) out vec4 _fragColor0; +layout(location=0) out vec4 _fragColor0; void main(void) { vec4 texel = texture(originalTexture, _texCoord0); diff --git a/libraries/render-utils/src/forward_simple_textured_unlit.slf b/libraries/render-utils/src/forward_simple_textured_unlit.slf index 0cc241b75e..cca371a1ff 100644 --- a/libraries/render-utils/src/forward_simple_textured_unlit.slf +++ b/libraries/render-utils/src/forward_simple_textured_unlit.slf @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// simple_textured_unlit.frag +// forward_simple_textured_unlit.frag // fragment shader // // Created by Clément Brisset on 5/29/15. @@ -15,13 +15,15 @@ <@include LightingModel.slh@> <@include gpu/Color.slh@> -layout(location = 0) out vec4 _fragColor0; +<@include render-utils/ShaderConstants.h@> + +layout(location=0) out vec4 _fragColor0; // the albedo texture -uniform sampler2D originalTexture; +layout(binding=0) uniform sampler2D originalTexture; -in vec4 _color; -in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; void main(void) { vec4 texel = texture(originalTexture, _texCoord0.st); diff --git a/libraries/render-utils/src/forward_simple_transparent.slf b/libraries/render-utils/src/forward_simple_transparent.slf index 8be2759571..46328b77b6 100644 --- a/libraries/render-utils/src/forward_simple_transparent.slf +++ b/libraries/render-utils/src/forward_simple_transparent.slf @@ -17,12 +17,12 @@ <$declareEvalGlobalLightingAlphaBlended()$> // the interpolated normal -in vec3 _normalWS; -in vec3 _normalMS; -in vec4 _color; -in vec2 _texCoord0; -in vec4 _positionMS; -in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_NORMAL_MS) in vec3 _normalMS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_POSITION_MS) in vec4 _positionMS; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; // For retro-compatibility #define _normal _normalWS @@ -30,7 +30,7 @@ in vec4 _positionES; #define _position _positionMS #define _eyePosition _positionES -layout(location = 0) out vec4 _fragColor0; +layout(location=0) out vec4 _fragColor0; //PROCEDURAL_COMMON_BLOCK diff --git a/libraries/render-utils/src/fxaa.slf b/libraries/render-utils/src/fxaa.slf index 94fa75c47f..2dddcc795b 100644 --- a/libraries/render-utils/src/fxaa.slf +++ b/libraries/render-utils/src/fxaa.slf @@ -22,13 +22,13 @@ precision mediump float; precision mediump int; #endif -uniform sampler2D colorTexture; +layout(binding=0) uniform sampler2D colorTexture; //uniform sampler2D historyTexture; -uniform vec2 texcoordOffset; +layout(location=0) uniform vec2 texcoordOffset; -in vec2 varTexCoord0; -layout(location = 0) out vec4 outFragColor; -//layout(location = 0) out vec4 outFragHistory; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 outFragColor; +//layout(location=0) out vec4 outFragHistory; void main() { outFragColor = vec4(texture(colorTexture, varTexCoord0).xyz, 1.0/8.0); diff --git a/libraries/render-utils/src/fxaa.slv b/libraries/render-utils/src/fxaa.slv index 35a96ceb24..037adc18bf 100644 --- a/libraries/render-utils/src/fxaa.slv +++ b/libraries/render-utils/src/fxaa.slv @@ -18,7 +18,7 @@ <$declareStandardTransform()$> -out vec2 varTexcoord; +layout(location=0) out vec2 varTexcoord; void main(void) { varTexcoord = inTexCoord0.xy; diff --git a/libraries/render-utils/src/fxaa_blend.slf b/libraries/render-utils/src/fxaa_blend.slf index 996344c881..aca050f047 100644 --- a/libraries/render-utils/src/fxaa_blend.slf +++ b/libraries/render-utils/src/fxaa_blend.slf @@ -12,13 +12,13 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -<@include DeferredBufferWrite.slh@> +<@include gpu/ShaderConstants.h@> -in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 outFragColor; -uniform sampler2D colorTexture; -uniform float sharpenIntensity; +layout(binding=0) uniform sampler2D colorTexture; +layout(location=GPU_UNIFORM_EXTRA0) uniform float sharpenIntensity; void main(void) { vec4 pixels[9]; diff --git a/libraries/render-utils/src/glowLine.slf b/libraries/render-utils/src/glowLine.slf index 6a7a6157a4..69757ec92a 100644 --- a/libraries/render-utils/src/glowLine.slf +++ b/libraries/render-utils/src/glowLine.slf @@ -9,10 +9,12 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -in vec4 _color; +<@include render-utils/ShaderConstants.h@> -in float distanceFromCenter; -out vec4 _fragColor; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; + +layout(location=1) in float distanceFromCenter; +layout(location=0) out vec4 _fragColor; void main(void) { // The incoming value actually ranges from -1 to 1, so modify it diff --git a/libraries/render-utils/src/glowLine.slv b/libraries/render-utils/src/glowLine.slv index 4532ed7b9f..70947350a4 100644 --- a/libraries/render-utils/src/glowLine.slv +++ b/libraries/render-utils/src/glowLine.slv @@ -10,28 +10,34 @@ // <@include gpu/Transform.slh@> +<@include render-utils/ShaderConstants.h@> + <$declareStandardTransform()$> -layout(std140) uniform lineData { +struct LineData { vec4 p1; vec4 p2; vec4 color; float width; }; -out vec4 _color; +layout(std140, binding=0) uniform LineDataBuffer { + LineData _lineData; +}; + +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; // the distance from the center in 'quad space' -out float distanceFromCenter; +layout(location=1) out float distanceFromCenter; void main(void) { - _color = color; + _color = _lineData.color; TransformCamera cam = getTransformCamera(); TransformObject obj = getTransformObject(); vec4 p1eye, p2eye; - <$transformModelToEyePos(cam, obj, p1, p1eye)$> - <$transformModelToEyePos(cam, obj, p2, p2eye)$> + <$transformModelToEyePos(cam, obj, _lineData.p1, p1eye)$> + <$transformModelToEyePos(cam, obj, _lineData.p2, p2eye)$> p1eye /= p1eye.w; p2eye /= p2eye.w; @@ -40,7 +46,7 @@ void main(void) { // Find the vector from the eye to one of the points vec3 v2 = normalize(p1eye.xyz); // The orthogonal vector is the cross product of these two - vec3 orthogonal = cross(v1, v2) * width; + vec3 orthogonal = cross(v1, v2) * _lineData.width; // Deteremine which end to emit based on the vertex id (even / odd) vec4 eye = (0 == gl_VertexID % 2) ? p1eye : p2eye; diff --git a/libraries/render-utils/src/grid.slf b/libraries/render-utils/src/grid.slf index a680e7093b..c2380c980d 100644 --- a/libraries/render-utils/src/grid.slf +++ b/libraries/render-utils/src/grid.slf @@ -1,7 +1,7 @@ <@include gpu/Config.slh@> <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> -// grid.slf +// grid.frag // fragment shader // // Created by Zach Pomerantz on 2/16/2016. @@ -11,6 +11,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +<@include gpu/ShaderConstants.h@> <@include gpu/Paint.slh@> struct Grid { @@ -19,13 +20,16 @@ struct Grid { vec4 edge; }; -uniform gridBuffer { Grid grid; }; +layout(binding=0) uniform gridBuffer { + Grid grid; +}; + Grid getGrid() { return grid; } -in vec2 varTexCoord0; -in vec4 varColor; +layout(location=GPU_ATTR_TEXCOORD0) in vec2 varTexCoord0; +layout(location=GPU_ATTR_COLOR) in vec4 varColor; -out vec4 outFragColor; +layout(location=0) out vec4 outFragColor; void main(void) { Grid grid = getGrid(); diff --git a/libraries/render-utils/src/hmd_ui.slf b/libraries/render-utils/src/hmd_ui.slf index 959e8d733c..d0e6798cec 100644 --- a/libraries/render-utils/src/hmd_ui.slf +++ b/libraries/render-utils/src/hmd_ui.slf @@ -11,20 +11,21 @@ // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +<@include render-utils/ShaderConstants.h@> -uniform sampler2D hudTexture; +layout(binding=0) uniform sampler2D hudTexture; struct HUDData { float alpha; }; -layout(std140) uniform hudBuffer { +layout(std140, binding=0) uniform hudBuffer { HUDData hud; }; -in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -out vec4 fragColor0; +layout(location=0) out vec4 fragColor0; void main() { vec4 color = texture(hudTexture, _texCoord0); diff --git a/libraries/render-utils/src/hmd_ui.slv b/libraries/render-utils/src/hmd_ui.slv index d6e02ff4cb..5352a5ba68 100644 --- a/libraries/render-utils/src/hmd_ui.slv +++ b/libraries/render-utils/src/hmd_ui.slv @@ -14,17 +14,19 @@ <@include gpu/Inputs.slh@> <@include gpu/Transform.slh@> +<@include render-utils/ShaderConstants.h@> + <$declareStandardTransform()$> struct HUDData { float alpha; }; -layout(std140) uniform hudBuffer { +layout(std140, binding=0) uniform hudBuffer { HUDData hud; }; -out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; void main() { _texCoord0 = inTexCoord0.st; diff --git a/libraries/render-utils/src/lightClusters_drawClusterContent.slf b/libraries/render-utils/src/lightClusters_drawClusterContent.slf index d4d97c5b16..65ae8f423e 100644 --- a/libraries/render-utils/src/lightClusters_drawClusterContent.slf +++ b/libraries/render-utils/src/lightClusters_drawClusterContent.slf @@ -1,7 +1,7 @@ <@include gpu/Config.slh@> <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> -// lightClusters_drawClusterFro Depth.slf +// lightClusters_drawClusterContent.frag // // Created by Sam Gateau on 9/8/2016. // Copyright 2015 High Fidelity, Inc. @@ -24,8 +24,8 @@ <$declareColorWheel()$> -in vec2 varTexCoord0; -out vec4 _fragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 _fragColor; void main(void) { diff --git a/libraries/render-utils/src/lightClusters_drawClusterContent.slv b/libraries/render-utils/src/lightClusters_drawClusterContent.slv index b88e2e9ee2..d7e4a66a6a 100644 --- a/libraries/render-utils/src/lightClusters_drawClusterContent.slv +++ b/libraries/render-utils/src/lightClusters_drawClusterContent.slv @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// lightClusters_drawClusterContent.slv +// lightClusters_drawClusterContent.vert // Vertex shader // // Created by Sam Gateau on 9/8/2016 @@ -21,7 +21,7 @@ <$declareColorWheel()$> -out vec4 varColor; +layout(location=0) out vec4 varColor; void main(void) { diff --git a/libraries/render-utils/src/lightClusters_drawClusterFromDepth.slf b/libraries/render-utils/src/lightClusters_drawClusterFromDepth.slf index c51d45ed44..4efb60a259 100644 --- a/libraries/render-utils/src/lightClusters_drawClusterFromDepth.slf +++ b/libraries/render-utils/src/lightClusters_drawClusterFromDepth.slf @@ -1,7 +1,7 @@ <@include gpu/Config.slh@> <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> -// lightClusters_drawClusterFro Depth.slf +// lightClusters_drawClusterFromDepth.frag // // Created by Sam Gateau on 9/8/2016. // Copyright 2015 High Fidelity, Inc. @@ -21,8 +21,8 @@ <$declareColorWheel()$> -in vec2 varTexCoord0; -out vec4 _fragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 _fragColor; void main(void) { diff --git a/libraries/render-utils/src/lightClusters_drawClusterFromDepth.slv b/libraries/render-utils/src/lightClusters_drawClusterFromDepth.slv index 912c39f93c..d35c7cb20b 100644 --- a/libraries/render-utils/src/lightClusters_drawClusterFromDepth.slv +++ b/libraries/render-utils/src/lightClusters_drawClusterFromDepth.slv @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// lightClusters_drawClusterFrom Depth.slv +// lightClusters_drawClusterFrom Depth.vert // Vertex shader // // Created by Sam Gateau on 9/8/2016 @@ -23,7 +23,7 @@ -out vec4 varColor; +layout(location=0) out vec4 varColor; void main(void) { diff --git a/libraries/render-utils/src/lightClusters_drawGrid.slf b/libraries/render-utils/src/lightClusters_drawGrid.slf index 33c8cc56b8..47ed84eeec 100644 --- a/libraries/render-utils/src/lightClusters_drawGrid.slf +++ b/libraries/render-utils/src/lightClusters_drawGrid.slf @@ -1,7 +1,7 @@ <@include gpu/Config.slh@> <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> -// lightClusters_drawGrid.slf +// lightClusters_drawGrid.frag // // Created by Sam Gateau on 9/8/2016. // Copyright 2015 High Fidelity, Inc. @@ -10,8 +10,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -in vec4 varColor; -out vec4 outFragColor; +layout(location=0) in vec4 varColor; +layout(location=0) out vec4 outFragColor; void main(void) { diff --git a/libraries/render-utils/src/lightClusters_drawGrid.slv b/libraries/render-utils/src/lightClusters_drawGrid.slv index aac7fe59a5..c4aff45beb 100644 --- a/libraries/render-utils/src/lightClusters_drawGrid.slv +++ b/libraries/render-utils/src/lightClusters_drawGrid.slv @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// lightClusters_drawGrid.slv +// lightClusters_drawGrid.vert // Vertex shader // // Created by Sam Gateau on 9/8/2016 @@ -23,7 +23,7 @@ -out vec4 varColor; +layout(location=0) out vec4 varColor; void main(void) { diff --git a/libraries/render-utils/src/local_lights_drawOutline.slf b/libraries/render-utils/src/local_lights_drawOutline.slf index f4a135ff0d..c2a53e0490 100644 --- a/libraries/render-utils/src/local_lights_drawOutline.slf +++ b/libraries/render-utils/src/local_lights_drawOutline.slf @@ -30,10 +30,11 @@ <@include LightClusterGrid.slh@> +<@include render-utils/ShaderConstants.h@> -in vec2 _texCoord0; -out vec4 _fragColor; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=0) out vec4 _fragColor; void main(void) { diff --git a/libraries/render-utils/src/local_lights_shading.slf b/libraries/render-utils/src/local_lights_shading.slf index b224fcb77d..60cd9c426d 100644 --- a/libraries/render-utils/src/local_lights_shading.slf +++ b/libraries/render-utils/src/local_lights_shading.slf @@ -19,8 +19,10 @@ <@include LightLocal.slh@> -in vec2 _texCoord0; -out vec4 _fragColor; +<@include render-utils/ShaderConstants.h@> + +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=0) out vec4 _fragColor; void main(void) { _fragColor = vec4(0.0); diff --git a/libraries/render-utils/src/model.slf b/libraries/render-utils/src/model.slf index e5c25c8bc1..20fa10f44c 100644 --- a/libraries/render-utils/src/model.slf +++ b/libraries/render-utils/src/model.slf @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// model_specular_map.frag +// model.frag // fragment shader // // Created by Andrzej Kapolka on 5/6/14. @@ -13,17 +13,16 @@ // <@include DeferredBufferWrite.slh@> - <@include graphics/Material.slh@> +<@include graphics/MaterialTextures.slh@> +<@include render-utils/ShaderConstants.h@> -<@include MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO, ROUGHNESS, _SCRIBE_NULL, METALLIC, EMISSIVE, OCCLUSION, SCATTERING)$> -in vec2 _texCoord0; -in vec2 _texCoord1; -in vec3 _normalWS; -in vec3 _color; - +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; void main(void) { Material mat = getMaterial(); diff --git a/libraries/render-utils/src/model.slv b/libraries/render-utils/src/model.slv index 7cfedfe877..1ec5cf83aa 100644 --- a/libraries/render-utils/src/model.slv +++ b/libraries/render-utils/src/model.slv @@ -1,7 +1,7 @@ <@include gpu/Config.slh@> <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> -// model.slv +// model.vert // vertex shader // // Created by Andrzej Kapolka on 10/14/13. @@ -14,17 +14,19 @@ <@include gpu/Inputs.slh@> <@include gpu/Color.slh@> <@include gpu/Transform.slh@> +<@include graphics/MaterialTextures.slh@> +<@include render-utils/ShaderConstants.h@> + <$declareStandardTransform()$> -<@include MaterialTextures.slh@> <$declareMaterialTexMapArrayBuffer()$> -out vec3 _color; -out float _alpha; -out vec2 _texCoord0; -out vec2 _texCoord1; -out vec4 _positionES; -out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; void main(void) { _color = color_sRGBToLinear(inColor.xyz); diff --git a/libraries/render-utils/src/model_fade.slf b/libraries/render-utils/src/model_fade.slf index 323d1828a0..31a4f4db6e 100644 --- a/libraries/render-utils/src/model_fade.slf +++ b/libraries/render-utils/src/model_fade.slf @@ -16,17 +16,19 @@ <@include graphics/Material.slh@> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO, ROUGHNESS, _SCRIBE_NULL, METALLIC, EMISSIVE, OCCLUSION)$> <@include Fade.slh@> <$declareFadeFragment()$> -in vec2 _texCoord0; -in vec2 _texCoord1; -in vec3 _normalWS; -in vec3 _color; -in vec4 _positionWS; +<@include render-utils/ShaderConstants.h@> + +layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; void main(void) { vec3 fadeEmissive; diff --git a/libraries/render-utils/src/model_fade.slv b/libraries/render-utils/src/model_fade.slv index 6e3a8271ce..e3f7924bc2 100644 --- a/libraries/render-utils/src/model_fade.slv +++ b/libraries/render-utils/src/model_fade.slv @@ -1,7 +1,7 @@ <@include gpu/Config.slh@> <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> -// model_fade.slv +// model_fade.vert // vertex shader // // Created by Olivier Prat on 04/24/17. @@ -16,16 +16,18 @@ <@include gpu/Transform.slh@> <$declareStandardTransform()$> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTexMapArrayBuffer()$> -out float _alpha; -out vec2 _texCoord0; -out vec2 _texCoord1; -out vec4 _positionES; -out vec4 _positionWS; -out vec3 _normalWS; -out vec3 _color; +<@include render-utils/ShaderConstants.h@> + +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; void main(void) { _color = color_sRGBToLinear(inColor.xyz); diff --git a/libraries/render-utils/src/model_lightmap.slf b/libraries/render-utils/src/model_lightmap.slf index c4eed4185e..3cd20b1a35 100644 --- a/libraries/render-utils/src/model_lightmap.slf +++ b/libraries/render-utils/src/model_lightmap.slf @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// model_lightmap_specular_map.frag +// model_lightmap.frag // fragment shader // // Created by Samuel Gateau on 11/19/14. @@ -13,17 +13,18 @@ // <@include DeferredBufferWrite.slh@> - <@include graphics/Material.slh@> +<@include graphics/MaterialTextures.slh@> +<@include render-utils/ShaderConstants.h@> -<@include MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO, ROUGHNESS, _SCRIBE_NULL, METALLIC)$> <$declareMaterialLightmap()$> -in vec2 _texCoord0; -in vec2 _texCoord1; -in vec3 _normalWS; -in vec3 _color; + +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; void main(void) { Material mat = getMaterial(); diff --git a/libraries/render-utils/src/model_lightmap.slv b/libraries/render-utils/src/model_lightmap.slv index b3f20357cd..e82fcaf85b 100644 --- a/libraries/render-utils/src/model_lightmap.slv +++ b/libraries/render-utils/src/model_lightmap.slv @@ -15,16 +15,18 @@ <@include gpu/Inputs.slh@> <@include gpu/Color.slh@> <@include gpu/Transform.slh@> +<@include graphics/MaterialTextures.slh@> +<@include render-utils/ShaderConstants.h@> + <$declareStandardTransform()$> -<@include MaterialTextures.slh@> <$declareMaterialTexMapArrayBuffer()$> -out vec4 _positionES; -out vec2 _texCoord0; -out vec2 _texCoord1; -out vec3 _normalWS; -out vec3 _color; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; void main(void) { // pass along the color in linear space diff --git a/libraries/render-utils/src/model_lightmap_fade.slf b/libraries/render-utils/src/model_lightmap_fade.slf index ba651711c3..c7852cfd3f 100644 --- a/libraries/render-utils/src/model_lightmap_fade.slf +++ b/libraries/render-utils/src/model_lightmap_fade.slf @@ -16,18 +16,20 @@ <@include graphics/Material.slh@> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO, ROUGHNESS, _SCRIBE_NULL, METALLIC)$> <$declareMaterialLightmap()$> <@include Fade.slh@> <$declareFadeFragment()$> -in vec2 _texCoord0; -in vec2 _texCoord1; -in vec3 _normalWS; -in vec3 _color; -in vec4 _positionWS; +<@include render-utils/ShaderConstants.h@> + +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; void main(void) { vec3 fadeEmissive; diff --git a/libraries/render-utils/src/model_lightmap_fade.slv b/libraries/render-utils/src/model_lightmap_fade.slv index 31abb36c4b..5be90e2384 100644 --- a/libraries/render-utils/src/model_lightmap_fade.slv +++ b/libraries/render-utils/src/model_lightmap_fade.slv @@ -17,15 +17,17 @@ <@include gpu/Transform.slh@> <$declareStandardTransform()$> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTexMapArrayBuffer()$> -out vec4 _positionES; -out vec2 _texCoord0; -out vec2 _texCoord1; -out vec3 _normalWS; -out vec3 _color; -out vec4 _positionWS; +<@include render-utils/ShaderConstants.h@> + +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; void main(void) { // pass along the color in linear space diff --git a/libraries/render-utils/src/model_lightmap_normal_map.slf b/libraries/render-utils/src/model_lightmap_normal_map.slf index 57aaa3ed2e..9f26c3063d 100644 --- a/libraries/render-utils/src/model_lightmap_normal_map.slf +++ b/libraries/render-utils/src/model_lightmap_normal_map.slf @@ -13,19 +13,19 @@ // <@include DeferredBufferWrite.slh@> - <@include graphics/Material.slh@> +<@include graphics/MaterialTextures.slh@> +<@include render-utils/ShaderConstants.h@> -<@include MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO, ROUGHNESS, NORMAL, METALLIC)$> <$declareMaterialLightmap()$> -in vec4 _positionES; -in vec2 _texCoord0; -in vec2 _texCoord1; -in vec3 _normalWS; -in vec3 _tangentWS; -in vec3 _color; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; void main(void) { Material mat = getMaterial(); diff --git a/libraries/render-utils/src/model_lightmap_normal_map.slv b/libraries/render-utils/src/model_lightmap_normal_map.slv index 15fc4099d5..02524268ec 100644 --- a/libraries/render-utils/src/model_lightmap_normal_map.slv +++ b/libraries/render-utils/src/model_lightmap_normal_map.slv @@ -15,17 +15,20 @@ <@include gpu/Inputs.slh@> <@include gpu/Color.slh@> <@include gpu/Transform.slh@> +<@include graphics/MaterialTextures.slh@> +<@include render-utils/ShaderConstants.h@> + <$declareStandardTransform()$> -<@include MaterialTextures.slh@> <$declareMaterialTexMapArrayBuffer()$> -out vec4 _positionES; -out vec2 _texCoord0; -out vec2 _texCoord1; -out vec3 _normalWS; -out vec3 _tangentWS; -out vec3 _color; + +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TANGENT_WS) out vec3 _tangentWS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; void main(void) { // pass along the color in linear space diff --git a/libraries/render-utils/src/model_lightmap_normal_map_fade.slf b/libraries/render-utils/src/model_lightmap_normal_map_fade.slf index 2cd5ac433f..b1563a6ad9 100644 --- a/libraries/render-utils/src/model_lightmap_normal_map_fade.slf +++ b/libraries/render-utils/src/model_lightmap_normal_map_fade.slf @@ -16,20 +16,22 @@ <@include graphics/Material.slh@> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO, ROUGHNESS, NORMAL, METALLIC)$> <$declareMaterialLightmap()$> <@include Fade.slh@> <$declareFadeFragment()$> -in vec4 _positionES; -in vec2 _texCoord0; -in vec2 _texCoord1; -in vec3 _normalWS; -in vec3 _tangentWS; -in vec3 _color; -in vec4 _positionWS; +<@include render-utils/ShaderConstants.h@> + +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; void main(void) { vec3 fadeEmissive; diff --git a/libraries/render-utils/src/model_lightmap_normal_map_fade.slv b/libraries/render-utils/src/model_lightmap_normal_map_fade.slv index 8fc3fa28d8..82f6d795d8 100644 --- a/libraries/render-utils/src/model_lightmap_normal_map_fade.slv +++ b/libraries/render-utils/src/model_lightmap_normal_map_fade.slv @@ -15,18 +15,20 @@ <@include gpu/Inputs.slh@> <@include gpu/Color.slh@> <@include gpu/Transform.slh@> -<$declareStandardTransform()$> +<@include graphics/MaterialTextures.slh@> +<@include render-utils/ShaderConstants.h@> -<@include MaterialTextures.slh@> +<$declareStandardTransform()$> <$declareMaterialTexMapArrayBuffer()$> -out vec4 _positionES; -out vec2 _texCoord0; -out vec2 _texCoord1; -out vec3 _normalWS; -out vec3 _tangentWS; -out vec3 _color; -out vec4 _positionWS; + +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TANGENT_WS) out vec3 _tangentWS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; void main(void) { // pass along the color in linear space diff --git a/libraries/render-utils/src/model_normal_map.slf b/libraries/render-utils/src/model_normal_map.slf index b13377af21..5d8ba00936 100644 --- a/libraries/render-utils/src/model_normal_map.slf +++ b/libraries/render-utils/src/model_normal_map.slf @@ -13,18 +13,18 @@ // <@include DeferredBufferWrite.slh@> - <@include graphics/Material.slh@> +<@include graphics/MaterialTextures.slh@> +<@include render-utils/ShaderConstants.h@> -<@include MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO, ROUGHNESS, NORMAL, METALLIC, EMISSIVE, OCCLUSION, SCATTERING)$> -in vec4 _positionES; -in vec2 _texCoord0; -in vec2 _texCoord1; -in vec3 _normalWS; -in vec3 _tangentWS; -in vec3 _color; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; void main(void) { Material mat = getMaterial(); diff --git a/libraries/render-utils/src/model_normal_map.slv b/libraries/render-utils/src/model_normal_map.slv index cc99c6d22d..52386d6e4f 100644 --- a/libraries/render-utils/src/model_normal_map.slv +++ b/libraries/render-utils/src/model_normal_map.slv @@ -15,18 +15,21 @@ <@include gpu/Inputs.slh@> <@include gpu/Color.slh@> <@include gpu/Transform.slh@> +<@include graphics/MaterialTextures.slh@> +<@include render-utils/ShaderConstants.h@> + <$declareStandardTransform()$> -<@include MaterialTextures.slh@> <$declareMaterialTexMapArrayBuffer()$> -out vec4 _positionES; -out vec2 _texCoord0; -out vec2 _texCoord1; -out vec3 _normalWS; -out vec3 _tangentWS; -out vec3 _color; -out float _alpha; + +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TANGENT_WS) out vec3 _tangentWS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; void main(void) { // pass along the color diff --git a/libraries/render-utils/src/model_normal_map_fade.slf b/libraries/render-utils/src/model_normal_map_fade.slf index 7ece8fea38..fb66fe167c 100644 --- a/libraries/render-utils/src/model_normal_map_fade.slf +++ b/libraries/render-utils/src/model_normal_map_fade.slf @@ -13,22 +13,22 @@ // <@include DeferredBufferWrite.slh@> - <@include graphics/Material.slh@> +<@include graphics/MaterialTextures.slh@> +<@include render-utils/ShaderConstants.h@> +<@include Fade.slh@> -<@include MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO, ROUGHNESS, NORMAL, METALLIC, EMISSIVE, OCCLUSION)$> -<@include Fade.slh@> <$declareFadeFragment()$> -in vec4 _positionES; -in vec2 _texCoord0; -in vec2 _texCoord1; -in vec3 _normalWS; -in vec3 _tangentWS; -in vec3 _color; -in vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; void main(void) { vec3 fadeEmissive; diff --git a/libraries/render-utils/src/model_normal_map_fade.slv b/libraries/render-utils/src/model_normal_map_fade.slv index a75087f93d..74d23d6057 100644 --- a/libraries/render-utils/src/model_normal_map_fade.slv +++ b/libraries/render-utils/src/model_normal_map_fade.slv @@ -15,19 +15,21 @@ <@include gpu/Inputs.slh@> <@include gpu/Color.slh@> <@include gpu/Transform.slh@> -<$declareStandardTransform()$> +<@include graphics/MaterialTextures.slh@> +<@include render-utils/ShaderConstants.h@> -<@include MaterialTextures.slh@> +<$declareStandardTransform()$> <$declareMaterialTexMapArrayBuffer()$> -out vec4 _positionES; -out vec4 _positionWS; -out vec2 _texCoord0; -out vec2 _texCoord1; -out vec3 _normalWS; -out vec3 _tangentWS; -out vec3 _color; -out float _alpha; + +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TANGENT_WS) out vec3 _tangentWS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; void main(void) { // pass along the color diff --git a/libraries/render-utils/src/model_shadow.slf b/libraries/render-utils/src/model_shadow.slf index 178ea7b387..6426759ec7 100644 --- a/libraries/render-utils/src/model_shadow.slf +++ b/libraries/render-utils/src/model_shadow.slf @@ -12,7 +12,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -layout(location = 0) out vec4 _fragColor; +layout(location=0) out vec4 _fragColor; void main(void) { // pass-through to set z-buffer diff --git a/libraries/render-utils/src/model_shadow_fade.slf b/libraries/render-utils/src/model_shadow_fade.slf index 403f32c457..c6c8c23f65 100644 --- a/libraries/render-utils/src/model_shadow_fade.slf +++ b/libraries/render-utils/src/model_shadow_fade.slf @@ -13,11 +13,14 @@ // <@include Fade.slh@> +<@include render-utils/ShaderConstants.h@> + <$declareFadeFragment()$> -layout(location = 0) out vec4 _fragColor; -in vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; + +layout(location=0) out vec4 _fragColor; void main(void) { FadeObjectParams fadeParams; diff --git a/libraries/render-utils/src/model_shadow_fade.slv b/libraries/render-utils/src/model_shadow_fade.slv index 72e4a1a823..cf180c2dc8 100644 --- a/libraries/render-utils/src/model_shadow_fade.slv +++ b/libraries/render-utils/src/model_shadow_fade.slv @@ -13,12 +13,13 @@ // <@include gpu/Inputs.slh@> - <@include gpu/Transform.slh@> +<@include render-utils/ShaderConstants.h@> <$declareStandardTransform()$> -out vec4 _positionWS; + +layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; void main(void) { // standard transform diff --git a/libraries/render-utils/src/model_translucent.slf b/libraries/render-utils/src/model_translucent.slf index b808ca4bab..cd170f29e7 100644 --- a/libraries/render-utils/src/model_translucent.slf +++ b/libraries/render-utils/src/model_translucent.slf @@ -12,29 +12,29 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +<@include gpu/Transform.slh@> <@include graphics/Material.slh@> - +<@include graphics/MaterialTextures.slh@> +<@include render-utils/ShaderConstants.h@> +<@include LightLocal.slh@> +<@include ShadingModel.slh@> <@include DeferredGlobalLight.slh@> <$declareEvalGlobalLightingAlphaBlendedWithHaze()$> -<@include LightLocal.slh@> - -<@include gpu/Transform.slh@> <$declareStandardCameraTransform()$> -<@include MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO, ROUGHNESS, _SCRIBE_NULL, _SCRIBE_NULL, EMISSIVE, OCCLUSION)$> -in vec2 _texCoord0; -in vec2 _texCoord1; -in vec4 _positionES; -in vec4 _positionWS; -in vec3 _normalWS; -in vec3 _color; -in float _alpha; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) in float _alpha; -out vec4 _fragColor; +layout(location=0) out vec4 _fragColor; void main(void) { Material mat = getMaterial(); @@ -83,7 +83,7 @@ void main(void) { 1.0, occlusionTex, fragPositionES, - fragPositionWS, + fragPositionWS, albedo, fresnel, metallic, diff --git a/libraries/render-utils/src/model_translucent.slv b/libraries/render-utils/src/model_translucent.slv index 61a1c96ce8..defdb87172 100644 --- a/libraries/render-utils/src/model_translucent.slv +++ b/libraries/render-utils/src/model_translucent.slv @@ -1,7 +1,7 @@ <@include gpu/Config.slh@> <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> -// model_translucent.slv +// model_translucent.vert // vertex shader // // Created by Olivier Prat on 15/01/18. @@ -16,16 +16,18 @@ <@include gpu/Transform.slh@> <$declareStandardTransform()$> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTexMapArrayBuffer()$> -out float _alpha; -out vec2 _texCoord0; -out vec2 _texCoord1; -out vec4 _positionES; -out vec4 _positionWS; -out vec3 _normalWS; -out vec3 _color; +<@include render-utils/ShaderConstants.h@> + +layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; void main(void) { _color = color_sRGBToLinear(inColor.xyz); diff --git a/libraries/render-utils/src/model_translucent_fade.slf b/libraries/render-utils/src/model_translucent_fade.slf index a93adee96b..81b9faf82d 100644 --- a/libraries/render-utils/src/model_translucent_fade.slf +++ b/libraries/render-utils/src/model_translucent_fade.slf @@ -16,21 +16,23 @@ <@include gpu/Transform.slh@> <$declareStandardCameraTransform()$> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO, ROUGHNESS, _SCRIBE_NULL, _SCRIBE_NULL, EMISSIVE, OCCLUSION)$> <@include Fade.slh@> <$declareFadeFragment()$> -in vec2 _texCoord0; -in vec2 _texCoord1; -in vec4 _positionES; -in vec4 _positionWS; -in vec3 _normalWS; -in vec3 _color; -in float _alpha; +<@include render-utils/ShaderConstants.h@> -out vec4 _fragColor; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) in float _alpha; + +layout(location=0) out vec4 _fragColor; void main(void) { vec3 fadeEmissive; diff --git a/libraries/render-utils/src/model_translucent_normal_map.slf b/libraries/render-utils/src/model_translucent_normal_map.slf index 750149dc1b..c813097dcf 100644 --- a/libraries/render-utils/src/model_translucent_normal_map.slf +++ b/libraries/render-utils/src/model_translucent_normal_map.slf @@ -23,19 +23,21 @@ <@include gpu/Transform.slh@> <$declareStandardCameraTransform()$> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO, ROUGHNESS, NORMAL, _SCRIBE_NULL, EMISSIVE, OCCLUSION)$> -in vec2 _texCoord0; -in vec2 _texCoord1; -in vec4 _positionES; -in vec4 _positionWS; -in vec3 _normalWS; -in vec3 _tangentWS; -in vec3 _color; -in float _alpha; +<@include render-utils/ShaderConstants.h@> -out vec4 _fragColor; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) in float _alpha; + +layout(location=0) out vec4 _fragColor; void main(void) { Material mat = getMaterial(); diff --git a/libraries/render-utils/src/model_translucent_normal_map.slv b/libraries/render-utils/src/model_translucent_normal_map.slv index 21d56418c0..257711ac24 100644 --- a/libraries/render-utils/src/model_translucent_normal_map.slv +++ b/libraries/render-utils/src/model_translucent_normal_map.slv @@ -1,7 +1,7 @@ <@include gpu/Config.slh@> <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> -// model_translucent_normal_map.slv +// model_translucent_normal_map.vert // vertex shader // // Created by Olivier Prat on 23/01/18. @@ -16,17 +16,19 @@ <@include gpu/Transform.slh@> <$declareStandardTransform()$> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTexMapArrayBuffer()$> -out float _alpha; -out vec2 _texCoord0; -out vec2 _texCoord1; -out vec4 _positionES; -out vec4 _positionWS; -out vec3 _normalWS; -out vec3 _tangentWS; -out vec3 _color; +<@include render-utils/ShaderConstants.h@> + +layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TANGENT_WS) out vec3 _tangentWS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; void main(void) { _color = color_sRGBToLinear(inColor.xyz); diff --git a/libraries/render-utils/src/model_translucent_normal_map_fade.slf b/libraries/render-utils/src/model_translucent_normal_map_fade.slf index c7615626ce..d17c5105b1 100644 --- a/libraries/render-utils/src/model_translucent_normal_map_fade.slf +++ b/libraries/render-utils/src/model_translucent_normal_map_fade.slf @@ -12,6 +12,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +<@include render-utils/ShaderConstants.h@> <@include graphics/Material.slh@> <@include DeferredGlobalLight.slh@> @@ -23,22 +24,24 @@ <@include gpu/Transform.slh@> <$declareStandardCameraTransform()$> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO, ROUGHNESS, NORMAL, _SCRIBE_NULL, EMISSIVE, OCCLUSION)$> <@include Fade.slh@> <$declareFadeFragment()$> -in vec2 _texCoord0; -in vec2 _texCoord1; -in vec4 _positionES; -in vec3 _normalWS; -in vec3 _tangentWS; -in vec3 _color; -in float _alpha; -in vec4 _positionWS; +<@include render-utils/ShaderConstants.h@> -out vec4 _fragColor; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) in float _alpha; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; + +layout(location=0) out vec4 _fragColor; void main(void) { vec3 fadeEmissive; diff --git a/libraries/render-utils/src/model_translucent_unlit.slf b/libraries/render-utils/src/model_translucent_unlit.slf index e5507dd2e0..eef3190d2b 100644 --- a/libraries/render-utils/src/model_translucent_unlit.slf +++ b/libraries/render-utils/src/model_translucent_unlit.slf @@ -14,15 +14,17 @@ <@include graphics/Material.slh@> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO, ROUGHNESS, _SCRIBE_NULL, _SCRIBE_NULL, EMISSIVE, OCCLUSION)$> <@include LightingModel.slh@> -in vec2 _texCoord0; -in vec3 _color; -in float _alpha; +<@include render-utils/ShaderConstants.h@> -out vec4 _fragColor; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) in float _alpha; + +layout(location=0) out vec4 _fragColor; void main(void) { Material mat = getMaterial(); diff --git a/libraries/render-utils/src/model_translucent_unlit_fade.slf b/libraries/render-utils/src/model_translucent_unlit_fade.slf index 016db4639f..4efdd7f4e5 100644 --- a/libraries/render-utils/src/model_translucent_unlit_fade.slf +++ b/libraries/render-utils/src/model_translucent_unlit_fade.slf @@ -14,19 +14,21 @@ <@include graphics/Material.slh@> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO, ROUGHNESS, _SCRIBE_NULL, _SCRIBE_NULL, EMISSIVE, OCCLUSION)$> <@include LightingModel.slh@> <@include Fade.slh@> <$declareFadeFragment()$> -in vec2 _texCoord0; -in vec3 _color; -in float _alpha; -in vec4 _positionWS; +<@include render-utils/ShaderConstants.h@> -out vec4 _fragColor; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) in float _alpha; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; + +layout(location=0) out vec4 _fragColor; void main(void) { vec3 fadeEmissive; diff --git a/libraries/render-utils/src/model_unlit.slf b/libraries/render-utils/src/model_unlit.slf index d4c1334e12..e920b3eb67 100644 --- a/libraries/render-utils/src/model_unlit.slf +++ b/libraries/render-utils/src/model_unlit.slf @@ -15,14 +15,15 @@ <@include DeferredBufferWrite.slh@> <@include LightingModel.slh@> <@include graphics/Material.slh@> +<@include graphics/MaterialTextures.slh@> +<@include render-utils/ShaderConstants.h@> -<@include MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO)$> -in vec2 _texCoord0; -in vec3 _normalWS; -in vec3 _color; -in float _alpha; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) in float _alpha; void main(void) { diff --git a/libraries/render-utils/src/model_unlit_fade.slf b/libraries/render-utils/src/model_unlit_fade.slf index d8f8cfce38..30d023da88 100644 --- a/libraries/render-utils/src/model_unlit_fade.slf +++ b/libraries/render-utils/src/model_unlit_fade.slf @@ -15,18 +15,19 @@ <@include DeferredBufferWrite.slh@> <@include LightingModel.slh@> <@include graphics/Material.slh@> - +<@include graphics/MaterialTextures.slh@> +<@include render-utils/ShaderConstants.h@> <@include Fade.slh@> + <$declareFadeFragment()$> -<@include MaterialTextures.slh@> <$declareMaterialTextures(ALBEDO)$> -in vec2 _texCoord0; -in vec3 _normalWS; -in vec3 _color; -in float _alpha; -in vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) in float _alpha; void main(void) { vec3 fadeEmissive; diff --git a/libraries/render-utils/src/nop.slf b/libraries/render-utils/src/nop.slf index f87db4e138..dd54f839ea 100644 --- a/libraries/render-utils/src/nop.slf +++ b/libraries/render-utils/src/nop.slf @@ -12,5 +12,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +layout(location=0) out vec4 _fragColor; + void main(void) { } diff --git a/libraries/render-utils/src/render-utils/ShaderConstants.h b/libraries/render-utils/src/render-utils/ShaderConstants.h new file mode 100644 index 0000000000..443e75159d --- /dev/null +++ b/libraries/render-utils/src/render-utils/ShaderConstants.h @@ -0,0 +1,238 @@ +// + +// <@if not RENDER_UTILS_SHADER_CONSTANTS_H@> +// <@def RENDER_UTILS_SHADER_CONSTANTS_H@> + +// Hack comment to absorb the extra '//' scribe prepends + +#ifndef RENDER_UTILS_SHADER_CONSTANTS_H +#define RENDER_UTILS_SHADER_CONSTANTS_H + +#define RENDER_UTILS_ATTR_TEXCOORD0 0 +#define RENDER_UTILS_ATTR_TEXCOORD1 1 +#define RENDER_UTILS_ATTR_COLOR 2 +#define RENDER_UTILS_ATTR_ALPHA 3 + +// World space +#define RENDER_UTILS_ATTR_POSITION_WS 4 +#define RENDER_UTILS_ATTR_NORMAL_WS 5 +#define RENDER_UTILS_ATTR_TANGENT_WS 6 + +// Model space +#define RENDER_UTILS_ATTR_POSITION_MS 7 +#define RENDER_UTILS_ATTR_NORMAL_MS 8 + +// Eye space +#define RENDER_UTILS_ATTR_POSITION_ES 9 + +// Fade +#define RENDER_UTILS_ATTR_FADE1 10 +#define RENDER_UTILS_ATTR_FADE2 11 +#define RENDER_UTILS_ATTR_FADE3 12 + + +#define RENDER_UTILS_BUFFER_DEFERRED_FRAME_TRANSFORM 0 +#define RENDER_UTILS_BUFFER_LIGHT_MODEL 3 +#define RENDER_UTILS_BUFFER_AMBIENT_LIGHT 6 +#define RENDER_UTILS_BUFFER_LIGHT_INDEX 7 + +#define RENDER_UTILS_UNIFORM_LIGHT_RADIUS 0 +#define RENDER_UTILS_UNIFORM_LIGHT_TEXCOORD_TRANSFORM 1 + +// Deferred lighting resolution +#define RENDER_UTILS_TEXTURE_DEFERRRED_COLOR 0 +#define RENDER_UTILS_TEXTURE_DEFERRRED_NORMAL 1 +#define RENDER_UTILS_TEXTURE_DEFERRRED_SPECULAR 2 +#define RENDER_UTILS_TEXTURE_DEFERRRED_DEPTH 3 +#define RENDER_UTILS_TEXTURE_DEFERRED_OBSCURANCE 4 +#define RENDER_UTILS_TEXTURE_DEFERRRED_LINEAR_Z_EYE 5 +#define RENDER_UTILS_TEXTURE_DEFERRED_CURVATURE 6 +#define RENDER_UTILS_TEXTURE_DEFERRED_DIFFUSED_CURVATURE 7 +#define RENDER_UTILS_TEXTURE_DEFERRED_LIGHTING 10 +#define RENDER_UTILS_TEXTURE_SKYBOX 11 + +#define RENDER_UTILS_BUFFER_SHADOW_PARAMS 2 +#define RENDER_UTILS_TEXTURE_SHADOW 12 + +#define RENDER_UTILS_BUFFER_LIGHT_CLUSTER_FRUSTUM_GRID 10 +#define RENDER_UTILS_BUFFER_LIGHT_CLUSTER_GRID 11 +#define RENDER_UTILS_BUFFER_LIGHT_CLUSTER_CONTENT 12 + +// Haze +#define RENDER_UTILS_BUFFER_HAZE_PARAMS 7 +#define RENDER_UTILS_TEXTURE_HAZE_COLOR 0 +#define RENDER_UTILS_TEXTURE_HAZE_LINEAR_DEPTH 1 + +// Fading +#define RENDER_UTILS_BUFFER_FADE_PARAMS 8 +#define RENDER_UTILS_BUFFER_FADE_OBJECT_PARAMS 9 +#define RENDER_UTILS_TEXTURE_FADE_MASK 10 + +// Highlighting +#define RENDER_UTILS_BUFFER_HIGHLIGHT_PARAMS 2 +#define RENDER_UTILS_TEXTURE_HIGHLIGHT_SCENE_DEPTH 0 +#define RENDER_UTILS_TEXTURE_HIGHLIGHT_DEPTH 1 + +// Subsurface scattering +#define RENDER_UTILS_BUFFER_SSSC_PARAMS 13 +#define RENDER_UTILS_TEXTURE_SSSC_PROFILE 12 +#define RENDER_UTILS_TEXTURE_SSSC_LUT 8 +#define RENDER_UTILS_TEXTURE_SSSC_SPECULAR_BECKMANN 9 + +// Ambient occlusion +#define RENDER_UTILS_BUFFER_SSAO_PARAMS 2 +#define RENDER_UTILS_BUFFER_SSAO_DEBUG_PARAMS 3 +#define RENDER_UTILS_TEXTURE_SSAO_PYRAMID 1 +#define RENDER_UTILS_TEXTURE_SSAO_OCCLUSION 0 + +// Temporal anti-aliasing +#define RENDER_UTILS_BUFFER_TAA_PARAMS 2 +#define RENDER_UTILS_TEXTURE_TAA_HISTORY 0 +#define RENDER_UTILS_TEXTURE_TAA_SOURCE 1 +#define RENDER_UTILS_TEXTURE_TAA_VELOCITY 2 +#define RENDER_UTILS_TEXTURE_TAA_DEPTH 3 +#define RENDER_UTILS_TEXTURE_TAA_NEXT 4 + +// Surface Geometry +#define RENDER_UTILS_BUFFER_SG_PARAMS 1 +#define RENDER_UTILS_TEXTURE_SG_DEPTH 0 +#define RENDER_UTILS_TEXTURE_SG_NORMAL 1 + +// Blur +#define RENDER_UTILS_BUFFER_BLUR_PARAMS 0 +#define RENDER_UTILS_TEXTURE_BLUR_SOURCE 0 +#define RENDER_UTILS_TEXTURE_BLUR_DEPTH 1 + +// Tone Mapping +#define RENDER_UTILS_BUFFER_TM_PARAMS 0 +#define RENDER_UTILS_TEXTURE_TM_COLOR 0 + +// Bloom +#define RENDER_UTILS_BUFFER_BLOOM_PARAMS 1 +#define RENDER_UTILS_TEXTURE_BLOOM_COLOR 0 + +// SDF Text rendering +#define RENDER_UTILS_TEXTURE_TEXT_FONT 0 +#define RENDER_UTILS_UNIFORM_TEXT_COLOR 0 +#define RENDER_UTILS_UNIFORM_TEXT_OUTLINE 1 + + +// Debugging +#define RENDER_UTILS_BUFFER_DEBUG_SKYBOX 5 +#define RENDER_UTILS_TEXTURE_DEBUG_DEPTH 11 +#define RENDER_UTILS_TEXTURE_DEBUG_HALF_DEPTH 12 +#define RENDER_UTILS_TEXTURE_DEBUG_OCCLUSION 13 +#define RENDER_UTILS_TEXTURE_DEBUG_OCCLUSION_BLURRED 14 +#define RENDER_UTILS_TEXTURE_DEBUG_VELOCITY 15 +#define RENDER_UTILS_TEXTURE_DEBUG_SHADOWS 16 +#define RENDER_UTILS_TEXTURE_DEBUG_HALF_NORMAL 17 +#define RENDER_UTILS_TEXTURE_DEBUG_SCATTERING 18 + +// + +namespace render_utils { namespace slot { + +namespace uniform { +enum Uniform { + TextColor = RENDER_UTILS_UNIFORM_TEXT_COLOR, + TextOutline = RENDER_UTILS_UNIFORM_TEXT_OUTLINE, + TaaSharpenIntensity = GPU_UNIFORM_EXTRA0, + HighlightOutlineWidth = GPU_UNIFORM_EXTRA0, + LightRadius = RENDER_UTILS_UNIFORM_LIGHT_RADIUS, + TexcoordTransform = RENDER_UTILS_UNIFORM_LIGHT_TEXCOORD_TRANSFORM, +}; +} + +namespace buffer { +enum Buffer { + DeferredFrameTransform = RENDER_UTILS_BUFFER_DEFERRED_FRAME_TRANSFORM, + LightModel = RENDER_UTILS_BUFFER_LIGHT_MODEL, + AmbientLight = RENDER_UTILS_BUFFER_AMBIENT_LIGHT, + HazeParams = RENDER_UTILS_BUFFER_HAZE_PARAMS, + FadeParameters = RENDER_UTILS_BUFFER_FADE_PARAMS, + FadeObjectParameters = RENDER_UTILS_BUFFER_FADE_OBJECT_PARAMS, + LightClusterFrustumGrid = RENDER_UTILS_BUFFER_LIGHT_CLUSTER_FRUSTUM_GRID, + LightClusterGrid = RENDER_UTILS_BUFFER_LIGHT_CLUSTER_GRID, + LightClusterContent = RENDER_UTILS_BUFFER_LIGHT_CLUSTER_CONTENT, + SsscParams = RENDER_UTILS_BUFFER_SSSC_PARAMS, + SsaoParams = RENDER_UTILS_BUFFER_SSAO_PARAMS, + SsaoDebugParams = RENDER_UTILS_BUFFER_SSAO_DEBUG_PARAMS, + LightIndex = RENDER_UTILS_BUFFER_LIGHT_INDEX, + TaaParams = RENDER_UTILS_BUFFER_TAA_PARAMS, + HighlightParams = RENDER_UTILS_BUFFER_HIGHLIGHT_PARAMS, + DebugSkyboxParams = RENDER_UTILS_BUFFER_DEBUG_SKYBOX, + SurfaceGeometryParams = RENDER_UTILS_BUFFER_SG_PARAMS, + BlurParams = RENDER_UTILS_BUFFER_BLUR_PARAMS, + BloomParams = RENDER_UTILS_BUFFER_BLOOM_PARAMS, + ToneMappingParams = RENDER_UTILS_BUFFER_TM_PARAMS, + ShadowParams = RENDER_UTILS_BUFFER_SHADOW_PARAMS, +}; +} // namespace buffer + +namespace texture { +enum Texture { + DeferredColor = RENDER_UTILS_TEXTURE_DEFERRRED_COLOR, + DeferredNormal = RENDER_UTILS_TEXTURE_DEFERRRED_NORMAL, + DeferredSpecular = RENDER_UTILS_TEXTURE_DEFERRRED_SPECULAR, + DeferredDepth = RENDER_UTILS_TEXTURE_DEFERRRED_DEPTH, + DeferredLinearZEye = RENDER_UTILS_TEXTURE_DEFERRRED_LINEAR_Z_EYE, + DeferredObscurance = RENDER_UTILS_TEXTURE_DEFERRED_OBSCURANCE, + DeferredLighting = RENDER_UTILS_TEXTURE_DEFERRED_LIGHTING, + DeferredCurvature = RENDER_UTILS_TEXTURE_DEFERRED_CURVATURE, + DeferredDiffusedCurvature = RENDER_UTILS_TEXTURE_DEFERRED_DIFFUSED_CURVATURE, + SsscLut = RENDER_UTILS_TEXTURE_SSSC_LUT, + SsscSpecularBeckmann = RENDER_UTILS_TEXTURE_SSSC_SPECULAR_BECKMANN, + SsscProfile = RENDER_UTILS_TEXTURE_SSSC_PROFILE, + FadeMask = RENDER_UTILS_TEXTURE_FADE_MASK, + Skybox = RENDER_UTILS_TEXTURE_SKYBOX, + HazeColor = RENDER_UTILS_TEXTURE_HAZE_COLOR, + HazeLinearDepth = RENDER_UTILS_TEXTURE_HAZE_LINEAR_DEPTH, + Shadow = RENDER_UTILS_TEXTURE_SHADOW, + TaaHistory = RENDER_UTILS_TEXTURE_TAA_HISTORY, + TaaSource = RENDER_UTILS_TEXTURE_TAA_SOURCE, + TaaVelocity = RENDER_UTILS_TEXTURE_TAA_VELOCITY, + TaaDepth = RENDER_UTILS_TEXTURE_TAA_DEPTH, + TaaNext = RENDER_UTILS_TEXTURE_TAA_NEXT, + SsaoOcclusion = RENDER_UTILS_TEXTURE_SSAO_OCCLUSION, + SsaoPyramid = RENDER_UTILS_TEXTURE_SSAO_PYRAMID, + HighlightSceneDepth = RENDER_UTILS_TEXTURE_HIGHLIGHT_SCENE_DEPTH, + HighlightDepth = RENDER_UTILS_TEXTURE_HIGHLIGHT_DEPTH, + SurfaceGeometryDepth = RENDER_UTILS_TEXTURE_SG_DEPTH, + SurfaceGeometryNormal = RENDER_UTILS_TEXTURE_SG_NORMAL, + BlurSource = RENDER_UTILS_TEXTURE_BLUR_SOURCE, + BlurDepth = RENDER_UTILS_TEXTURE_BLUR_DEPTH, + BloomColor = RENDER_UTILS_TEXTURE_BLOOM_COLOR, + ToneMappingColor = RENDER_UTILS_TEXTURE_TM_COLOR, + TextFont = RENDER_UTILS_TEXTURE_TEXT_FONT, + DebugDepth = RENDER_UTILS_TEXTURE_DEBUG_DEPTH, + DebugHalfDepth = RENDER_UTILS_TEXTURE_DEBUG_HALF_DEPTH, + DebugOcclusion = RENDER_UTILS_TEXTURE_DEBUG_OCCLUSION, + DebugOcclusionBlurred = RENDER_UTILS_TEXTURE_DEBUG_OCCLUSION_BLURRED, + DebugVelocity = RENDER_UTILS_TEXTURE_DEBUG_VELOCITY, + DebugShadows = RENDER_UTILS_TEXTURE_DEBUG_SHADOWS, + DebugHalfNormal = RENDER_UTILS_TEXTURE_DEBUG_HALF_NORMAL, + DebugScattering = RENDER_UTILS_TEXTURE_DEBUG_SCATTERING, +}; +} // namespace texture + +} } // namespace render_utils::slot + +// !> +// Hack Comment + +#endif // RENDER_UTILS_SHADER_CONSTANTS_H + +// <@if 1@> +// Trigger Scribe include +// <@endif@> + +// <@endif@> + +// Hack Comment diff --git a/libraries/render-utils/src/sdf_text3D.slf b/libraries/render-utils/src/sdf_text3D.slf index 08e50ee8c5..b4be4d1d02 100644 --- a/libraries/render-utils/src/sdf_text3D.slf +++ b/libraries/render-utils/src/sdf_text3D.slf @@ -11,14 +11,15 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html <@include DeferredBufferWrite.slh@> +<@include render-utils/ShaderConstants.h@> -uniform sampler2D Font; -uniform bool Outline; -uniform vec4 Color; +layout(binding=0) uniform sampler2D Font; +layout(location=RENDER_UTILS_UNIFORM_TEXT_OUTLINE) uniform bool Outline; +layout(location=RENDER_UTILS_UNIFORM_TEXT_COLOR) uniform vec4 Color; // the interpolated normal -in vec3 _normalWS; -in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; #define TAA_TEXTURE_LOD_BIAS -3.0 diff --git a/libraries/render-utils/src/sdf_text3D.slv b/libraries/render-utils/src/sdf_text3D.slv index bcf42c3cff..fa7ee6d409 100644 --- a/libraries/render-utils/src/sdf_text3D.slv +++ b/libraries/render-utils/src/sdf_text3D.slv @@ -11,14 +11,14 @@ // <@include gpu/Inputs.slh@> - <@include gpu/Transform.slh@> +<@include render-utils/ShaderConstants.h@> <$declareStandardTransform()$> // the interpolated normal -out vec3 _normalWS; -out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; void main() { _texCoord0 = inTexCoord0.xy; diff --git a/libraries/render-utils/src/sdf_text3D_transparent.slf b/libraries/render-utils/src/sdf_text3D_transparent.slf index 10eb88b198..8e8a6db504 100644 --- a/libraries/render-utils/src/sdf_text3D_transparent.slf +++ b/libraries/render-utils/src/sdf_text3D_transparent.slf @@ -11,14 +11,15 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html <@include DeferredBufferWrite.slh@> +<@include render-utils/ShaderConstants.h@> -uniform sampler2D Font; -uniform bool Outline; -uniform vec4 Color; +layout(binding=0) uniform sampler2D Font; +layout(location=RENDER_UTILS_UNIFORM_TEXT_OUTLINE) uniform bool Outline; +layout(location=RENDER_UTILS_UNIFORM_TEXT_COLOR) uniform vec4 Color; // the interpolated normal -in vec3 _normalWS; -in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; const float gamma = 2.2; const float smoothing = 32.0; diff --git a/libraries/render-utils/src/simple.slf b/libraries/render-utils/src/simple.slf index 7591dc1882..ace0afc60d 100644 --- a/libraries/render-utils/src/simple.slf +++ b/libraries/render-utils/src/simple.slf @@ -14,13 +14,15 @@ <@include DeferredBufferWrite.slh@> +<@include render-utils/ShaderConstants.h@> + // the interpolated normal -in vec3 _normalWS; -in vec3 _normalMS; -in vec4 _color; -in vec2 _texCoord0; -in vec4 _positionMS; -in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_NORMAL_MS) in vec3 _normalMS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_POSITION_MS) in vec4 _positionMS; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; // For retro-compatibility #define _normal _normalWS @@ -28,7 +30,7 @@ in vec4 _positionES; #define _position _positionMS #define _eyePosition _positionES -//PROCEDURAL_COMMON_BLOCK +<@include procedural/ProceduralCommon.slh@> #line 1001 //PROCEDURAL_BLOCK diff --git a/libraries/render-utils/src/simple.slv b/libraries/render-utils/src/simple.slv index 01338be15f..f4bd6795e3 100644 --- a/libraries/render-utils/src/simple.slv +++ b/libraries/render-utils/src/simple.slv @@ -17,13 +17,15 @@ <@include gpu/Transform.slh@> <$declareStandardTransform()$> +<@include render-utils/ShaderConstants.h@> + // the interpolated normal -out vec3 _normalWS; -out vec3 _normalMS; -out vec4 _color; -out vec2 _texCoord0; -out vec4 _positionMS; -out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_NORMAL_MS) out vec3 _normalMS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_POSITION_MS) out vec4 _positionMS; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; void main(void) { _color = color_sRGBAToLinear(inColor); diff --git a/libraries/render-utils/src/simple_fade.slf b/libraries/render-utils/src/simple_fade.slf index 0710c3e10b..c07a608a99 100644 --- a/libraries/render-utils/src/simple_fade.slf +++ b/libraries/render-utils/src/simple_fade.slf @@ -17,14 +17,16 @@ <@include Fade.slh@> <$declareFadeFragmentInstanced()$> +<@include render-utils/ShaderConstants.h@> + // the interpolated normal -in vec3 _normalWS; -in vec3 _normalMS; -in vec4 _color; -in vec2 _texCoord0; -in vec4 _positionMS; -in vec4 _positionES; -in vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_NORMAL_MS) in vec3 _normalMS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_POSITION_MS) in vec4 _positionMS; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; // For retro-compatibility #define _normal _normalWS @@ -32,7 +34,7 @@ in vec4 _positionWS; #define _position _positionMS #define _eyePosition _positionES -//PROCEDURAL_COMMON_BLOCK +<@include procedural/ProceduralCommon.slh@> #line 1001 //PROCEDURAL_BLOCK diff --git a/libraries/render-utils/src/simple_fade.slv b/libraries/render-utils/src/simple_fade.slv index c7d7c5d1b3..24aada33b9 100644 --- a/libraries/render-utils/src/simple_fade.slv +++ b/libraries/render-utils/src/simple_fade.slv @@ -20,14 +20,16 @@ <@include Fade.slh@> <$declareFadeVertexInstanced()$> +<@include render-utils/ShaderConstants.h@> + // the interpolated normal -out vec3 _normalWS; -out vec3 _normalMS; -out vec4 _color; -out vec2 _texCoord0; -out vec4 _positionMS; -out vec4 _positionES; -out vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_NORMAL_MS) out vec3 _normalMS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_POSITION_MS) out vec4 _positionMS; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; void main(void) { _color = color_sRGBAToLinear(inColor); diff --git a/libraries/render-utils/src/simple_opaque_web_browser.slf b/libraries/render-utils/src/simple_opaque_web_browser.slf index 3492e0cc90..3b77fbf431 100644 --- a/libraries/render-utils/src/simple_opaque_web_browser.slf +++ b/libraries/render-utils/src/simple_opaque_web_browser.slf @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// simple_opaque_web_browser.slf +// simple_opaque_web_browser.frag // fragment shader // // Created by Anthony Thibault on 7/25/16. @@ -15,13 +15,15 @@ <@include gpu/Color.slh@> <@include DeferredBufferWrite.slh@> +<@include render-utils/ShaderConstants.h@> + // the albedo texture -uniform sampler2D originalTexture; +layout(binding=0) uniform sampler2D originalTexture; // the interpolated normal -in vec3 _normalWS; -in vec4 _color; -in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; void main(void) { vec4 texel = texture(originalTexture, _texCoord0.st); diff --git a/libraries/render-utils/src/simple_textured.slf b/libraries/render-utils/src/simple_textured.slf index 072e2e8e18..c123a9671f 100644 --- a/libraries/render-utils/src/simple_textured.slf +++ b/libraries/render-utils/src/simple_textured.slf @@ -2,10 +2,10 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// simple_textured.slf +// simple_textured.frag // fragment shader // -// Created by Clément Brisset on 5/29/15. +// Created by Clement Brisset on 5/29/15. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. @@ -14,13 +14,15 @@ <@include DeferredBufferWrite.slh@> +<@include render-utils/ShaderConstants.h@> + // the albedo texture -uniform sampler2D originalTexture; +layout(binding=0) uniform sampler2D originalTexture; // the interpolated normal -in vec3 _normalWS; -in vec4 _color; -in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; void main(void) { vec4 texel = texture(originalTexture, _texCoord0); diff --git a/libraries/render-utils/src/simple_textured_fade.slf b/libraries/render-utils/src/simple_textured_fade.slf index 9ec02798ef..850282d40f 100644 --- a/libraries/render-utils/src/simple_textured_fade.slf +++ b/libraries/render-utils/src/simple_textured_fade.slf @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// simple_textured_fade.slf +// simple_textured_fade.frag // fragment shader // // Created by Olivier Prat on 06/05/17. @@ -17,14 +17,16 @@ <@include Fade.slh@> +<@include render-utils/ShaderConstants.h@> + // the albedo texture -uniform sampler2D originalTexture; +layout(binding=0) uniform sampler2D originalTexture; // the interpolated normal -in vec3 _normalWS; -in vec4 _color; -in vec2 _texCoord0; -in vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; // Declare after all samplers to prevent sampler location mix up with originalTexture <$declareFadeFragmentInstanced()$> diff --git a/libraries/render-utils/src/simple_textured_unlit.slf b/libraries/render-utils/src/simple_textured_unlit.slf index c5cca9e0f8..78ef85ee21 100644 --- a/libraries/render-utils/src/simple_textured_unlit.slf +++ b/libraries/render-utils/src/simple_textured_unlit.slf @@ -5,7 +5,7 @@ // simple_textured_unlit.frag // fragment shader // -// Created by Clément Brisset on 5/29/15. +// Created by Clement Brisset on 5/29/15. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. @@ -15,13 +15,15 @@ <@include gpu/Color.slh@> <@include DeferredBufferWrite.slh@> +<@include render-utils/ShaderConstants.h@> + // the albedo texture -uniform sampler2D originalTexture; +layout(binding=0) uniform sampler2D originalTexture; // the interpolated normal -in vec3 _normalWS; -in vec4 _color; -in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; void main(void) { vec4 texel = texture(originalTexture, _texCoord0.st); diff --git a/libraries/render-utils/src/simple_textured_unlit_fade.slf b/libraries/render-utils/src/simple_textured_unlit_fade.slf index a8d0f3bffe..c5882c2173 100644 --- a/libraries/render-utils/src/simple_textured_unlit_fade.slf +++ b/libraries/render-utils/src/simple_textured_unlit_fade.slf @@ -17,14 +17,16 @@ <@include Fade.slh@> +<@include render-utils/ShaderConstants.h@> + // the albedo texture -uniform sampler2D originalTexture; +layout(binding=0) uniform sampler2D originalTexture; // the interpolated normal -in vec3 _normalWS; -in vec4 _color; -in vec2 _texCoord0; -in vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; // Declare after all samplers to prevent sampler location mix up with originalTexture <$declareFadeFragmentInstanced()$> diff --git a/libraries/render-utils/src/simple_transparent.slf b/libraries/render-utils/src/simple_transparent.slf index ee79d2c0c4..b52c2a613e 100644 --- a/libraries/render-utils/src/simple_transparent.slf +++ b/libraries/render-utils/src/simple_transparent.slf @@ -14,13 +14,15 @@ <@include DeferredBufferWrite.slh@> +<@include render-utils/ShaderConstants.h@> + // the interpolated normal -in vec3 _normalWS; -in vec3 _normalMS; -in vec4 _color; -in vec2 _texCoord0; -in vec4 _positionMS; -in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_NORMAL_MS) in vec3 _normalMS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_POSITION_MS) in vec4 _positionMS; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; // For retro-compatibility #define _normal _normalWS @@ -28,7 +30,7 @@ in vec4 _positionES; #define _position _positionMS #define _eyePosition _positionES -//PROCEDURAL_COMMON_BLOCK +<@include procedural/ProceduralCommon.slh@> #line 1001 //PROCEDURAL_BLOCK diff --git a/libraries/render-utils/src/simple_transparent_textured.slf b/libraries/render-utils/src/simple_transparent_textured.slf index 96895f74f3..b7396c3d37 100644 --- a/libraries/render-utils/src/simple_transparent_textured.slf +++ b/libraries/render-utils/src/simple_transparent_textured.slf @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// simple_transparent_textured.slf +// simple_transparent_textured.frag // fragment shader // // Created by Sam Gateau on 4/3/17. @@ -14,13 +14,15 @@ <@include DeferredBufferWrite.slh@> +<@include render-utils/ShaderConstants.h@> + // the albedo texture -uniform sampler2D originalTexture; +layout(location=0) uniform sampler2D originalTexture; // the interpolated normal -in vec3 _normalWS; -in vec4 _color; -in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; void main(void) { vec4 texel = texture(originalTexture, _texCoord0); diff --git a/libraries/render-utils/src/simple_transparent_textured_fade.slf b/libraries/render-utils/src/simple_transparent_textured_fade.slf index 947640687c..92c6fde0bd 100644 --- a/libraries/render-utils/src/simple_transparent_textured_fade.slf +++ b/libraries/render-utils/src/simple_transparent_textured_fade.slf @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// simple_transparent_textured_fade.slf +// simple_transparent_textured_fade.frag // fragment shader // // Created by Olivier Prat on 06/05/17. @@ -23,14 +23,16 @@ <@include Fade.slh@> -// the albedo texture -uniform sampler2D originalTexture; +<@include render-utils/ShaderConstants.h@> -in vec4 _positionES; -in vec3 _normalWS; -in vec4 _color; -in vec2 _texCoord0; -in vec4 _positionWS; +// the albedo texture +layout(binding=0) uniform sampler2D originalTexture; + +layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; // Declare after all samplers to prevent sampler location mix up with originalTexture <$declareFadeFragmentInstanced()$> diff --git a/libraries/render-utils/src/simple_transparent_textured_unlit.slf b/libraries/render-utils/src/simple_transparent_textured_unlit.slf index 7582af59c6..a3e7c65cd1 100644 --- a/libraries/render-utils/src/simple_transparent_textured_unlit.slf +++ b/libraries/render-utils/src/simple_transparent_textured_unlit.slf @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// simple_transparent_textured_unlit.slf +// simple_transparent_textured_unlit.frag // fragment shader // // Created by Sam Gateau on 4/3/17. @@ -14,13 +14,15 @@ <@include gpu/Color.slh@> +<@include render-utils/ShaderConstants.h@> + // the albedo texture -uniform sampler2D originalTexture; +layout(binding=0) uniform sampler2D originalTexture; -in vec4 _color; -in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location = 0) out vec4 _fragColor0; +layout(location=0) out vec4 _fragColor0; void main(void) { vec4 texel = texture(originalTexture, _texCoord0.st); diff --git a/libraries/render-utils/src/simple_transparent_textured_unlit_fade.slf b/libraries/render-utils/src/simple_transparent_textured_unlit_fade.slf index b4f95fc317..508ea9a68b 100644 --- a/libraries/render-utils/src/simple_transparent_textured_unlit_fade.slf +++ b/libraries/render-utils/src/simple_transparent_textured_unlit_fade.slf @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// simple_transparent_textured_unlit_fade.slf +// simple_transparent_textured_unlit_fade.frag // fragment shader // // Created by Olivier Prat on 06/05/17. @@ -16,14 +16,16 @@ <@include Fade.slh@> +<@include render-utils/ShaderConstants.h@> + // the albedo texture -uniform sampler2D originalTexture; +layout(binding=0) uniform sampler2D originalTexture; -in vec4 _color; -in vec2 _texCoord0; -in vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; -layout(location = 0) out vec4 _fragColor0; +layout(location=0) out vec4 _fragColor0; // Declare after all samplers to prevent sampler location mix up with originalTexture <$declareFadeFragmentInstanced()$> diff --git a/libraries/render-utils/src/simple_transparent_web_browser.slf b/libraries/render-utils/src/simple_transparent_web_browser.slf index bb2a0846ed..3f05a8a480 100644 --- a/libraries/render-utils/src/simple_transparent_web_browser.slf +++ b/libraries/render-utils/src/simple_transparent_web_browser.slf @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// simple_transparent_web_browser.slf +// simple_transparent_web_browser.frag // fragment shader // // Created by Anthony Thibault on 7/25/16. @@ -15,13 +15,15 @@ <@include gpu/Color.slh@> <@include DeferredBufferWrite.slh@> +<@include render-utils/ShaderConstants.h@> + // the albedo texture -uniform sampler2D originalTexture; +layout(binding=0) uniform sampler2D originalTexture; // the interpolated normal -in vec3 _normalWS; -in vec4 _color; -in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; void main(void) { vec4 texel = texture(originalTexture, _texCoord0.st); diff --git a/libraries/render-utils/src/skin_model.slv b/libraries/render-utils/src/skin_model.slv index 1d5013e623..fb2f8a8e34 100644 --- a/libraries/render-utils/src/skin_model.slv +++ b/libraries/render-utils/src/skin_model.slv @@ -20,15 +20,17 @@ <@include Skinning.slh@> <$declareUseDualQuaternionSkinning()$> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTexMapArrayBuffer()$> -out vec4 _positionES; -out vec2 _texCoord0; -out vec2 _texCoord1; -out vec3 _normalWS; -out vec3 _color; -out float _alpha; +<@include render-utils/ShaderConstants.h@> + +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; void main(void) { vec4 position = vec4(0.0, 0.0, 0.0, 0.0); diff --git a/libraries/render-utils/src/skin_model_dq.slv b/libraries/render-utils/src/skin_model_dq.slv index 21191e966d..db062087be 100644 --- a/libraries/render-utils/src/skin_model_dq.slv +++ b/libraries/render-utils/src/skin_model_dq.slv @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// skin_model.vert +// skin_model_dq.vert // vertex shader // // Created by Andrzej Kapolka on 10/14/13. @@ -20,15 +20,17 @@ <@include Skinning.slh@> <$declareUseDualQuaternionSkinning(1)$> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTexMapArrayBuffer()$> -out vec4 _positionES; -out vec2 _texCoord0; -out vec2 _texCoord1; -out vec3 _normalWS; -out vec3 _color; -out float _alpha; +<@include render-utils/ShaderConstants.h@> + +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; void main(void) { vec4 position = vec4(0.0, 0.0, 0.0, 0.0); diff --git a/libraries/render-utils/src/skin_model_fade.slv b/libraries/render-utils/src/skin_model_fade.slv index 6c3df7586d..30b3122334 100644 --- a/libraries/render-utils/src/skin_model_fade.slv +++ b/libraries/render-utils/src/skin_model_fade.slv @@ -20,16 +20,18 @@ <@include Skinning.slh@> <$declareUseDualQuaternionSkinning()$> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTexMapArrayBuffer()$> -out vec4 _positionES; -out vec2 _texCoord0; -out vec2 _texCoord1; -out vec3 _normalWS; -out vec3 _color; -out float _alpha; -out vec4 _positionWS; +<@include render-utils/ShaderConstants.h@> + +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; void main(void) { vec4 position = vec4(0.0, 0.0, 0.0, 0.0); diff --git a/libraries/render-utils/src/skin_model_fade_dq.slv b/libraries/render-utils/src/skin_model_fade_dq.slv index 9d9ddaeaf8..fb23e283bc 100644 --- a/libraries/render-utils/src/skin_model_fade_dq.slv +++ b/libraries/render-utils/src/skin_model_fade_dq.slv @@ -20,16 +20,18 @@ <@include Skinning.slh@> <$declareUseDualQuaternionSkinning(1)$> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTexMapArrayBuffer()$> -out vec4 _positionES; -out vec2 _texCoord0; -out vec2 _texCoord1; -out vec3 _normalWS; -out vec3 _color; -out float _alpha; -out vec4 _positionWS; +<@include render-utils/ShaderConstants.h@> + +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; void main(void) { vec4 position = vec4(0.0, 0.0, 0.0, 0.0); diff --git a/libraries/render-utils/src/skin_model_normal_map.slv b/libraries/render-utils/src/skin_model_normal_map.slv index fd3efd087e..288e338b10 100644 --- a/libraries/render-utils/src/skin_model_normal_map.slv +++ b/libraries/render-utils/src/skin_model_normal_map.slv @@ -20,16 +20,18 @@ <@include Skinning.slh@> <$declareUseDualQuaternionSkinning()$> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTexMapArrayBuffer()$> -out vec4 _positionES; -out vec2 _texCoord0; -out vec2 _texCoord1; -out vec3 _normalWS; -out vec3 _tangentWS; -out vec3 _color; -out float _alpha; +<@include render-utils/ShaderConstants.h@> + +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TANGENT_WS) out vec3 _tangentWS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; void main(void) { vec4 position = vec4(0.0, 0.0, 0.0, 0.0); diff --git a/libraries/render-utils/src/skin_model_normal_map_dq.slv b/libraries/render-utils/src/skin_model_normal_map_dq.slv index 4c56e0d64d..90e85f8a92 100644 --- a/libraries/render-utils/src/skin_model_normal_map_dq.slv +++ b/libraries/render-utils/src/skin_model_normal_map_dq.slv @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// skin_model_normal_map.vert +// skin_model_normal_map_dq.vert // vertex shader // // Created by Andrzej Kapolka on 10/29/13. @@ -15,21 +15,22 @@ <@include gpu/Inputs.slh@> <@include gpu/Color.slh@> <@include gpu/Transform.slh@> +<@include render-utils/ShaderConstants.h@> <$declareStandardTransform()$> <@include Skinning.slh@> <$declareUseDualQuaternionSkinning(1)$> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTexMapArrayBuffer()$> -out vec4 _positionES; -out vec2 _texCoord0; -out vec2 _texCoord1; -out vec3 _normalWS; -out vec3 _tangentWS; -out vec3 _color; -out float _alpha; +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TANGENT_WS) out vec3 _tangentWS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; void main(void) { vec4 position = vec4(0.0, 0.0, 0.0, 0.0); diff --git a/libraries/render-utils/src/skin_model_normal_map_fade.slv b/libraries/render-utils/src/skin_model_normal_map_fade.slv index 47cc790f70..393a756e7e 100644 --- a/libraries/render-utils/src/skin_model_normal_map_fade.slv +++ b/libraries/render-utils/src/skin_model_normal_map_fade.slv @@ -20,17 +20,19 @@ <@include Skinning.slh@> <$declareUseDualQuaternionSkinning()$> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTexMapArrayBuffer()$> -out vec4 _positionES; -out vec2 _texCoord0; -out vec2 _texCoord1; -out vec3 _normalWS; -out vec3 _tangentWS; -out vec3 _color; -out float _alpha; -out vec4 _positionWS; +<@include render-utils/ShaderConstants.h@> + +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TANGENT_WS) out vec3 _tangentWS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; void main(void) { vec4 position = vec4(0.0, 0.0, 0.0, 0.0); diff --git a/libraries/render-utils/src/skin_model_normal_map_fade_dq.slv b/libraries/render-utils/src/skin_model_normal_map_fade_dq.slv index 092d7b214f..862c14297f 100644 --- a/libraries/render-utils/src/skin_model_normal_map_fade_dq.slv +++ b/libraries/render-utils/src/skin_model_normal_map_fade_dq.slv @@ -20,17 +20,19 @@ <@include Skinning.slh@> <$declareUseDualQuaternionSkinning(1)$> -<@include MaterialTextures.slh@> +<@include graphics/MaterialTextures.slh@> <$declareMaterialTexMapArrayBuffer()$> -out vec4 _positionES; -out vec2 _texCoord0; -out vec2 _texCoord1; -out vec3 _normalWS; -out vec3 _tangentWS; -out vec3 _color; -out float _alpha; -out vec4 _positionWS; +<@include render-utils/ShaderConstants.h@> + +layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; +layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; +layout(location=RENDER_UTILS_ATTR_TANGENT_WS) out vec3 _tangentWS; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; void main(void) { vec4 position = vec4(0.0, 0.0, 0.0, 0.0); diff --git a/libraries/render-utils/src/skin_model_shadow_dq.slv b/libraries/render-utils/src/skin_model_shadow_dq.slv index 74cd4076bc..a60eed62d3 100644 --- a/libraries/render-utils/src/skin_model_shadow_dq.slv +++ b/libraries/render-utils/src/skin_model_shadow_dq.slv @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// skin_model_shadow.vert +// skin_model_shadow_dq.vert // vertex shader // // Created by Andrzej Kapolka on 3/24/14. diff --git a/libraries/render-utils/src/skin_model_shadow_fade.slv b/libraries/render-utils/src/skin_model_shadow_fade.slv index e3ddd25e81..4881cb9f62 100644 --- a/libraries/render-utils/src/skin_model_shadow_fade.slv +++ b/libraries/render-utils/src/skin_model_shadow_fade.slv @@ -14,12 +14,14 @@ <@include gpu/Inputs.slh@> <@include gpu/Transform.slh@> +<@include render-utils/ShaderConstants.h@> + <$declareStandardTransform()$> <@include Skinning.slh@> <$declareUseDualQuaternionSkinning()$> -out vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; void main(void) { vec4 position = vec4(0.0, 0.0, 0.0, 0.0); diff --git a/libraries/render-utils/src/skin_model_shadow_fade_dq.slv b/libraries/render-utils/src/skin_model_shadow_fade_dq.slv index dcb15c6e84..c45107b47c 100644 --- a/libraries/render-utils/src/skin_model_shadow_fade_dq.slv +++ b/libraries/render-utils/src/skin_model_shadow_fade_dq.slv @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// skin_model_shadow_fade.vert +// skin_model_shadow_fade_dq.vert // vertex shader // // Created by Olivier Prat on 06/045/17. @@ -14,12 +14,14 @@ <@include gpu/Inputs.slh@> <@include gpu/Transform.slh@> +<@include render-utils/ShaderConstants.h@> +<@include Skinning.slh@> + <$declareStandardTransform()$> -<@include Skinning.slh@> <$declareUseDualQuaternionSkinning(1)$> -out vec4 _positionWS; +layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; void main(void) { vec4 position = vec4(0.0, 0.0, 0.0, 0.0); diff --git a/libraries/render-utils/src/ssao.slh b/libraries/render-utils/src/ssao.slh index c9b27bc2c8..5341a1682a 100644 --- a/libraries/render-utils/src/ssao.slh +++ b/libraries/render-utils/src/ssao.slh @@ -11,6 +11,8 @@ <@if not SSAO_SLH@> <@def SSAO_SLH@> +<@include render-utils/ShaderConstants.h@> + <@func declarePackOcclusionDepth()@> const float FAR_PLANE_Z = -300.0; @@ -42,7 +44,7 @@ struct AmbientOcclusionParams { float _gaussianCoefs[8]; }; -uniform ambientOcclusionParamsBuffer { +layout(binding=RENDER_UTILS_BUFFER_SSAO_PARAMS) uniform ambientOcclusionParamsBuffer { AmbientOcclusionParams params; }; @@ -230,7 +232,7 @@ vec3 getTapLocationClamped(int sampleNumber, float spinAngle, float outerRadius, // the depth pyramid texture -uniform sampler2D pyramidMap; +layout(binding=RENDER_UTILS_TEXTURE_SSAO_PYRAMID) uniform sampler2D pyramidMap; float getZEye(ivec2 pixel, int level) { return -texelFetch(pyramidMap, pixel, level).x; @@ -311,7 +313,7 @@ float evalAO(in vec3 C, in vec3 n_C, in vec3 Q) { <$declareAmbientOcclusion()$> // the source occlusion texture -uniform sampler2D occlusionMap; +layout(binding=RENDER_UTILS_TEXTURE_SSAO_OCCLUSION) uniform sampler2D occlusionMap; vec2 fetchOcclusionDepthRaw(ivec2 coords, out vec3 raw) { raw = texelFetch(occlusionMap, coords, 0).xyz; diff --git a/libraries/render-utils/src/ssao_debugOcclusion.slf b/libraries/render-utils/src/ssao_debugOcclusion.slf index 6af457db67..007fd0cd7b 100644 --- a/libraries/render-utils/src/ssao_debugOcclusion.slf +++ b/libraries/render-utils/src/ssao_debugOcclusion.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// ssao_debugOcclusion.frag +// // Created by Sam Gateau on 1/1/16. // Copyright 2016 High Fidelity, Inc. // @@ -24,7 +26,7 @@ struct DebugParams{ vec4 pixelInfo; }; -uniform debugAmbientOcclusionBuffer { +layout(binding=RENDER_UTILS_BUFFER_SSAO_DEBUG_PARAMS) uniform debugAmbientOcclusionBuffer { DebugParams debugParams; }; @@ -32,7 +34,7 @@ vec2 getDebugCursorTexcoord(){ return debugParams.pixelInfo.xy; } -out vec4 outFragColor; +layout(location=0) out vec4 outFragColor; void main(void) { vec2 imageSize = getSideImageSize(getResolutionLevel()); diff --git a/libraries/render-utils/src/ssao_makeHorizontalBlur.slf b/libraries/render-utils/src/ssao_makeHorizontalBlur.slf index 7c10a2a208..94dbb2b00c 100644 --- a/libraries/render-utils/src/ssao_makeHorizontalBlur.slf +++ b/libraries/render-utils/src/ssao_makeHorizontalBlur.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// ssao_makeHorizontalBlur.frag +// // Created by Sam Gateau on 1/1/16. // Copyright 2016 High Fidelity, Inc. // @@ -15,7 +17,7 @@ const ivec2 horizontal = ivec2(1,0); <$declareBlurPass(horizontal)$> -out vec4 outFragColor; +layout(location=0) out vec4 outFragColor; void main(void) { outFragColor = vec4(getBlurredOcclusion(gl_FragCoord.xy), 1.0); diff --git a/libraries/render-utils/src/ssao_makeOcclusion.slf b/libraries/render-utils/src/ssao_makeOcclusion.slf index 4c808342c5..1b638d4270 100644 --- a/libraries/render-utils/src/ssao_makeOcclusion.slf +++ b/libraries/render-utils/src/ssao_makeOcclusion.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// ssao_makeOcclusion.frag +// // Created by Sam Gateau on 1/1/16. // Copyright 2016 High Fidelity, Inc. // @@ -17,7 +19,7 @@ <$declarePackOcclusionDepth()$> -out vec4 outFragColor; +layout(location=0) out vec4 outFragColor; void main(void) { vec2 imageSize = getSideImageSize(getResolutionLevel()); diff --git a/libraries/render-utils/src/ssao_makePyramid.slf b/libraries/render-utils/src/ssao_makePyramid.slf index 70d46fb432..c87fe1e682 100644 --- a/libraries/render-utils/src/ssao_makePyramid.slf +++ b/libraries/render-utils/src/ssao_makePyramid.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// ssao_makePyramid.frag +// // Created by Sam Gateau on 1/1/16. // Copyright 2016 High Fidelity, Inc. // @@ -12,9 +14,9 @@ <@include ssao.slh@> <$declareAmbientOcclusion()$> -uniform sampler2D depthMap; +layout(binding=0) uniform sampler2D depthMap; -out vec4 outFragColor; +layout(location=0) out vec4 outFragColor; void main(void) { float Zdb = texelFetch(depthMap, ivec2(gl_FragCoord.xy), 0).x; diff --git a/libraries/render-utils/src/ssao_makeVerticalBlur.slf b/libraries/render-utils/src/ssao_makeVerticalBlur.slf index 3325bfb79c..0b9b5c7eaf 100644 --- a/libraries/render-utils/src/ssao_makeVerticalBlur.slf +++ b/libraries/render-utils/src/ssao_makeVerticalBlur.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// ssao_makeVerticalBlur.frag +// // Created by Sam Gateau on 1/1/16. // Copyright 2016 High Fidelity, Inc. // @@ -13,7 +15,7 @@ const ivec2 vertical = ivec2(0,1); <$declareBlurPass(vertical)$> -out vec4 outFragColor; +layout(location=0) out vec4 outFragColor; void main(void) { float occlusion = getBlurredOcclusion(gl_FragCoord.xy).x; diff --git a/libraries/render-utils/src/standardDrawTexture.slf b/libraries/render-utils/src/standardDrawTexture.slf index 95ac82557c..1a8af0f71c 100644 --- a/libraries/render-utils/src/standardDrawTexture.slf +++ b/libraries/render-utils/src/standardDrawTexture.slf @@ -11,15 +11,17 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +<@include gpu/ShaderConstants.h@> + // the texture -uniform sampler2D colorMap; +layout(binding=0) uniform sampler2D colorMap; -in vec3 varPosition; -in vec3 varNormal; -in vec2 varTexCoord0; -in vec4 varColor; +layout(location=GPU_ATTR_POSITION) in vec3 varPosition; +layout(location=GPU_ATTR_NORMAL) in vec3 varNormal; +layout(location=GPU_ATTR_TEXCOORD0) in vec2 varTexCoord0; +layout(location=GPU_ATTR_COLOR) in vec4 varColor; -out vec4 outFragColor; +layout(location=0) out vec4 outFragColor; void main(void) { vec4 color = texture(colorMap, varTexCoord0); diff --git a/libraries/render-utils/src/standardTransformPNTC.slv b/libraries/render-utils/src/standardTransformPNTC.slv index 8ec685cea0..5f933aa037 100644 --- a/libraries/render-utils/src/standardTransformPNTC.slv +++ b/libraries/render-utils/src/standardTransformPNTC.slv @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// standardTransformPNTC.slv +// standardTransformPNTC.vert // vertex shader // // Created by Sam Gateau on 6/10/2015. @@ -17,10 +17,10 @@ <@include gpu/Transform.slh@> <$declareStandardTransform()$> -out vec3 varPosition; -out vec3 varNormal; -out vec2 varTexCoord0; -out vec4 varColor; +layout(location=GPU_ATTR_POSITION) out vec3 varPosition; +layout(location=GPU_ATTR_NORMAL) out vec3 varNormal; +layout(location=GPU_ATTR_TEXCOORD0) out vec2 varTexCoord0; +layout(location=GPU_ATTR_COLOR) out vec4 varColor; void main(void) { varTexCoord0 = inTexCoord0.st; diff --git a/libraries/render-utils/src/stencil_drawMask.slf b/libraries/render-utils/src/stencil_drawMask.slf index 3eedeecb82..5ba09a8264 100644 --- a/libraries/render-utils/src/stencil_drawMask.slf +++ b/libraries/render-utils/src/stencil_drawMask.slf @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// stencil_drawMask.slf +// stencil_drawMask.frag // fragment shader // // Created by Sam Gateau on 5/31/17. @@ -12,7 +12,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -in vec2 varTexCoord0; +layout(location=0) in vec2 varTexCoord0; float aspectRatio = 0.95; diff --git a/libraries/render-utils/src/subsurfaceScattering_drawScattering.slf b/libraries/render-utils/src/subsurfaceScattering_drawScattering.slf index e66d881e11..00b60d6fd4 100644 --- a/libraries/render-utils/src/subsurfaceScattering_drawScattering.slf +++ b/libraries/render-utils/src/subsurfaceScattering_drawScattering.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// subsurfaceScattering_drawScattering.frag +// // Created by Sam Gateau on 6/8/16. // Copyright 2016 High Fidelity, Inc. // @@ -10,6 +12,7 @@ // +<@include gpu/ShaderConstants.h@> <@include DeferredBufferRead.slh@> <@include graphics/Light.slh@> @@ -20,10 +23,10 @@ <@include SubsurfaceScattering.slh@> <$declareSubsurfaceScatteringBRDF()$> -in vec2 varTexCoord0; -out vec4 _fragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 _fragColor; -uniform vec2 uniformCursorTexcoord = vec2(0.5); +layout(location=GPU_UNIFORM_EXTRA0) uniform vec2 uniformCursorTexcoord = vec2(0.5); //uniform vec3 uniformLightVector = vec3(1.0); diff --git a/libraries/render-utils/src/subsurfaceScattering_makeLUT.slf b/libraries/render-utils/src/subsurfaceScattering_makeLUT.slf index 1cbf599558..6e10861875 100644 --- a/libraries/render-utils/src/subsurfaceScattering_makeLUT.slf +++ b/libraries/render-utils/src/subsurfaceScattering_makeLUT.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// subsurfaceScattering_makeLUT.frag +// // Created by Sam Gateau on 6/8/16. // Copyright 2016 High Fidelity, Inc. // @@ -13,8 +15,8 @@ <$declareSubsurfaceScatteringProfileSource()$> <$declareSubsurfaceScatteringIntegrate(2000)$> -in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 outFragColor; void main(void) { diff --git a/libraries/render-utils/src/subsurfaceScattering_makeProfile.slf b/libraries/render-utils/src/subsurfaceScattering_makeProfile.slf index ea4a864448..31122dcb1f 100644 --- a/libraries/render-utils/src/subsurfaceScattering_makeProfile.slf +++ b/libraries/render-utils/src/subsurfaceScattering_makeProfile.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// subsurfaceScattering_makeProfile.frag +// // Created by Sam Gateau on 6/27/16. // Copyright 2016 High Fidelity, Inc. // @@ -12,8 +14,8 @@ <@include SubsurfaceScattering.slh@> <$declareSubsurfaceScatteringGenerateProfileMap()$> -in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 outFragColor; void main(void) { outFragColor = vec4(generateProfile(varTexCoord0.xy), 1.0); diff --git a/libraries/render-utils/src/subsurfaceScattering_makeSpecularBeckmann.slf b/libraries/render-utils/src/subsurfaceScattering_makeSpecularBeckmann.slf index f10d287c35..59e73100dd 100644 --- a/libraries/render-utils/src/subsurfaceScattering_makeSpecularBeckmann.slf +++ b/libraries/render-utils/src/subsurfaceScattering_makeSpecularBeckmann.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// subsurfaceScattering_makeSpecularBeckmann.frag +// // Created by Sam Gateau on 6/30/16. // Copyright 2016 High Fidelity, Inc. // @@ -11,8 +13,8 @@ -in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 outFragColor; float specularBeckmann(float ndoth, float roughness) { float alpha = acos(ndoth); diff --git a/libraries/render-utils/src/surfaceGeometry_copyDepth.slf b/libraries/render-utils/src/surfaceGeometry_copyDepth.slf index 9db8cdbb01..7eb097224e 100644 --- a/libraries/render-utils/src/surfaceGeometry_copyDepth.slf +++ b/libraries/render-utils/src/surfaceGeometry_copyDepth.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// surfaceGeometry_copyDepth.frag +// // Created by Olivier Prat on 08/08/17. // Copyright 2017 High Fidelity, Inc. // @@ -9,9 +11,9 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -uniform sampler2D depthMap; +layout(binding=0) uniform sampler2D depthMap; -out vec4 outFragColor; +layout(location=0) out vec4 outFragColor; void main(void) { float Zdb = texelFetch(depthMap, ivec2(gl_FragCoord.xy), 0).x; diff --git a/libraries/render-utils/src/surfaceGeometry_downsampleDepthNormal.slf b/libraries/render-utils/src/surfaceGeometry_downsampleDepthNormal.slf index 82895d4684..34e78ea4ff 100644 --- a/libraries/render-utils/src/surfaceGeometry_downsampleDepthNormal.slf +++ b/libraries/render-utils/src/surfaceGeometry_downsampleDepthNormal.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// surfaceGeometry_downsampleDepthNormal.frag +// // Created by Sam Gateau on 6/3/16. // Copyright 2016 High Fidelity, Inc. // @@ -11,14 +13,15 @@ <@include gpu/PackedNormal.slh@> +<@include render-utils/ShaderConstants.h@> -uniform sampler2D linearDepthMap; -uniform sampler2D normalMap; +layout(binding=RENDER_UTILS_TEXTURE_SG_DEPTH) uniform sampler2D linearDepthMap; +layout(binding=RENDER_UTILS_TEXTURE_SG_NORMAL) uniform sampler2D normalMap; -in vec2 varTexCoord0; +layout(location=0) in vec2 varTexCoord0; -layout(location = 0) out vec4 outLinearDepth; -layout(location = 1) out vec4 outNormal; +layout(location=0) out vec4 outLinearDepth; +layout(location=1) out vec4 outNormal; void main(void) { // Gather 2 by 2 quads from texture and downsample diff --git a/libraries/render-utils/src/surfaceGeometry_makeCurvature.slf b/libraries/render-utils/src/surfaceGeometry_makeCurvature.slf index ecbc60b648..b49bd618da 100644 --- a/libraries/render-utils/src/surfaceGeometry_makeCurvature.slf +++ b/libraries/render-utils/src/surfaceGeometry_makeCurvature.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// surfaceGeometry_makeCurvature.frag +// // Created by Sam Gateau on 6/3/16. // Copyright 2016 High Fidelity, Inc. // @@ -10,6 +12,8 @@ // <@include DeferredTransform.slh@> +<@include render-utils/ShaderConstants.h@> + <$declareDeferredFrameTransform()$> <@include gpu/PackedNormal.slh@> @@ -21,7 +25,7 @@ struct SurfaceGeometryParams { vec4 curvatureInfo; }; -uniform surfaceGeometryParamsBuffer { +layout(binding= RENDER_UTILS_BUFFER_SG_PARAMS) uniform surfaceGeometryParamsBuffer { SurfaceGeometryParams params; }; @@ -42,7 +46,8 @@ bool isFullResolution() { } -uniform sampler2D linearDepthMap; +layout(binding=RENDER_UTILS_TEXTURE_SG_DEPTH) uniform sampler2D linearDepthMap; + float getZEye(ivec2 pixel) { return -texelFetch(linearDepthMap, pixel, 0).x; } @@ -54,7 +59,7 @@ vec2 sideToFrameTexcoord(vec2 side, vec2 texcoordPos) { return vec2((texcoordPos.x + side.x) * side.y, texcoordPos.y); } -uniform sampler2D normalMap; +layout(binding=RENDER_UTILS_TEXTURE_SG_NORMAL) uniform sampler2D normalMap; vec3 getRawNormal(vec2 texcoord) { return texture(normalMap, texcoord).xyz; @@ -79,8 +84,8 @@ float getEyeDepthDiff(vec2 texcoord, vec2 delta) { -in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 outFragColor; void main(void) { // Pixel being shaded diff --git a/libraries/render-utils/src/surfaceGeometry_makeLinearDepth.slf b/libraries/render-utils/src/surfaceGeometry_makeLinearDepth.slf index d512f613bc..116f3b7686 100644 --- a/libraries/render-utils/src/surfaceGeometry_makeLinearDepth.slf +++ b/libraries/render-utils/src/surfaceGeometry_makeLinearDepth.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// surfaceGeometry_makeLinearDepth.frag +// // Created by Sam Gateau on 6/3/16. // Copyright 2016 High Fidelity, Inc. // @@ -9,13 +11,14 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +<@include render-utils/ShaderConstants.h@> + <@include DeferredTransform.slh@> <$declareDeferredFrameTransform()$> +layout(binding=RENDER_UTILS_TEXTURE_SG_DEPTH) uniform sampler2D depthMap; -uniform sampler2D depthMap; - -out vec4 outFragColor; +layout(location=0) out vec4 outFragColor; void main(void) { float Zdb = texelFetch(depthMap, ivec2(gl_FragCoord.xy), 0).x; diff --git a/libraries/render-utils/src/taa.slf b/libraries/render-utils/src/taa.slf index 8d172871d4..a2b58d3050 100644 --- a/libraries/render-utils/src/taa.slf +++ b/libraries/render-utils/src/taa.slf @@ -15,8 +15,8 @@ <@include taa.slh@> -in vec2 varTexCoord0; -layout(location = 0) out vec4 outFragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 outFragColor; void main() { vec2 fragUV = varTexCoord0; diff --git a/libraries/render-utils/src/taa.slh b/libraries/render-utils/src/taa.slh index 3ca5b10d57..26ffe55263 100644 --- a/libraries/render-utils/src/taa.slh +++ b/libraries/render-utils/src/taa.slh @@ -13,13 +13,14 @@ <@include DeferredTransform.slh@> <$declareDeferredFrameTransform()$> +<@include render-utils/ShaderConstants.h@> <@include gpu/Color.slh@> -uniform sampler2D depthMap; -uniform sampler2D sourceMap; -uniform sampler2D historyMap; -uniform sampler2D velocityMap; -uniform sampler2D nextMap; +layout(binding=RENDER_UTILS_TEXTURE_TAA_HISTORY) uniform sampler2D historyMap; +layout(binding=RENDER_UTILS_TEXTURE_TAA_SOURCE) uniform sampler2D sourceMap; +layout(binding=RENDER_UTILS_TEXTURE_TAA_VELOCITY) uniform sampler2D velocityMap; +layout(binding=RENDER_UTILS_TEXTURE_TAA_DEPTH) uniform sampler2D depthMap; +layout(binding=RENDER_UTILS_TEXTURE_TAA_NEXT) uniform sampler2D nextMap; struct TAAParams { @@ -32,7 +33,7 @@ struct TAAParams vec4 regionInfo; }; -layout(std140) uniform taaParamsBuffer { +layout(std140, binding=RENDER_UTILS_BUFFER_TAA_PARAMS) uniform taaParamsBuffer { TAAParams params; }; @@ -518,4 +519,5 @@ vec3 taa_evalFXAA(vec2 fragUV) { } else { return rgbB; } -} \ No newline at end of file +} + diff --git a/libraries/render-utils/src/taa_blend.slf b/libraries/render-utils/src/taa_blend.slf index aca934ca71..d2e23b590f 100644 --- a/libraries/render-utils/src/taa_blend.slf +++ b/libraries/render-utils/src/taa_blend.slf @@ -14,8 +14,8 @@ <@include taa.slh@> -in vec2 varTexCoord0; -layout(location = 0) out vec4 outFragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 outFragColor; void main(void) { vec3 nextColor = texture(nextMap, varTexCoord0).xyz; diff --git a/libraries/render-utils/src/text/Font.cpp b/libraries/render-utils/src/text/Font.cpp index 66f052e25f..aca6ddb79f 100644 --- a/libraries/render-utils/src/text/Font.cpp +++ b/libraries/render-utils/src/text/Font.cpp @@ -8,6 +8,7 @@ #include #include +#include "../render-utils/ShaderConstants.h" #include "../RenderUtilsLogging.h" #include "FontFamilies.h" #include "../StencilMaskPass.h" @@ -222,15 +223,6 @@ void Font::setupGPU() { { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::sdf_text3D); gpu::ShaderPointer programTransparent = gpu::Shader::createProgram(shader::render_utils::program::sdf_text3D_transparent); - - gpu::Shader::BindingSet slotBindings; - gpu::Shader::makeProgram(*program, slotBindings); - gpu::Shader::makeProgram(*programTransparent, slotBindings); - - _fontLoc = program->getTextures().findLocation("Font"); - _outlineLoc = program->getUniforms().findLocation("Outline"); - _colorLoc = program->getUniforms().findLocation("Color"); - auto state = std::make_shared(); state->setCullMode(gpu::State::CULL_BACK); state->setDepthTest(true, true, gpu::LESS_EQUAL); @@ -362,19 +354,11 @@ void Font::drawString(gpu::Batch& batch, float x, float y, const QString& str, c setupGPU(); batch.setPipeline(((*color).a < 1.0f || layered) ? _transparentPipeline : _pipeline); - if (_fontLoc >= 0) { - batch.setResourceTexture(_fontLoc, _texture); - } - if (_outlineLoc >= 0) { - batch._glUniform1i(_outlineLoc, (effectType == OUTLINE_EFFECT)); - } - + batch.setResourceTexture(render_utils::slot::texture::TextFont, _texture); + batch._glUniform1i(render_utils::slot::uniform::TextOutline, (effectType == OUTLINE_EFFECT)); // need the gamma corrected color here glm::vec4 lrgba = ColorUtils::sRGBToLinearVec4(*color); - if (_colorLoc >= 0) { - batch._glUniform4fv(_colorLoc, 1, (const float*)&lrgba); - } - + batch._glUniform4fv(render_utils::slot::uniform::TextColor, 1, (const float*)&lrgba); batch.setInputFormat(_format); batch.setInputBuffer(0, _verticesBuffer, 0, _format->getChannels().at(0)._stride); batch.setIndexBuffer(gpu::UINT16, _indicesBuffer, 0); diff --git a/libraries/render-utils/src/text/Font.h b/libraries/render-utils/src/text/Font.h index a41f720f15..2fa2b65fa5 100644 --- a/libraries/render-utils/src/text/Font.h +++ b/libraries/render-utils/src/text/Font.h @@ -72,10 +72,6 @@ private: unsigned int _numVertices = 0; unsigned int _numIndices = 0; - int _fontLoc = -1; - int _outlineLoc = -1; - int _colorLoc = -1; - // last string render characteristics QString _lastStringRendered; glm::vec2 _lastBounds; diff --git a/libraries/render-utils/src/toneMapping.slf b/libraries/render-utils/src/toneMapping.slf index d6504b5bff..8d89e54a1b 100644 --- a/libraries/render-utils/src/toneMapping.slf +++ b/libraries/render-utils/src/toneMapping.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on Sat Oct 24 09:34:37 2015 // +// toneMapping.frag +// // Draw texture 0 fetched at texcoord.xy // // Created by Sam Gateau on 6/22/2015 @@ -11,6 +13,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +<@include render-utils/ShaderConstants.h@> + struct ToneMappingParams { vec4 _exp_2powExp_s0_s1; ivec4 _toneCurve_s0_s1_s2; @@ -22,7 +26,7 @@ const int ToneCurveGamma22 = 1; const int ToneCurveReinhard = 2; const int ToneCurveFilmic = 3; -uniform toneMappingParamsBuffer { +layout(binding=RENDER_UTILS_BUFFER_TM_PARAMS) uniform toneMappingParamsBuffer { ToneMappingParams params; }; float getTwoPowExposure() { @@ -32,10 +36,10 @@ int getToneCurve() { return params._toneCurve_s0_s1_s2.x; } -uniform sampler2D colorMap; +layout(binding=RENDER_UTILS_TEXTURE_TM_COLOR) uniform sampler2D colorMap; -in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 outFragColor; void main(void) { vec4 fragColorRaw = texture(colorMap, varTexCoord0); diff --git a/libraries/render-utils/src/velocityBuffer_cameraMotion.slf b/libraries/render-utils/src/velocityBuffer_cameraMotion.slf index 548feb87dc..6932766d63 100644 --- a/libraries/render-utils/src/velocityBuffer_cameraMotion.slf +++ b/libraries/render-utils/src/velocityBuffer_cameraMotion.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// velocityBuffer_cameraMotion.frag +// // Created by Sam Gateau on 6/3/16. // Copyright 2016 High Fidelity, Inc. // @@ -12,10 +14,10 @@ <@include DeferredTransform.slh@> <$declareDeferredFrameTransform()$> -in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 outFragColor; -uniform sampler2D depthMap; +layout(binding=RENDER_UTILS_TEXTURE_TAA_DEPTH) uniform sampler2D depthMap; void main(void) { diff --git a/libraries/render-utils/src/zone_drawAmbient.slf b/libraries/render-utils/src/zone_drawAmbient.slf index 3407fe8467..e560d91308 100644 --- a/libraries/render-utils/src/zone_drawAmbient.slf +++ b/libraries/render-utils/src/zone_drawAmbient.slf @@ -19,8 +19,8 @@ <$declareLightingAmbient(_SCRIBE_NULL, 1, _SCRIBE_NULL, _SCRIBE_NULL)$> -in vec2 varTexCoord0; -out vec4 _fragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 _fragColor; void main(void) { diff --git a/libraries/render-utils/src/zone_drawKeyLight.slf b/libraries/render-utils/src/zone_drawKeyLight.slf index 5f0f0265d3..99e9357cb0 100644 --- a/libraries/render-utils/src/zone_drawKeyLight.slf +++ b/libraries/render-utils/src/zone_drawKeyLight.slf @@ -18,8 +18,8 @@ <@include LightDirectional.slh@> <$declareLightingDirectional(_SCRIBE_NULL)$> -in vec2 varTexCoord0; -out vec4 _fragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 _fragColor; void main(void) { diff --git a/libraries/render-utils/src/zone_drawSkybox.slf b/libraries/render-utils/src/zone_drawSkybox.slf index fd6976365e..77de75a305 100644 --- a/libraries/render-utils/src/zone_drawSkybox.slf +++ b/libraries/render-utils/src/zone_drawSkybox.slf @@ -9,19 +9,21 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // <@include zone_draw.slh@> +<@include render-utils/ShaderConstants.h@> -uniform samplerCube skyboxMap; +// FIXME use declareSkyboxMap from LightAmbient.slh? +layout(binding=RENDER_UTILS_TEXTURE_SKYBOX) uniform samplerCube skyboxMap; struct Skybox { vec4 color; }; -uniform skyboxBuffer { +layout(binding=RENDER_UTILS_BUFFER_DEBUG_SKYBOX) uniform skyboxBuffer { Skybox skybox; }; -in vec2 varTexCoord0; -out vec4 _fragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 _fragColor; void main(void) { <$evalGlobeWidget()$> diff --git a/libraries/render/src/render/BlurTask.cpp b/libraries/render/src/render/BlurTask.cpp index 3699922074..b76793ea2d 100644 --- a/libraries/render/src/render/BlurTask.cpp +++ b/libraries/render/src/render/BlurTask.cpp @@ -204,12 +204,6 @@ BlurGaussian::BlurGaussian(bool generateOutputFramebuffer, unsigned int downsamp gpu::PipelinePointer BlurGaussian::getBlurVPipeline() { if (!_blurVPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::blurGaussianV); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("blurParamsBuffer"), BlurTask_ParamsSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("sourceMap"), BlurTask_SourceSlot)); - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); // Stencil test the curvature pass for objects pixels only, not the background @@ -224,12 +218,6 @@ gpu::PipelinePointer BlurGaussian::getBlurVPipeline() { gpu::PipelinePointer BlurGaussian::getBlurHPipeline() { if (!_blurHPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::blurGaussianH); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("blurParamsBuffer"), BlurTask_ParamsSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("sourceMap"), BlurTask_SourceSlot)); - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); // Stencil test the curvature pass for objects pixels only, not the background @@ -314,13 +302,6 @@ BlurGaussianDepthAware::BlurGaussianDepthAware(bool generateOutputFramebuffer, c gpu::PipelinePointer BlurGaussianDepthAware::getBlurVPipeline() { if (!_blurVPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::blurGaussianDepthAwareV); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("blurParamsBuffer"), BlurTask_ParamsSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("sourceMap"), BlurTask_SourceSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("depthMap"), BlurTask_DepthSlot)); - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); // Stencil test the curvature pass for objects pixels only, not the background @@ -335,13 +316,6 @@ gpu::PipelinePointer BlurGaussianDepthAware::getBlurVPipeline() { gpu::PipelinePointer BlurGaussianDepthAware::getBlurHPipeline() { if (!_blurHPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::blurGaussianDepthAwareH); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("blurParamsBuffer"), BlurTask_ParamsSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("sourceMap"), BlurTask_SourceSlot)); - slotBindings.insert(gpu::Shader::Binding(std::string("depthMap"), BlurTask_DepthSlot)); - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); // Stencil test the curvature pass for objects pixels only, not the background diff --git a/libraries/render/src/render/BlurTask.slh b/libraries/render/src/render/BlurTask.slh index 37f29496bd..c07e71688a 100644 --- a/libraries/render/src/render/BlurTask.slh +++ b/libraries/render/src/render/BlurTask.slh @@ -21,7 +21,7 @@ struct BlurParameters { vec2 taps[BLUR_MAX_NUM_TAPS]; }; -uniform blurParamsBuffer { +layout(binding=0) uniform blurParamsBuffer { BlurParameters parameters; }; @@ -76,7 +76,7 @@ float getPosLinearDepthFar() { <$declareBlurUniforms()$> -uniform sampler2D sourceMap; +layout(binding=0) uniform sampler2D sourceMap; vec4 pixelShaderGaussian(vec2 texcoord, vec2 direction, vec2 pixelStep) { texcoord = evalTexcoordTransformed(texcoord); @@ -112,8 +112,8 @@ vec4 pixelShaderGaussian(vec2 texcoord, vec2 direction, vec2 pixelStep) { <$declareBlurUniforms()$> -uniform sampler2D sourceMap; -uniform sampler2D depthMap; +layout(binding=0) uniform sampler2D sourceMap; +layout(binding=1) uniform sampler2D depthMap; vec4 pixelShaderGaussianDepthAware(vec2 texcoord, vec2 direction, vec2 pixelStep) { texcoord = evalTexcoordTransformed(texcoord); diff --git a/libraries/render/src/render/DrawSceneOctree.cpp b/libraries/render/src/render/DrawSceneOctree.cpp index 5de538759a..b8014b4e4f 100644 --- a/libraries/render/src/render/DrawSceneOctree.cpp +++ b/libraries/render/src/render/DrawSceneOctree.cpp @@ -29,12 +29,6 @@ using namespace render; const gpu::PipelinePointer DrawSceneOctree::getDrawCellBoundsPipeline() { if (!_drawCellBoundsPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::drawCellBounds); - - gpu::Shader::BindingSet slotBindings; - gpu::Shader::makeProgram(*program, slotBindings); - - _drawCellLocationLoc = program->getUniforms().findLocation("inCellLocation"); - auto state = std::make_shared(); state->setDepthTest(true, false, gpu::LESS_EQUAL); @@ -51,10 +45,6 @@ const gpu::PipelinePointer DrawSceneOctree::getDrawCellBoundsPipeline() { const gpu::PipelinePointer DrawSceneOctree::getDrawLODReticlePipeline() { if (!_drawLODReticlePipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::drawLODReticle); - gpu::Shader::makeProgram(*program); - - // _drawCellLocationLoc = program->getUniforms().findLocation("inCellLocation"); - auto state = std::make_shared(); // Blend on transparent @@ -111,7 +101,7 @@ void DrawSceneOctree::run(const RenderContextPointer& renderContext, const ItemS cellLocation.w *= -1; } if (doDraw) { - batch._glUniform4iv(_drawCellLocationLoc, 1, ((const int*)(&cellLocation))); + batch._glUniform4iv(gpu::slot::uniform::Extra0, 1, ((const int*)(&cellLocation))); batch.draw(gpu::LINES, 24, 0); } } @@ -129,7 +119,7 @@ void DrawSceneOctree::run(const RenderContextPointer& renderContext, const ItemS cellLocation.w *= -1; } if (doDraw) { - batch._glUniform4iv(_drawCellLocationLoc, 1, ((const int*)(&cellLocation))); + batch._glUniform4iv(gpu::slot::uniform::Extra0, 1, ((const int*)(&cellLocation))); batch.draw(gpu::LINES, 24, 0); } } @@ -152,13 +142,9 @@ const gpu::PipelinePointer DrawItemSelection::getDrawItemBoundPipeline() { if (!_drawItemBoundPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::drawItemBounds); - gpu::Shader::BindingSet slotBindings; - gpu::Shader::makeProgram(*program, slotBindings); - - _drawItemBoundPosLoc = program->getUniforms().findLocation("inBoundPos"); - _drawItemBoundDimLoc = program->getUniforms().findLocation("inBoundDim"); - - _drawCellLocationLoc = program->getUniforms().findLocation("inCellLocation"); + //_drawItemBoundPosLoc = program->getUniforms().findLocation("inBoundPos"); + //_drawItemBoundDimLoc = program->getUniforms().findLocation("inBoundDim"); + //_drawCellLocationLoc = program->getUniforms().findLocation("inCellLocation"); auto state = std::make_shared(); @@ -208,9 +194,9 @@ void DrawItemSelection::run(const RenderContextPointer& renderContext, const Ite auto itemCell = scene->getSpatialTree().getCellLocation(item.getCell()); glm::ivec4 cellLocation(0, 0, 0, itemCell.depth); - batch._glUniform4iv(_drawCellLocationLoc, 1, ((const int*)(&cellLocation))); - batch._glUniform3fv(_drawItemBoundPosLoc, 1, (const float*)(&itemBound.getCorner())); - batch._glUniform3fv(_drawItemBoundDimLoc, 1, (const float*)(&itemBound.getScale())); + //batch._glUniform4iv(_drawCellLocationLoc, 1, ((const int*)(&cellLocation))); + //batch._glUniform3fv(_drawItemBoundPosLoc, 1, (const float*)(&itemBound.getCorner())); + //batch._glUniform3fv(_drawItemBoundDimLoc, 1, (const float*)(&itemBound.getScale())); batch.draw(gpu::LINES, 24, 0); } @@ -223,9 +209,9 @@ void DrawItemSelection::run(const RenderContextPointer& renderContext, const Ite auto itemCell = scene->getSpatialTree().getCellLocation(item.getCell()); glm::ivec4 cellLocation(0, 0, 1, itemCell.depth); - batch._glUniform4iv(_drawCellLocationLoc, 1, ((const int*)(&cellLocation))); - batch._glUniform3fv(_drawItemBoundPosLoc, 1, (const float*)(&itemBound.getCorner())); - batch._glUniform3fv(_drawItemBoundDimLoc, 1, (const float*)(&itemBound.getScale())); + //batch._glUniform4iv(_drawCellLocationLoc, 1, ((const int*)(&cellLocation))); + //batch._glUniform3fv(_drawItemBoundPosLoc, 1, (const float*)(&itemBound.getCorner())); + //batch._glUniform3fv(_drawItemBoundDimLoc, 1, (const float*)(&itemBound.getScale())); batch.draw(gpu::LINES, 24, 0); } @@ -238,9 +224,9 @@ void DrawItemSelection::run(const RenderContextPointer& renderContext, const Ite auto itemCell = scene->getSpatialTree().getCellLocation(item.getCell()); glm::ivec4 cellLocation(0, 0, 0, itemCell.depth); - batch._glUniform4iv(_drawCellLocationLoc, 1, ((const int*)(&cellLocation))); - batch._glUniform3fv(_drawItemBoundPosLoc, 1, (const float*)(&itemBound.getCorner())); - batch._glUniform3fv(_drawItemBoundDimLoc, 1, (const float*)(&itemBound.getScale())); + //batch._glUniform4iv(_drawCellLocationLoc, 1, ((const int*)(&cellLocation))); + //batch._glUniform3fv(_drawItemBoundPosLoc, 1, (const float*)(&itemBound.getCorner())); + //batch._glUniform3fv(_drawItemBoundDimLoc, 1, (const float*)(&itemBound.getScale())); batch.draw(gpu::LINES, 24, 0); } @@ -252,9 +238,9 @@ void DrawItemSelection::run(const RenderContextPointer& renderContext, const Ite auto itemBound = item.getBound(); auto itemCell = scene->getSpatialTree().getCellLocation(item.getCell()); glm::ivec4 cellLocation(0, 0, 1, itemCell.depth); - batch._glUniform4iv(_drawCellLocationLoc, 1, ((const int*)(&cellLocation))); - batch._glUniform3fv(_drawItemBoundPosLoc, 1, (const float*)(&itemBound.getCorner())); - batch._glUniform3fv(_drawItemBoundDimLoc, 1, (const float*)(&itemBound.getScale())); + //batch._glUniform4iv(_drawCellLocationLoc, 1, ((const int*)(&cellLocation))); + //batch._glUniform3fv(_drawItemBoundPosLoc, 1, (const float*)(&itemBound.getCorner())); + //batch._glUniform3fv(_drawItemBoundDimLoc, 1, (const float*)(&itemBound.getScale())); batch.draw(gpu::LINES, 24, 0); } diff --git a/libraries/render/src/render/DrawSceneOctree.h b/libraries/render/src/render/DrawSceneOctree.h index 9c416262ca..54c14e45f2 100644 --- a/libraries/render/src/render/DrawSceneOctree.h +++ b/libraries/render/src/render/DrawSceneOctree.h @@ -51,15 +51,9 @@ namespace render { }; class DrawSceneOctree { - - int _drawCellLocationLoc; gpu::PipelinePointer _drawCellBoundsPipeline; gpu::BufferPointer _cells; - gpu::PipelinePointer _drawLODReticlePipeline; - - int _drawItemBoundPosLoc = -1; - int _drawItemBoundDimLoc = -1; gpu::PipelinePointer _drawItemBoundPipeline; bool _showVisibleCells; // initialized by Config @@ -112,10 +106,6 @@ namespace render { }; class DrawItemSelection { - - int _drawItemBoundPosLoc = -1; - int _drawItemBoundDimLoc = -1; - int _drawCellLocationLoc = -1; gpu::PipelinePointer _drawItemBoundPipeline; bool _showInsideItems; // initialized by Config diff --git a/libraries/render/src/render/DrawStatus.cpp b/libraries/render/src/render/DrawStatus.cpp index b8fef0d987..2894a85a30 100644 --- a/libraries/render/src/render/DrawStatus.cpp +++ b/libraries/render/src/render/DrawStatus.cpp @@ -33,13 +33,9 @@ void DrawStatusConfig::dirtyHelper() { const gpu::PipelinePointer DrawStatus::getDrawItemBoundsPipeline() { if (!_drawItemBoundsPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::drawItemBounds); - - gpu::Shader::BindingSet slotBindings; - gpu::Shader::makeProgram(*program, slotBindings); - - _drawItemBoundPosLoc = program->getUniforms().findLocation("inBoundPos"); - _drawItemBoundDimLoc = program->getUniforms().findLocation("inBoundDim"); - _drawItemCellLocLoc = program->getUniforms().findLocation("inCellLocation"); + //_drawItemBoundPosLoc = program->getUniforms().findLocation("inBoundPos"); + //_drawItemBoundDimLoc = program->getUniforms().findLocation("inBoundDim"); + //_drawItemCellLocLoc = program->getUniforms().findLocation("inCellLocation"); auto state = std::make_shared(); @@ -58,16 +54,11 @@ const gpu::PipelinePointer DrawStatus::getDrawItemBoundsPipeline() { const gpu::PipelinePointer DrawStatus::getDrawItemStatusPipeline() { if (!_drawItemStatusPipeline) { - gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::drawItemStatus); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("iconStatusMap"), 0)); - gpu::Shader::makeProgram(*program, slotBindings); - - _drawItemStatusPosLoc = program->getUniforms().findLocation("inBoundPos"); - _drawItemStatusDimLoc = program->getUniforms().findLocation("inBoundDim"); - _drawItemStatusValue0Loc = program->getUniforms().findLocation("inStatus0"); - _drawItemStatusValue1Loc = program->getUniforms().findLocation("inStatus1"); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::blurGaussianDepthAwareV); + //_drawItemStatusPosLoc = program->getUniforms().findLocation(""); + //_drawItemStatusDimLoc = program->getUniforms().findLocation(""); + //_drawItemStatusValue0Loc = program->getUniforms().findLocation(""); + //_drawItemStatusValue1Loc = program->getUniforms().findLocation(""); auto state = std::make_shared(); @@ -182,11 +173,10 @@ void DrawStatus::run(const RenderContextPointer& renderContext, const Input& inp if (_showDisplay) { for (int i = 0; i < nbItems; i++) { - batch._glUniform3fv(_drawItemBoundPosLoc, 1, (const float*)&(_itemBounds[i])); - batch._glUniform3fv(_drawItemBoundDimLoc, 1, ((const float*)&(_itemBounds[i])) + VEC3_ADRESS_OFFSET); - - glm::ivec4 cellLocation(_itemCells[i].pos, _itemCells[i].depth); - batch._glUniform4iv(_drawItemCellLocLoc, 1, ((const int*)(&cellLocation))); + //batch._glUniform3fv(gpu::slot::uniform::Extra0, 1, (const float*)&(_itemBounds[i])); + //batch._glUniform3fv(gpu::slot::uniform::Extra1, 1, ((const float*)&(_itemBounds[i])) + VEC3_ADRESS_OFFSET); + //glm::ivec4 cellLocation(_itemCells[i].pos, _itemCells[i].depth); + //batch._glUniform4iv(_drawItemCellLocLoc, 1, ((const int*)(&cellLocation))); batch.draw(gpu::LINES, 24, 0); } } @@ -197,10 +187,10 @@ void DrawStatus::run(const RenderContextPointer& renderContext, const Input& inp if (_showNetwork) { for (int i = 0; i < nbItems; i++) { - batch._glUniform3fv(_drawItemStatusPosLoc, 1, (const float*)&(_itemBounds[i])); - batch._glUniform3fv(_drawItemStatusDimLoc, 1, ((const float*)&(_itemBounds[i])) + VEC3_ADRESS_OFFSET); - batch._glUniform4iv(_drawItemStatusValue0Loc, 1, (const int*)&(_itemStatus[i].first)); - batch._glUniform4iv(_drawItemStatusValue1Loc, 1, (const int*)&(_itemStatus[i].second)); + batch._glUniform3fv(gpu::slot::uniform::Extra0, 1, (const float*)&(_itemBounds[i])); + batch._glUniform3fv(gpu::slot::uniform::Extra1, 1, ((const float*)&(_itemBounds[i])) + VEC3_ADRESS_OFFSET); + batch._glUniform4iv(gpu::slot::uniform::Extra2, 1, (const int*)&(_itemStatus[i].first)); + batch._glUniform4iv(gpu::slot::uniform::Extra3, 1, (const int*)&(_itemStatus[i].second)); batch.draw(gpu::TRIANGLES, 24 * NUM_STATUS_VEC4_PER_ITEM, 0); } } diff --git a/libraries/render/src/render/DrawStatus.h b/libraries/render/src/render/DrawStatus.h index 9e05471cd6..4228d1bd8d 100644 --- a/libraries/render/src/render/DrawStatus.h +++ b/libraries/render/src/render/DrawStatus.h @@ -58,14 +58,6 @@ namespace render { bool _showDisplay; // initialized by Config bool _showNetwork; // initialized by Config - int _drawItemBoundPosLoc = -1; - int _drawItemBoundDimLoc = -1; - int _drawItemCellLocLoc = -1; - int _drawItemStatusPosLoc = -1; - int _drawItemStatusDimLoc = -1; - int _drawItemStatusValue0Loc = -1; - int _drawItemStatusValue1Loc = -1; - gpu::Stream::FormatPointer _drawItemFormat; gpu::PipelinePointer _drawItemBoundsPipeline; gpu::PipelinePointer _drawItemStatusPipeline; diff --git a/libraries/render/src/render/DrawTask.cpp b/libraries/render/src/render/DrawTask.cpp index 08be053ddf..69fe870992 100755 --- a/libraries/render/src/render/DrawTask.cpp +++ b/libraries/render/src/render/DrawTask.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include "Logging.h" @@ -158,12 +159,6 @@ void DrawLight::run(const RenderContextPointer& renderContext, const ItemBounds& const gpu::PipelinePointer DrawBounds::getPipeline() { if (!_boundsPipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render::program::drawItemBounds); - - gpu::Shader::BindingSet slotBindings; - gpu::Shader::makeProgram(*program, slotBindings); - - _colorLocation = program->getUniforms().findLocation("inColor"); - auto state = std::make_shared(); state->setDepthTest(true, false, gpu::LESS_EQUAL); state->setBlendFunction(true, @@ -207,7 +202,7 @@ void DrawBounds::run(const RenderContextPointer& renderContext, batch.setPipeline(getPipeline()); glm::vec4 color(glm::vec3(0.0f), -(float) numItems); - batch._glUniform4fv(_colorLocation, 1, (const float*)(&color)); + batch._glUniform4fv(gpu::slot::uniform::Color, 1, (const float*)(&color)); batch.setResourceBuffer(0, _drawBuffer); static const int NUM_VERTICES_PER_CUBE = 24; @@ -263,11 +258,6 @@ gpu::PipelinePointer DrawQuadVolume::getPipeline() { if (!pipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::gpu::program::drawColor); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding("color", 0)); - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setDepthTest(gpu::State::DepthTest(true, false)); pipeline = gpu::Pipeline::create(program, state); diff --git a/libraries/render/src/render/DrawTask.h b/libraries/render/src/render/DrawTask.h index 6f98e3bef1..b8ff5a2a42 100755 --- a/libraries/render/src/render/DrawTask.h +++ b/libraries/render/src/render/DrawTask.h @@ -66,8 +66,6 @@ private: const gpu::PipelinePointer getPipeline(); gpu::PipelinePointer _boundsPipeline; gpu::BufferPointer _drawBuffer; - - int _colorLocation { -1 }; }; class DrawQuadVolumeConfig : public render::JobConfig { diff --git a/libraries/render/src/render/ResampleTask.cpp b/libraries/render/src/render/ResampleTask.cpp index 880d13fde1..ed4d0ddfd0 100644 --- a/libraries/render/src/render/ResampleTask.cpp +++ b/libraries/render/src/render/ResampleTask.cpp @@ -52,10 +52,6 @@ void HalfDownsample::run(const RenderContextPointer& renderContext, const gpu::F if (!_pipeline) { gpu::ShaderPointer program = gpu::Shader::createProgram(shader::gpu::program::drawTransformUnitQuadTextureOpaque); - - gpu::Shader::BindingSet slotBindings; - gpu::Shader::makeProgram(*program, slotBindings); - gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setDepthTest(gpu::State::DepthTest(false, false)); _pipeline = gpu::Pipeline::create(program, state); @@ -111,13 +107,7 @@ void Upsample::run(const RenderContextPointer& renderContext, const gpu::Framebu resampledFrameBuffer = getResampledFrameBuffer(sourceFramebuffer); if (resampledFrameBuffer != sourceFramebuffer) { if (!_pipeline) { - auto vs = gpu::StandardShaderLib::getDrawTransformUnitQuadVS(); - auto ps = gpu::StandardShaderLib::getDrawTextureOpaquePS(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - - gpu::Shader::BindingSet slotBindings; - gpu::Shader::makeProgram(*program, slotBindings); - + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::gpu::program::drawTransformUnitQuadTextureOpaque); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setDepthTest(gpu::State::DepthTest(false, false)); _pipeline = gpu::Pipeline::create(program, state); diff --git a/libraries/render/src/render/ShapePipeline.cpp b/libraries/render/src/render/ShapePipeline.cpp index 8cd04f8067..2b2accde37 100644 --- a/libraries/render/src/render/ShapePipeline.cpp +++ b/libraries/render/src/render/ShapePipeline.cpp @@ -12,12 +12,26 @@ #include "ShapePipeline.h" #include +#include +#include +#include +#include <../render-utils/src/render-utils/ShaderConstants.h> -#include "DependencyManager.h" #include "Logging.h" + using namespace render; +namespace ru { + using render_utils::slot::texture::Texture; + using render_utils::slot::buffer::Buffer; +} + +namespace gr { + using graphics::slot::texture::Texture; + using graphics::slot::buffer::Buffer; +} + ShapePipeline::CustomFactoryMap ShapePipeline::_globalCustomFactoryMap; ShapePipeline::CustomKey ShapePipeline::registerCustomShapePipelineFactory(CustomFactory factory) { @@ -71,70 +85,30 @@ void ShapePlumber::addPipeline(const Key& key, const gpu::ShaderPointer& program void ShapePlumber::addPipeline(const Filter& filter, const gpu::ShaderPointer& program, const gpu::StatePointer& state, BatchSetter batchSetter, ItemSetter itemSetter) { - ShapeKey key{ filter._flags }; - - - // don't call makeProgram on shaders that are already made. - if (program->getNumCompilationAttempts() < 1) { - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("lightingModelBuffer"), Slot::BUFFER::LIGHTING_MODEL)); - slotBindings.insert(gpu::Shader::Binding(std::string("skinClusterBuffer"), Slot::BUFFER::SKINNING)); - slotBindings.insert(gpu::Shader::Binding(std::string("materialBuffer"), Slot::BUFFER::MATERIAL)); - slotBindings.insert(gpu::Shader::Binding(std::string("texMapArrayBuffer"), Slot::BUFFER::TEXMAPARRAY)); - slotBindings.insert(gpu::Shader::Binding(std::string("albedoMap"), Slot::MAP::ALBEDO)); - slotBindings.insert(gpu::Shader::Binding(std::string("roughnessMap"), Slot::MAP::ROUGHNESS)); - slotBindings.insert(gpu::Shader::Binding(std::string("normalMap"), Slot::MAP::NORMAL)); - slotBindings.insert(gpu::Shader::Binding(std::string("metallicMap"), Slot::MAP::METALLIC)); - slotBindings.insert(gpu::Shader::Binding(std::string("emissiveMap"), Slot::MAP::EMISSIVE_LIGHTMAP)); - slotBindings.insert(gpu::Shader::Binding(std::string("occlusionMap"), Slot::MAP::OCCLUSION)); - slotBindings.insert(gpu::Shader::Binding(std::string("scatteringMap"), Slot::MAP::SCATTERING)); - slotBindings.insert(gpu::Shader::Binding(std::string("keyLightBuffer"), Slot::BUFFER::KEY_LIGHT)); - slotBindings.insert(gpu::Shader::Binding(std::string("lightBuffer"), Slot::BUFFER::LIGHT_ARRAY_BUFFER)); - slotBindings.insert(gpu::Shader::Binding(std::string("lightAmbientBuffer"), Slot::BUFFER::LIGHT_AMBIENT_BUFFER)); - slotBindings.insert(gpu::Shader::Binding(std::string("skyboxMap"), Slot::MAP::LIGHT_AMBIENT_MAP)); - slotBindings.insert(gpu::Shader::Binding(std::string("fadeMaskMap"), Slot::MAP::FADE_MASK)); - slotBindings.insert(gpu::Shader::Binding(std::string("fadeParametersBuffer"), Slot::BUFFER::FADE_PARAMETERS)); - slotBindings.insert(gpu::Shader::Binding(std::string("fadeObjectParametersBuffer"), Slot::BUFFER::FADE_OBJECT_PARAMETERS)); - slotBindings.insert(gpu::Shader::Binding(std::string("hazeBuffer"), Slot::BUFFER::HAZE_MODEL)); - - if (key.isTranslucent()) { - slotBindings.insert(gpu::Shader::Binding(std::string("clusterGridBuffer"), Slot::BUFFER::LIGHT_CLUSTER_GRID_CLUSTER_GRID_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("clusterContentBuffer"), Slot::BUFFER::LIGHT_CLUSTER_GRID_CLUSTER_CONTENT_SLOT)); - slotBindings.insert(gpu::Shader::Binding(std::string("frustumGridBuffer"), Slot::BUFFER::LIGHT_CLUSTER_GRID_FRUSTUM_GRID_SLOT)); - } - - gpu::Shader::makeProgram(*program, slotBindings); - } - auto locations = std::make_shared(); - - locations->albedoTextureUnit = program->getTextures().findLocation("albedoMap"); - locations->roughnessTextureUnit = program->getTextures().findLocation("roughnessMap"); - locations->normalTextureUnit = program->getTextures().findLocation("normalMap"); - locations->metallicTextureUnit = program->getTextures().findLocation("metallicMap"); - locations->emissiveTextureUnit = program->getTextures().findLocation("emissiveMap"); - locations->occlusionTextureUnit = program->getTextures().findLocation("occlusionMap"); - locations->lightingModelBufferUnit = program->getUniformBuffers().findLocation("lightingModelBuffer"); - locations->skinClusterBufferUnit = program->getUniformBuffers().findLocation("skinClusterBuffer"); - locations->materialBufferUnit = program->getUniformBuffers().findLocation("materialBuffer"); - locations->texMapArrayBufferUnit = program->getUniformBuffers().findLocation("texMapArrayBuffer"); - locations->keyLightBufferUnit = program->getUniformBuffers().findLocation("keyLightBuffer"); - locations->lightBufferUnit = program->getUniformBuffers().findLocation("lightBuffer"); - locations->lightAmbientBufferUnit = program->getUniformBuffers().findLocation("lightAmbientBuffer"); - locations->lightAmbientMapUnit = program->getTextures().findLocation("skyboxMap"); - locations->fadeMaskTextureUnit = program->getTextures().findLocation("fadeMaskMap"); - locations->fadeParameterBufferUnit = program->getUniformBuffers().findLocation("fadeParametersBuffer"); - locations->fadeObjectParameterBufferUnit = program->getUniformBuffers().findLocation("fadeObjectParametersBuffer"); - locations->hazeParameterBufferUnit = program->getUniformBuffers().findLocation("hazeBuffer"); + locations->albedoTextureUnit = program->getTextures().isValid(graphics::slot::texture::MaterialAlbedo); + locations->roughnessTextureUnit = program->getTextures().isValid(graphics::slot::texture::MaterialRoughness); + locations->normalTextureUnit = program->getTextures().isValid(graphics::slot::texture::MaterialNormal); + locations->metallicTextureUnit = program->getTextures().isValid(graphics::slot::texture::MaterialMetallic); + locations->emissiveTextureUnit = program->getTextures().isValid(graphics::slot::texture::MaterialEmissiveLightmap); + locations->occlusionTextureUnit = program->getTextures().isValid(graphics::slot::texture::MaterialOcclusion); + locations->lightingModelBufferUnit = program->getUniformBuffers().isValid(render_utils::slot::buffer::LightModel); + locations->skinClusterBufferUnit = program->getUniformBuffers().isValid(graphics::slot::buffer::Skinning); + locations->materialBufferUnit = program->getUniformBuffers().isValid(graphics::slot::buffer::Material); + locations->texMapArrayBufferUnit = program->getUniformBuffers().isValid(graphics::slot::buffer::TexMapArray); + locations->keyLightBufferUnit = program->getUniformBuffers().isValid(graphics::slot::buffer::KeyLight); + locations->lightBufferUnit = program->getUniformBuffers().isValid(graphics::slot::buffer::Light); + locations->lightAmbientBufferUnit = program->getUniformBuffers().isValid(graphics::slot::buffer::AmbientLight); + locations->lightAmbientMapUnit = program->getTextures().isValid(graphics::slot::texture::Skybox); + locations->fadeMaskTextureUnit = program->getTextures().isValid(render_utils::slot::texture::FadeMask); + locations->fadeParameterBufferUnit = program->getUniformBuffers().isValid(render_utils::slot::buffer::FadeParameters); + locations->fadeObjectParameterBufferUnit = program->getUniformBuffers().isValid(render_utils::slot::buffer::FadeObjectParameters); + locations->hazeParameterBufferUnit = program->getUniformBuffers().isValid(render_utils::slot::buffer::HazeParams); if (key.isTranslucent()) { - locations->lightClusterGridBufferUnit = program->getUniformBuffers().findLocation("clusterGridBuffer"); - locations->lightClusterContentBufferUnit = program->getUniformBuffers().findLocation("clusterContentBuffer"); - locations->lightClusterFrustumBufferUnit = program->getUniformBuffers().findLocation("frustumGridBuffer"); - } else { - locations->lightClusterGridBufferUnit = -1; - locations->lightClusterContentBufferUnit = -1; - locations->lightClusterFrustumBufferUnit = -1; + locations->lightClusterGridBufferUnit = program->getUniformBuffers().isValid(render_utils::slot::buffer::LightClusterGrid); + locations->lightClusterContentBufferUnit = program->getUniformBuffers().isValid(render_utils::slot::buffer::LightClusterContent); + locations->lightClusterFrustumBufferUnit = program->getUniformBuffers().isValid(render_utils::slot::buffer::LightClusterFrustumGrid); } { diff --git a/libraries/render/src/render/ShapePipeline.h b/libraries/render/src/render/ShapePipeline.h index 10f1b757cc..bac1076dd6 100644 --- a/libraries/render/src/render/ShapePipeline.h +++ b/libraries/render/src/render/ShapePipeline.h @@ -228,62 +228,29 @@ inline QDebug operator<<(QDebug debug, const ShapeKey& key) { // Meta-information (pipeline and locations) to render a shape class ShapePipeline { public: - class Slot { - public: - enum BUFFER { - SKINNING = 0, - MATERIAL, - TEXMAPARRAY, - LIGHTING_MODEL, - KEY_LIGHT, - LIGHT_ARRAY_BUFFER, - LIGHT_AMBIENT_BUFFER, - HAZE_MODEL, - FADE_PARAMETERS, - FADE_OBJECT_PARAMETERS, - LIGHT_CLUSTER_GRID_FRUSTUM_GRID_SLOT, - LIGHT_CLUSTER_GRID_CLUSTER_GRID_SLOT, - LIGHT_CLUSTER_GRID_CLUSTER_CONTENT_SLOT, - - }; - - enum MAP { - ALBEDO = 0, - NORMAL, - METALLIC, - EMISSIVE_LIGHTMAP, - ROUGHNESS, - OCCLUSION, - SCATTERING, - - LIGHT_AMBIENT_MAP = 10, - FADE_MASK, - }; - }; - class Locations { public: - int albedoTextureUnit; - int normalTextureUnit; - int roughnessTextureUnit; - int metallicTextureUnit; - int emissiveTextureUnit; - int occlusionTextureUnit; - int lightingModelBufferUnit; - int skinClusterBufferUnit; - int materialBufferUnit; - int texMapArrayBufferUnit; - int keyLightBufferUnit; - int lightBufferUnit; - int lightAmbientBufferUnit; - int lightAmbientMapUnit; - int fadeMaskTextureUnit; - int fadeParameterBufferUnit; - int fadeObjectParameterBufferUnit; - int hazeParameterBufferUnit; - int lightClusterGridBufferUnit; - int lightClusterContentBufferUnit; - int lightClusterFrustumBufferUnit; + bool albedoTextureUnit{ false }; + bool normalTextureUnit{ false }; + bool roughnessTextureUnit{ false }; + bool metallicTextureUnit{ false }; + bool emissiveTextureUnit{ false }; + bool occlusionTextureUnit{ false }; + bool lightingModelBufferUnit{ false }; + bool skinClusterBufferUnit{ false }; + bool materialBufferUnit{ false }; + bool texMapArrayBufferUnit{ false }; + bool keyLightBufferUnit{ false }; + bool lightBufferUnit{ false }; + bool lightAmbientBufferUnit{ false }; + bool lightAmbientMapUnit{ false }; + bool fadeMaskTextureUnit{ false }; + bool fadeParameterBufferUnit{ false }; + bool fadeObjectParameterBufferUnit{ false }; + bool hazeParameterBufferUnit{ false }; + bool lightClusterGridBufferUnit{ false }; + bool lightClusterContentBufferUnit{ false }; + bool lightClusterFrustumBufferUnit{ false }; }; using LocationsPointer = std::shared_ptr; @@ -330,7 +297,7 @@ public: using Pipeline = ShapePipeline; using PipelinePointer = ShapePipelinePointer; using PipelineMap = std::unordered_map; - using Slot = Pipeline::Slot; + using Slot = int32_t; using Locations = Pipeline::Locations; using LocationsPointer = Pipeline::LocationsPointer; using BatchSetter = Pipeline::BatchSetter; diff --git a/libraries/render/src/render/blurGaussianDepthAwareH.slf b/libraries/render/src/render/blurGaussianDepthAwareH.slf index aab1fe2b02..09a92909ff 100644 --- a/libraries/render/src/render/blurGaussianDepthAwareH.slf +++ b/libraries/render/src/render/blurGaussianDepthAwareH.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// blurGaussianDepthAwareH.frag +// // Created by Sam Gateau on 6/7/16. // Copyright 2016 High Fidelity, Inc. // @@ -12,9 +14,9 @@ <@include BlurTask.slh@> <$declareBlurGaussianDepthAware()$> -in vec2 varTexCoord0; +layout(location=0) in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=0) out vec4 outFragColor; void main(void) { outFragColor = pixelShaderGaussianDepthAware(varTexCoord0, vec2(1.0, 0.0), getViewportInvWidthHeight()); diff --git a/libraries/render/src/render/blurGaussianDepthAwareV.slf b/libraries/render/src/render/blurGaussianDepthAwareV.slf index 35f0d3a381..4f9bc86c01 100644 --- a/libraries/render/src/render/blurGaussianDepthAwareV.slf +++ b/libraries/render/src/render/blurGaussianDepthAwareV.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// blurGaussianDepthAwareV.frag +// // Created by Sam Gateau on 6/7/16. // Copyright 2016 High Fidelity, Inc. // @@ -12,9 +14,9 @@ <@include BlurTask.slh@> <$declareBlurGaussianDepthAware()$> -in vec2 varTexCoord0; +layout(location=0) in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=0) out vec4 outFragColor; void main(void) { outFragColor = pixelShaderGaussianDepthAware(varTexCoord0, vec2(0.0, 1.0), getViewportInvWidthHeight()); diff --git a/libraries/render/src/render/blurGaussianH.slf b/libraries/render/src/render/blurGaussianH.slf index 02cc73fe13..1c13664907 100644 --- a/libraries/render/src/render/blurGaussianH.slf +++ b/libraries/render/src/render/blurGaussianH.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// blurGaussianH.frag +// // Created by Sam Gateau on 6/7/16. // Copyright 2016 High Fidelity, Inc. // @@ -13,9 +15,9 @@ <$declareBlurGaussian()$> -in vec2 varTexCoord0; +layout(location=0) in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=0) out vec4 outFragColor; void main(void) { outFragColor = pixelShaderGaussian(varTexCoord0, vec2(1.0, 0.0), getViewportInvWidthHeight()); diff --git a/libraries/render/src/render/blurGaussianV.slf b/libraries/render/src/render/blurGaussianV.slf index 99beab6275..f8351f9670 100644 --- a/libraries/render/src/render/blurGaussianV.slf +++ b/libraries/render/src/render/blurGaussianV.slf @@ -2,6 +2,8 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // +// blurGaussianV.frag +// // Created by Sam Gateau on 6/7/16. // Copyright 2016 High Fidelity, Inc. // @@ -12,9 +14,9 @@ <$declareBlurGaussian()$> -in vec2 varTexCoord0; +layout(location=0) in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=0) out vec4 outFragColor; void main(void) { outFragColor = pixelShaderGaussian(varTexCoord0, vec2(0.0, 1.0), getViewportInvWidthHeight()); diff --git a/libraries/render/src/render/drawCellBounds.slf b/libraries/render/src/render/drawCellBounds.slf index 6b9f5b96bc..410f0f5d78 100644 --- a/libraries/render/src/render/drawCellBounds.slf +++ b/libraries/render/src/render/drawCellBounds.slf @@ -1,7 +1,7 @@ <@include gpu/Config.slh@> <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> -// drawCellBounds.slf +// drawCellBounds.frag // fragment shader // // Created by Sam Gateau on 1/25/2016. @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -in vec4 varColor; -out vec4 outFragColor; +layout(location=0) in vec4 varColor; +layout(location=0) out vec4 outFragColor; void main(void) { diff --git a/libraries/render/src/render/drawCellBounds.slv b/libraries/render/src/render/drawCellBounds.slv index f50331f15c..8336885365 100644 --- a/libraries/render/src/render/drawCellBounds.slv +++ b/libraries/render/src/render/drawCellBounds.slv @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// drawCellBounds.slv +// drawCellBounds.vert // Vertex shader // // Created by Sam Gateau on 1/25/2016 @@ -20,9 +20,9 @@ <$declareColorWheel()$> <@include SceneOctree.slh@> -uniform ivec4 inCellLocation; +layout(location=GPU_UNIFORM_EXTRA0) uniform ivec4 inCellLocation; -out vec4 varColor; +layout(location=0) out vec4 varColor; void main(void) { diff --git a/libraries/render/src/render/drawItemBounds.slf b/libraries/render/src/render/drawItemBounds.slf index 84c47d0933..90faaff05c 100644 --- a/libraries/render/src/render/drawItemBounds.slf +++ b/libraries/render/src/render/drawItemBounds.slf @@ -11,9 +11,9 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -in vec4 varColor; -in vec2 varTexcoord; -out vec4 outFragColor; +layout(location=0) in vec4 varColor; +layout(location=1) in vec2 varTexcoord; +layout(location=0) out vec4 outFragColor; void main(void) { float var = step(fract(varTexcoord.x * varTexcoord.y * 1.0), 0.5); diff --git a/libraries/render/src/render/drawItemBounds.slv b/libraries/render/src/render/drawItemBounds.slv index 0bb2b795bd..059538de47 100644 --- a/libraries/render/src/render/drawItemBounds.slv +++ b/libraries/render/src/render/drawItemBounds.slv @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// drawItemBounds.slv +// drawItemBounds.vert // vertex shader // // Created by Sam Gateau on 6/29/2015. @@ -12,13 +12,16 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +<@include gpu/ShaderConstants.h@> + <@include gpu/Transform.slh@> <$declareStandardTransform()$> <@include gpu/Color.slh@> <$declareColorWheel()$> -uniform vec4 inColor; + +layout(location=GPU_UNIFORM_COLOR) uniform vec4 inColor; struct ItemBound { @@ -27,7 +30,7 @@ struct ItemBound { }; #if defined(GPU_GL410) -uniform samplerBuffer ssbo0Buffer; +layout(binding=0) uniform samplerBuffer ssbo0Buffer; ItemBound getItemBound(int i) { int offset = 2 * i; ItemBound bound; @@ -36,7 +39,7 @@ ItemBound getItemBound(int i) { return bound; } #else -layout(std140) buffer ssbo0Buffer { +layout(std140, binding=0) buffer ssbo0Buffer { ItemBound bounds[]; }; ItemBound getItemBound(int i) { @@ -47,8 +50,8 @@ ItemBound getItemBound(int i) { -out vec4 varColor; -out vec2 varTexcoord; +layout(location=0) out vec4 varColor; +layout(location=1) out vec2 varTexcoord; void main(void) { const vec4 UNIT_BOX[8] = vec4[8]( diff --git a/libraries/render/src/render/drawItemStatus.slf b/libraries/render/src/render/drawItemStatus.slf index 40cf450363..309a73ae15 100644 --- a/libraries/render/src/render/drawItemStatus.slf +++ b/libraries/render/src/render/drawItemStatus.slf @@ -11,11 +11,11 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -in vec4 varColor; -in vec3 varTexcoord; -out vec4 outFragColor; +layout(location=0) in vec4 varColor; +layout(location=1) in vec3 varTexcoord; +layout(location=0) out vec4 outFragColor; -uniform sampler2D _icons; +layout(binding=0) uniform sampler2D _icons; vec2 getIconTexcoord(float icon, vec2 uv) { const vec2 ICON_COORD_SIZE = vec2(0.0625, 1.0); return vec2((uv.x + icon) * ICON_COORD_SIZE.x, uv.y * ICON_COORD_SIZE.y); diff --git a/libraries/render/src/render/drawItemStatus.slv b/libraries/render/src/render/drawItemStatus.slv index 792f2733c5..e92bdda248 100644 --- a/libraries/render/src/render/drawItemStatus.slv +++ b/libraries/render/src/render/drawItemStatus.slv @@ -2,7 +2,7 @@ <$VERSION_HEADER$> // Generated on <$_SCRIBE_DATE$> // -// drawItemStatus.slv +// drawItemStatus.vert // vertex shader // // Created by Sam Gateau on 6/30/2015. @@ -13,16 +13,17 @@ // <@include gpu/Transform.slh@> +<@include gpu/ShaderConstants.h@> <$declareStandardTransform()$> -out vec4 varColor; -out vec3 varTexcoord; +layout(location=0) out vec4 varColor; +layout(location=1) out vec3 varTexcoord; -uniform vec3 inBoundPos; -uniform vec3 inBoundDim; -uniform ivec4 inStatus0; -uniform ivec4 inStatus1; +layout(location=GPU_UNIFORM_EXTRA0) uniform vec3 inBoundPos; +layout(location=GPU_UNIFORM_EXTRA1) uniform vec3 inBoundDim; +layout(location=GPU_UNIFORM_EXTRA2) uniform ivec4 inStatus0; +layout(location=GPU_UNIFORM_EXTRA3) uniform ivec4 inStatus1; vec3 paintRainbow(float normalizedHue) { float v = normalizedHue * 6.f; diff --git a/libraries/render/src/render/drawLODReticle.slf b/libraries/render/src/render/drawLODReticle.slf index 68eb27b775..61d0cf32fb 100644 --- a/libraries/render/src/render/drawLODReticle.slf +++ b/libraries/render/src/render/drawLODReticle.slf @@ -11,8 +11,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -in vec2 varTexCoord0; -out vec4 outFragColor; +layout(location=0) in vec2 varTexCoord0; +layout(location=0) out vec4 outFragColor; void main(void) { vec2 circlePos = 2.0 * ( varTexCoord0.xy * 2.0 - vec2(1.0) ); diff --git a/libraries/shaders/CMakeLists.txt b/libraries/shaders/CMakeLists.txt index de188089a6..1c4824ac02 100644 --- a/libraries/shaders/CMakeLists.txt +++ b/libraries/shaders/CMakeLists.txt @@ -3,6 +3,7 @@ set(TARGET_NAME gpu) AUTOSCRIBE_SHADER_LIB(gpu) AUTOSCRIBE_PROGRAM(NAME drawColor VERTEX DrawTransformVertexPosition FRAGMENT DrawColor) AUTOSCRIBE_PROGRAM(NAME drawTransformUnitQuadTextureOpaque VERTEX DrawTransformUnitQuad FRAGMENT DrawTextureOpaque) +AUTOSCRIBE_PROGRAM(NAME drawTexture VERTEX DrawUnitQuadTexcoord FRAGMENT DrawTexture) AUTOSCRIBE_PROGRAM(NAME drawUnitQuatTextureOpaque VERTEX DrawUnitQuadTexcoord FRAGMENT DrawTextureOpaque) AUTOSCRIBE_PROGRAM(NAME drawTextureOpaqueTexcoordRect VERTEX DrawTexcoordRectTransformUnitQuad FRAGMENT DrawTextureOpaque) AUTOSCRIBE_PROGRAM(NAME drawNothing VERTEX DrawVertexPosition FRAGMENT DrawNada) @@ -11,6 +12,11 @@ set(TARGET_NAME graphics) AUTOSCRIBE_SHADER_LIB(gpu) AUTOSCRIBE_PROGRAM(NAME skybox) +set(TARGET_NAME display-plugins) +AUTOSCRIBE_SHADER_LIB(display-plugins) +AUTOSCRIBE_PROGRAM(NAME InterleavedSrgbToLinear VERTEX gpu::vertex::DrawUnitQuadTexcoord) +AUTOSCRIBE_PROGRAM(NAME SrgbToLinear VERTEX gpu::vertex::DrawUnitQuadTexcoord) + set(TARGET_NAME procedural) AUTOSCRIBE_SHADER_LIB(gpu graphics) @@ -171,5 +177,15 @@ AUTOSCRIBE_PROGRAM(NAME textured_particle) set(TARGET_NAME shaders) autoscribe_shader_finish() setup_hifi_library(Gui) +add_dependencies(${TARGET_NAME} compiled_shaders reflected_shaders) + +# Despite the dependency above, the autogen logic will attempt to compile the QRC before +# the compiled_shaders project is built causing an error on a clean workspace because the +# QRC references files generated by the compiled_shaders target +# To fix that we need to explicitly add every shader as a dependnecy of the autogen process +foreach(COMPILED_SHADER ${COMPILED_SHADERS}) + set_property(TARGET ${TARGET_NAME} APPEND PROPERTY AUTOGEN_TARGET_DEPENDS "${COMPILED_SHADER}") +endforeach() + link_hifi_libraries(shared) diff --git a/libraries/shaders/Shaders.cpp.in b/libraries/shaders/ShaderEnums.cpp.in similarity index 65% rename from libraries/shaders/Shaders.cpp.in rename to libraries/shaders/ShaderEnums.cpp.in index 795367cc4e..7f4751f116 100644 --- a/libraries/shaders/Shaders.cpp.in +++ b/libraries/shaders/ShaderEnums.cpp.in @@ -1,10 +1,10 @@ -#include "Shaders.h" +#include "ShaderEnums.h" namespace shader { uint32_t all_programs[] = { @SHADER_PROGRAMS_ARRAY@ - INVALID_SHADER + (uint32_t)-1 }; } diff --git a/libraries/shaders/ShaderEnums.h.in b/libraries/shaders/ShaderEnums.h.in new file mode 100644 index 0000000000..153f1d6fab --- /dev/null +++ b/libraries/shaders/ShaderEnums.h.in @@ -0,0 +1,9 @@ +#include +#include + +namespace shader { + +@SHADER_ENUMS@ + +} + diff --git a/libraries/shaders/Shaders.h.in b/libraries/shaders/Shaders.h.in deleted file mode 100644 index fd9b5c9ba9..0000000000 --- a/libraries/shaders/Shaders.h.in +++ /dev/null @@ -1,14 +0,0 @@ -#include -#include - -namespace shader { - -@SHADER_ENUMS@ - -extern uint32_t all_programs[]; - -static const uint32_t INVALID_SHADER = (uint32_t)-1; - -std::string loadShaderSource(uint32_t shaderId); -} - diff --git a/libraries/shaders/src/shaders/Shaders.cpp b/libraries/shaders/src/shaders/Shaders.cpp new file mode 100644 index 0000000000..50a7d38a69 --- /dev/null +++ b/libraries/shaders/src/shaders/Shaders.cpp @@ -0,0 +1,95 @@ +// +// Created by Bradley Austin Davis on 2018/06/02 +// Copyright 2013-2018 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "Shaders.h" + +#include +#include +#include +#include +#include + +#include +#include +#include + +// Can't use the Q_INIT_RESOURCE macro inside a namespace on Mac, +// so this is done out of line +void initShaders() { + static std::once_flag once; + std::call_once(once, [] { + Q_INIT_RESOURCE(shaders); + }); +} + +static std::vector splitStringIntoLines(const std::string& s) { + std::stringstream ss(s); + std::vector result; + + std::string line; + while (std::getline(ss, line, '\n')) { + result.push_back(line); + } + return result; +} + +static std::string loadResource(const std::string& path) { + return FileUtils::readFile(path.c_str()).toStdString(); +} + +namespace shader { + +void cleanShaderSource(std::string& shaderSource) { + static const std::regex LAYOUT_REGEX{ R"REGEX(^layout\((\s*std140\s*,\s*)?(?:binding|location)\s*=\s*(?:\b\w+\b)\)\s*(?!(?:flat\s+)?(?:out|in|buffer))\b(.*)$)REGEX" }; + static const int GROUP_STD140 = 1; + static const int THE_REST_OF_THE_OWL = 2; + std::vector lines = splitStringIntoLines(shaderSource); + std::vector outLines; + std::unordered_map locationDefines; + for (const auto& line : lines) { + std::cmatch m; + if (std::regex_match(line.c_str(), m, LAYOUT_REGEX)) { + std::string outLine; + if (m[GROUP_STD140].matched) { + outLine = "layout(std140) "; + } + outLine += m[THE_REST_OF_THE_OWL].str(); + outLines.push_back(outLine); + continue; + // On mac we have to strip out all the explicit binding location layouts, + // because GL 4.1 doesn't support them + } + outLines.push_back(line); + } + std::ostringstream joined; + std::copy(outLines.begin(), outLines.end(), std::ostream_iterator(joined, "\n")); + shaderSource = joined.str(); +} + +std::string loadShaderSource(uint32_t shaderId) { + initShaders(); + auto shaderStr = loadResource(std::string(":/shaders/") + std::to_string(shaderId)); +#if defined(Q_OS_MAC) + // OSX only supports OpenGL 4.1 without ARB_shading_language_420pack or + // ARB_explicit_uniform_location or basically anything useful that's + // been released in the last 8 fucking years, so in that case we need to + // strip out all explicit locations and do a bunch of background magic to + // make the system seem like it is using the explicit locations + cleanShaderSource(shaderStr); +#endif + return shaderStr; +} + +std::string loadShaderReflection(uint32_t shaderId) { + initShaders(); + auto path = std::string(":/shaders/") + std::to_string(shaderId) + std::string("_reflection"); + auto json = loadResource(path); + return json; +} + +} diff --git a/libraries/shaders/src/shaders/Shaders.h b/libraries/shaders/src/shaders/Shaders.h new file mode 100644 index 0000000000..1335c1b49b --- /dev/null +++ b/libraries/shaders/src/shaders/Shaders.h @@ -0,0 +1,34 @@ +// +// Created by Bradley Austin Davis on 2018/07/09 +// Copyright 2013-2018 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#pragma once +#include +#include +#include +#include + +namespace shader { + +static const uint32_t INVALID_SHADER = (uint32_t)-1; +static const uint32_t INVALID_PROGRAM = (uint32_t)-1; + +extern uint32_t all_programs[]; + +std::string loadShaderSource(uint32_t shaderId); +std::string loadShaderReflection(uint32_t shaderId); + +inline uint32_t getVertexId(uint32_t programId) { + return (programId >> 16) & UINT16_MAX; +} + +inline uint32_t getFragmentId(uint32_t programId) { + return programId & UINT16_MAX; +} + +} + diff --git a/libraries/shaders/src/shaders/ShadersCommon.cpp b/libraries/shaders/src/shaders/ShadersCommon.cpp deleted file mode 100644 index 03c8bd2918..0000000000 --- a/libraries/shaders/src/shaders/ShadersCommon.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include -#include - -namespace shader { - -std::string loadShaderSource(uint32_t shaderId) { - static std::once_flag once; - std::call_once(once, [] { - Q_INIT_RESOURCE(shaders); - }); - auto shaderPath = std::string(":/shaders/") + std::to_string(shaderId); - auto shaderData = FileUtils::readFile(shaderPath.c_str()); - return shaderData.toStdString(); -} - -} diff --git a/libraries/shared/src/shared/GlobalAppProperties.cpp b/libraries/shared/src/shared/GlobalAppProperties.cpp index 6c9f3f9601..54e50da3ea 100644 --- a/libraries/shared/src/shared/GlobalAppProperties.cpp +++ b/libraries/shared/src/shared/GlobalAppProperties.cpp @@ -21,7 +21,6 @@ namespace hifi { namespace properties { namespace gl { const char* BACKEND = "com.highfidelity.gl.backend"; - const char* MAKE_PROGRAM_CALLBACK = "com.highfidelity.gl.makeProgram"; const char* PRIMARY_CONTEXT = "com.highfidelity.gl.primaryContext"; } diff --git a/libraries/test-utils/src/test-utils/Utils.cpp b/libraries/test-utils/src/test-utils/Utils.cpp new file mode 100644 index 0000000000..16df34bb8b --- /dev/null +++ b/libraries/test-utils/src/test-utils/Utils.cpp @@ -0,0 +1,40 @@ +// +// Created by Bradley Austin Davis on 2018/05/13 +// Copyright 2013-2018 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "Utils.h" + +#include +#include +#include + +#if defined(Q_OS_WIN) +#include +#endif + + +#include "FileDownloader.h" + +static QtMessageHandler originalHandler; + +static void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message) { +#if defined(Q_OS_WIN) + OutputDebugStringA(message.toStdString().c_str()); + OutputDebugStringA("\n"); +#endif + originalHandler(type, context, message); +} + + +void installTestMessageHandler() { + originalHandler = qInstallMessageHandler(messageHandler); +} + +bool downloadFile(const QString& file, const std::function handler) { + FileDownloader(file, handler).waitForDownload(); + return true; +} \ No newline at end of file diff --git a/libraries/test-utils/src/test-utils/Utils.h b/libraries/test-utils/src/test-utils/Utils.h new file mode 100644 index 0000000000..27ed1f8207 --- /dev/null +++ b/libraries/test-utils/src/test-utils/Utils.h @@ -0,0 +1,17 @@ +// +// Created by Bradley Austin Davis on 2018/05/13 +// Copyright 2013-2018 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// +#pragma once + +class QByteArray; +class QString; + +#include + +void installTestMessageHandler(); + +bool downloadFile(const QString& url, const std::function handler); \ No newline at end of file diff --git a/plugins/openvr/src/OpenVrDisplayPlugin.cpp b/plugins/openvr/src/OpenVrDisplayPlugin.cpp index cd56eeff39..fae2144caf 100644 --- a/plugins/openvr/src/OpenVrDisplayPlugin.cpp +++ b/plugins/openvr/src/OpenVrDisplayPlugin.cpp @@ -23,7 +23,6 @@ #include #include - #include #include #include @@ -36,7 +35,7 @@ Q_DECLARE_LOGGING_CATEGORY(displayplugins) -const char* OpenVrThreadedSubmit { "OpenVR Threaded Submit" }; // this probably shouldn't be hardcoded here +const char* OpenVrThreadedSubmit{ "OpenVR Threaded Submit" }; // this probably shouldn't be hardcoded here PoseData _nextRenderPoseData; PoseData _nextSimPoseData; @@ -44,8 +43,8 @@ PoseData _nextSimPoseData; #define MIN_CORES_FOR_NORMAL_RENDER 5 bool forceInterleavedReprojection = (QThread::idealThreadCount() < MIN_CORES_FOR_NORMAL_RENDER); -static std::array VR_EYES { { vr::Eye_Left, vr::Eye_Right } }; -bool _openVrDisplayActive { false }; +static std::array VR_EYES{ { vr::Eye_Left, vr::Eye_Right } }; +bool _openVrDisplayActive{ false }; // Flip y-axis since GL UV coords are backwards. static vr::VRTextureBounds_t OPENVR_TEXTURE_BOUNDS_LEFT{ 0, 0, 0.5f, 1 }; static vr::VRTextureBounds_t OPENVR_TEXTURE_BOUNDS_RIGHT{ 0.5f, 0, 1, 1 }; @@ -164,9 +163,7 @@ public: friend class OpenVrDisplayPlugin; std::shared_ptr _canvas; - OpenVrSubmitThread(OpenVrDisplayPlugin& plugin) : _plugin(plugin) { - setObjectName("OpenVR Submit Thread"); - } + OpenVrSubmitThread(OpenVrDisplayPlugin& plugin) : _plugin(plugin) { setObjectName("OpenVR Submit Thread"); } void updateSource() { _plugin.withNonPresentThreadLock([&] { @@ -190,18 +187,18 @@ public: }); } - GLuint _program { 0 }; + GLuint _program{ 0 }; void updateProgram() { if (!_program) { std::string vsSource = HMD_REPROJECTION_VERT; std::string fsSource = HMD_REPROJECTION_FRAG; - GLuint vertexShader { 0 }, fragmentShader { 0 }; + GLuint vertexShader{ 0 }, fragmentShader{ 0 }; std::string error; - ::gl::CachedShader binary; ::gl::compileShader(GL_VERTEX_SHADER, vsSource, vertexShader, error); ::gl::compileShader(GL_FRAGMENT_SHADER, fsSource, fragmentShader, error); - _program = ::gl::compileProgram({ { vertexShader, fragmentShader } }, error, binary); + _program = ::gl::buildProgram({ { vertexShader, fragmentShader } }); + ::gl::linkProgram(_program, error); glDeleteShader(vertexShader); glDeleteShader(fragmentShader); qDebug() << "Rebuild proigram"; @@ -211,14 +208,13 @@ public: #define COLOR_BUFFER_COUNT 4 void run() override { - - GLuint _framebuffer { 0 }; + GLuint _framebuffer{ 0 }; std::array _colors; - size_t currentColorBuffer { 0 }; - size_t globalColorBufferCount { 0 }; - GLuint _uniformBuffer { 0 }; - GLuint _vao { 0 }; - GLuint _depth { 0 }; + size_t currentColorBuffer{ 0 }; + size_t globalColorBufferCount{ 0 }; + GLuint _uniformBuffer{ 0 }; + GLuint _vao{ 0 }; + GLuint _depth{ 0 }; Reprojection _reprojection; QThread::currentThread()->setPriority(QThread::Priority::TimeCriticalPriority); @@ -229,7 +225,6 @@ public: glCreateVertexArrays(1, &_vao); glBindVertexArray(_vao); - glCreateFramebuffers(1, &_framebuffer); { glCreateRenderbuffers(1, &_depth); @@ -253,7 +248,6 @@ public: continue; } - updateProgram(); { auto presentRotation = glm::mat3(_nextRender.poses[0]); @@ -281,13 +275,15 @@ public: static const vr::VRTextureBounds_t leftBounds{ 0, 0, 0.5f, 1 }; static const vr::VRTextureBounds_t rightBounds{ 0.5f, 0, 1, 1 }; - vr::Texture_t texture{ (void*)(uintptr_t)_colors[currentColorBuffer], vr::TextureType_OpenGL, vr::ColorSpace_Auto }; + vr::Texture_t texture{ (void*)(uintptr_t)_colors[currentColorBuffer], vr::TextureType_OpenGL, + vr::ColorSpace_Auto }; vr::VRCompositor()->Submit(vr::Eye_Left, &texture, &leftBounds); vr::VRCompositor()->Submit(vr::Eye_Right, &texture, &rightBounds); _plugin._presentRate.increment(); PoseData nextRender, nextSim; nextRender.frameIndex = _plugin.presentCount(); - vr::VRCompositor()->WaitGetPoses(nextRender.vrPoses, vr::k_unMaxTrackedDeviceCount, nextSim.vrPoses, vr::k_unMaxTrackedDeviceCount); + vr::VRCompositor()->WaitGetPoses(nextRender.vrPoses, vr::k_unMaxTrackedDeviceCount, nextSim.vrPoses, + vr::k_unMaxTrackedDeviceCount); // Copy invalid poses in nextSim from nextRender for (uint32_t i = 0; i < vr::k_unMaxTrackedDeviceCount; ++i) { @@ -297,9 +293,7 @@ public: } mat4 sensorResetMat; - _plugin.withNonPresentThreadLock([&] { - sensorResetMat = _plugin._sensorResetMat; - }); + _plugin.withNonPresentThreadLock([&] { sensorResetMat = _plugin._sensorResetMat; }); nextRender.update(sensorResetMat); nextSim.update(sensorResetMat); @@ -327,16 +321,12 @@ public: _canvas->doneCurrent(); } - void update(const CompositeInfo& newCompositeInfo) { - _queue.push(newCompositeInfo); - } + void update(const CompositeInfo& newCompositeInfo) { _queue.push(newCompositeInfo); } void waitForPresent() { auto lastCount = _presentCount.load(); Lock lock(_plugin._presentMutex); - _presented.wait(lock, [&]()->bool { - return _presentCount.load() > lastCount; - }); + _presented.wait(lock, [&]() -> bool { return _presentCount.load() > lastCount; }); _nextSimPoseData = _nextSim; _nextRenderPoseData = _nextRender; } @@ -345,9 +335,9 @@ public: CompositeInfo::Queue _queue; PoseData _nextRender, _nextSim; - bool _quit { false }; - GLuint _currentTexture { 0 }; - std::atomic _presentCount { 0 }; + bool _quit{ false }; + GLuint _currentTexture{ 0 }; + std::atomic _presentCount{ 0 }; Condition _presented; OpenVrDisplayPlugin& _plugin; }; @@ -451,7 +441,7 @@ bool OpenVrDisplayPlugin::internalActivate() { _openVrDisplayActive = true; _system->GetRecommendedRenderTargetSize(&_renderTargetSize.x, &_renderTargetSize.y); - // Recommended render target size is per-eye, so double the X size for + // Recommended render target size is per-eye, so double the X size for // left + right eyes _renderTargetSize.x *= 2; @@ -468,7 +458,6 @@ bool OpenVrDisplayPlugin::internalActivate() { if (forceInterleavedReprojection) { vr::VRCompositor()->ForceInterleavedReprojectionOn(true); } - // set up default sensor space such that the UI overlay will align with the front of the room. auto chaperone = vr::VRChaperone(); @@ -482,9 +471,9 @@ bool OpenVrDisplayPlugin::internalActivate() { glm::vec3 uiPos(0.0f, UI_HEIGHT, UI_RADIUS - (0.5f * zSize) - UI_Z_OFFSET); _sensorResetMat = glm::inverse(createMatFromQuatAndPos(glm::quat(), uiPos)); } else { - #if DEV_BUILD - qDebug() << "OpenVR: error could not get chaperone pointer"; - #endif +#if DEV_BUILD + qDebug() << "OpenVR: error could not get chaperone pointer"; +#endif } if (_threadedSubmit) { @@ -523,7 +512,9 @@ void OpenVrDisplayPlugin::customizeContext() { _compositeInfos[0].texture = _compositeFramebuffer->getRenderBuffer(0); for (size_t i = 0; i < COMPOSITING_BUFFER_SIZE; ++i) { if (0 != i) { - _compositeInfos[i].texture = gpu::Texture::createRenderBuffer(gpu::Element::COLOR_RGBA_32, _renderTargetSize.x, _renderTargetSize.y, gpu::Texture::SINGLE_MIP, gpu::Sampler(gpu::Sampler::FILTER_MIN_MAG_POINT)); + _compositeInfos[i].texture = gpu::Texture::createRenderBuffer(gpu::Element::COLOR_RGBA_32, _renderTargetSize.x, + _renderTargetSize.y, gpu::Texture::SINGLE_MIP, + gpu::Sampler(gpu::Sampler::FILTER_MIN_MAG_POINT)); } _compositeInfos[i].textureID = getGLBackend()->getTextureID(_compositeInfos[i].texture); } @@ -544,9 +535,7 @@ void OpenVrDisplayPlugin::uncustomizeContext() { void OpenVrDisplayPlugin::resetSensors() { glm::mat4 m; - withNonPresentThreadLock([&] { - m = toGlm(_nextSimPoseData.vrPoses[0].mDeviceToAbsoluteTracking); - }); + withNonPresentThreadLock([&] { m = toGlm(_nextSimPoseData.vrPoses[0].mDeviceToAbsoluteTracking); }); _sensorResetMat = glm::inverse(cancelOutRollAndPitch(m)); } @@ -567,9 +556,7 @@ bool OpenVrDisplayPlugin::beginFrameRender(uint32_t frameIndex) { _currentRenderFrameInfo = FrameInfo(); PoseData nextSimPoseData; - withNonPresentThreadLock([&] { - nextSimPoseData = _nextSimPoseData; - }); + withNonPresentThreadLock([&] { nextSimPoseData = _nextSimPoseData; }); // HACK: when interface is launched and steam vr is NOT running, openvr will return bad HMD poses for a few frames // To workaround this, filter out any hmd poses that are obviously bad, i.e. beneath the floor. @@ -582,10 +569,11 @@ bool OpenVrDisplayPlugin::beginFrameRender(uint32_t frameIndex) { _lastGoodHMDPose = nextSimPoseData.vrPoses[vr::k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking; } - vr::TrackedDeviceIndex_t handIndices[2] { vr::k_unTrackedDeviceIndexInvalid, vr::k_unTrackedDeviceIndexInvalid }; + vr::TrackedDeviceIndex_t handIndices[2]{ vr::k_unTrackedDeviceIndexInvalid, vr::k_unTrackedDeviceIndexInvalid }; { - vr::TrackedDeviceIndex_t controllerIndices[2] ; - auto trackedCount = _system->GetSortedTrackedDeviceIndicesOfClass(vr::TrackedDeviceClass_Controller, controllerIndices, 2); + vr::TrackedDeviceIndex_t controllerIndices[2]; + auto trackedCount = + _system->GetSortedTrackedDeviceIndicesOfClass(vr::TrackedDeviceClass_Controller, controllerIndices, 2); // Find the left and right hand controllers, if they exist for (uint32_t i = 0; i < std::min(trackedCount, 2); ++i) { if (nextSimPoseData.vrPoses[i].bPoseIsValid) { @@ -614,13 +602,12 @@ bool OpenVrDisplayPlugin::beginFrameRender(uint32_t frameIndex) { const vec3& angularVelocity = nextSimPoseData.angularVelocities[deviceIndex]; auto correctedPose = openVrControllerPoseToHandPose(i == 0, mat, linearVelocity, angularVelocity); static const glm::quat HAND_TO_LASER_ROTATION = glm::rotation(Vectors::UNIT_Z, Vectors::UNIT_NEG_Y); - handPoses[i] = glm::translate(glm::mat4(), correctedPose.translation) * glm::mat4_cast(correctedPose.rotation * HAND_TO_LASER_ROTATION); + handPoses[i] = glm::translate(glm::mat4(), correctedPose.translation) * + glm::mat4_cast(correctedPose.rotation * HAND_TO_LASER_ROTATION); } } - withNonPresentThreadLock([&] { - _frameInfos[frameIndex] = _currentRenderFrameInfo; - }); + withNonPresentThreadLock([&] { _frameInfos[frameIndex] = _currentRenderFrameInfo; }); return Parent::beginFrameRender(frameIndex); } @@ -652,9 +639,7 @@ void OpenVrDisplayPlugin::compositeLayers() { if (!newComposite.textureID) { newComposite.textureID = getGLBackend()->getTextureID(newComposite.texture); } - withPresentThreadLock([&] { - _submitThread->update(newComposite); - }); + withPresentThreadLock([&] { _submitThread->update(newComposite); }); } } @@ -665,7 +650,7 @@ void OpenVrDisplayPlugin::hmdPresent() { _submitThread->waitForPresent(); } else { GLuint glTexId = getGLBackend()->getTextureID(_compositeFramebuffer->getRenderBuffer(0)); - vr::Texture_t vrTexture { (void*)(uintptr_t)glTexId, vr::TextureType_OpenGL, vr::ColorSpace_Auto }; + vr::Texture_t vrTexture{ (void*)(uintptr_t)glTexId, vr::TextureType_OpenGL, vr::ColorSpace_Auto }; vr::VRCompositor()->Submit(vr::Eye_Left, &vrTexture, &OPENVR_TEXTURE_BOUNDS_LEFT); vr::VRCompositor()->Submit(vr::Eye_Right, &vrTexture, &OPENVR_TEXTURE_BOUNDS_RIGHT); vr::VRCompositor()->PostPresentHandoff(); @@ -687,17 +672,14 @@ void OpenVrDisplayPlugin::postPreview() { _hmdActivityLevel = _system->GetTrackedDeviceActivityLevel(vr::k_unTrackedDeviceIndex_Hmd); if (!_threadedSubmit) { - vr::VRCompositor()->WaitGetPoses(nextRender.vrPoses, vr::k_unMaxTrackedDeviceCount, nextSim.vrPoses, vr::k_unMaxTrackedDeviceCount); + vr::VRCompositor()->WaitGetPoses(nextRender.vrPoses, vr::k_unMaxTrackedDeviceCount, nextSim.vrPoses, + vr::k_unMaxTrackedDeviceCount); glm::mat4 resetMat; - withPresentThreadLock([&] { - resetMat = _sensorResetMat; - }); + withPresentThreadLock([&] { resetMat = _sensorResetMat; }); nextRender.update(resetMat); nextSim.update(resetMat); - withPresentThreadLock([&] { - _nextSimPoseData = nextSim; - }); + withPresentThreadLock([&] { _nextSimPoseData = nextSim; }); _nextRenderPoseData = nextRender; } @@ -715,7 +697,7 @@ void OpenVrDisplayPlugin::updatePresentPose() { _currentPresentFrameInfo.presentPose = _nextRenderPoseData.poses[vr::k_unTrackedDeviceIndex_Hmd]; } -bool OpenVrDisplayPlugin::suppressKeyboard() { +bool OpenVrDisplayPlugin::suppressKeyboard() { if (isOpenVrKeyboardShown()) { return false; } @@ -736,10 +718,10 @@ void OpenVrDisplayPlugin::unsuppressKeyboard() { } bool OpenVrDisplayPlugin::isKeyboardVisible() { - return isOpenVrKeyboardShown(); + return isOpenVrKeyboardShown(); } -int OpenVrDisplayPlugin::getRequiredThreadCount() const { +int OpenVrDisplayPlugin::getRequiredThreadCount() const { return Parent::getRequiredThreadCount() + (_threadedSubmit ? 1 : 0); } @@ -768,4 +750,3 @@ QString OpenVrDisplayPlugin::getPreferredAudioOutDevice() const { } return device; } - diff --git a/tests-manual/gpu-textures/src/TestHelpers.cpp b/tests-manual/gpu-textures/src/TestHelpers.cpp index f952a4385f..f0fe31cec6 100644 --- a/tests-manual/gpu-textures/src/TestHelpers.cpp +++ b/tests-manual/gpu-textures/src/TestHelpers.cpp @@ -9,17 +9,6 @@ #include "TestHelpers.h" #include -gpu::ShaderPointer makeShader(const std::string & vertexShaderSrc, const std::string & fragmentShaderSrc, const gpu::Shader::BindingSet & bindings) { - auto vs = gpu::Shader::createVertex(vertexShaderSrc); - auto fs = gpu::Shader::createPixel(fragmentShaderSrc); - auto shader = gpu::Shader::createProgram(vs, fs); - if (!gpu::Shader::makeProgram(*shader, bindings)) { - printf("Could not compile shader\n"); - exit(-1); - } - return shader; -} - QString projectRootDir() { static QString projectRootPath = QFileInfo(QFileInfo(__FILE__).absolutePath() + "/..").absoluteFilePath(); return projectRootPath; diff --git a/tests-manual/gpu-textures/src/TestHelpers.h b/tests-manual/gpu-textures/src/TestHelpers.h index 17730c3642..e752df7bf7 100644 --- a/tests-manual/gpu-textures/src/TestHelpers.h +++ b/tests-manual/gpu-textures/src/TestHelpers.h @@ -36,5 +36,4 @@ public: }; uint32_t toCompactColor(const glm::vec4& color); -gpu::ShaderPointer makeShader(const std::string & vertexShaderSrc, const std::string & fragmentShaderSrc, const gpu::Shader::BindingSet & bindings); QString projectRootDir(); diff --git a/tests-manual/gpu-textures/src/TestTextures.cpp b/tests-manual/gpu-textures/src/TestTextures.cpp index 7aedb506da..701e60fab8 100644 --- a/tests-manual/gpu-textures/src/TestTextures.cpp +++ b/tests-manual/gpu-textures/src/TestTextures.cpp @@ -81,11 +81,9 @@ TexturesTest::TexturesTest() { connect(&stats, &TextureTestStats::prevTexture, this, &TexturesTest::onPrevTexture); connect(&stats, &TextureTestStats::maxTextureMemory, this, &TexturesTest::onMaxTextureMemory); { - auto VS = gpu::Shader::createVertex(vertexShaderSource); - auto PS = gpu::Shader::createPixel(fragmentShaderSource); + auto VS = gpu::Shader::createVertex({ vertexShaderSource, {} }); + auto PS = gpu::Shader::createPixel({ fragmentShaderSource, {} }); auto program = gpu::Shader::createProgram(VS, PS); - gpu::Shader::BindingSet slotBindings; - gpu::Shader::makeProgram(*program, slotBindings); // If the pipeline did not exist, make it auto state = std::make_shared(); state->setCullMode(gpu::State::CULL_NONE); diff --git a/tests-manual/gpu/src/TestHelpers.cpp b/tests-manual/gpu/src/TestHelpers.cpp index 75586da904..f46e997567 100644 --- a/tests-manual/gpu/src/TestHelpers.cpp +++ b/tests-manual/gpu/src/TestHelpers.cpp @@ -7,14 +7,3 @@ // #include "TestHelpers.h" - -gpu::ShaderPointer makeShader(const std::string & vertexShaderSrc, const std::string & fragmentShaderSrc, const gpu::Shader::BindingSet & bindings) { - auto vs = gpu::Shader::createVertex(vertexShaderSrc); - auto fs = gpu::Shader::createPixel(fragmentShaderSrc); - auto shader = gpu::Shader::createProgram(vs, fs); - if (!gpu::Shader::makeProgram(*shader, bindings)) { - printf("Could not compile shader\n"); - exit(-1); - } - return shader; -} diff --git a/tests-manual/gpu/src/TestHelpers.h b/tests-manual/gpu/src/TestHelpers.h index fd8989f628..4f8137e641 100644 --- a/tests-manual/gpu/src/TestHelpers.h +++ b/tests-manual/gpu/src/TestHelpers.h @@ -29,5 +29,4 @@ public: }; uint32_t toCompactColor(const glm::vec4& color); -gpu::ShaderPointer makeShader(const std::string & vertexShaderSrc, const std::string & fragmentShaderSrc, const gpu::Shader::BindingSet & bindings); diff --git a/tests-manual/render-perf/CMakeLists.txt b/tests-manual/render-perf/CMakeLists.txt index 93ff325a98..0cc3f87bd9 100644 --- a/tests-manual/render-perf/CMakeLists.txt +++ b/tests-manual/render-perf/CMakeLists.txt @@ -14,7 +14,8 @@ set_target_properties(${TARGET_NAME} PROPERTIES FOLDER "Tests/manual-tests/") # link in the shared libraries link_hifi_libraries( shared task workload networking animation - ktx image octree gl gpu ${PLATFORM_GL_BACKEND} + ktx image octree + shaders gl gpu ${PLATFORM_GL_BACKEND} render render-utils graphics fbx model-networking graphics-scripting entities entities-renderer audio avatars script-engine diff --git a/tests-manual/render-perf/src/main.cpp b/tests-manual/render-perf/src/main.cpp index 7126b333f6..9238e0dc1c 100644 --- a/tests-manual/render-perf/src/main.cpp +++ b/tests-manual/render-perf/src/main.cpp @@ -42,13 +42,13 @@ #include #include #include +#include #include #include #include #include -#include #include @@ -120,18 +120,26 @@ public: class QWindowCamera : public SimpleCamera { Key forKey(int key) { switch (key) { - case Qt::Key_W: return FORWARD; - case Qt::Key_S: return BACK; - case Qt::Key_A: return LEFT; - case Qt::Key_D: return RIGHT; - case Qt::Key_E: return UP; - case Qt::Key_C: return DOWN; - default: break; + case Qt::Key_W: + return FORWARD; + case Qt::Key_S: + return BACK; + case Qt::Key_A: + return LEFT; + case Qt::Key_D: + return RIGHT; + case Qt::Key_E: + return UP; + case Qt::Key_C: + return DOWN; + default: + break; } return INVALID; } vec2 _lastMouse; + public: void onKeyPress(QKeyEvent* event) { Key k = forKey(event->key()); @@ -168,7 +176,7 @@ public: }; static QString toHumanSize(size_t size, size_t maxUnit = std::numeric_limits::max()) { - static const std::vector SUFFIXES { { "B", "KB", "MB", "GB", "TB", "PB" } }; + static const std::vector SUFFIXES{ { "B", "KB", "MB", "GB", "TB", "PB" } }; const size_t maxIndex = std::min(maxUnit, SUFFIXES.size() - 1); size_t suffixIndex = 0; @@ -180,40 +188,28 @@ static QString toHumanSize(size_t size, size_t maxUnit = std::numeric_limits _presentCount; QElapsedTimer _elapsed; - std::atomic _fps { 1 }; + std::atomic _fps{ 1 }; RateCounter<200> _fpsCounter; std::mutex _mutex; std::shared_ptr _backend; std::vector _frameTimes; - size_t _frameIndex { 0 }; + size_t _frameIndex{ 0 }; std::mutex _frameLock; std::queue _pendingFrames; gpu::FramePointer _activeFrame; QSize _size; - static const size_t FRAME_TIME_BUFFER_SIZE { 8192 }; + static const size_t FRAME_TIME_BUFFER_SIZE{ 8192 }; void submitFrame(const gpu::FramePointer& frame) { std::unique_lock lock(_frameLock); @@ -246,18 +242,12 @@ public: RENDER_THREAD = QThread::currentThread(); // Wait until the context has been moved to this thread - { - std::unique_lock lock(_mutex); - } + { std::unique_lock lock(_mutex); } _context.makeCurrent(); _frameTimes.resize(FRAME_TIME_BUFFER_SIZE, 0); { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = gpu::Shader::createPixel(std::string(SRGB_TO_LINEAR_FRAG)); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - gpu::Shader::BindingSet slotBindings; - gpu::Shader::makeProgram(*program, slotBindings); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::display_plugins::program::SrgbToLinear); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); _presentPipeline = gpu::Pipeline::create(program, state); } @@ -287,7 +277,6 @@ public: _gpuContext->executeFrame(frame); { - auto geometryCache = DependencyManager::get(); gpu::Batch presentBatch; presentBatch.setViewportTransform({ 0, 0, _size.width(), _size.height() }); @@ -304,7 +293,7 @@ public: _context.makeCurrent(); _context.swapBuffers(); _fpsCounter.increment(); - static size_t _frameCount { 0 }; + static size_t _frameCount{ 0 }; ++_frameCount; if (_elapsed.elapsed() >= 500) { _fps = _fpsCounter.rate(); @@ -374,16 +363,13 @@ public: class TestActionFactory : public EntityDynamicFactoryInterface { public: virtual EntityDynamicPointer factory(EntityDynamicType type, - const QUuid& id, - EntityItemPointer ownerEntity, - QVariantMap arguments) override { + const QUuid& id, + EntityItemPointer ownerEntity, + QVariantMap arguments) override { return EntityDynamicPointer(); } - - virtual EntityDynamicPointer factoryBA(EntityItemPointer ownerEntity, QByteArray data) override { - return nullptr; - } + virtual EntityDynamicPointer factoryBA(EntityItemPointer ownerEntity, QByteArray data) override { return nullptr; } }; // Background Render Data & rendering functions @@ -391,96 +377,77 @@ class BackgroundRenderData { public: typedef render::Payload Payload; typedef Payload::DataPointer Pointer; - static render::ItemID _item; // unique WorldBoxRenderData + static render::ItemID _item; // unique WorldBoxRenderData }; render::ItemID BackgroundRenderData::_item = 0; QSharedPointer logger; namespace render { - template <> const ItemKey payloadGetKey(const BackgroundRenderData::Pointer& stuff) { - return ItemKey::Builder::background(); - } - - template <> const Item::Bound payloadGetBound(const BackgroundRenderData::Pointer& stuff) { - return Item::Bound(); - } - - template <> void payloadRender(const BackgroundRenderData::Pointer& background, RenderArgs* args) { - Q_ASSERT(args->_batch); - gpu::Batch& batch = *args->_batch; - - // Background rendering decision - auto skyStage = DependencyManager::get()->getSkyStage(); - auto backgroundMode = skyStage->getBackgroundMode(); - - switch (backgroundMode) { - case graphics::SunSkyStage::SKY_BOX: { - auto skybox = skyStage->getSkybox(); - if (skybox) { - PerformanceTimer perfTimer("skybox"); - skybox->render(batch, args->getViewFrustum()); - break; - } - } - default: - // this line intentionally left blank - break; - } - } +template <> +const ItemKey payloadGetKey(const BackgroundRenderData::Pointer& stuff) { + return ItemKey::Builder::background(); } -OffscreenGLCanvas* _chromiumShareContext{ nullptr }; -Q_GUI_EXPORT void qt_gl_set_global_share_context(QOpenGLContext *context); +template <> +const Item::Bound payloadGetBound(const BackgroundRenderData::Pointer& stuff) { + return Item::Bound(); +} +template <> +void payloadRender(const BackgroundRenderData::Pointer& background, RenderArgs* args) { + Q_ASSERT(args->_batch); + gpu::Batch& batch = *args->_batch; + + // Background rendering decision + auto skyStage = DependencyManager::get()->getSkyStage(); + auto backgroundMode = skyStage->getBackgroundMode(); + + switch (backgroundMode) { + case graphics::SunSkyStage::SKY_BOX: { + auto skybox = skyStage->getSkybox(); + if (skybox) { + PerformanceTimer perfTimer("skybox"); + skybox->render(batch, args->getViewFrustum()); + break; + } + } + default: + // this line intentionally left blank + break; + } +} +} // namespace render + +OffscreenGLCanvas* _chromiumShareContext{ nullptr }; +Q_GUI_EXPORT void qt_gl_set_global_share_context(QOpenGLContext* context); // Create a simple OpenGL window that renders text in various ways class QTestWindow : public QWindow, public AbstractViewStateInterface { - protected: - void copyCurrentViewFrustum(ViewFrustum& viewOut) const override { - viewOut = _viewFrustum; - } + void copyCurrentViewFrustum(ViewFrustum& viewOut) const override { viewOut = _viewFrustum; } - const ConicalViewFrustums& getConicalViews() const override { - return _view; - } + const ConicalViewFrustums& getConicalViews() const override { return _view; } - QThread* getMainThread() override { - return QThread::currentThread(); - } + QThread* getMainThread() override { return QThread::currentThread(); } - PickRay computePickRay(float x, float y) const override { - return PickRay(); - } + PickRay computePickRay(float x, float y) const override { return PickRay(); } - glm::vec3 getAvatarPosition() const override { - return vec3(); - } + glm::vec3 getAvatarPosition() const override { return vec3(); } void postLambdaEvent(const std::function& f) override {} void sendLambdaEvent(const std::function& f) override {} - qreal getDevicePixelRatio() override { - return 1.0f; - } + qreal getDevicePixelRatio() override { return 1.0f; } - render::ScenePointer getMain3DScene() override { - return _main3DScene; - } + render::ScenePointer getMain3DScene() override { return _main3DScene; } - render::EnginePointer getRenderEngine() override { - return _renderEngine; - } + render::EnginePointer getRenderEngine() override { return _renderEngine; } std::map> _postUpdateLambdas; - void pushPostUpdateLambda(void* key, const std::function& func) override { - _postUpdateLambdas[key] = func; - } + void pushPostUpdateLambda(void* key, const std::function& func) override { _postUpdateLambdas[key] = func; } - bool isHMDMode() const override { - return false; - } + bool isHMDMode() const override { return false; } public: //"/-17.2049,-8.08629,-19.4153/0,0.881994,0,-0.47126" @@ -521,7 +488,7 @@ public: nodeList->setPermissions(permissions); { - SimpleEntitySimulationPointer simpleSimulation { new SimpleEntitySimulation() }; + SimpleEntitySimulationPointer simpleSimulation{ new SimpleEntitySimulation() }; simpleSimulation->setEntityTree(_octree->getTree()); _octree->getTree()->setSimulation(simpleSimulation); _entitySimulation = simpleSimulation; @@ -556,7 +523,6 @@ public: _initContext.makeCurrent(); } - // FIXME use a wait condition QThread::msleep(1000); _renderThread.submitFrame(gpu::FramePointer()); @@ -575,16 +541,14 @@ public: restorePosition(); QTimer* timer = new QTimer(this); - timer->setInterval(0); // Qt::CoarseTimer acceptable - connect(timer, &QTimer::timeout, this, [this] { - draw(); - }); + timer->setInterval(0); // Qt::CoarseTimer acceptable + connect(timer, &QTimer::timeout, this, [this] { draw(); }); timer->start(); _ready = true; } virtual ~QTestWindow() { - getEntities()->shutdown(); // tell the entities system we're shutting down, so it will stop running scripts + getEntities()->shutdown(); // tell the entities system we're shutting down, so it will stop running scripts _renderEngine.reset(); _main3DScene.reset(); EntityTreePointer tree = getEntities()->getTree(); @@ -611,8 +575,7 @@ public: } protected: - - bool eventFilter(QObject *obj, QEvent *event) override { + bool eventFilter(QObject* obj, QEvent* event) override { if (event->type() == QEvent::Close) { _renderThread.terminate(); } @@ -668,22 +631,16 @@ protected: _camera.onKeyPress(event); } - void keyReleaseEvent(QKeyEvent* event) override { - _camera.onKeyRelease(event); - } + void keyReleaseEvent(QKeyEvent* event) override { _camera.onKeyRelease(event); } - void mouseMoveEvent(QMouseEvent* event) override { - _camera.onMouseMove(event); - } + void mouseMoveEvent(QMouseEvent* event) override { _camera.onMouseMove(event); } - void resizeEvent(QResizeEvent* ev) override { - resizeWindow(ev->size()); - } + void resizeEvent(QResizeEvent* ev) override { resizeWindow(ev->size()); } private: - static bool cull(const RenderArgs* args, const AABox& bounds) { - float renderAccuracy = calculateRenderAccuracy(args->getViewFrustum().getPosition(), bounds, args->_sizeScale, args->_boundaryLevelAdjust); + float renderAccuracy = + calculateRenderAccuracy(args->getViewFrustum().getPosition(), bounds, args->_sizeScale, args->_boundaryLevelAdjust); return (renderAccuracy > 0.0f); } @@ -702,10 +659,8 @@ private: update(); _initContext.makeCurrent(); - RenderArgs renderArgs(_renderThread._gpuContext, DEFAULT_OCTREE_SIZE_SCALE, - 0, RenderArgs::DEFAULT_RENDER_MODE, - RenderArgs::MONO, RenderArgs::RENDER_DEBUG_NONE); - + RenderArgs renderArgs(_renderThread._gpuContext, DEFAULT_OCTREE_SIZE_SCALE, 0, RenderArgs::DEFAULT_RENDER_MODE, + RenderArgs::MONO, RenderArgs::RENDER_DEBUG_NONE); QSize windowSize = _size; if (_renderMode == NORMAL) { @@ -719,16 +674,16 @@ private: eyeProjections[i] = _viewFrustum.getProjection(); } } else if (_renderMode == HMD) { - eyeOffsets[0][3] = vec4 { -0.0327499993, 0.0, 0.0149999997, 1.0 }; - eyeOffsets[1][3] = vec4 { 0.0327499993, 0.0, 0.0149999997, 1.0 }; - eyeProjections[0][0] = vec4 { 0.759056330, 0.000000000, 0.000000000, 0.000000000 }; - eyeProjections[0][1] = vec4 { 0.000000000, 0.682773232, 0.000000000, 0.000000000 }; - eyeProjections[0][2] = vec4 { -0.0580431037, -0.00619550655, -1.00000489, -1.00000000 }; - eyeProjections[0][3] = vec4 { 0.000000000, 0.000000000, -0.0800003856, 0.000000000 }; - eyeProjections[1][0] = vec4 { 0.752847493, 0.000000000, 0.000000000, 0.000000000 }; - eyeProjections[1][1] = vec4 { 0.000000000, 0.678060353, 0.000000000, 0.000000000 }; - eyeProjections[1][2] = vec4 { 0.0578232110, -0.00669418881, -1.00000489, -1.000000000 }; - eyeProjections[1][3] = vec4 { 0.000000000, 0.000000000, -0.0800003856, 0.000000000 }; + eyeOffsets[0][3] = vec4{ -0.0327499993, 0.0, 0.0149999997, 1.0 }; + eyeOffsets[1][3] = vec4{ 0.0327499993, 0.0, 0.0149999997, 1.0 }; + eyeProjections[0][0] = vec4{ 0.759056330, 0.000000000, 0.000000000, 0.000000000 }; + eyeProjections[0][1] = vec4{ 0.000000000, 0.682773232, 0.000000000, 0.000000000 }; + eyeProjections[0][2] = vec4{ -0.0580431037, -0.00619550655, -1.00000489, -1.00000000 }; + eyeProjections[0][3] = vec4{ 0.000000000, 0.000000000, -0.0800003856, 0.000000000 }; + eyeProjections[1][0] = vec4{ 0.752847493, 0.000000000, 0.000000000, 0.000000000 }; + eyeProjections[1][1] = vec4{ 0.000000000, 0.678060353, 0.000000000, 0.000000000 }; + eyeProjections[1][2] = vec4{ 0.0578232110, -0.00669418881, -1.00000489, -1.000000000 }; + eyeProjections[1][3] = vec4{ 0.000000000, 0.000000000, -0.0800003856, 0.000000000 }; windowSize = { 2048, 2048 }; } renderArgs._context->setStereoProjections(eyeProjections); @@ -774,10 +729,11 @@ private: void updateText() { QString title = QString("FPS %1 Culling %2 TextureMemory GPU %3 CPU %4 Max GPU %5") - .arg(_fps).arg(_cullingEnabled) - .arg(toHumanSize(gpu::Context::getTextureGPUMemSize(), 2)) - .arg(toHumanSize(gpu::Texture::getTextureCPUMemSize(), 2)) - .arg(toHumanSize(gpu::Texture::getAllowedGPUMemoryUsage(), 2)); + .arg(_fps) + .arg(_cullingEnabled) + .arg(toHumanSize(gpu::Context::getTextureGPUMemSize(), 2)) + .arg(toHumanSize(gpu::Texture::getTextureCPUMemSize(), 2)) + .arg(toHumanSize(gpu::Texture::getAllowedGPUMemoryUsage(), 2)); setTitle(title); #if 0 { @@ -818,34 +774,34 @@ private: if (commandParams.length() < 2) { qDebug() << "No wait time specified"; return; - } + } int seconds = commandParams[1].toInt(); _nextCommandTime = usecTimestampNow() + seconds * USECS_PER_SECOND; - } else if (verb == "load") { - if (commandParams.length() < 2) { - qDebug() << "No load file specified"; - return; - } - QString file = commandParams[1]; - if (QFileInfo(file).isRelative()) { - file = _commandPath + "/" + file; - } - if (!QFileInfo(file).exists()) { - qDebug() << "Cannot find scene file " + file; - return; - } + } else if (verb == "load") { + if (commandParams.length() < 2) { + qDebug() << "No load file specified"; + return; + } + QString file = commandParams[1]; + if (QFileInfo(file).isRelative()) { + file = _commandPath + "/" + file; + } + if (!QFileInfo(file).exists()) { + qDebug() << "Cannot find scene file " + file; + return; + } - importScene(file); - } else if (verb == "go") { - if (commandParams.length() < 2) { - qDebug() << "No destination specified for go command"; - return; + importScene(file); + } else if (verb == "go") { + if (commandParams.length() < 2) { + qDebug() << "No destination specified for go command"; + return; + } + parsePath(commandParams[1]); + } else { + qDebug() << "Unknown command " << command; } - parsePath(commandParams[1]); - } else { - qDebug() << "Unknown command " << command; } -} void runNextCommand(quint64 now) { if (_commands.empty()) { @@ -918,15 +874,12 @@ private: _main3DScene->processTransactionQueue(); } - } void render(RenderArgs* renderArgs) { auto& gpuContext = renderArgs->_context; gpuContext->beginFrame(); - gpu::doInBatch("QTestWindow::render", gpuContext, [&](gpu::Batch& batch) { - batch.resetStages(); - }); + gpu::doInBatch("QTestWindow::render", gpuContext, [&](gpu::Batch& batch) { batch.resetStages(); }); PROFILE_RANGE(render, __FUNCTION__); PerformanceTimer perfTimer("draw"); // The pending changes collecting the changes here @@ -953,8 +906,6 @@ private: if (!_renderThread.isThreaded()) { _renderThread.process(); } - - } void resizeWindow(const QSize& size) { @@ -972,31 +923,27 @@ private: static const QString FLOAT_REGEX_STRING = "([-+]?[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?)"; static const QString SPACED_COMMA_REGEX_STRING = "\\s*,\\s*"; static const QString POSITION_REGEX_STRING = QString("\\/") + FLOAT_REGEX_STRING + SPACED_COMMA_REGEX_STRING + - FLOAT_REGEX_STRING + SPACED_COMMA_REGEX_STRING + FLOAT_REGEX_STRING + "\\s*(?:$|\\/)"; + FLOAT_REGEX_STRING + SPACED_COMMA_REGEX_STRING + FLOAT_REGEX_STRING + + "\\s*(?:$|\\/)"; static const QString QUAT_REGEX_STRING = QString("\\/") + FLOAT_REGEX_STRING + SPACED_COMMA_REGEX_STRING + - FLOAT_REGEX_STRING + SPACED_COMMA_REGEX_STRING + FLOAT_REGEX_STRING + SPACED_COMMA_REGEX_STRING + - FLOAT_REGEX_STRING + "\\s*$"; + FLOAT_REGEX_STRING + SPACED_COMMA_REGEX_STRING + FLOAT_REGEX_STRING + + SPACED_COMMA_REGEX_STRING + FLOAT_REGEX_STRING + "\\s*$"; static QRegExp orientationRegex(QUAT_REGEX_STRING); static QRegExp positionRegex(POSITION_REGEX_STRING); if (positionRegex.indexIn(viewpointString) != -1) { // we have at least a position, so emit our signal to say we need to change position - glm::vec3 newPosition(positionRegex.cap(1).toFloat(), - positionRegex.cap(2).toFloat(), - positionRegex.cap(3).toFloat()); + glm::vec3 newPosition(positionRegex.cap(1).toFloat(), positionRegex.cap(2).toFloat(), + positionRegex.cap(3).toFloat()); _camera.setPosition(newPosition); if (!glm::any(glm::isnan(newPosition))) { // we may also have an orientation - if (viewpointString[positionRegex.matchedLength() - 1] == QChar('/') - && orientationRegex.indexIn(viewpointString, positionRegex.matchedLength() - 1) != -1) { - - glm::vec4 v = glm::vec4( - orientationRegex.cap(1).toFloat(), - orientationRegex.cap(2).toFloat(), - orientationRegex.cap(3).toFloat(), - orientationRegex.cap(4).toFloat()); + if (viewpointString[positionRegex.matchedLength() - 1] == QChar('/') && + orientationRegex.indexIn(viewpointString, positionRegex.matchedLength() - 1) != -1) { + glm::vec4 v = glm::vec4(orientationRegex.cap(1).toFloat(), orientationRegex.cap(2).toFloat(), + orientationRegex.cap(3).toFloat(), orientationRegex.cap(4).toFloat()); if (!glm::any(glm::isnan(v))) { _camera.setRotation(glm::quat(v.w, v.x, v.y, v.z)); } @@ -1056,9 +1003,7 @@ private: // /-17.2049,-8.08629,-19.4153/0,-0.48551,0,0.874231 glm::quat q = _camera.getOrientation(); glm::vec3 v = _camera.position; - QString viewpoint = QString("/%1,%2,%3/%4,%5,%6,%7"). - arg(v.x).arg(v.y).arg(v.z). - arg(q.x).arg(q.y).arg(q.z).arg(q.w); + QString viewpoint = QString("/%1,%2,%3/%4,%5,%6,%7").arg(v.x).arg(v.y).arg(v.z).arg(q.x).arg(q.y).arg(q.z).arg(q.w); _settings.setValue(LAST_LOCATION_KEY, viewpoint); _camera.setRotation(q); } @@ -1076,30 +1021,26 @@ private: _camera.setPosition(vec3()); } - void toggleCulling() { - _cullingEnabled = !_cullingEnabled; - } + void toggleCulling() { _cullingEnabled = !_cullingEnabled; } void cycleMode() { static auto defaultProjection = SimpleCamera().matrices.perspective; _renderMode = (RenderMode)((_renderMode + 1) % RENDER_MODE_COUNT); if (_renderMode == HMD) { - _camera.matrices.perspective[0] = vec4 { 0.759056330, 0.000000000, 0.000000000, 0.000000000 }; - _camera.matrices.perspective[1] = vec4 { 0.000000000, 0.682773232, 0.000000000, 0.000000000 }; - _camera.matrices.perspective[2] = vec4 { -0.0580431037, -0.00619550655, -1.00000489, -1.00000000 }; - _camera.matrices.perspective[3] = vec4 { 0.000000000, 0.000000000, -0.0800003856, 0.000000000 }; + _camera.matrices.perspective[0] = vec4{ 0.759056330, 0.000000000, 0.000000000, 0.000000000 }; + _camera.matrices.perspective[1] = vec4{ 0.000000000, 0.682773232, 0.000000000, 0.000000000 }; + _camera.matrices.perspective[2] = vec4{ -0.0580431037, -0.00619550655, -1.00000489, -1.00000000 }; + _camera.matrices.perspective[3] = vec4{ 0.000000000, 0.000000000, -0.0800003856, 0.000000000 }; } else { _camera.matrices.perspective = defaultProjection; _camera.setAspectRatio((float)_size.width() / (float)_size.height()); } } - QSharedPointer getEntities() { - return _octree; - } + QSharedPointer getEntities() { return _octree; } private: - render::CullFunctor _cullFunctor { [&](const RenderArgs* args, const AABox& bounds)->bool { + render::CullFunctor _cullFunctor{ [&](const RenderArgs* args, const AABox& bounds) -> bool { if (_cullingEnabled) { return cull(args, bounds); } else { @@ -1107,8 +1048,8 @@ private: } } }; - render::EnginePointer _renderEngine { new render::RenderEngine() }; - render::ScenePointer _main3DScene { new render::Scene(glm::vec3(-0.5f * (float)TREE_SCALE), (float)TREE_SCALE) }; + render::EnginePointer _renderEngine{ new render::RenderEngine() }; + render::ScenePointer _main3DScene{ new render::Scene(glm::vec3(-0.5f * (float)TREE_SCALE), (float)TREE_SCALE) }; QSize _size; QSettings _settings; @@ -1116,39 +1057,39 @@ private: gl::OffscreenContext _initContext; RenderThread _renderThread; QWindowCamera _camera; - ViewFrustum _viewFrustum; // current state of view frustum, perspective, orientation, etc. + ViewFrustum _viewFrustum; // current state of view frustum, perspective, orientation, etc. graphics::SunSkyStage _sunSkyStage; - graphics::LightPointer _globalLight { std::make_shared() }; - bool _ready { false }; + graphics::LightPointer _globalLight{ std::make_shared() }; + bool _ready{ false }; EntitySimulationPointer _entitySimulation; ConicalViewFrustums _view; QStringList _commands; QString _commandPath; - int _commandLoops { 0 }; - int _commandIndex { -1 }; - uint64_t _nextCommandTime { 0 }; + int _commandLoops{ 0 }; + int _commandIndex{ -1 }; + uint64_t _nextCommandTime{ 0 }; //TextOverlay* _textOverlay; static bool _cullingEnabled; - enum RenderMode { + enum RenderMode + { NORMAL = 0, STEREO, HMD, RENDER_MODE_COUNT }; - RenderMode _renderMode { NORMAL }; + RenderMode _renderMode{ NORMAL }; QSharedPointer _octree; }; bool QTestWindow::_cullingEnabled = true; -const char * LOG_FILTER_RULES = R"V0G0N( +const char* LOG_FILTER_RULES = R"V0G0N( hifi.gpu=true )V0G0N"; - int main(int argc, char** argv) { setupHifiApplication("RenderPerf"); @@ -1164,4 +1105,3 @@ int main(int argc, char** argv) { } #include "main.moc" - diff --git a/tests-manual/render-texture-load/CMakeLists.txt b/tests-manual/render-texture-load/CMakeLists.txt index b3e49d830b..36526ecd42 100644 --- a/tests-manual/render-texture-load/CMakeLists.txt +++ b/tests-manual/render-texture-load/CMakeLists.txt @@ -14,7 +14,7 @@ set_target_properties(${TARGET_NAME} PROPERTIES FOLDER "Tests/manual-tests/") # link in the shared libraries link_hifi_libraries( shared task networking octree - gl gpu render ktx image animation + shaders gl gpu render ktx image animation graphics fbx model-networking render-utils entities entities-renderer audio avatars diff --git a/tests-manual/render-texture-load/src/main.cpp b/tests-manual/render-texture-load/src/main.cpp index ce666065e3..b6dca48979 100644 --- a/tests-manual/render-texture-load/src/main.cpp +++ b/tests-manual/render-texture-load/src/main.cpp @@ -44,11 +44,11 @@ #include #include #include +#include #include #include #include -#include #include #include @@ -154,11 +154,7 @@ public: //wglSwapIntervalEXT(0); _frameTimes.resize(FRAME_TIME_BUFFER_SIZE, 0); { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = gpu::StandardShaderLib::getDrawTexturePS(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - gpu::Shader::BindingSet slotBindings; - gpu::Shader::makeProgram(*program, slotBindings); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::gpu::program::drawTransformUnitQuadTextureOpaque); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); _presentPipeline = gpu::Pipeline::create(program, state); } @@ -345,10 +341,7 @@ public: _renderThread.submitFrame(gpu::FramePointer()); _initContext.makeCurrent(); { - auto vs = gpu::StandardShaderLib::getDrawUnitQuadTexcoordVS(); - auto ps = gpu::StandardShaderLib::getDrawTexturePS(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - gpu::Shader::makeProgram(*program); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::gpu::program::drawTransformUnitQuadTextureOpaque); gpu::StatePointer state = gpu::StatePointer(new gpu::State()); state->setDepthTest(gpu::State::DepthTest(false)); state->setScissorEnable(true); diff --git a/tests-manual/render-utils/src/main.cpp b/tests-manual/render-utils/src/main.cpp index e30a80f3d9..b5bc5daebb 100644 --- a/tests-manual/render-utils/src/main.cpp +++ b/tests-manual/render-utils/src/main.cpp @@ -153,13 +153,6 @@ protected: //static const wchar_t* EXAMPLE_TEXT = L"Hello"; //static const wchar_t* EXAMPLE_TEXT = L"\xC1y Hello 1.0\ny\xC1 line 2\n\xC1y"; -void testShaderBuild(const char* vs_src, const char * fs_src) { - auto vs = gpu::Shader::createVertex(std::string(vs_src)); - auto fs = gpu::Shader::createPixel(std::string(fs_src)); - auto pr = gpu::Shader::createProgram(vs, fs); - gpu::Shader::makeProgram(*pr); -} - void QTestWindow::draw() { if (!isVisible()) { return; diff --git a/tests-manual/shaders/CMakeLists.txt b/tests-manual/shaders/CMakeLists.txt deleted file mode 100644 index 44394db6a0..0000000000 --- a/tests-manual/shaders/CMakeLists.txt +++ /dev/null @@ -1,27 +0,0 @@ - -set(TARGET_NAME shaders-test) - -# This is not a testcase -- just set it up as a regular hifi project -setup_hifi_project(Quick Gui) -set_target_properties(${TARGET_NAME} PROPERTIES FOLDER "Tests/manual-tests/") - -setup_memory_debugger() - -# link in the shared libraries -link_hifi_libraries( - shared octree gl gpu graphics render fbx networking entities - script-engine physics - render-utils entities-renderer - ${PLATFORM_GL_BACKEND} -) - -include_directories("${PROJECT_BINARY_DIR}/../../libraries/gpu/") -include_directories("${PROJECT_BINARY_DIR}/../../libraries/render-utils/") -include_directories("${PROJECT_BINARY_DIR}/../../libraries/entities-renderer/") -include_directories("${PROJECT_BINARY_DIR}/../../libraries/graphics/") - -if (WIN32) - add_dependency_external_projects(wasapi) -endif () - -package_libraries_for_deployment() diff --git a/tests-manual/shaders/src/main.cpp b/tests-manual/shaders/src/main.cpp deleted file mode 100644 index 6e117b33cb..0000000000 --- a/tests-manual/shaders/src/main.cpp +++ /dev/null @@ -1,222 +0,0 @@ -// -// Copyright 2014 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include - -#include -#include -#include -#include - -#include -#include -#include - -#include -#include - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include - -#include -#include - -#include -#include - -// Create a simple OpenGL window that renders text in various ways -class QTestWindow : public QWindow { - Q_OBJECT - QOpenGLContextWrapper _context; - -protected: - void renderText(); - -public: - QTestWindow() { - setSurfaceType(QSurface::OpenGLSurface); - QSurfaceFormat format = getDefaultOpenGLSurfaceFormat(); - setFormat(format); - _context.setFormat(format); - _context.create(); - - show(); - makeCurrent(); - gl::initModuleGl(); - gpu::Context::init(); - makeCurrent(); - resize(QSize(800, 600)); - } - - virtual ~QTestWindow() { - } - - void draw(); - void makeCurrent() { - _context.makeCurrent(this); - } -}; - - - -const std::string VERTEX_SHADER_DEFINES{ R"GLSL( -#version 410 core -#define GPU_VERTEX_SHADER -#define GPU_TRANSFORM_IS_STEREO -#define GPU_TRANSFORM_STEREO_CAMERA -#define GPU_TRANSFORM_STEREO_CAMERA_INSTANCED -#define GPU_TRANSFORM_STEREO_SPLIT_SCREEN -)GLSL" }; - -const std::string PIXEL_SHADER_DEFINES{ R"GLSL( -#version 410 core -#define GPU_PIXEL_SHADER -#define GPU_TRANSFORM_IS_STEREO -#define GPU_TRANSFORM_STEREO_CAMERA -#define GPU_TRANSFORM_STEREO_CAMERA_INSTANCED -#define GPU_TRANSFORM_STEREO_SPLIT_SCREEN -)GLSL" }; - -void testShaderBuild(const std::string& vs_src, const std::string& fs_src) { - std::string error; - GLuint vs, fs; - if (!gl::compileShader(GL_VERTEX_SHADER, VERTEX_SHADER_DEFINES + vs_src, vs, error) || - !gl::compileShader(GL_FRAGMENT_SHADER, PIXEL_SHADER_DEFINES + fs_src, fs, error)) { - throw std::runtime_error("Failed to compile shader"); - } - gl::CachedShader binary; - auto pr = gl::compileProgram({ vs, fs }, error, binary); - if (!pr) { - throw std::runtime_error("Failed to link shader"); - } -} - -void QTestWindow::draw() { - if (!isVisible()) { - return; - } - - makeCurrent(); - glClearColor(0.2f, 0.2f, 0.2f, 1.0f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - static std::once_flag once; - std::call_once(once, [&]{ - testShaderBuild(sdf_text3D_vert::getSource(), sdf_text3D_frag::getSource()); - - testShaderBuild(DrawTransformUnitQuad_vert::getSource(), DrawTexture_frag::getSource()); - testShaderBuild(DrawTexcoordRectTransformUnitQuad_vert::getSource(), DrawTexture_frag::getSource()); - testShaderBuild(DrawViewportQuadTransformTexcoord_vert::getSource(), DrawTexture_frag::getSource()); - testShaderBuild(DrawTransformUnitQuad_vert::getSource(), DrawTextureOpaque_frag::getSource()); - testShaderBuild(DrawTransformUnitQuad_vert::getSource(), DrawColoredTexture_frag::getSource()); - - testShaderBuild(skybox_vert::getSource(), skybox_frag::getSource()); - testShaderBuild(simple_vert::getSource(), simple_frag::getSource()); - testShaderBuild(simple_vert::getSource(), simple_textured_frag::getSource()); - testShaderBuild(simple_vert::getSource(), simple_textured_unlit_frag::getSource()); - testShaderBuild(deferred_light_vert::getSource(), directional_ambient_light_frag::getSource()); - testShaderBuild(deferred_light_vert::getSource(), directional_skybox_light_frag::getSource()); - testShaderBuild(standardTransformPNTC_vert::getSource(), standardDrawTexture_frag::getSource()); - testShaderBuild(standardTransformPNTC_vert::getSource(), DrawTextureOpaque_frag::getSource()); - - testShaderBuild(model_vert::getSource(), model_frag::getSource()); - testShaderBuild(model_normal_map_vert::getSource(), model_normal_map_frag::getSource()); - testShaderBuild(model_vert::getSource(), model_translucent_frag::getSource()); - testShaderBuild(model_normal_map_vert::getSource(), model_translucent_frag::getSource()); - testShaderBuild(model_lightmap_vert::getSource(), model_lightmap_frag::getSource()); - testShaderBuild(model_lightmap_normal_map_vert::getSource(), model_lightmap_normal_map_frag::getSource()); - - testShaderBuild(skin_model_vert::getSource(), model_frag::getSource()); - testShaderBuild(skin_model_normal_map_vert::getSource(), model_normal_map_frag::getSource()); - testShaderBuild(skin_model_vert::getSource(), model_translucent_frag::getSource()); - testShaderBuild(skin_model_normal_map_vert::getSource(), model_translucent_frag::getSource()); - - testShaderBuild(model_shadow_vert::getSource(), model_shadow_frag::getSource()); - testShaderBuild(textured_particle_vert::getSource(), textured_particle_frag::getSource()); -/* FIXME: Bring back the ssao shader tests - testShaderBuild(gaussian_blur_vert::getSource()ical_vert::getSource(), gaussian_blur_frag::getSource()); - testShaderBuild(gaussian_blur_horizontal_vert::getSource(), gaussian_blur_frag::getSource()); - testShaderBuild(ambient_occlusion_vert::getSource(), ambient_occlusion_frag::getSource()); - testShaderBuild(ambient_occlusion_vert::getSource(), occlusion_blend_frag::getSource()); -*/ - - testShaderBuild(paintStroke_vert::getSource(),paintStroke_frag::getSource()); - testShaderBuild(polyvox_vert::getSource(), polyvox_frag::getSource()); - - }); - _context.swapBuffers(this); -} - -const char * LOG_FILTER_RULES = R"V0G0N( -hifi.gpu=true -)V0G0N"; - -int main(int argc, char** argv) { - setupHifiApplication("Shaders Test"); - - QGuiApplication app(argc, argv); - QLoggingCategory::setFilterRules(LOG_FILTER_RULES); - QTestWindow window; - QTimer timer; - timer.setInterval(1); - app.connect(&timer, &QTimer::timeout, &app, [&] { - window.draw(); - }); - timer.start(); - app.exec(); - return 0; -} - -#include "main.moc" diff --git a/tests/gpu/src/ShaderLoadTest.cpp b/tests/gpu/src/ShaderLoadTest.cpp index 09752dc385..ba738bbe9a 100644 --- a/tests/gpu/src/ShaderLoadTest.cpp +++ b/tests/gpu/src/ShaderLoadTest.cpp @@ -23,23 +23,14 @@ #include +#include + QTEST_MAIN(ShaderLoadTest) extern std::atomic gpuBinaryShadersLoaded; extern const QString& getShaderCacheFile(); - -QtMessageHandler originalHandler; - -void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message) { -#if defined(Q_OS_WIN) - OutputDebugStringA(message.toStdString().c_str()); - OutputDebugStringA("\n"); -#endif - originalHandler(type, context, message); -} - std::pair>> parseCachedShaderString(const QString& cachedShaderString) { std::pair>> result; @@ -194,7 +185,7 @@ bool ShaderLoadTest::buildProgram(const Program& programFiles) { } void ShaderLoadTest::initTestCase() { - originalHandler = qInstallMessageHandler(messageHandler); + installTestMessageHandler(); DependencyManager::set(); { const auto& shaderCacheFile = getShaderCacheFile(); @@ -237,9 +228,15 @@ void ShaderLoadTest::cleanupTestCase() { } void ShaderLoadTest::testShaderLoad() { - auto gpuContext = std::make_shared(); + _gpuContext = std::make_shared(); QVERIFY(gpuBinaryShadersLoaded == 0); + auto backend = std::static_pointer_cast(_gpuContext->getBackend()); + std::unordered_set shaderNames; + for (const auto& entry : _shaderSources) { + shaderNames.insert(entry.first); + } + QElapsedTimer timer; // Initial load of all the shaders @@ -252,7 +249,7 @@ void ShaderLoadTest::testShaderLoad() { qDebug() << "Uncached shader load took" << timer.elapsed() << "ms"; QVERIFY(gpuBinaryShadersLoaded == 0); } - gpuContext->recycle(); + _gpuContext->recycle(); glFinish(); // Reload the shaders within the same GPU context lifetime. @@ -270,10 +267,10 @@ void ShaderLoadTest::testShaderLoad() { // Shaders will use the cached binaries from disk { gpuBinaryShadersLoaded = 0; - gpuContext->recycle(); - gpuContext->shutdown(); - gpuContext.reset(); - gpuContext = std::make_shared(); + _gpuContext->recycle(); + _gpuContext->shutdown(); + _gpuContext.reset(); + _gpuContext = std::make_shared(); _canvas.makeCurrent(); timer.start(); for (const auto& program : _programs) { diff --git a/tests/gpu/src/ShaderLoadTest.h b/tests/gpu/src/ShaderLoadTest.h index cfb01501b2..8321d8e5e7 100644 --- a/tests/gpu/src/ShaderLoadTest.h +++ b/tests/gpu/src/ShaderLoadTest.h @@ -17,7 +17,7 @@ #include #include -#define USE_LOCAL_SHADERS 0 +#define USE_LOCAL_SHADERS 1 namespace std { template <> @@ -52,12 +52,11 @@ private slots: void cleanupTestCase(); void testShaderLoad(); - private: - ShadersByName _shaderSources; Programs _programs; QString _resourcesPath; OffscreenGLCanvas _canvas; + gpu::ContextPointer _gpuContext; const glm::uvec2 _size{ 640, 480 }; }; diff --git a/tests/gpu/src/TextureTest.cpp b/tests/gpu/src/TextureTest.cpp index 72fe1bfbfe..23e9c35dcc 100644 --- a/tests/gpu/src/TextureTest.cpp +++ b/tests/gpu/src/TextureTest.cpp @@ -16,12 +16,12 @@ #include #include #include -#include #include #include #include +#include QTEST_MAIN(TextureTest) @@ -86,7 +86,6 @@ void TextureTest::initTestCase() { gpu::Context::init(); _gpuContext = std::make_shared(); - if (QProcessEnvironment::systemEnvironment().contains(KTX_TEST_DIR_ENV)) { // For local testing with larger data sets _resourcesPath = QProcessEnvironment::systemEnvironment().value(KTX_TEST_DIR_ENV); @@ -94,16 +93,14 @@ void TextureTest::initTestCase() { _resourcesPath = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + "/" + TEST_DIR_NAME; if (!QFileInfo(_resourcesPath).exists()) { QDir(_resourcesPath).mkpath("."); - FileDownloader(TEST_DATA, - [&](const QByteArray& data) { - QTemporaryFile zipFile; - if (zipFile.open()) { - zipFile.write(data); - zipFile.close(); - } - JlCompress::extractDir(zipFile.fileName(), _resourcesPath); - }) - .waitForDownload(); + downloadFile(TEST_DATA, [&](const QByteArray& data) { + QTemporaryFile zipFile; + if (zipFile.open()) { + zipFile.write(data); + zipFile.close(); + } + JlCompress::extractDir(zipFile.fileName(), _resourcesPath); + }); } } @@ -114,8 +111,6 @@ void TextureTest::initTestCase() { auto VS = gpu::Shader::createVertex(vertexShaderSource); auto PS = gpu::Shader::createPixel(fragmentShaderSource); auto program = gpu::Shader::createProgram(VS, PS); - gpu::Shader::BindingSet slotBindings; - gpu::Shader::makeProgram(*program, slotBindings); // If the pipeline did not exist, make it auto state = std::make_shared(); state->setCullMode(gpu::State::CULL_NONE); @@ -180,7 +175,6 @@ void TextureTest::endFrame() { QThread::msleep(10); } - void TextureTest::renderFrame(const std::function& renderLambda) { beginFrame(); gpu::doInBatch("Test::body", _gpuContext, renderLambda); @@ -190,7 +184,7 @@ void TextureTest::renderFrame(const std::function& renderLamb extern QString getTextureMemoryPressureModeString(); void TextureTest::testTextureLoading() { - QBENCHMARK{ + QBENCHMARK { _frameCount = 0; auto textures = loadTestTextures(); QVERIFY(textures.size() > 0); diff --git a/tests/shaders/src/ShaderTests.cpp b/tests/shaders/src/ShaderTests.cpp index 3953c5042c..74ddc1f0eb 100644 --- a/tests/shaders/src/ShaderTests.cpp +++ b/tests/shaders/src/ShaderTests.cpp @@ -12,6 +12,10 @@ #include "ShaderTests.h" #include +#include +#include +#include + #include #include @@ -24,6 +28,7 @@ #include #include #include +#include QTEST_MAIN(ShaderTests) @@ -39,62 +44,162 @@ void ShaderTests::initTestCase() { } void ShaderTests::cleanupTestCase() { + qDebug() << "Done"; } - -QVariantList slotSetToVariantList(const gpu::Shader::SlotSet& slotSet) { - QVariantList result; - for (const auto slot : slotSet) { - QVariantMap inputMap; - inputMap["name"] = slot._name.c_str(); - inputMap["location"] = slot._location; - result.append(inputMap); +template +QStringList toStringList(const C& c, F f) { + QStringList result; + for (const auto& v : c) { + result << f(v); } return result; } -std::string reflect(const gpu::ShaderPointer& program) { - QVariantMap result; - if (!program->getInputs().empty()) { - result["inputs"] = slotSetToVariantList(program->getInputs()); +gpu::Shader::ReflectionMap mergeReflection(const std::initializer_list& list) { + gpu::Shader::ReflectionMap result; + std::unordered_map> usedLocationsByType; + for (const auto& source : list) { + const auto& reflection = source.getReflection(); + for (const auto& entry : reflection) { + const auto& type = entry.first; + if (entry.first == gpu::Shader::BindingType::INPUT || entry.first == gpu::Shader::BindingType::OUTPUT) { + continue; + } + auto& outLocationMap = result[type]; + auto& usedLocations = usedLocationsByType[type]; + const auto& locationMap = entry.second; + for (const auto& entry : locationMap) { + const auto& name = entry.first; + const auto& location = entry.second; + if (0 != usedLocations.count(location) && usedLocations[location] != name) { + qWarning() << QString("Location %1 used by both %2 and %3") + .arg(location) + .arg(name.c_str()) + .arg(usedLocations[location].c_str()); + throw std::runtime_error("Location collision"); + } + usedLocations[location] = name; + outLocationMap[name] = location; + } + } } - if (!program->getOutputs().empty()) { - result["outputs"] = slotSetToVariantList(program->getOutputs()); - } - if (!program->getResourceBuffers().empty()) { - result["storage_buffers"] = slotSetToVariantList(program->getResourceBuffers()); - } - if (!program->getSamplers().empty()) { - result["samplers"] = slotSetToVariantList(program->getSamplers()); - } - if (!program->getTextures().empty()) { - result["textures"] = slotSetToVariantList(program->getTextures()); - } - if (!program->getUniforms().empty()) { - result["uniforms"] = slotSetToVariantList(program->getUniforms()); - } - if (!program->getUniformBuffers().empty()) { - result["uniform_buffers"] = slotSetToVariantList(program->getUniformBuffers()); - } - - return QJsonDocument::fromVariant(result).toJson(QJsonDocument::Indented).toStdString(); + return result; } void ShaderTests::testShaderLoad() { - size_t index = 0; - uint32_t INVALID_SHADER_ID = (uint32_t)-1; - while (INVALID_SHADER_ID != shader::all_programs[index]) { - auto programId = shader::all_programs[index]; - uint32_t vertexId = programId >> 16; - uint32_t fragmentId = programId & 0xFF; - auto vertexSource = shader::loadShaderSource(vertexId); - QVERIFY(!vertexSource.empty()); - auto fragmentSource = shader::loadShaderSource(fragmentId); - QVERIFY(!fragmentSource.empty()); - auto program = gpu::Shader::createProgram(programId); - QVERIFY(gpu::Shader::makeProgram(*program, {})); - auto reflectionData = reflect(program); - std::ofstream(std::string("d:/reflection/") + std::to_string(index) + std::string(".json")) << reflectionData; - ++index; + std::set usedShaders; + uint32_t maxShader = 0; + try { + size_t index = 0; + while (shader::INVALID_PROGRAM != shader::all_programs[index]) { + auto programId = shader::all_programs[index]; + ++index; + + uint32_t vertexId = shader::getVertexId(programId); + //QVERIFY(0 != vertexId); + uint32_t fragmentId = shader::getFragmentId(programId); + QVERIFY(0 != fragmentId); + usedShaders.insert(vertexId); + usedShaders.insert(fragmentId); + maxShader = std::max(maxShader, std::max(fragmentId, vertexId)); + auto vertexSource = gpu::Shader::getShaderSource(vertexId); + QVERIFY(!vertexSource.getCode().empty()); + auto fragmentSource = gpu::Shader::getShaderSource(fragmentId); + QVERIFY(!fragmentSource.getCode().empty()); + + auto expectedBindings = mergeReflection({ vertexSource, fragmentSource }); + + auto program = gpu::Shader::createProgram(programId); + auto glBackend = std::static_pointer_cast(_gpuContext->getBackend()); + auto glshader = gpu::gl::GLShader::sync(*glBackend, *program); + if (!glshader) { + qDebug() << "Failed to compile or link vertex " << vertexId << " fragment " << fragmentId; + continue; + } + + QVERIFY(glshader != nullptr); + for (const auto& shaderObject : glshader->_shaderObjects) { + const auto& program = shaderObject.glprogram; + + // Uniforms + { + +#ifdef Q_OS_MAC + const auto& uniformRemap = shaderObject.uniformRemap; +#endif + auto uniforms = gl::Uniform::load(program); + auto expectedUniforms = expectedBindings[gpu::Shader::BindingType::PUSH_CONSTANT]; + if (uniforms.size() != expectedUniforms.size()) { + qDebug() << "Found" << toStringList(uniforms, [](const auto& v) { return v.name.c_str(); }); + qDebug() << "Expected" << toStringList(expectedUniforms, [](const auto& v) { return v.first.c_str(); }); + qDebug() << "Uniforms size mismatch"; + } + for (const auto& uniform : uniforms) { + if (0 != expectedUniforms.count(uniform.name)) { + auto expectedLocation = expectedUniforms[uniform.name]; +#ifdef Q_OS_MAC + if (0 != uniformRemap.count(expectedLocation)) { + expectedLocation = uniformRemap.at(expectedLocation); + } +#endif + QVERIFY(expectedLocation == uniform.binding); + } + } + } + + // Textures + { + const auto textures = gl::Uniform::loadTextures(program); + const auto expectedTextures = expectedBindings[gpu::Shader::BindingType::TEXTURE]; + if (textures.size() != expectedTextures.size()) { + qDebug() << "Found" << toStringList(textures, [](const auto& v) { return v.name.c_str(); }); + qDebug() << "Expected" << toStringList(expectedTextures, [](const auto& v) { return v.first.c_str(); }); + qDebug() << "Uniforms size mismatch"; + } + for (const auto& texture : textures) { + if (0 != expectedTextures.count(texture.name)) { + const auto& location = texture.binding; + const auto& expectedUnit = expectedTextures.at(texture.name); + GLint actualUnit = -1; + glGetUniformiv(program, location, &actualUnit); + QVERIFY(expectedUnit == actualUnit); + } + } + } + + // UBOs + { + auto ubos = gl::UniformBlock::load(program); + auto expectedUbos = expectedBindings[gpu::Shader::BindingType::UNIFORM_BUFFER]; + if (ubos.size() != expectedUbos.size()) { + qDebug() << "Found" << toStringList(ubos, [](const auto& v) { return v.name.c_str(); }); + qDebug() << "Expected" << toStringList(expectedUbos, [](const auto& v) { return v.first.c_str(); }); + qDebug() << "UBOs size mismatch"; + } + for (const auto& ubo : ubos) { + if (0 != expectedUbos.count(ubo.name)) { + QVERIFY(expectedUbos[ubo.name] == ubo.binding); + } + } + } + + // FIXME add storage buffer validation + } + } + } catch (const std::runtime_error& error) { + QFAIL(error.what()); } + + for (uint32_t i = 0; i <= maxShader; ++i) { + auto used = usedShaders.count(i); + if (0 != usedShaders.count(i)) { + continue; + } + auto reflectionJson = shader::loadShaderReflection(i); + auto name = QJsonDocument::fromJson(reflectionJson.c_str()).object()["name"].toString(); + qDebug() << "Unused shader" << name; + } + + qDebug() << "Completed all shaders"; } diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index 1c36306410..9b36180bc2 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -2,6 +2,9 @@ add_subdirectory(scribe) set_target_properties(scribe PROPERTIES FOLDER "Tools") +add_subdirectory(shreflect) +set_target_properties(shreflect PROPERTIES FOLDER "Tools") + find_npm() if (NPM_EXECUTABLE) add_subdirectory(jsdoc) diff --git a/tools/shreflect/CMakeLists.txt b/tools/shreflect/CMakeLists.txt new file mode 100644 index 0000000000..0748f59d31 --- /dev/null +++ b/tools/shreflect/CMakeLists.txt @@ -0,0 +1,10 @@ +set(TARGET_NAME shreflect) + +# don't use the setup_hifi_project macro as we don't want Qt or GLM dependencies +file(GLOB TARGET_SRCS src/*) +add_executable(${TARGET_NAME} ${TARGET_SRCS}) +target_json() + +if (WIN32) + set_property(TARGET ${TARGET_NAME} APPEND_STRING PROPERTY LINK_FLAGS_DEBUG "/OPT:NOREF /OPT:NOICF") +endif() diff --git a/tools/shreflect/src/main.cpp b/tools/shreflect/src/main.cpp new file mode 100644 index 0000000000..b95b36fd94 --- /dev/null +++ b/tools/shreflect/src/main.cpp @@ -0,0 +1,196 @@ +// +// Bradley Austin Davis on 2018/05/24 +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +std::vector splitStringIntoLines(const std::string& s) { + std::stringstream ss(s); + std::vector result; + std::string line; + while (std::getline(ss, line, '\n')) { + result.push_back(line); + } + return result; +} + +std::string readFile(const std::string& file) { + std::ifstream t(file); + std::string str((std::istreambuf_iterator(t)), + std::istreambuf_iterator()); + return str; +} + +void writeFile(const std::string& file, const std::string& out) { + std::ofstream t(file, std::ios::trunc); + t << out; + t.close(); +} + +// Convert a Perl style multi-line commented regex into a C++ style regex +// All whitespace will be removed and lines with '#' comments will have the comments removed +std::string getUnformattedRegex(const std::string& formatted) { + static const std::regex WHITESPACE = std::regex("\\s+"); + static const std::string EMPTY; + std::string result; + result.reserve(formatted.size()); + auto lines = splitStringIntoLines(formatted); + for (auto line : lines) { + auto commentStart = line.find('#'); + if (std::string::npos != commentStart) { + line = line.substr(0, commentStart); + } + line = std::regex_replace(line, WHITESPACE, EMPTY); + result += line; + } + + return result; +} + +static std::string LAYOUT_REGEX_STRING{ R"REGEX( +^layout\( # BEGIN layout declaration block + (\s*std140\s*,\s*)? # Optional std140 marker + (binding|location) # binding / location + \s*=\s* + (?: + (\b\d+\b) # literal numeric binding like binding=1 + | + (\b[A-Z_0-9]+\b) # Preprocessor macro binding like binding=GPU_TEXTURE_FOO + ) +\)\s* # END layout declaration block +(?: + ( # Texture or simple uniform like `layout(binding=0) uniform sampler2D originalTexture;` + uniform\s+ + (\b\w+\b)\s+ + (\b\w+\b)\s* + (?:\[\d*\])? + (?:\s*=.*)? + \s*;.*$ + ) + | + ( # UBO or SSBO like `layout(std140, binding=GPU_STORAGE_TRANSFORM_OBJECT) buffer transformObjectBuffer {` + \b(uniform|buffer)\b\s+ + \b(\w+\b) + \s*\{.*$ + ) + | + ( # Input or output attribute like `layout(location=GPU_ATTR_POSITION) in vec4 inPosition;` + \b(in|out)\b\s+ + \b(\w+)\b\s+ + \b(\w+)\b\s*;\s*$ + ) +) +)REGEX" }; + +enum Groups { + STD140 = 1, + LOCATION_TYPE = 2, + LOCATION_LITERAL = 3, + LOCATION_DEFINE = 4, + DECL_SIMPLE = 5, + SIMPLE_TYPE = 6, + SIMPLE_NAME = 7, + DECL_STRUCT = 8, + STRUCT_TYPE = 9, + STRUCT_NAME = 10, + DECL_INOUT = 11, + INOUT_DIRECTION = 12, + INOUT_TYPE = 13, + INOUT_NAME = 14, +}; + +json reflectShader(const std::string& shaderPath) { + static const std::regex DEFINE("^#define\\s+([_A-Z0-9]+)\\s+(\\d+)\\s*$"); + static const std::regex LAYOUT_QUALIFIER{ getUnformattedRegex(LAYOUT_REGEX_STRING) }; + + + auto shaderSource = readFile(shaderPath); + std::vector lines = splitStringIntoLines(shaderSource); + using Map = std::unordered_map; + + json inputs; + json outputs; + json textures; + json uniforms; + json storageBuffers; + json uniformBuffers; + Map locationDefines; + for (const auto& line : lines) { + std::cmatch m; + if (std::regex_match(line.c_str(), m, DEFINE)) { + locationDefines[m[1].str()] = std::stoi(m[2].first); + } else if (std::regex_match(line.c_str(), m, LAYOUT_QUALIFIER)) { + int binding = -1; + if (m[LOCATION_LITERAL].matched) { + binding = std::stoi(m[LOCATION_LITERAL].str()); + } else { + binding = locationDefines[m[LOCATION_DEFINE].str()]; + } + if (m[DECL_SIMPLE].matched) { + auto name = m[SIMPLE_NAME].str(); + auto type = m[SIMPLE_TYPE].str(); + auto& map = 0 == type.find("sampler") ? textures : uniforms; + map[name] = binding; + } else if (m[DECL_STRUCT].matched) { + auto name = m[STRUCT_NAME].str(); + auto type = m[STRUCT_TYPE].str(); + auto& map = (type == "buffer") ? storageBuffers : uniformBuffers; + map[name] = binding; + } else if (m[DECL_INOUT].matched) { + auto name = m[INOUT_NAME].str(); + auto& map = (m[INOUT_DIRECTION].str() == "in") ? inputs : outputs; + map[name] = binding; + } + } + } + + json result; + if (!inputs.empty()) { + result["inputs"] = inputs; + } + if (!outputs.empty()) { + result["outputs"] = outputs; + } + if (!textures.empty()) { + result["textures"] = textures; + } + if (!uniforms.empty()) { + result["uniforms"] = uniforms; + } + if (!storageBuffers.empty()) { + result["storageBuffers"] = storageBuffers; + } + if (!uniformBuffers.empty()) { + result["uniformBuffers"] = uniformBuffers; + } + + result["name"] = shaderPath; + + return result; +} + +int main (int argc, char** argv) { + auto path = std::string(argv[1]); + auto shaderReflection = reflectShader(path); + writeFile(path + ".json", shaderReflection.dump(4)); + return 0; +} From a1a1a03bbc40bc2f96d289193c052ff82d7f2eb3 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Wed, 18 Jul 2018 12:28:00 -0700 Subject: [PATCH 22/37] Fixing crash on exit, deferred debugging tool --- .../gpu-gl-common/src/gpu/gl/GLBackend.h | 7 ++- .../render-utils/src/DebugDeferredBuffer.cpp | 51 ++++++++++--------- 2 files changed, 31 insertions(+), 27 deletions(-) diff --git a/libraries/gpu-gl-common/src/gpu/gl/GLBackend.h b/libraries/gpu-gl-common/src/gpu/gl/GLBackend.h index ff3e94fd16..0d47d75ba4 100644 --- a/libraries/gpu-gl-common/src/gpu/gl/GLBackend.h +++ b/libraries/gpu-gl-common/src/gpu/gl/GLBackend.h @@ -425,8 +425,11 @@ protected: return offset == other.offset && size == other.size && buffer == other.buffer; } }; - std::array _buffers; - //Buffers _buffers { }; + + // MAX_NUM_UNIFORM_BUFFERS-1 is the max uniform index BATCHES are allowed to set, but + // MIN_REQUIRED_UNIFORM_BUFFER_BINDINGS is used here because the backend sets some + // internal UBOs for things like camera correction + std::array _buffers; } _uniform; // Helper function that provides common code diff --git a/libraries/render-utils/src/DebugDeferredBuffer.cpp b/libraries/render-utils/src/DebugDeferredBuffer.cpp index e7268f2799..cab95e50be 100644 --- a/libraries/render-utils/src/DebugDeferredBuffer.cpp +++ b/libraries/render-utils/src/DebugDeferredBuffer.cpp @@ -422,7 +422,6 @@ void DebugDeferredBuffer::run(const RenderContextPointer& renderContext, const I return; } -#if 0 assert(renderContext->args); assert(renderContext->args->hasViewFrustum()); RenderArgs* args = renderContext->args; @@ -465,10 +464,11 @@ void DebugDeferredBuffer::run(const RenderContextPointer& renderContext, const I batch.setResourceTexture(Textures::DeferredLighting, deferredFramebuffer->getLightingTexture()); } if (velocityFramebuffer) { - batch.setResourceTexture(Textures::TaaVelocity, velocityFramebuffer->getVelocityTexture()); + batch.setResourceTexture(Textures::DebugVelocity, velocityFramebuffer->getVelocityTexture()); } - batch.setUniformBuffer(UBOs:: DebugParametersBuffer, _parameters); + // FIXME can't find the corresponding buffer + // batch.setUniformBuffer(UBOs:: DebugParametersBuffer, _parameters); auto lightStage = renderContext->_scene->getStage(); assert(lightStage); @@ -482,41 +482,42 @@ void DebugDeferredBuffer::run(const RenderContextPointer& renderContext, const I } if (linearDepthTarget) { - batch.setResourceTexture(Textures::LLinearDepth, linearDepthTarget->getLinearDepthTexture()); - batch.setResourceTexture(HalfLinearDepth, linearDepthTarget->getHalfLinearDepthTexture()); - batch.setResourceTexture(HalfNormal, linearDepthTarget->getHalfNormalTexture()); + batch.setResourceTexture(Textures::DebugDepth, linearDepthTarget->getLinearDepthTexture()); + batch.setResourceTexture(Textures::DebugHalfDepth, linearDepthTarget->getHalfLinearDepthTexture()); + batch.setResourceTexture(Textures::DebugHalfNormal, linearDepthTarget->getHalfNormalTexture()); } if (surfaceGeometryFramebuffer) { - batch.setResourceTexture(Curvature, surfaceGeometryFramebuffer->getCurvatureTexture()); - batch.setResourceTexture(DiffusedCurvature, surfaceGeometryFramebuffer->getLowCurvatureTexture()); + batch.setResourceTexture(Textures::DeferredCurvature, surfaceGeometryFramebuffer->getCurvatureTexture()); + batch.setResourceTexture(Textures::DeferredDiffusedCurvature, + surfaceGeometryFramebuffer->getLowCurvatureTexture()); } if (ambientOcclusionFramebuffer) { - batch.setResourceTexture(Textures::SsaoOcclusion, ambientOcclusionFramebuffer->getOcclusionTexture()); - batch.setResourceTexture(AmbientOcclusionBlurred, ambientOcclusionFramebuffer->getOcclusionBlurredTexture()); + batch.setResourceTexture(Textures::DebugOcclusion, ambientOcclusionFramebuffer->getOcclusionTexture()); + batch.setResourceTexture(Textures::DebugOcclusionBlurred, + ambientOcclusionFramebuffer->getOcclusionBlurredTexture()); } const glm::vec4 color(1.0f, 1.0f, 1.0f, 1.0f); const glm::vec2 bottomLeft(_size.x, _size.y); const glm::vec2 topRight(_size.z, _size.w); geometryBuffer->renderQuad(batch, bottomLeft, topRight, color, _geometryId); - batch.setResourceTexture(Albedo, nullptr); - batch.setResourceTexture(Normal, nullptr); - batch.setResourceTexture(Specular, nullptr); - batch.setResourceTexture(Depth, nullptr); - batch.setResourceTexture(Lighting, nullptr); - batch.setResourceTexture(Shadow, nullptr); - batch.setResourceTexture(LinearDepth, nullptr); - batch.setResourceTexture(HalfLinearDepth, nullptr); - batch.setResourceTexture(HalfNormal, nullptr); + batch.setResourceTexture(Textures::DeferredColor, nullptr); + batch.setResourceTexture(Textures::DeferredNormal, nullptr); + batch.setResourceTexture(Textures::DeferredSpecular, nullptr); + batch.setResourceTexture(Textures::DeferredDepth, nullptr); + batch.setResourceTexture(Textures::DeferredLighting, nullptr); + batch.setResourceTexture(Textures::Shadow, nullptr); + batch.setResourceTexture(Textures::DebugDepth, nullptr); + batch.setResourceTexture(Textures::DebugHalfDepth, nullptr); + batch.setResourceTexture(Textures::DebugHalfNormal, nullptr); - batch.setResourceTexture(Curvature, nullptr); - batch.setResourceTexture(DiffusedCurvature, nullptr); + batch.setResourceTexture(Textures::DeferredCurvature, nullptr); + batch.setResourceTexture(Textures::DeferredDiffusedCurvature, nullptr); - batch.setResourceTexture(AmbientOcclusion, nullptr); - batch.setResourceTexture(AmbientOcclusionBlurred, nullptr); + batch.setResourceTexture(Textures::DebugOcclusion, nullptr); + batch.setResourceTexture(Textures::DebugOcclusionBlurred, nullptr); - batch.setResourceTexture(Velocity, nullptr); + batch.setResourceTexture(Textures::DebugVelocity, nullptr); }); -#endif } From 8eb97dc79c809e9978948a4f2729f0705ca03b1e Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Wed, 18 Jul 2018 19:35:28 -0700 Subject: [PATCH 23/37] PR feedback --- libraries/gpu/src/gpu/Shader.cpp | 48 ++++++++++++------- libraries/gpu/src/gpu/Shader.h | 5 +- .../procedural/src/procedural/Procedural.cpp | 4 +- tests/shaders/src/ShaderTests.cpp | 2 +- 4 files changed, 35 insertions(+), 24 deletions(-) diff --git a/libraries/gpu/src/gpu/Shader.cpp b/libraries/gpu/src/gpu/Shader.cpp index 1166e86cd1..cea7ec6e14 100755 --- a/libraries/gpu/src/gpu/Shader.cpp +++ b/libraries/gpu/src/gpu/Shader.cpp @@ -82,8 +82,8 @@ Shader::Pointer Shader::createOrReuseDomainShader(Type type, const Source& sourc if (0 != reflection.count(BindingType::UNIFORM_BUFFER)) { populateSlotSet(shader->_uniformBuffers, reflection.find(BindingType::UNIFORM_BUFFER)->second); } - if (0 != reflection.count(BindingType::STORAGE_BUFFER)) { - populateSlotSet(shader->_resourceBuffers, reflection.find(BindingType::STORAGE_BUFFER)->second); + if (0 != reflection.count(BindingType::RESOURCE_BUFFER)) { + populateSlotSet(shader->_resourceBuffers, reflection.find(BindingType::RESOURCE_BUFFER)->second); } if (0 != reflection.count(BindingType::TEXTURE)) { populateSlotSet(shader->_textures, reflection.find(BindingType::TEXTURE)->second); @@ -91,8 +91,8 @@ Shader::Pointer Shader::createOrReuseDomainShader(Type type, const Source& sourc if (0 != reflection.count(BindingType::SAMPLER)) { populateSlotSet(shader->_samplers, reflection.find(BindingType::SAMPLER)->second); } - if (0 != reflection.count(BindingType::PUSH_CONSTANT)) { - populateSlotSet(shader->_uniforms, reflection.find(BindingType::PUSH_CONSTANT)->second); + if (0 != reflection.count(BindingType::UNIFORM)) { + populateSlotSet(shader->_uniforms, reflection.find(BindingType::UNIFORM)->second); } _domainShaderMaps[type].emplace(source, std::weak_ptr(shader)); return shader; @@ -144,8 +144,8 @@ ShaderPointer Shader::createOrReuseProgramShader(Type type, const Pointer& verte if (0 != reflection.count(BindingType::UNIFORM_BUFFER)) { populateSlotSet(program->_uniformBuffers, reflection.find(BindingType::UNIFORM_BUFFER)->second); } - if (0 != reflection.count(BindingType::STORAGE_BUFFER)) { - populateSlotSet(program->_resourceBuffers, reflection.find(BindingType::STORAGE_BUFFER)->second); + if (0 != reflection.count(BindingType::RESOURCE_BUFFER)) { + populateSlotSet(program->_resourceBuffers, reflection.find(BindingType::RESOURCE_BUFFER)->second); } if (0 != reflection.count(BindingType::TEXTURE)) { populateSlotSet(program->_textures, reflection.find(BindingType::TEXTURE)->second); @@ -153,8 +153,8 @@ ShaderPointer Shader::createOrReuseProgramShader(Type type, const Pointer& verte if (0 != reflection.count(BindingType::SAMPLER)) { populateSlotSet(program->_samplers, reflection.find(BindingType::SAMPLER)->second); } - if (0 != reflection.count(BindingType::PUSH_CONSTANT)) { - populateSlotSet(program->_uniforms, reflection.find(BindingType::PUSH_CONSTANT)->second); + if (0 != reflection.count(BindingType::UNIFORM)) { + populateSlotSet(program->_uniforms, reflection.find(BindingType::UNIFORM)->second); } } @@ -215,6 +215,13 @@ Shader::ReflectionMap getShaderReflection(const std::string& reflectionJson) { return {}; } +#define REFLECT_KEY_INPUTS "inputs" +#define REFLECT_KEY_OUTPUTS "outputs" +#define REFLECT_KEY_UBOS "uniformBuffers" +#define REFLECT_KEY_SSBOS "storageBuffers" +#define REFLECT_KEY_UNIFORMS "uniforms" +#define REFLECT_KEY_TEXTURES "textures" + auto doc = QJsonDocument::fromJson(reflectionJson.c_str()); if (doc.isNull()) { qWarning() << "Invalid shader reflection JSON" << reflectionJson.c_str(); @@ -223,21 +230,26 @@ Shader::ReflectionMap getShaderReflection(const std::string& reflectionJson) { Shader::ReflectionMap result; auto json = doc.object(); - if (json.contains("inputs")) { - updateBindingsFromJsonObject(result[Shader::BindingType::INPUT], json["inputs"].toObject()); + if (json.contains(REFLECT_KEY_INPUTS)) { + updateBindingsFromJsonObject(result[Shader::BindingType::INPUT], json[REFLECT_KEY_INPUTS].toObject()); } - if (json.contains("outputs")) { - updateBindingsFromJsonObject(result[Shader::BindingType::OUTPUT], json["outputs"].toObject()); + if (json.contains(REFLECT_KEY_OUTPUTS)) { + updateBindingsFromJsonObject(result[Shader::BindingType::OUTPUT], json[REFLECT_KEY_OUTPUTS].toObject()); } - if (json.contains("uniformBuffers")) { - updateBindingsFromJsonObject(result[Shader::BindingType::UNIFORM_BUFFER], json["uniformBuffers"].toObject()); + if (json.contains(REFLECT_KEY_UBOS)) { + updateBindingsFromJsonObject(result[Shader::BindingType::UNIFORM_BUFFER], json[REFLECT_KEY_UBOS].toObject()); } - if (json.contains("textures")) { - updateBindingsFromJsonObject(result[Shader::BindingType::TEXTURE], json["textures"].toObject()); + if (json.contains(REFLECT_KEY_TEXTURES)) { + updateBindingsFromJsonObject(result[Shader::BindingType::TEXTURE], json[REFLECT_KEY_TEXTURES].toObject()); } - if (json.contains("uniforms")) { - updateBindingsFromJsonObject(result[Shader::BindingType::PUSH_CONSTANT], json["uniforms"].toObject()); + if (json.contains(REFLECT_KEY_UNIFORMS)) { + updateBindingsFromJsonObject(result[Shader::BindingType::UNIFORM], json[REFLECT_KEY_UNIFORMS].toObject()); } + if (json.contains(REFLECT_KEY_SSBOS)) { + updateBindingsFromJsonObject(result[Shader::BindingType::UNIFORM], json[REFLECT_KEY_SSBOS].toObject()); + } + + return result; } diff --git a/libraries/gpu/src/gpu/Shader.h b/libraries/gpu/src/gpu/Shader.h index d713433bd6..ad828a0cff 100755 --- a/libraries/gpu/src/gpu/Shader.h +++ b/libraries/gpu/src/gpu/Shader.h @@ -51,9 +51,8 @@ public: TEXTURE, SAMPLER, UNIFORM_BUFFER, - STORAGE_BUFFER, - PUSH_CONSTANT, // Equivalent to uniforms in GL - SPECIALIZATION_CONSTANT, + RESOURCE_BUFFER, + UNIFORM, }; using LocationMap = std::unordered_map; diff --git a/libraries/procedural/src/procedural/Procedural.cpp b/libraries/procedural/src/procedural/Procedural.cpp index 644212864e..09e30eab2e 100644 --- a/libraries/procedural/src/procedural/Procedural.cpp +++ b/libraries/procedural/src/procedural/Procedural.cpp @@ -253,10 +253,10 @@ void Procedural::prepare(gpu::Batch& batch, // Build the fragment shader std::string opaqueShaderSource = replaceProceduralBlock(_opaquefragmentSource.getCode()); auto opaqueReflection = _opaquefragmentSource.getReflection(); - auto& opaqueUniforms = opaqueReflection[gpu::Shader::BindingType::PUSH_CONSTANT]; + auto& opaqueUniforms = opaqueReflection[gpu::Shader::BindingType::UNIFORM]; std::string transparentShaderSource = replaceProceduralBlock(_transparentfragmentSource.getCode()); auto transparentReflection = _transparentfragmentSource.getReflection(); - auto& transparentUniforms = transparentReflection[gpu::Shader::BindingType::PUSH_CONSTANT]; + auto& transparentUniforms = transparentReflection[gpu::Shader::BindingType::UNIFORM]; // Set any userdata specified uniforms int customSlot = procedural::slot::uniform::Custom; diff --git a/tests/shaders/src/ShaderTests.cpp b/tests/shaders/src/ShaderTests.cpp index 74ddc1f0eb..dffd69054d 100644 --- a/tests/shaders/src/ShaderTests.cpp +++ b/tests/shaders/src/ShaderTests.cpp @@ -129,7 +129,7 @@ void ShaderTests::testShaderLoad() { const auto& uniformRemap = shaderObject.uniformRemap; #endif auto uniforms = gl::Uniform::load(program); - auto expectedUniforms = expectedBindings[gpu::Shader::BindingType::PUSH_CONSTANT]; + auto expectedUniforms = expectedBindings[gpu::Shader::BindingType::UNIFORM]; if (uniforms.size() != expectedUniforms.size()) { qDebug() << "Found" << toStringList(uniforms, [](const auto& v) { return v.name.c_str(); }); qDebug() << "Expected" << toStringList(expectedUniforms, [](const auto& v) { return v.first.c_str(); }); From eca803503c6024dbec447cf0ea164cce589c5c1b Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Mon, 30 Jul 2018 10:57:23 -0700 Subject: [PATCH 24/37] Fix resolution scaling --- libraries/gpu/src/gpu/DrawTextureOpaque.slf | 2 +- .../src/standardDrawTextureNoBlend.slf | 30 +++++++++++++++++++ libraries/shaders/CMakeLists.txt | 2 +- 3 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 libraries/render-utils/src/standardDrawTextureNoBlend.slf diff --git a/libraries/gpu/src/gpu/DrawTextureOpaque.slf b/libraries/gpu/src/gpu/DrawTextureOpaque.slf index d98daa1c9a..b3227325bf 100755 --- a/libraries/gpu/src/gpu/DrawTextureOpaque.slf +++ b/libraries/gpu/src/gpu/DrawTextureOpaque.slf @@ -18,7 +18,7 @@ layout(binding=0) uniform sampler2D colorMap; -layout(location=GPU_ATTR_TEXCOORD0) in vec2 varTexCoord0; +layout(location=0) in vec2 varTexCoord0; layout(location=0) out vec4 outFragColor; diff --git a/libraries/render-utils/src/standardDrawTextureNoBlend.slf b/libraries/render-utils/src/standardDrawTextureNoBlend.slf new file mode 100644 index 0000000000..95138d123f --- /dev/null +++ b/libraries/render-utils/src/standardDrawTextureNoBlend.slf @@ -0,0 +1,30 @@ +<@include gpu/Config.slh@> +<$VERSION_HEADER$> +// Generated on <$_SCRIBE_DATE$> +// standardDrawTexture.frag +// fragment shader +// +// Created by Sam Gateau on 6/10/15. +// Copyright 2015 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +<@include gpu/ShaderConstants.h@> + +// the texture +layout(binding=0) uniform sampler2D colorMap; + +layout(location=GPU_ATTR_POSITION) in vec3 varPosition; +layout(location=GPU_ATTR_NORMAL) in vec3 varNormal; +layout(location=GPU_ATTR_TEXCOORD0) in vec2 varTexCoord0; +layout(location=GPU_ATTR_COLOR) in vec4 varColor; + +layout(location=0) out vec4 outFragColor; + +void main(void) { + vec4 color = texture(colorMap, varTexCoord0); + outFragColor = color * varColor; + outFragColor.a = 1.0; +} diff --git a/libraries/shaders/CMakeLists.txt b/libraries/shaders/CMakeLists.txt index 1c4824ac02..06998e3ef5 100644 --- a/libraries/shaders/CMakeLists.txt +++ b/libraries/shaders/CMakeLists.txt @@ -80,7 +80,7 @@ AUTOSCRIBE_PROGRAM(NAME ssao_debugOcclusion VERTEX gpu::vertex::DrawViewportQuad AUTOSCRIBE_PROGRAM(NAME stencil_drawMask VERTEX gpu::vertex::DrawUnitQuadTexcoord) AUTOSCRIBE_PROGRAM(NAME standardDrawTexture VERTEX standardTransformPNTC) -AUTOSCRIBE_PROGRAM(NAME standardDrawTextureNoBlend VERTEX standardTransformPNTC FRAGMENT gpu::fragment::DrawTextureOpaque) +AUTOSCRIBE_PROGRAM(NAME standardDrawTextureNoBlend VERTEX standardTransformPNTC) AUTOSCRIBE_PROGRAM(NAME subsurfaceScattering_makeProfile VERTEX gpu::vertex::DrawUnitQuadTexcoord) AUTOSCRIBE_PROGRAM(NAME subsurfaceScattering_makeLUT VERTEX gpu::vertex::DrawUnitQuadTexcoord) From df031b5d9321eb7d0235ba38ce7b48af2d9e7e36 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Mon, 30 Jul 2018 14:46:16 -0700 Subject: [PATCH 25/37] Fix procedural rendering with custom uniforms --- libraries/gl/src/gl/GLShaders.cpp | 14 +++++ libraries/gl/src/gl/GLShaders.h | 1 + .../gpu-gl-common/src/gpu/gl/GLBackend.h | 4 +- .../src/gpu/gl/GLBackendShader.cpp | 36 +++++++++++++ libraries/gpu-gl-common/src/gpu/gl/GLShader.h | 2 - libraries/gpu-gl/src/gpu/gl41/GL41Backend.h | 1 - .../gpu-gl/src/gpu/gl41/GL41BackendShader.cpp | 51 +------------------ 7 files changed, 54 insertions(+), 55 deletions(-) diff --git a/libraries/gl/src/gl/GLShaders.cpp b/libraries/gl/src/gl/GLShaders.cpp index f4a7dc1fa2..03b807fbbf 100644 --- a/libraries/gl/src/gl/GLShaders.cpp +++ b/libraries/gl/src/gl/GLShaders.cpp @@ -110,6 +110,20 @@ Uniforms Uniform::load(GLuint glprogram, const std::vector& cnames) return load(glprogram, indices); } + +template +std::vector toCNames(const C& container, F lambda) { + std::vector result; + result.reserve(container.size()); + std::transform(container.begin(), container.end(), std::back_inserter(result), lambda); + return result; +} + +Uniforms Uniform::load(GLuint glprogram, const std::vector& names) { + auto cnames = toCNames(names, [](const std::string& name) { return name.c_str(); }); + return load(glprogram, cnames); +} + void UniformBlock::load(GLuint glprogram, int index) { this->index = index; GLint length = 0; diff --git a/libraries/gl/src/gl/GLShaders.h b/libraries/gl/src/gl/GLShaders.h index 7666bba823..5d16bd443e 100644 --- a/libraries/gl/src/gl/GLShaders.h +++ b/libraries/gl/src/gl/GLShaders.h @@ -40,6 +40,7 @@ struct Uniform : public ShaderBinding { static Vector load(GLuint glprogram); static Vector load(GLuint glprogram, const std::vector& indices); static Vector load(GLuint glprogram, const std::vector& names); + static Vector load(GLuint glprogram, const std::vector& names); template static Vector loadByName(GLuint glprogram, const C& names) { diff --git a/libraries/gpu-gl-common/src/gpu/gl/GLBackend.h b/libraries/gpu-gl-common/src/gpu/gl/GLBackend.h index 0d47d75ba4..2be13bbae4 100644 --- a/libraries/gpu-gl-common/src/gpu/gl/GLBackend.h +++ b/libraries/gpu-gl-common/src/gpu/gl/GLBackend.h @@ -260,7 +260,7 @@ public: bool isTextureManagementSparseEnabled() const override { return (_textureManagement._sparseCapable && Texture::getEnableSparseTextures()); } protected: - virtual GLint getRealUniformLocation(GLint location) const { return location; } + virtual GLint getRealUniformLocation(GLint location) const; void recycle() const override; @@ -494,7 +494,7 @@ protected: } _pipeline; // Backend dependant compilation of the shader - virtual void postLinkProgram(ShaderObject& programObject, const Shader& program) const {} + virtual void postLinkProgram(ShaderObject& programObject, const Shader& program) const; virtual GLShader* compileBackendProgram(const Shader& program, const Shader::CompilationHandler& handler); virtual GLShader* compileBackendShader(const Shader& shader, const Shader::CompilationHandler& handler); virtual std::string getBackendShaderHeader() const = 0; diff --git a/libraries/gpu-gl-common/src/gpu/gl/GLBackendShader.cpp b/libraries/gpu-gl-common/src/gpu/gl/GLBackendShader.cpp index 7379417574..88d2e8609f 100644 --- a/libraries/gpu-gl-common/src/gpu/gl/GLBackendShader.cpp +++ b/libraries/gpu-gl-common/src/gpu/gl/GLBackendShader.cpp @@ -244,6 +244,42 @@ GLShader* GLBackend::compileBackendProgram(const Shader& program, const Shader:: return object; } +static const GLint INVALID_UNIFORM_INDEX = -1; + +GLint GLBackend::getRealUniformLocation(GLint location) const { + auto& shader = _pipeline._programShader->_shaderObjects[(GLShader::Version)isStereo()]; + auto itr = shader.uniformRemap.find(location); + if (itr == shader.uniformRemap.end()) { + // This shouldn't happen, because we use reflection to determine all the possible + // uniforms. If someone is requesting a uniform that isn't in the remapping structure + // that's a bug from the calling code, because it means that location wasn't in the + // reflection + qWarning() << "Unexpected location requested for shader"; + return INVALID_UNIFORM_INDEX; + } + return itr->second; +} + +void GLBackend::postLinkProgram(ShaderObject& shaderObject, const Shader& program) const { + const auto& glprogram = shaderObject.glprogram; + const auto& expectedUniforms = program.getUniforms(); + const auto expectedLocationsByName = expectedUniforms.getLocationsByName(); + const auto uniforms = ::gl::Uniform::load(glprogram, expectedUniforms.getNames()); + auto& uniformRemap = shaderObject.uniformRemap; + + // Pre-initialize all the uniforms with an invalid location + for (const auto& entry : expectedLocationsByName) { + uniformRemap[entry.second] = INVALID_UNIFORM_INDEX; + } + + // Now load up all the actual found uniform location + for (const auto& uniform : uniforms) { + const auto& name = uniform.name; + const auto& expectedLocation = expectedLocationsByName.at(name); + const auto& location = uniform.binding; + uniformRemap[expectedLocation] = location; + } +} GLBackend::ElementResource GLBackend::getFormatFromGLUniform(GLenum gltype) { switch (gltype) { diff --git a/libraries/gpu-gl-common/src/gpu/gl/GLShader.h b/libraries/gpu-gl-common/src/gpu/gl/GLShader.h index 8e3eafcb0f..5d5d8a4a3c 100644 --- a/libraries/gpu-gl-common/src/gpu/gl/GLShader.h +++ b/libraries/gpu-gl-common/src/gpu/gl/GLShader.h @@ -17,10 +17,8 @@ struct ShaderObject { GLuint glshader { 0 }; GLuint glprogram { 0 }; -#if defined(Q_OS_MAC) using LocationMap = std::unordered_map ; LocationMap uniformRemap; -#endif }; class GLShader : public GPUObject { diff --git a/libraries/gpu-gl/src/gpu/gl41/GL41Backend.h b/libraries/gpu-gl/src/gpu/gl41/GL41Backend.h index 1adb62c2d0..8cf44a33d8 100644 --- a/libraries/gpu-gl/src/gpu/gl41/GL41Backend.h +++ b/libraries/gpu-gl/src/gpu/gl41/GL41Backend.h @@ -173,7 +173,6 @@ protected: std::string getBackendShaderHeader() const override; void postLinkProgram(ShaderObject& programObject, const Shader& program) const override; - GLint getRealUniformLocation(GLint location) const override; }; } } diff --git a/libraries/gpu-gl/src/gpu/gl41/GL41BackendShader.cpp b/libraries/gpu-gl/src/gpu/gl41/GL41BackendShader.cpp index 798da06b01..2c3010e0f5 100644 --- a/libraries/gpu-gl/src/gpu/gl41/GL41BackendShader.cpp +++ b/libraries/gpu-gl/src/gpu/gl41/GL41BackendShader.cpp @@ -22,46 +22,8 @@ std::string GL41Backend::getBackendShaderHeader() const { return header; } -template -std::vector toCNames(const C& container, F lambda) { - std::vector result; - result.reserve(container.size()); - std::transform(container.begin(), container.end(), std::back_inserter(result), lambda); - return result; -} - -#if defined(Q_OS_MAC) -ShaderObject::LocationMap buildRemap(GLuint glprogram, const gpu::Shader::SlotSet& slotSet) { - static const GLint INVALID_INDEX = -1; - ShaderObject::LocationMap result; - const auto expectedNames = slotSet.getNames(); - const auto count = expectedNames.size(); - std::vector indices; - indices.resize(count); - glGetUniformIndices(glprogram, (GLsizei)count, - toCNames(expectedNames, [](const std::string& name) { return name.c_str(); }).data(), - (GLuint*)indices.data()); - - const auto expectedLocationsByName = slotSet.getLocationsByName(); - for (size_t i = 0; i < count; ++i) { - const auto& index = indices[i]; - const auto& name = expectedNames[i]; - const auto& expectedLocation = expectedLocationsByName.at(name); - if (INVALID_INDEX == index) { - result[expectedLocation] = gpu::Shader::INVALID_LOCATION; - continue; - } - - ::gl::Uniform uniformInfo(glprogram, index); - if (expectedLocation != uniformInfo.binding) { - result[expectedLocation] = uniformInfo.binding; - } - } - return result; -} -#endif - void GL41Backend::postLinkProgram(ShaderObject& programObject, const Shader& program) const { + Parent::postLinkProgram(programObject, program); const auto& glprogram = programObject.glprogram; // For the UBOs, use glUniformBlockBinding to fixup the locations based on the reflection { @@ -106,14 +68,3 @@ void GL41Backend::postLinkProgram(ShaderObject& programObject, const Shader& pro } -GLint GL41Backend::getRealUniformLocation(GLint location) const { - GLint result = location; -#if defined(Q_OS_MAC) - auto& shader = _pipeline._programShader->_shaderObjects[(GLShader::Version)isStereo()]; - auto itr = shader.uniformRemap.find(location); - if (itr != shader.uniformRemap.end()) { - result = itr->second; - } -#endif - return result; -} From 6ed751211278d9512e8a7c38483c9102b0807434 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Mon, 30 Jul 2018 16:06:39 -0700 Subject: [PATCH 26/37] Fix build failures after parabola merge --- interface/src/raypick/ParabolaPointer.cpp | 14 +++----------- libraries/render-utils/src/parabola.slf | 4 ++-- libraries/render-utils/src/parabola.slv | 4 ++-- libraries/shaders/CMakeLists.txt | 2 ++ 4 files changed, 9 insertions(+), 15 deletions(-) diff --git a/interface/src/raypick/ParabolaPointer.cpp b/interface/src/raypick/ParabolaPointer.cpp index 9371995a2a..c7ef6582d1 100644 --- a/interface/src/raypick/ParabolaPointer.cpp +++ b/interface/src/raypick/ParabolaPointer.cpp @@ -12,11 +12,9 @@ #include #include +#include + #include "ParabolaPick.h" - -#include "render-utils/parabola_vert.h" -#include "render-utils/parabola_frag.h" - const glm::vec4 ParabolaPointer::RenderState::ParabolaRenderItem::DEFAULT_PARABOLA_COLOR { 1.0f }; const float ParabolaPointer::RenderState::ParabolaRenderItem::DEFAULT_PARABOLA_WIDTH { 0.01f }; const bool ParabolaPointer::RenderState::ParabolaRenderItem::DEFAULT_PARABOLA_ISVISIBLEINSECONDARYCAMERA { false }; @@ -326,13 +324,7 @@ void ParabolaPointer::RenderState::ParabolaRenderItem::updateKey() { const gpu::PipelinePointer ParabolaPointer::RenderState::ParabolaRenderItem::getParabolaPipeline() { if (!_parabolaPipeline || !_transparentParabolaPipeline) { - auto vs = parabola_vert::getShader(); - auto ps = parabola_frag::getShader(); - gpu::ShaderPointer program = gpu::Shader::createProgram(vs, ps); - - gpu::Shader::BindingSet slotBindings; - slotBindings.insert(gpu::Shader::Binding(std::string("parabolaData"), 0)); - gpu::Shader::makeProgram(*program, slotBindings); + gpu::ShaderPointer program = gpu::Shader::createProgram(shader::render_utils::program::parabola); { auto state = std::make_shared(); diff --git a/libraries/render-utils/src/parabola.slf b/libraries/render-utils/src/parabola.slf index ae7a44ddd1..8863f37083 100644 --- a/libraries/render-utils/src/parabola.slf +++ b/libraries/render-utils/src/parabola.slf @@ -9,9 +9,9 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -in vec4 _color; +layout(location=0) in vec4 _color; -out vec4 _fragColor; +layout(location=0) out vec4 _fragColor; void main(void) { _fragColor = _color; diff --git a/libraries/render-utils/src/parabola.slv b/libraries/render-utils/src/parabola.slv index c40fc89302..46d6924191 100644 --- a/libraries/render-utils/src/parabola.slv +++ b/libraries/render-utils/src/parabola.slv @@ -12,7 +12,7 @@ <@include gpu/Transform.slh@> <$declareStandardTransform()$> -layout(std140) uniform parabolaData { +layout(std140, binding=0) uniform parabolaData { vec3 velocity; float parabolicDistance; vec3 acceleration; @@ -22,7 +22,7 @@ layout(std140) uniform parabolaData { ivec3 spare; }; -out vec4 _color; +layout(location=0) out vec4 _color; void main(void) { _color = color; diff --git a/libraries/shaders/CMakeLists.txt b/libraries/shaders/CMakeLists.txt index 06998e3ef5..d27dacc769 100644 --- a/libraries/shaders/CMakeLists.txt +++ b/libraries/shaders/CMakeLists.txt @@ -69,6 +69,8 @@ AUTOSCRIBE_PROGRAM(NAME simple_textured_unlit_fade VERTEX simple_fade) AUTOSCRIBE_PROGRAM(NAME simple_transparent_textured_fade VERTEX simple_fade) AUTOSCRIBE_PROGRAM(NAME simple_transparent_textured_unlit_fade VERTEX simple_fade) +AUTOSCRIBE_PROGRAM(NAME parabola) + AUTOSCRIBE_PROGRAM(NAME sdf_text3D) AUTOSCRIBE_PROGRAM(NAME sdf_text3D_transparent VERTEX sdf_text3D) From a1cd39f4c2d89a8b081ca6c447d5edcdaedbc3c9 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Mon, 30 Jul 2018 16:07:00 -0700 Subject: [PATCH 27/37] Fix some explicit bindings that should be binding, not location --- .../src/display-plugins/InterleavedSrgbToLinear.slf | 2 +- libraries/render-utils/src/BloomApply.slf | 2 +- libraries/render-utils/src/BloomThreshold.slf | 2 +- libraries/render-utils/src/drawWorkloadView.slv | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/libraries/display-plugins/src/display-plugins/InterleavedSrgbToLinear.slf b/libraries/display-plugins/src/display-plugins/InterleavedSrgbToLinear.slf index db94594fe9..5f7b3f3411 100644 --- a/libraries/display-plugins/src/display-plugins/InterleavedSrgbToLinear.slf +++ b/libraries/display-plugins/src/display-plugins/InterleavedSrgbToLinear.slf @@ -2,7 +2,7 @@ struct TextureData { ivec2 textureSize; }; -layout(std140, location=0) uniform textureDataBuffer { +layout(std140, binding=0) uniform textureDataBuffer { TextureData textureData; }; diff --git a/libraries/render-utils/src/BloomApply.slf b/libraries/render-utils/src/BloomApply.slf index 576a71c7c4..caee76b651 100644 --- a/libraries/render-utils/src/BloomApply.slf +++ b/libraries/render-utils/src/BloomApply.slf @@ -15,7 +15,7 @@ layout(binding=0) uniform sampler2D blurMap0; layout(binding=1) uniform sampler2D blurMap1; layout(binding=2) uniform sampler2D blurMap2; -layout(std140, location=0) uniform parametersBuffer { +layout(std140, binding=RENDER_UTILS_BUFFER_BLOOM_PARAMS) uniform parametersBuffer { Parameters parameters; }; diff --git a/libraries/render-utils/src/BloomThreshold.slf b/libraries/render-utils/src/BloomThreshold.slf index 2756e7aa01..621aa31622 100644 --- a/libraries/render-utils/src/BloomThreshold.slf +++ b/libraries/render-utils/src/BloomThreshold.slf @@ -13,7 +13,7 @@ <@include render-utils/ShaderConstants.h@> layout(binding=RENDER_UTILS_TEXTURE_BLOOM_COLOR) uniform sampler2D colorMap; -layout(std140, location=RENDER_UTILS_BUFFER_BLOOM_PARAMS) uniform parametersBuffer { +layout(std140, binding=RENDER_UTILS_BUFFER_BLOOM_PARAMS) uniform parametersBuffer { Parameters parameters; }; diff --git a/libraries/render-utils/src/drawWorkloadView.slv b/libraries/render-utils/src/drawWorkloadView.slv index 2211bfb1ac..294c3bfa99 100644 --- a/libraries/render-utils/src/drawWorkloadView.slv +++ b/libraries/render-utils/src/drawWorkloadView.slv @@ -65,7 +65,7 @@ struct DrawMesh { vec4 verts[NUM_SEGMENT_PER_VIEW_REGION]; }; -layout(std140, location=0) uniform DrawMeshBuffer { +layout(std140, binding=0) uniform DrawMeshBuffer { DrawMesh _drawMeshBuffer; }; From f30b552e1953ec77efcd0544bb2dc54a2c16aba4 Mon Sep 17 00:00:00 2001 From: Dante Ruiz Date: Fri, 3 Aug 2018 15:50:11 -0700 Subject: [PATCH 28/37] fix-flying --- interface/src/avatar/MyAvatar.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 98fbd8fea2..3f738ea4cb 100755 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -1135,7 +1135,6 @@ void MyAvatar::saveData() { settings.setValue("collisionSoundURL", _collisionSoundURL); settings.setValue("useSnapTurn", _useSnapTurn); settings.setValue("userHeight", getUserHeight()); - settings.setValue("flyingDesktop", getFlyingDesktopPref()); settings.setValue("flyingHMD", getFlyingHMDPref()); settings.endGroup(); @@ -1289,7 +1288,6 @@ void MyAvatar::loadData() { // Flying preferences must be loaded before calling setFlyingEnabled() Setting::Handle firstRunVal { Settings::firstRun, true }; - setFlyingDesktopPref(firstRunVal.get() ? true : settings.value("flyingDesktop").toBool()); setFlyingHMDPref(firstRunVal.get() ? false : settings.value("flyingHMD").toBool()); setFlyingEnabled(getFlyingEnabled()); From fc51b9369105d92233a3cd3cfdca79342611be8d Mon Sep 17 00:00:00 2001 From: Bradley Austin Davis Date: Mon, 30 Jul 2018 17:33:30 -0700 Subject: [PATCH 29/37] Fix OSX build --- libraries/gl/src/gl/Context.cpp | 4 +- libraries/gl/src/gl/GLHelpers.cpp | 25 +++- libraries/gl/src/gl/GLHelpers.h | 12 +- libraries/gl/src/gl/GLShaders.cpp | 93 +++++++------ libraries/gl/src/gl/GLShaders.h | 5 + .../gpu-gl-common/src/gpu/gl/GLBackend.cpp | 2 - .../gpu-gl-common/src/gpu/gl/GLBackend.h | 1 - .../gpu-gl/src/gpu/gl/GLDesktopBackend.cpp | 6 +- libraries/gpu-gl/src/gpu/gl41/GL41Backend.h | 4 - .../gpu-gl/src/gpu/gl41/GL41BackendShader.cpp | 43 +++--- libraries/gpu-gl/src/gpu/gl45/GL45Backend.cpp | 2 + libraries/gpu-gl/src/gpu/gl45/GL45Backend.h | 1 + libraries/gpu/src/gpu/Shader.cpp | 52 ++++++-- libraries/gpu/src/gpu/ShaderConstants.h | 3 + libraries/gpu/src/gpu/TextureTable.slh | 3 +- libraries/gpu/src/gpu/Transform.slh | 4 +- libraries/render-utils/src/BloomApply.slf | 1 + libraries/render-utils/src/Haze.slf | 3 - .../render-utils/src/RenderDeferredTask.cpp | 2 + libraries/render-utils/src/deferred_light.slv | 8 +- .../src/deferred_light_limited.slv | 8 +- .../render-utils/src/deferred_light_point.slv | 2 +- .../render-utils/src/deferred_light_spot.slv | 2 +- .../src/directional_ambient_light.slf | 5 +- .../src/directional_ambient_light_shadow.slf | 4 +- .../src/directional_skybox_light.slf | 4 +- .../src/directional_skybox_light_shadow.slf | 4 +- libraries/render-utils/src/forward_model.slf | 9 +- .../src/forward_model_normal_map.slf | 9 +- .../src/forward_model_translucent.slf | 12 +- .../render-utils/src/forward_model_unlit.slf | 8 +- libraries/render-utils/src/forward_simple.slf | 4 +- .../src/forward_simple_textured.slf | 4 +- .../forward_simple_textured_transparent.slf | 4 +- .../src/forward_simple_textured_unlit.slf | 4 +- .../src/forward_simple_transparent.slf | 4 +- libraries/render-utils/src/glowLine.slf | 3 +- libraries/render-utils/src/glowLine.slv | 2 +- libraries/render-utils/src/hmd_ui.slf | 4 +- libraries/render-utils/src/hmd_ui.slv | 4 +- .../src/local_lights_drawOutline.slf | 4 +- .../render-utils/src/local_lights_shading.slf | 4 +- libraries/render-utils/src/model.slf | 9 +- libraries/render-utils/src/model.slv | 14 +- libraries/render-utils/src/model_fade.slf | 9 +- libraries/render-utils/src/model_fade.slv | 14 +- libraries/render-utils/src/model_lightmap.slf | 9 +- libraries/render-utils/src/model_lightmap.slv | 11 +- .../render-utils/src/model_lightmap_fade.slf | 9 +- .../render-utils/src/model_lightmap_fade.slv | 12 +- .../src/model_lightmap_normal_map.slf | 9 +- .../src/model_lightmap_normal_map.slv | 12 +- .../src/model_lightmap_normal_map_fade.slf | 9 +- .../src/model_lightmap_normal_map_fade.slv | 12 +- .../render-utils/src/model_normal_map.slf | 9 +- .../render-utils/src/model_normal_map.slv | 14 +- .../src/model_normal_map_fade.slf | 9 +- .../src/model_normal_map_fade.slv | 14 +- .../render-utils/src/model_translucent.slf | 12 +- .../render-utils/src/model_translucent.slv | 14 +- .../src/model_translucent_fade.slf | 12 +- .../src/model_translucent_normal_map.slf | 12 +- .../src/model_translucent_normal_map.slv | 14 +- .../src/model_translucent_normal_map_fade.slf | 12 +- .../src/model_translucent_unlit.slf | 11 +- .../src/model_translucent_unlit_fade.slf | 11 +- libraries/render-utils/src/model_unlit.slf | 9 +- .../render-utils/src/model_unlit_fade.slf | 9 +- .../src/render-utils/ShaderConstants.h | 27 ++-- libraries/render-utils/src/sdf_text3D.slf | 4 +- libraries/render-utils/src/sdf_text3D.slv | 4 +- .../src/sdf_text3D_transparent.slf | 4 +- libraries/render-utils/src/simple.slf | 4 +- libraries/render-utils/src/simple.slv | 4 +- libraries/render-utils/src/simple_fade.slf | 4 +- libraries/render-utils/src/simple_fade.slv | 4 +- .../src/simple_opaque_web_browser.slf | 4 +- .../render-utils/src/simple_textured.slf | 4 +- .../render-utils/src/simple_textured_fade.slf | 4 +- .../src/simple_textured_unlit.slf | 4 +- .../src/simple_textured_unlit_fade.slf | 4 +- .../render-utils/src/simple_transparent.slf | 4 +- .../src/simple_transparent_textured.slf | 4 +- .../src/simple_transparent_textured_fade.slf | 4 +- .../src/simple_transparent_textured_unlit.slf | 4 +- ...simple_transparent_textured_unlit_fade.slf | 4 +- .../src/simple_transparent_web_browser.slf | 4 +- libraries/render-utils/src/skin_model.slv | 14 +- libraries/render-utils/src/skin_model_dq.slv | 14 +- .../render-utils/src/skin_model_fade.slv | 14 +- .../render-utils/src/skin_model_fade_dq.slv | 14 +- .../src/skin_model_normal_map.slv | 14 +- .../src/skin_model_normal_map_dq.slv | 14 +- .../src/skin_model_normal_map_fade.slv | 14 +- .../src/skin_model_normal_map_fade_dq.slv | 14 +- libraries/shaders/CMakeLists.txt | 2 +- libraries/shaders/src/shaders/Shaders.cpp | 29 ++-- libraries/ui/src/ui/OffscreenQmlSurface.cpp | 10 ++ tests-manual/render-utils/src/main.cpp | 9 +- tests/shaders/src/ShaderTests.cpp | 124 +++++++++++++++--- tools/shreflect/src/main.cpp | 10 +- 101 files changed, 637 insertions(+), 431 deletions(-) diff --git a/libraries/gl/src/gl/Context.cpp b/libraries/gl/src/gl/Context.cpp index 309839808e..ad7e51fbd3 100644 --- a/libraries/gl/src/gl/Context.cpp +++ b/libraries/gl/src/gl/Context.cpp @@ -269,7 +269,9 @@ void Context::create() { #if defined(USE_GLES) _version = 0x0200; #else - if (GLAD_GL_VERSION_4_5) { + if (gl::disableGl45()) { + _version = 0x0401; + } else if (GLAD_GL_VERSION_4_5) { _version = 0x0405; } else if (GLAD_GL_VERSION_4_3) { _version = 0x0403; diff --git a/libraries/gl/src/gl/GLHelpers.cpp b/libraries/gl/src/gl/GLHelpers.cpp index e3f85afa78..7ebba4f8d8 100644 --- a/libraries/gl/src/gl/GLHelpers.cpp +++ b/libraries/gl/src/gl/GLHelpers.cpp @@ -24,6 +24,26 @@ size_t evalGLFormatSwapchainPixelSize(const QSurfaceFormat& format) { return pixelSize; } +bool gl::disableGl45() { +#if defined(USE_GLES) + return false; +#else + static const QString DEBUG_FLAG("HIFI_DISABLE_OPENGL_45"); + static bool disableOpenGL45 = QProcessEnvironment::systemEnvironment().contains(DEBUG_FLAG); + return disableOpenGL45; +#endif +} + +void gl::getTargetVersion(int& major, int& minor) { +#if defined(USE_GLES) + major = 3; + minor = 2; +#else + major = 4; + minor = disableGl45() ? 1 : 5; +#endif +} + const QSurfaceFormat& getDefaultOpenGLSurfaceFormat() { static QSurfaceFormat format; static std::once_flag once; @@ -40,7 +60,10 @@ const QSurfaceFormat& getDefaultOpenGLSurfaceFormat() { // Qt Quick may need a depth and stencil buffer. Always make sure these are available. format.setDepthBufferSize(DEFAULT_GL_DEPTH_BUFFER_BITS); format.setStencilBufferSize(DEFAULT_GL_STENCIL_BUFFER_BITS); - setGLFormatVersion(format); + int major, minor; + ::gl::getTargetVersion(major, minor); + format.setMajorVersion(major); + format.setMinorVersion(minor); QSurfaceFormat::setDefaultFormat(format); }); return format; diff --git a/libraries/gl/src/gl/GLHelpers.h b/libraries/gl/src/gl/GLHelpers.h index dcbf5a9e77..6252eba2f0 100644 --- a/libraries/gl/src/gl/GLHelpers.h +++ b/libraries/gl/src/gl/GLHelpers.h @@ -26,15 +26,6 @@ class QOpenGLDebugMessage; class QSurfaceFormat; class QGLFormat; -template -// https://bugreports.qt.io/browse/QTBUG-64703 prevents us from using "defined(QT_OPENGL_ES_3_1)" -#if defined(USE_GLES) -void setGLFormatVersion(F& format, int major = 3, int minor = 2) -#else -void setGLFormatVersion(F& format, int major = 4, int minor = 5) -#endif - { format.setVersion(major, minor); } - size_t evalGLFormatSwapchainPixelSize(const QSurfaceFormat& format); const QSurfaceFormat& getDefaultOpenGLSurfaceFormat(); @@ -50,6 +41,9 @@ namespace gl { bool checkGLErrorDebug(const char* name); + bool disableGl45(); + + void getTargetVersion(int& major, int& minor); } // namespace gl #define CHECK_GL_ERROR() ::gl::checkGLErrorDebug(__FUNCTION__) diff --git a/libraries/gl/src/gl/GLShaders.cpp b/libraries/gl/src/gl/GLShaders.cpp index 03b807fbbf..a0d976d727 100644 --- a/libraries/gl/src/gl/GLShaders.cpp +++ b/libraries/gl/src/gl/GLShaders.cpp @@ -102,8 +102,23 @@ Uniforms Uniform::load(GLuint glprogram, const std::vector& indices) { return result; } +Uniform Uniform::loadByName(GLuint glprogram, const std::string& name) { + GLuint index; + const char* nameCStr = name.c_str(); + glGetUniformIndices(glprogram, 1, &nameCStr, &index); + Uniform result; + if (index != GL_INVALID_INDEX) { + result.load(glprogram, index); + } + return result; +} + + Uniforms Uniform::load(GLuint glprogram, const std::vector& cnames) { GLsizei count = static_cast(cnames.size()); + if (0 == count) { + return {}; + } std::vector indices; indices.resize(count); glGetUniformIndices(glprogram, count, cnames.data(), indices.data()); @@ -232,58 +247,28 @@ bool gl::compileShader(GLenum shaderDomain, GLint compiled = 0; glGetShaderiv(glshader, GL_COMPILE_STATUS, &compiled); - GLint infoLength = 0; - glGetShaderiv(glshader, GL_INFO_LOG_LENGTH, &infoLength); - - if ((infoLength > 0) || !compiled) { - char* temp = new char[infoLength]; - glGetShaderInfoLog(glshader, infoLength, NULL, temp); - - message = std::string(temp); - - // if compilation fails - if (!compiled) { - // save the source code to a temp file so we can debug easily - /* - std::ofstream filestream; - filestream.open("debugshader.glsl"); - if (filestream.is_open()) { - for (const auto& str : cstrs) { - filestream << str; - } - filestream.close(); + getShaderInfoLog(glshader, message); + // if compilation fails + if (!compiled) { + qCCritical(glLogging) << "GLShader::compileShader - failed to compile the gl shader object:"; + int lineNumber = 0; + for (const auto& s : cstrs) { + QString str(s); + QStringList lines = str.split("\n"); + for (auto& line : lines) { + qCCritical(glLogging).noquote() << QString("%1: %2").arg(lineNumber++, 5, 10, QChar('0')).arg(line); } - */ - - /* - filestream.open("debugshader.glsl.info.txt"); - if (filestream.is_open()) { - filestream << std::string(temp); - filestream.close(); - } - */ - - qCCritical(glLogging) << "GLShader::compileShader - failed to compile the gl shader object:"; - int lineNumber = 0; - for (const auto& s : cstrs) { - QString str(s); - QStringList lines = str.split("\n"); - for (auto& line : lines) { - qCCritical(glLogging).noquote() << QString("%1: %2").arg(lineNumber++, 5, 10, QChar('0')).arg(line); - } - } - qCCritical(glLogging) << "GLShader::compileShader - errors:"; - qCCritical(glLogging) << temp; - - delete[] temp; - glDeleteShader(glshader); - return false; } + qCCritical(glLogging) << "GLShader::compileShader - errors:"; + qCCritical(glLogging) << message.c_str(); + glDeleteShader(glshader); + return false; + } + if (!message.empty()) { // Compilation success qCWarning(glLogging) << "GLShader::compileShader - Success:"; - qCWarning(glLogging) << temp; - delete[] temp; + qCWarning(glLogging) << message.c_str(); } #ifdef SEPARATE_PROGRAM @@ -341,6 +326,20 @@ bool gl::compileShader(GLenum shaderDomain, return true; } +void gl::getShaderInfoLog(GLuint glshader, std::string& message) { + std::string result; + GLint infoLength = 0; + glGetShaderiv(glshader, GL_INFO_LOG_LENGTH, &infoLength); + if (infoLength > 0) { + char* temp = new char[infoLength]; + glGetShaderInfoLog(glshader, infoLength, NULL, temp); + message = std::string(temp); + delete[] temp; + } else { + message.clear(); + } +} + void gl::getProgramInfoLog(GLuint glprogram, std::string& message) { std::string result; GLint infoLength = 0; diff --git a/libraries/gl/src/gl/GLShaders.h b/libraries/gl/src/gl/GLShaders.h index 5d16bd443e..c12e9d2305 100644 --- a/libraries/gl/src/gl/GLShaders.h +++ b/libraries/gl/src/gl/GLShaders.h @@ -41,9 +41,13 @@ struct Uniform : public ShaderBinding { static Vector load(GLuint glprogram, const std::vector& indices); static Vector load(GLuint glprogram, const std::vector& names); static Vector load(GLuint glprogram, const std::vector& names); + static Uniform loadByName(GLuint glprogram, const std::string& names); template static Vector loadByName(GLuint glprogram, const C& names) { + if (names.empty()) { + return {}; + } std::vector cnames; cnames.reserve(names.size()); for (const auto& name : names) { @@ -113,6 +117,7 @@ bool compileShader(GLenum shaderDomain, GLuint buildProgram(const std::vector& glshaders); GLuint buildProgram(const CachedShader& binary); bool linkProgram(GLuint glprogram, std::string& message); +void getShaderInfoLog(GLuint glshader, std::string& message); void getProgramInfoLog(GLuint glprogram, std::string& message); void getProgramBinary(GLuint glprogram, CachedShader& cachedShader); } // namespace gl diff --git a/libraries/gpu-gl-common/src/gpu/gl/GLBackend.cpp b/libraries/gpu-gl-common/src/gpu/gl/GLBackend.cpp index 2d26b4b347..01424c2ac6 100644 --- a/libraries/gpu-gl-common/src/gpu/gl/GLBackend.cpp +++ b/libraries/gpu-gl-common/src/gpu/gl/GLBackend.cpp @@ -108,7 +108,6 @@ GLint GLBackend::MAX_COMBINED_UNIFORM_BLOCKS{ 0 }; GLint GLBackend::MAX_COMBINED_TEXTURE_IMAGE_UNITS{ 0 }; GLint GLBackend::MAX_UNIFORM_BLOCK_SIZE{ 0 }; GLint GLBackend::UNIFORM_BUFFER_OFFSET_ALIGNMENT{ 1 }; -GLint GLBackend::MAX_UNIFORM_LOCATIONS{ 0 }; void GLBackend::init() { static std::once_flag once; @@ -127,7 +126,6 @@ void GLBackend::init() { GL_GET_INTEGER(MAX_COMBINED_UNIFORM_BLOCKS); GL_GET_INTEGER(MAX_UNIFORM_BLOCK_SIZE); GL_GET_INTEGER(UNIFORM_BUFFER_OFFSET_ALIGNMENT); - GL_GET_INTEGER(MAX_UNIFORM_LOCATIONS); qCDebug(gpugllogging) << "GL Version: " << QString((const char*) glGetString(GL_VERSION)); qCDebug(gpugllogging) << "GL Shader Language Version: " << QString((const char*) glGetString(GL_SHADING_LANGUAGE_VERSION)); diff --git a/libraries/gpu-gl-common/src/gpu/gl/GLBackend.h b/libraries/gpu-gl-common/src/gpu/gl/GLBackend.h index 2be13bbae4..cadcec7a56 100644 --- a/libraries/gpu-gl-common/src/gpu/gl/GLBackend.h +++ b/libraries/gpu-gl-common/src/gpu/gl/GLBackend.h @@ -90,7 +90,6 @@ public: static GLint MAX_COMBINED_UNIFORM_BLOCKS; static GLint MAX_COMBINED_TEXTURE_IMAGE_UNITS; static GLint MAX_UNIFORM_BLOCK_SIZE; - static GLint MAX_UNIFORM_LOCATIONS; static GLint UNIFORM_BUFFER_OFFSET_ALIGNMENT; virtual ~GLBackend(); diff --git a/libraries/gpu-gl/src/gpu/gl/GLDesktopBackend.cpp b/libraries/gpu-gl/src/gpu/gl/GLDesktopBackend.cpp index be8b8cb082..bc7cbdff4a 100644 --- a/libraries/gpu-gl/src/gpu/gl/GLDesktopBackend.cpp +++ b/libraries/gpu-gl/src/gpu/gl/GLDesktopBackend.cpp @@ -16,6 +16,7 @@ #include #include +#include #include #include "../gl41/GL41Backend.h" @@ -24,9 +25,6 @@ using namespace gpu; using namespace gpu::gl; -static const QString DEBUG_FLAG("HIFI_DISABLE_OPENGL_45"); -static bool disableOpenGL45 = QProcessEnvironment::systemEnvironment().contains(DEBUG_FLAG); - static GLBackend* INSTANCE{ nullptr }; BackendPointer GLBackend::createBackend() { @@ -34,7 +32,7 @@ BackendPointer GLBackend::createBackend() { // Where the gpuContext is initialized and where the TRUE Backend is created and assigned auto version = QOpenGLContextWrapper::currentContextVersion(); std::shared_ptr result; - if (!disableOpenGL45 && version >= 0x0405) { + if (!::gl::disableGl45() && version >= 0x0405) { qCDebug(gpugllogging) << "Using OpenGL 4.5 backend"; result = std::make_shared(); } else { diff --git a/libraries/gpu-gl/src/gpu/gl41/GL41Backend.h b/libraries/gpu-gl/src/gpu/gl41/GL41Backend.h index 8cf44a33d8..c6fbc43ae5 100644 --- a/libraries/gpu-gl/src/gpu/gl41/GL41Backend.h +++ b/libraries/gpu-gl/src/gpu/gl41/GL41Backend.h @@ -19,11 +19,7 @@ #define GPU_CORE_41 410 #define GPU_CORE_43 430 -#ifdef Q_OS_MAC #define GPU_INPUT_PROFILE GPU_CORE_41 -#else -#define GPU_INPUT_PROFILE GPU_CORE_43 -#endif namespace gpu { namespace gl41 { diff --git a/libraries/gpu-gl/src/gpu/gl41/GL41BackendShader.cpp b/libraries/gpu-gl/src/gpu/gl41/GL41BackendShader.cpp index 2c3010e0f5..8a67ff9619 100644 --- a/libraries/gpu-gl/src/gpu/gl41/GL41BackendShader.cpp +++ b/libraries/gpu-gl/src/gpu/gl41/GL41BackendShader.cpp @@ -35,36 +35,41 @@ void GL41Backend::postLinkProgram(ShaderObject& programObject, const Shader& pro continue; } const auto& targetLocation = expectedUbos.at(name); - if (ubo.binding != targetLocation) { - glUniformBlockBinding(glprogram, ubo.index, targetLocation); + glUniformBlockBinding(glprogram, ubo.index, targetLocation); + } + } + + // For the Textures, use glUniform1i to fixup the active texture slots based on the reflection + { + const auto expectedTextures = program.getTextures().getLocationsByName(); + for (const auto& expectedTexture : expectedTextures) { + auto location = glGetUniformLocation(glprogram, expectedTexture.first.c_str()); + if (location < 0) { + continue; } + glProgramUniform1i(glprogram, location, expectedTexture.second); } } - // For the Textures, us glUniform1i to fixup the active texture slots based on the reflection + // For the resource buffers, do the same as for the textures, since in GL 4.1 that's how they're implemented { - const auto expectedTextures = program.getTextures().getLocationsByName(); - const auto textureUniforms = ::gl::Uniform::loadByName(glprogram, program.getTextures().getNames()); - for (const auto& texture : textureUniforms) { - const auto& targetBinding = expectedTextures.at(texture.name); - glProgramUniform1i(glprogram, texture.binding, targetBinding); + const auto expectedResourceBuffers = program.getResourceBuffers().getLocationsByName(); + const auto resourceBufferUniforms = ::gl::Uniform::loadByName(glprogram, program.getResourceBuffers().getNames()); + for (const auto& resourceBuffer : resourceBufferUniforms) { + const auto& targetBinding = expectedResourceBuffers.at(resourceBuffer.name); + glProgramUniform1i(glprogram, resourceBuffer.binding, targetBinding); } } - // For the resource buffers + // Special case for the transformObjectBuffer, which is filtered out of the reflection data at shader load time + // { - const auto expectedTextures = program.getTextures().getLocationsByName(); - const auto textureUniforms = ::gl::Uniform::loadByName(glprogram, program.getTextures().getNames()); - for (const auto& texture : textureUniforms) { - const auto& targetBinding = expectedTextures.at(texture.name); - glProgramUniform1i(glprogram, texture.binding, targetBinding); + static const std::string TRANSFORM_OBJECT_BUFFER = "transformObjectBuffer"; + const auto uniform = ::gl::Uniform::loadByName(glprogram, TRANSFORM_OBJECT_BUFFER); + if (-1 != uniform.binding) { + glProgramUniform1i(glprogram, uniform.binding, ::gpu::slot::texture::ObjectTransforms); } } - -#if defined(Q_OS_MAC) - // For the uniforms, we need to create a remapping layer - programObject.uniformRemap = buildRemap(glprogram, program.getUniforms()); -#endif } diff --git a/libraries/gpu-gl/src/gpu/gl45/GL45Backend.cpp b/libraries/gpu-gl/src/gpu/gl45/GL45Backend.cpp index 8f8e158334..bbe011d237 100644 --- a/libraries/gpu-gl/src/gpu/gl45/GL45Backend.cpp +++ b/libraries/gpu-gl/src/gpu/gl45/GL45Backend.cpp @@ -19,11 +19,13 @@ using namespace gpu; using namespace gpu::gl45; GLint GL45Backend::MAX_COMBINED_SHADER_STORAGE_BLOCKS{ 0 }; +GLint GL45Backend::MAX_UNIFORM_LOCATIONS{ 0 }; static void staticInit() { static std::once_flag once; std::call_once(once, [&] { glGetIntegerv(GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS, &GL45Backend::MAX_COMBINED_SHADER_STORAGE_BLOCKS); + glGetIntegerv(GL_MAX_UNIFORM_LOCATIONS, &GL45Backend::MAX_UNIFORM_LOCATIONS); }); } const std::string GL45Backend::GL45_VERSION { "GL45" }; diff --git a/libraries/gpu-gl/src/gpu/gl45/GL45Backend.h b/libraries/gpu-gl/src/gpu/gl45/GL45Backend.h index 8694e15d97..658bea2a3e 100644 --- a/libraries/gpu-gl/src/gpu/gl45/GL45Backend.h +++ b/libraries/gpu-gl/src/gpu/gl45/GL45Backend.h @@ -34,6 +34,7 @@ class GL45Backend : public GLBackend { public: static GLint MAX_COMBINED_SHADER_STORAGE_BLOCKS; + static GLint MAX_UNIFORM_LOCATIONS; #if GPU_BINDLESS_TEXTURES virtual bool supportsBindless() const override { return true; } #endif diff --git a/libraries/gpu/src/gpu/Shader.cpp b/libraries/gpu/src/gpu/Shader.cpp index cea7ec6e14..0191d9d4f1 100755 --- a/libraries/gpu/src/gpu/Shader.cpp +++ b/libraries/gpu/src/gpu/Shader.cpp @@ -204,9 +204,33 @@ Shader::Pointer Shader::createProgram(const Pointer& vertexShader, const Pointer return createOrReuseProgramShader(PROGRAM, vertexShader, geometryShader, pixelShader); } +static const std::string IGNORED_BINDING = "transformObjectBuffer"; + void updateBindingsFromJsonObject(Shader::LocationMap& inOutSet, const QJsonObject& json) { for (const auto& key : json.keys()) { - inOutSet[key.toStdString()] = json[key].toInt(); + auto keyStr = key.toStdString(); + if (IGNORED_BINDING == keyStr) { + continue; + } + inOutSet[keyStr] = json[key].toInt(); + } +} + +void updateTextureAndResourceBuffersFromJsonObjects(Shader::LocationMap& inOutTextures, Shader::LocationMap& inOutResourceBuffers, + const QJsonObject& json, const QJsonObject& types) { + static const std::string RESOURCE_BUFFER_TEXTURE_TYPE = "samplerBuffer"; + for (const auto& key : json.keys()) { + auto keyStr = key.toStdString(); + if (keyStr == IGNORED_BINDING) { + continue; + } + auto location = json[key].toInt(); + auto type = types[key].toString().toStdString(); + if (type == RESOURCE_BUFFER_TEXTURE_TYPE) { + inOutResourceBuffers[keyStr] = location; + } else { + inOutTextures[key.toStdString()] = location; + } } } @@ -221,6 +245,7 @@ Shader::ReflectionMap getShaderReflection(const std::string& reflectionJson) { #define REFLECT_KEY_SSBOS "storageBuffers" #define REFLECT_KEY_UNIFORMS "uniforms" #define REFLECT_KEY_TEXTURES "textures" +#define REFLECT_KEY_TEXTURE_TYPES "textureTypes" auto doc = QJsonDocument::fromJson(reflectionJson.c_str()); if (doc.isNull()) { @@ -236,17 +261,28 @@ Shader::ReflectionMap getShaderReflection(const std::string& reflectionJson) { if (json.contains(REFLECT_KEY_OUTPUTS)) { updateBindingsFromJsonObject(result[Shader::BindingType::OUTPUT], json[REFLECT_KEY_OUTPUTS].toObject()); } - if (json.contains(REFLECT_KEY_UBOS)) { - updateBindingsFromJsonObject(result[Shader::BindingType::UNIFORM_BUFFER], json[REFLECT_KEY_UBOS].toObject()); - } - if (json.contains(REFLECT_KEY_TEXTURES)) { - updateBindingsFromJsonObject(result[Shader::BindingType::TEXTURE], json[REFLECT_KEY_TEXTURES].toObject()); - } + // FIXME eliminate the last of the uniforms if (json.contains(REFLECT_KEY_UNIFORMS)) { updateBindingsFromJsonObject(result[Shader::BindingType::UNIFORM], json[REFLECT_KEY_UNIFORMS].toObject()); } + if (json.contains(REFLECT_KEY_UBOS)) { + updateBindingsFromJsonObject(result[Shader::BindingType::UNIFORM_BUFFER], json[REFLECT_KEY_UBOS].toObject()); + } + + // SSBOs need to come BEFORE the textures. In GL 4.5 the reflection slots aren't really used, but in 4.1 the slots + // are used to explicitly setup bindings after shader linkage, so we want the resource buffer slots to contain the + // texture locations, not the SSBO locations if (json.contains(REFLECT_KEY_SSBOS)) { - updateBindingsFromJsonObject(result[Shader::BindingType::UNIFORM], json[REFLECT_KEY_SSBOS].toObject()); + updateBindingsFromJsonObject(result[Shader::BindingType::RESOURCE_BUFFER], json[REFLECT_KEY_SSBOS].toObject()); + } + + // samplerBuffer textures map to gpu ResourceBuffer, while all other textures map to regular gpu Texture + if (json.contains(REFLECT_KEY_TEXTURES)) { + updateTextureAndResourceBuffersFromJsonObjects( + result[Shader::BindingType::TEXTURE], + result[Shader::BindingType::RESOURCE_BUFFER], + json[REFLECT_KEY_TEXTURES].toObject(), + json[REFLECT_KEY_TEXTURE_TYPES].toObject()); } diff --git a/libraries/gpu/src/gpu/ShaderConstants.h b/libraries/gpu/src/gpu/ShaderConstants.h index dd9b350a4e..dc5879e7ad 100644 --- a/libraries/gpu/src/gpu/ShaderConstants.h +++ b/libraries/gpu/src/gpu/ShaderConstants.h @@ -37,6 +37,9 @@ #define GPU_ATTR_STEREO_SIDE 14 #define GPU_ATTR_DRAW_CALL_INFO 15 +// OSX seems to have an issue using 14 as an attribute location for passing from the vertex to the fragment shader +#define GPU_ATTR_V2F_STEREO_SIDE 8 + #define GPU_UNIFORM_COLOR 101 #define GPU_UNIFORM_TEXCOORD_RECT 102 #define GPU_UNIFORM_EXTRA0 110 diff --git a/libraries/gpu/src/gpu/TextureTable.slh b/libraries/gpu/src/gpu/TextureTable.slh index f2d89e753b..bedbff954b 100644 --- a/libraries/gpu/src/gpu/TextureTable.slh +++ b/libraries/gpu/src/gpu/TextureTable.slh @@ -22,8 +22,7 @@ struct GPUTextureTable { #define tableTex(name, slot) sampler2D(name._textures[slot].xy) #define tableTexMinLod(name, slot) float(name._textures[slot].z) -#define tableTexValue(name, slot, uv) \ - tableTexValueLod(tableTex(matTex, albedoMap), tableTexMinLod(matTex, albedoMap), uv) +#define tableTexValue(name, slot, uv) tableTexValueLod(tableTex(matTex, albedoMap), tableTexMinLod(matTex, albedoMap), uv) vec4 tableTexValueLod(sampler2D sampler, float minLod, vec2 uv) { float queryLod = textureQueryLod(sampler, uv).x; diff --git a/libraries/gpu/src/gpu/Transform.slh b/libraries/gpu/src/gpu/Transform.slh index fd389e1d50..d0b7587da6 100644 --- a/libraries/gpu/src/gpu/Transform.slh +++ b/libraries/gpu/src/gpu/Transform.slh @@ -35,7 +35,7 @@ layout(std140, binding=GPU_BUFFER_TRANSFORM_CAMERA) uniform transformCameraBuffe layout(location=GPU_ATTR_STEREO_SIDE) in int _inStereoSide; #endif -layout(location=GPU_ATTR_STEREO_SIDE) flat out int _stereoSide; +layout(location=GPU_ATTR_V2F_STEREO_SIDE) flat out int _stereoSide; // In stereo drawcall mode Instances are drawn twice (left then right) hence the true InstanceID is the gl_InstanceID / 2 int gpu_InstanceID() { @@ -60,7 +60,7 @@ int gpu_InstanceID() { #ifdef GPU_PIXEL_SHADER #ifdef GPU_TRANSFORM_STEREO_CAMERA -layout(location=GPU_ATTR_STEREO_SIDE) flat in int _stereoSide; +layout(location=GPU_ATTR_V2F_STEREO_SIDE) flat in int _stereoSide; #endif #endif diff --git a/libraries/render-utils/src/BloomApply.slf b/libraries/render-utils/src/BloomApply.slf index caee76b651..a53894de60 100644 --- a/libraries/render-utils/src/BloomApply.slf +++ b/libraries/render-utils/src/BloomApply.slf @@ -10,6 +10,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // <@include BloomApply.shared.slh@> +<@include render-utils/ShaderConstants.h@> layout(binding=0) uniform sampler2D blurMap0; layout(binding=1) uniform sampler2D blurMap1; diff --git a/libraries/render-utils/src/Haze.slf b/libraries/render-utils/src/Haze.slf index ce5141d3c6..bb3c0bc769 100644 --- a/libraries/render-utils/src/Haze.slf +++ b/libraries/render-utils/src/Haze.slf @@ -19,9 +19,6 @@ <@include LightingModel.slh@> <$declareLightBuffer()$> -<@include LightDirectional.slh@> -<$declareLightingDirectional(_SCRIBE_NULL)$> - <@include Haze.slh@> layout(binding=RENDER_UTILS_TEXTURE_HAZE_LINEAR_DEPTH) uniform sampler2D linearDepthMap; diff --git a/libraries/render-utils/src/RenderDeferredTask.cpp b/libraries/render-utils/src/RenderDeferredTask.cpp index ea9655d26d..59c86acd19 100644 --- a/libraries/render-utils/src/RenderDeferredTask.cpp +++ b/libraries/render-utils/src/RenderDeferredTask.cpp @@ -12,6 +12,8 @@ #include "RenderDeferredTask.h" +#include + #include #include diff --git a/libraries/render-utils/src/deferred_light.slv b/libraries/render-utils/src/deferred_light.slv index 3b8aee6aae..654e9a69b2 100644 --- a/libraries/render-utils/src/deferred_light.slv +++ b/libraries/render-utils/src/deferred_light.slv @@ -14,7 +14,7 @@ <@include render-utils/ShaderConstants.h@> -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_UNIFORM_LIGHT_TEXCOORD_TRANSFORM) uniform vec4 texcoordFrameTransform; @@ -28,10 +28,10 @@ void main(void) { ); vec4 pos = UNIT_QUAD[gl_VertexID]; - _texCoord0 = (pos.xy + 1.0) * 0.5; + _texCoord01.xy = (pos.xy + 1.0) * 0.5; - _texCoord0 *= texcoordFrameTransform.zw; - _texCoord0 += texcoordFrameTransform.xy; + _texCoord01.xy *= texcoordFrameTransform.zw; + _texCoord01.xy += texcoordFrameTransform.xy; gl_Position = pos; } diff --git a/libraries/render-utils/src/deferred_light_limited.slv b/libraries/render-utils/src/deferred_light_limited.slv index 790c305204..fb59b8e78f 100644 --- a/libraries/render-utils/src/deferred_light_limited.slv +++ b/libraries/render-utils/src/deferred_light_limited.slv @@ -20,7 +20,7 @@ uniform vec4 sphereParam; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec4 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; void main(void) { if (sphereParam.w != 0.0) { @@ -41,7 +41,7 @@ void main(void) { } #endif #endif - _texCoord0 = vec4(projected.xy, 0.0, 1.0) * gl_Position.w; + _texCoord01.xy = vec4(projected.xy, 0.0, 1.0) * gl_Position.w; } else { const float depth = -1.0; //Draw at near plane const vec4 UNIT_QUAD[4] = vec4[4]( @@ -60,13 +60,13 @@ void main(void) { #endif #endif - _texCoord0 = vec4((pos.xy + 1.0) * 0.5, 0.0, 1.0); + _texCoord01.xy = vec4((pos.xy + 1.0) * 0.5, 0.0, 1.0); #ifdef GPU_TRANSFORM_IS_STEREO #ifdef GPU_TRANSFORM_STEREO_SPLIT_SCREEN #else if (cam_isStereo()) { - _texCoord0.x = 0.5 * (_texCoord0.x + cam_getStereoSide()); + _texCoord01.x = 0.5 * (_texCoord01.x + cam_getStereoSide()); } #endif #endif diff --git a/libraries/render-utils/src/deferred_light_point.slv b/libraries/render-utils/src/deferred_light_point.slv index 85707b322d..1f4c66b6e5 100644 --- a/libraries/render-utils/src/deferred_light_point.slv +++ b/libraries/render-utils/src/deferred_light_point.slv @@ -26,7 +26,7 @@ layout(binding=RENDER_UTILS_BUFFER_LIGHT_INDEX) uniform lightIndexBuffer { int lightIndex[256]; }; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec4 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord0; void main(void) { diff --git a/libraries/render-utils/src/deferred_light_spot.slv b/libraries/render-utils/src/deferred_light_spot.slv index 637df14175..c86551936b 100644 --- a/libraries/render-utils/src/deferred_light_spot.slv +++ b/libraries/render-utils/src/deferred_light_spot.slv @@ -24,7 +24,7 @@ layout(binding=RENDER_UTILS_BUFFER_LIGHT_INDEX) uniform lightIndexBuffer { int lightIndex[256]; }; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec4 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord0; void main(void) { vec4 coneVertex = inPosition; diff --git a/libraries/render-utils/src/directional_ambient_light.slf b/libraries/render-utils/src/directional_ambient_light.slf index 86adc744e2..3105b76bde 100644 --- a/libraries/render-utils/src/directional_ambient_light.slf +++ b/libraries/render-utils/src/directional_ambient_light.slf @@ -22,8 +22,9 @@ <$declareEvalAmbientSphereGlobalColor(supportScattering)$> - -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=0) out vec4 _fragColor; void main(void) { diff --git a/libraries/render-utils/src/directional_ambient_light_shadow.slf b/libraries/render-utils/src/directional_ambient_light_shadow.slf index f54f01c4af..88c0188048 100644 --- a/libraries/render-utils/src/directional_ambient_light_shadow.slf +++ b/libraries/render-utils/src/directional_ambient_light_shadow.slf @@ -20,7 +20,9 @@ <$declareEvalLightmappedColor()$> <$declareEvalAmbientSphereGlobalColor(isScattering)$> -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=0) out vec4 _fragColor; void main(void) { diff --git a/libraries/render-utils/src/directional_skybox_light.slf b/libraries/render-utils/src/directional_skybox_light.slf index f9b7664d10..56a7cd1883 100644 --- a/libraries/render-utils/src/directional_skybox_light.slf +++ b/libraries/render-utils/src/directional_skybox_light.slf @@ -19,7 +19,9 @@ <$declareEvalLightmappedColor()$> <$declareEvalSkyboxGlobalColor(isScattering)$> -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=0) out vec4 _fragColor; void main(void) { diff --git a/libraries/render-utils/src/directional_skybox_light_shadow.slf b/libraries/render-utils/src/directional_skybox_light_shadow.slf index 34a836e5b0..6eaa989c6b 100644 --- a/libraries/render-utils/src/directional_skybox_light_shadow.slf +++ b/libraries/render-utils/src/directional_skybox_light_shadow.slf @@ -20,7 +20,9 @@ <$declareEvalLightmappedColor()$> <$declareEvalSkyboxGlobalColor(isScattering)$> -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=0) out vec4 _fragColor; void main(void) { diff --git a/libraries/render-utils/src/forward_model.slf b/libraries/render-utils/src/forward_model.slf index 6df5343c5c..82d776602f 100644 --- a/libraries/render-utils/src/forward_model.slf +++ b/libraries/render-utils/src/forward_model.slf @@ -26,10 +26,11 @@ <$declareMaterialTextures(ALBEDO, ROUGHNESS, _SCRIBE_NULL, METALLIC, EMISSIVE, OCCLUSION)$> layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=0) out vec4 _fragColor0; @@ -45,7 +46,7 @@ void main(void) { vec3 albedo = getMaterialAlbedo(mat); <$evalMaterialAlbedo(albedoTex, albedo, matKey, albedo)$>; - albedo *= _color; + albedo *= _color.rgb; float roughness = getMaterialRoughness(mat); <$evalMaterialRoughness(roughnessTex, roughness, matKey, roughness)$>; diff --git a/libraries/render-utils/src/forward_model_normal_map.slf b/libraries/render-utils/src/forward_model_normal_map.slf index 88f9df1ecf..21ed0b9359 100644 --- a/libraries/render-utils/src/forward_model_normal_map.slf +++ b/libraries/render-utils/src/forward_model_normal_map.slf @@ -24,11 +24,12 @@ <$declareMaterialTextures(ALBEDO, ROUGHNESS, NORMAL, METALLIC, EMISSIVE, OCCLUSION)$> layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=0) out vec4 _fragColor0; @@ -44,7 +45,7 @@ void main(void) { vec3 albedo = getMaterialAlbedo(mat); <$evalMaterialAlbedo(albedoTex, albedo, matKey, albedo)$>; - albedo *= _color; + albedo *= _color.rgb; float roughness = getMaterialRoughness(mat); <$evalMaterialRoughness(roughnessTex, roughness, matKey, roughness)$>; diff --git a/libraries/render-utils/src/forward_model_translucent.slf b/libraries/render-utils/src/forward_model_translucent.slf index 5b69a6cb21..74d200542f 100644 --- a/libraries/render-utils/src/forward_model_translucent.slf +++ b/libraries/render-utils/src/forward_model_translucent.slf @@ -23,12 +23,12 @@ <$declareMaterialTextures(ALBEDO, ROUGHNESS, _SCRIBE_NULL, METALLIC, EMISSIVE, OCCLUSION)$> -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) in float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=0) out vec4 _fragColor0; @@ -38,13 +38,13 @@ void main(void) { <$fetchMaterialTexturesCoord0(matKey, _texCoord0, albedoTex, roughnessTex, _SCRIBE_NULL, metallicTex, emissiveTex)$> <$fetchMaterialTexturesCoord1(matKey, _texCoord1, occlusionTex)$> - float opacity = getMaterialOpacity(mat) * _alpha; + float opacity = getMaterialOpacity(mat) * _color.a; <$evalMaterialOpacity(albedoTex.a, opacity, matKey, opacity)$>; <$discardTransparent(opacity)$>; vec3 albedo = getMaterialAlbedo(mat); <$evalMaterialAlbedo(albedoTex, albedo, matKey, albedo)$>; - albedo *= _color; + albedo *= _color.rgb; float roughness = getMaterialRoughness(mat); <$evalMaterialRoughness(roughnessTex, roughness, matKey, roughness)$>; diff --git a/libraries/render-utils/src/forward_model_unlit.slf b/libraries/render-utils/src/forward_model_unlit.slf index d01bd70815..daad2ee6b9 100644 --- a/libraries/render-utils/src/forward_model_unlit.slf +++ b/libraries/render-utils/src/forward_model_unlit.slf @@ -19,8 +19,10 @@ <$declareMaterialTextures(ALBEDO)$> -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=0) out vec4 _fragColor0; @@ -36,7 +38,7 @@ void main(void) { vec3 albedo = getMaterialAlbedo(mat); <$evalMaterialAlbedo(albedoTex, albedo, matKey, albedo)$>; - albedo *= _color; + albedo *= _color.rgb; if (opacity != 1.0) { discard; diff --git a/libraries/render-utils/src/forward_simple.slf b/libraries/render-utils/src/forward_simple.slf index d4cf85d802..09365635cf 100644 --- a/libraries/render-utils/src/forward_simple.slf +++ b/libraries/render-utils/src/forward_simple.slf @@ -21,7 +21,9 @@ layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_NORMAL_MS) in vec3 _normalMS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_POSITION_MS) in vec4 _positionMS; layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; diff --git a/libraries/render-utils/src/forward_simple_textured.slf b/libraries/render-utils/src/forward_simple_textured.slf index 0c50b0b599..532d12dd17 100644 --- a/libraries/render-utils/src/forward_simple_textured.slf +++ b/libraries/render-utils/src/forward_simple_textured.slf @@ -27,7 +27,9 @@ layout(binding=0) uniform sampler2D originalTexture; // the interpolated normal layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=0) out vec4 _fragColor0; diff --git a/libraries/render-utils/src/forward_simple_textured_transparent.slf b/libraries/render-utils/src/forward_simple_textured_transparent.slf index d1cd21b4cb..98dc0bb368 100644 --- a/libraries/render-utils/src/forward_simple_textured_transparent.slf +++ b/libraries/render-utils/src/forward_simple_textured_transparent.slf @@ -27,7 +27,9 @@ layout(binding=0) uniform sampler2D originalTexture; // the interpolated normal layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=0) out vec4 _fragColor0; diff --git a/libraries/render-utils/src/forward_simple_textured_unlit.slf b/libraries/render-utils/src/forward_simple_textured_unlit.slf index cca371a1ff..7d3bf5912a 100644 --- a/libraries/render-utils/src/forward_simple_textured_unlit.slf +++ b/libraries/render-utils/src/forward_simple_textured_unlit.slf @@ -23,7 +23,9 @@ layout(location=0) out vec4 _fragColor0; layout(binding=0) uniform sampler2D originalTexture; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; void main(void) { vec4 texel = texture(originalTexture, _texCoord0.st); diff --git a/libraries/render-utils/src/forward_simple_transparent.slf b/libraries/render-utils/src/forward_simple_transparent.slf index 46328b77b6..a47d5963a2 100644 --- a/libraries/render-utils/src/forward_simple_transparent.slf +++ b/libraries/render-utils/src/forward_simple_transparent.slf @@ -20,7 +20,9 @@ layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_NORMAL_MS) in vec3 _normalMS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_POSITION_MS) in vec4 _positionMS; layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; diff --git a/libraries/render-utils/src/glowLine.slf b/libraries/render-utils/src/glowLine.slf index 69757ec92a..4e80b3358a 100644 --- a/libraries/render-utils/src/glowLine.slf +++ b/libraries/render-utils/src/glowLine.slf @@ -12,8 +12,7 @@ <@include render-utils/ShaderConstants.h@> layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; - -layout(location=1) in float distanceFromCenter; +layout(location=0) in float distanceFromCenter; layout(location=0) out vec4 _fragColor; void main(void) { diff --git a/libraries/render-utils/src/glowLine.slv b/libraries/render-utils/src/glowLine.slv index 70947350a4..075b291589 100644 --- a/libraries/render-utils/src/glowLine.slv +++ b/libraries/render-utils/src/glowLine.slv @@ -27,7 +27,7 @@ layout(std140, binding=0) uniform LineDataBuffer { layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; // the distance from the center in 'quad space' -layout(location=1) out float distanceFromCenter; +layout(location=0) out float distanceFromCenter; void main(void) { _color = _lineData.color; diff --git a/libraries/render-utils/src/hmd_ui.slf b/libraries/render-utils/src/hmd_ui.slf index d0e6798cec..b8bca889bf 100644 --- a/libraries/render-utils/src/hmd_ui.slf +++ b/libraries/render-utils/src/hmd_ui.slf @@ -23,7 +23,9 @@ layout(std140, binding=0) uniform hudBuffer { HUDData hud; }; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=0) out vec4 fragColor0; diff --git a/libraries/render-utils/src/hmd_ui.slv b/libraries/render-utils/src/hmd_ui.slv index 5352a5ba68..ab0d77c42a 100644 --- a/libraries/render-utils/src/hmd_ui.slv +++ b/libraries/render-utils/src/hmd_ui.slv @@ -26,10 +26,10 @@ layout(std140, binding=0) uniform hudBuffer { HUDData hud; }; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; void main() { - _texCoord0 = inTexCoord0.st; + _texCoord01.xy = inTexCoord0.st; // standard transform TransformCamera cam = getTransformCamera(); diff --git a/libraries/render-utils/src/local_lights_drawOutline.slf b/libraries/render-utils/src/local_lights_drawOutline.slf index c2a53e0490..ff6476e21c 100644 --- a/libraries/render-utils/src/local_lights_drawOutline.slf +++ b/libraries/render-utils/src/local_lights_drawOutline.slf @@ -33,7 +33,9 @@ <@include render-utils/ShaderConstants.h@> -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=0) out vec4 _fragColor; void main(void) { diff --git a/libraries/render-utils/src/local_lights_shading.slf b/libraries/render-utils/src/local_lights_shading.slf index 60cd9c426d..14cecd1815 100644 --- a/libraries/render-utils/src/local_lights_shading.slf +++ b/libraries/render-utils/src/local_lights_shading.slf @@ -21,7 +21,9 @@ <@include render-utils/ShaderConstants.h@> -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=0) out vec4 _fragColor; void main(void) { diff --git a/libraries/render-utils/src/model.slf b/libraries/render-utils/src/model.slf index 20fa10f44c..70b71e0d22 100644 --- a/libraries/render-utils/src/model.slf +++ b/libraries/render-utils/src/model.slf @@ -19,10 +19,11 @@ <$declareMaterialTextures(ALBEDO, ROUGHNESS, _SCRIBE_NULL, METALLIC, EMISSIVE, OCCLUSION, SCATTERING)$> -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; void main(void) { Material mat = getMaterial(); @@ -36,7 +37,7 @@ void main(void) { vec3 albedo = getMaterialAlbedo(mat); <$evalMaterialAlbedo(albedoTex, albedo, matKey, albedo)$>; - albedo *= _color; + albedo *= _color.rgb; float roughness = getMaterialRoughness(mat); <$evalMaterialRoughness(roughnessTex, roughness, matKey, roughness)$>; diff --git a/libraries/render-utils/src/model.slv b/libraries/render-utils/src/model.slv index 1ec5cf83aa..3763b8d2de 100644 --- a/libraries/render-utils/src/model.slv +++ b/libraries/render-utils/src/model.slv @@ -22,19 +22,17 @@ <$declareMaterialTexMapArrayBuffer()$> layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; void main(void) { - _color = color_sRGBToLinear(inColor.xyz); - _alpha = inColor.w; + _color.rgb = color_sRGBToLinear(inColor.rgb); + _color.a = inColor.a; TexMapArray texMapArray = getTexMapArray(); - <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord0)$> - <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord1)$> + <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord01.xy)$> + <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord01.zw)$> // standard transform TransformCamera cam = getTransformCamera(); diff --git a/libraries/render-utils/src/model_fade.slf b/libraries/render-utils/src/model_fade.slf index 31a4f4db6e..23c629ddb0 100644 --- a/libraries/render-utils/src/model_fade.slf +++ b/libraries/render-utils/src/model_fade.slf @@ -25,10 +25,11 @@ <@include render-utils/ShaderConstants.h@> layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; void main(void) { vec3 fadeEmissive; @@ -48,7 +49,7 @@ void main(void) { vec3 albedo = getMaterialAlbedo(mat); <$evalMaterialAlbedo(albedoTex, albedo, matKey, albedo)$>; - albedo *= _color; + albedo *= _color.rgb; float roughness = getMaterialRoughness(mat); <$evalMaterialRoughness(roughnessTex, roughness, matKey, roughness)$>; diff --git a/libraries/render-utils/src/model_fade.slv b/libraries/render-utils/src/model_fade.slv index e3f7924bc2..84f4f08fed 100644 --- a/libraries/render-utils/src/model_fade.slv +++ b/libraries/render-utils/src/model_fade.slv @@ -23,19 +23,17 @@ layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; void main(void) { - _color = color_sRGBToLinear(inColor.xyz); - _alpha = inColor.w; + _color.rgb = color_sRGBToLinear(inColor.rgb); + _color.a = inColor.w; TexMapArray texMapArray = getTexMapArray(); - <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord0)$> - <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord1)$> + <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord01.xy)$> + <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord01.zw)$> // standard transform TransformCamera cam = getTransformCamera(); diff --git a/libraries/render-utils/src/model_lightmap.slf b/libraries/render-utils/src/model_lightmap.slf index 3cd20b1a35..34da0a8a05 100644 --- a/libraries/render-utils/src/model_lightmap.slf +++ b/libraries/render-utils/src/model_lightmap.slf @@ -21,10 +21,11 @@ <$declareMaterialLightmap()$> -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; void main(void) { Material mat = getMaterial(); @@ -35,7 +36,7 @@ void main(void) { packDeferredFragmentLightmap( normalize(_normalWS), evalOpaqueFinalAlpha(getMaterialOpacity(mat), albedo.a), - getMaterialAlbedo(mat) * albedo.rgb * _color, + getMaterialAlbedo(mat) * albedo.rgb * _color.rgb, getMaterialRoughness(mat) * roughness, getMaterialMetallic(mat) * metallicTex, /*metallicTex, // no use of */getMaterialFresnel(mat), diff --git a/libraries/render-utils/src/model_lightmap.slv b/libraries/render-utils/src/model_lightmap.slv index e82fcaf85b..7306e2c831 100644 --- a/libraries/render-utils/src/model_lightmap.slv +++ b/libraries/render-utils/src/model_lightmap.slv @@ -23,19 +23,18 @@ <$declareMaterialTexMapArrayBuffer()$> layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; void main(void) { // pass along the color in linear space - _color = color_sRGBToLinear(inColor.xyz); + _color.rgb = color_sRGBToLinear(inColor.xyz); // and the texture coordinates TexMapArray texMapArray = getTexMapArray(); - <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord0)$> - <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord1, _texCoord1)$> + <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord01.xy)$> + <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord1, _texCoord01.zw)$> // standard transform TransformCamera cam = getTransformCamera(); diff --git a/libraries/render-utils/src/model_lightmap_fade.slf b/libraries/render-utils/src/model_lightmap_fade.slf index c7852cfd3f..6f6dd9c413 100644 --- a/libraries/render-utils/src/model_lightmap_fade.slf +++ b/libraries/render-utils/src/model_lightmap_fade.slf @@ -25,10 +25,11 @@ <@include render-utils/ShaderConstants.h@> -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; void main(void) { @@ -46,7 +47,7 @@ void main(void) { packDeferredFragmentLightmap( normalize(_normalWS), evalOpaqueFinalAlpha(getMaterialOpacity(mat), albedo.a), - getMaterialAlbedo(mat) * albedo.rgb * _color, + getMaterialAlbedo(mat) * albedo.rgb * _color.rgb, getMaterialRoughness(mat) * roughness, getMaterialMetallic(mat) * metallicTex, /*metallicTex, // no use of */getMaterialFresnel(mat), diff --git a/libraries/render-utils/src/model_lightmap_fade.slv b/libraries/render-utils/src/model_lightmap_fade.slv index 5be90e2384..d174d3c1d3 100644 --- a/libraries/render-utils/src/model_lightmap_fade.slv +++ b/libraries/render-utils/src/model_lightmap_fade.slv @@ -23,20 +23,20 @@ <@include render-utils/ShaderConstants.h@> layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; void main(void) { // pass along the color in linear space - _color = color_sRGBToLinear(inColor.xyz); + _color.rgb = color_sRGBToLinear(inColor.xyz); + _color.a = 1.0; // and the texture coordinates TexMapArray texMapArray = getTexMapArray(); - <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord0)$> - <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord1, _texCoord1)$> + <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord01.xy)$> + <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord1, _texCoord01.zw)$> // standard transform TransformCamera cam = getTransformCamera(); diff --git a/libraries/render-utils/src/model_lightmap_normal_map.slf b/libraries/render-utils/src/model_lightmap_normal_map.slf index 9f26c3063d..362c331f63 100644 --- a/libraries/render-utils/src/model_lightmap_normal_map.slf +++ b/libraries/render-utils/src/model_lightmap_normal_map.slf @@ -21,11 +21,12 @@ <$declareMaterialLightmap()$> layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; void main(void) { Material mat = getMaterial(); @@ -39,7 +40,7 @@ void main(void) { packDeferredFragmentLightmap( normalize(fragNormal.xyz), evalOpaqueFinalAlpha(getMaterialOpacity(mat), albedo.a), - getMaterialAlbedo(mat) * albedo.rgb * _color, + getMaterialAlbedo(mat) * albedo.rgb * _color.rgb, getMaterialRoughness(mat) * roughness, getMaterialMetallic(mat) * metallicTex, /*specular, // no use of */ getMaterialFresnel(mat), diff --git a/libraries/render-utils/src/model_lightmap_normal_map.slv b/libraries/render-utils/src/model_lightmap_normal_map.slv index 02524268ec..17794bce5f 100644 --- a/libraries/render-utils/src/model_lightmap_normal_map.slv +++ b/libraries/render-utils/src/model_lightmap_normal_map.slv @@ -24,19 +24,19 @@ layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) out vec3 _tangentWS; -layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; void main(void) { // pass along the color in linear space - _color = color_sRGBToLinear(inColor.xyz); + _color.rgb = color_sRGBToLinear(inColor.xyz); + _color.a = 1.0; TexMapArray texMapArray = getTexMapArray(); - <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord0)$> - <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord1, _texCoord1)$> + <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord01.xy)$> + <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord1, _texCoord01.zw)$> // standard transform TransformCamera cam = getTransformCamera(); diff --git a/libraries/render-utils/src/model_lightmap_normal_map_fade.slf b/libraries/render-utils/src/model_lightmap_normal_map_fade.slf index b1563a6ad9..bbeade488e 100644 --- a/libraries/render-utils/src/model_lightmap_normal_map_fade.slf +++ b/libraries/render-utils/src/model_lightmap_normal_map_fade.slf @@ -26,11 +26,12 @@ <@include render-utils/ShaderConstants.h@> layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; void main(void) { @@ -51,7 +52,7 @@ void main(void) { packDeferredFragmentLightmap( normalize(fragNormal.xyz), evalOpaqueFinalAlpha(getMaterialOpacity(mat), albedo.a), - getMaterialAlbedo(mat) * albedo.rgb * _color, + getMaterialAlbedo(mat) * albedo.rgb * _color.rgb, getMaterialRoughness(mat) * roughness, getMaterialMetallic(mat) * metallicTex, /*specular, // no use of */ getMaterialFresnel(mat), diff --git a/libraries/render-utils/src/model_lightmap_normal_map_fade.slv b/libraries/render-utils/src/model_lightmap_normal_map_fade.slv index 82f6d795d8..50a2bc43c9 100644 --- a/libraries/render-utils/src/model_lightmap_normal_map_fade.slv +++ b/libraries/render-utils/src/model_lightmap_normal_map_fade.slv @@ -23,20 +23,20 @@ layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) out vec3 _tangentWS; -layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; void main(void) { // pass along the color in linear space - _color = color_sRGBToLinear(inColor.xyz); + _color.rgb = color_sRGBToLinear(inColor.xyz); + _color.a = 1.0; TexMapArray texMapArray = getTexMapArray(); - <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord0)$> - <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord1, _texCoord1)$> + <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord01.xy)$> + <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord1, _texCoord01.zw)$> // standard transform TransformCamera cam = getTransformCamera(); diff --git a/libraries/render-utils/src/model_normal_map.slf b/libraries/render-utils/src/model_normal_map.slf index 5d8ba00936..4e89dfb3e8 100644 --- a/libraries/render-utils/src/model_normal_map.slf +++ b/libraries/render-utils/src/model_normal_map.slf @@ -20,11 +20,12 @@ <$declareMaterialTextures(ALBEDO, ROUGHNESS, NORMAL, METALLIC, EMISSIVE, OCCLUSION, SCATTERING)$> layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; void main(void) { Material mat = getMaterial(); @@ -38,7 +39,7 @@ void main(void) { vec3 albedo = getMaterialAlbedo(mat); <$evalMaterialAlbedo(albedoTex, albedo, matKey, albedo)$>; - albedo *= _color; + albedo *= _color.rgb; float roughness = getMaterialRoughness(mat); <$evalMaterialRoughness(roughnessTex, roughness, matKey, roughness)$>; diff --git a/libraries/render-utils/src/model_normal_map.slv b/libraries/render-utils/src/model_normal_map.slv index 52386d6e4f..4a1a0c9264 100644 --- a/libraries/render-utils/src/model_normal_map.slv +++ b/libraries/render-utils/src/model_normal_map.slv @@ -24,21 +24,19 @@ layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) out vec3 _tangentWS; -layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; void main(void) { // pass along the color - _color = color_sRGBToLinear(inColor.rgb); - _alpha = inColor.a; + _color.rgb = color_sRGBToLinear(inColor.rgb); + _color.a = inColor.a; TexMapArray texMapArray = getTexMapArray(); - <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord0)$> - <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord1)$> + <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord01.xy)$> + <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord01.zw)$> // standard transform TransformCamera cam = getTransformCamera(); diff --git a/libraries/render-utils/src/model_normal_map_fade.slf b/libraries/render-utils/src/model_normal_map_fade.slf index fb66fe167c..16b8138efe 100644 --- a/libraries/render-utils/src/model_normal_map_fade.slf +++ b/libraries/render-utils/src/model_normal_map_fade.slf @@ -24,11 +24,12 @@ layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; void main(void) { vec3 fadeEmissive; @@ -48,7 +49,7 @@ void main(void) { vec3 albedo = getMaterialAlbedo(mat); <$evalMaterialAlbedo(albedoTex, albedo, matKey, albedo)$>; - albedo *= _color; + albedo *= _color.rgb; float roughness = getMaterialRoughness(mat); <$evalMaterialRoughness(roughnessTex, roughness, matKey, roughness)$>; diff --git a/libraries/render-utils/src/model_normal_map_fade.slv b/libraries/render-utils/src/model_normal_map_fade.slv index 74d23d6057..090027ac79 100644 --- a/libraries/render-utils/src/model_normal_map_fade.slv +++ b/libraries/render-utils/src/model_normal_map_fade.slv @@ -24,21 +24,19 @@ layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) out vec3 _tangentWS; -layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; void main(void) { // pass along the color - _color = color_sRGBToLinear(inColor.rgb); - _alpha = inColor.a; + _color.rgb = color_sRGBToLinear(inColor.rgb); + _color.a = inColor.a; TexMapArray texMapArray = getTexMapArray(); - <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord0)$> - <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord1)$> + <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord01.xy)$> + <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord01.zw)$> // standard transform TransformCamera cam = getTransformCamera(); diff --git a/libraries/render-utils/src/model_translucent.slf b/libraries/render-utils/src/model_translucent.slf index cd170f29e7..7fe81ab992 100644 --- a/libraries/render-utils/src/model_translucent.slf +++ b/libraries/render-utils/src/model_translucent.slf @@ -26,13 +26,13 @@ <$declareMaterialTextures(ALBEDO, ROUGHNESS, _SCRIBE_NULL, _SCRIBE_NULL, EMISSIVE, OCCLUSION)$> -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) in float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=0) out vec4 _fragColor; @@ -42,13 +42,13 @@ void main(void) { <$fetchMaterialTexturesCoord0(matKey, _texCoord0, albedoTex, roughnessTex, _SCRIBE_NULL, _SCRIBE_NULL, emissiveTex)$> <$fetchMaterialTexturesCoord1(matKey, _texCoord1, occlusionTex)$> - float opacity = getMaterialOpacity(mat) * _alpha; + float opacity = getMaterialOpacity(mat) * _color.a; <$evalMaterialOpacity(albedoTex.a, opacity, matKey, opacity)$>; <$discardTransparent(opacity)$>; vec3 albedo = getMaterialAlbedo(mat); <$evalMaterialAlbedo(albedoTex, albedo, matKey, albedo)$>; - albedo *= _color; + albedo *= _color.rgb; float roughness = getMaterialRoughness(mat); <$evalMaterialRoughness(roughnessTex, roughness, matKey, roughness)$>; diff --git a/libraries/render-utils/src/model_translucent.slv b/libraries/render-utils/src/model_translucent.slv index defdb87172..70e61cd788 100644 --- a/libraries/render-utils/src/model_translucent.slv +++ b/libraries/render-utils/src/model_translucent.slv @@ -21,21 +21,19 @@ <@include render-utils/ShaderConstants.h@> -layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; void main(void) { - _color = color_sRGBToLinear(inColor.xyz); - _alpha = inColor.w; + _color.rgb = color_sRGBToLinear(inColor.rgb); + _color.a = inColor.a; TexMapArray texMapArray = getTexMapArray(); - <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord0)$> - <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord1)$> + <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord01.xy)$> + <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord01.zw)$> // standard transform TransformCamera cam = getTransformCamera(); diff --git a/libraries/render-utils/src/model_translucent_fade.slf b/libraries/render-utils/src/model_translucent_fade.slf index 81b9faf82d..b9df51fcb9 100644 --- a/libraries/render-utils/src/model_translucent_fade.slf +++ b/libraries/render-utils/src/model_translucent_fade.slf @@ -24,13 +24,13 @@ <@include render-utils/ShaderConstants.h@> -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) in float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=0) out vec4 _fragColor; @@ -46,13 +46,13 @@ void main(void) { <$fetchMaterialTexturesCoord0(matKey, _texCoord0, albedoTex, roughnessTex, _SCRIBE_NULL, _SCRIBE_NULL, emissiveTex)$> <$fetchMaterialTexturesCoord1(matKey, _texCoord1, occlusionTex)$> - float opacity = getMaterialOpacity(mat) * _alpha; + float opacity = getMaterialOpacity(mat) * _color.a; <$evalMaterialOpacity(albedoTex.a, opacity, matKey, opacity)$>; <$discardTransparent(opacity)$>; vec3 albedo = getMaterialAlbedo(mat); <$evalMaterialAlbedo(albedoTex, albedo, matKey, albedo)$>; - albedo *= _color; + albedo *= _color.rgb; float roughness = getMaterialRoughness(mat); <$evalMaterialRoughness(roughnessTex, roughness, matKey, roughness)$>; diff --git a/libraries/render-utils/src/model_translucent_normal_map.slf b/libraries/render-utils/src/model_translucent_normal_map.slf index c813097dcf..c023f78e25 100644 --- a/libraries/render-utils/src/model_translucent_normal_map.slf +++ b/libraries/render-utils/src/model_translucent_normal_map.slf @@ -28,14 +28,14 @@ <@include render-utils/ShaderConstants.h@> -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) in float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=0) out vec4 _fragColor; @@ -45,13 +45,13 @@ void main(void) { <$fetchMaterialTexturesCoord0(matKey, _texCoord0, albedoTex, roughnessTex, normalTex, _SCRIBE_NULL, emissiveTex)$> <$fetchMaterialTexturesCoord1(matKey, _texCoord1, occlusionTex)$> - float opacity = getMaterialOpacity(mat) * _alpha; + float opacity = getMaterialOpacity(mat) * _color.a; <$evalMaterialOpacity(albedoTex.a, opacity, matKey, opacity)$>; <$discardTransparent(opacity)$>; vec3 albedo = getMaterialAlbedo(mat); <$evalMaterialAlbedo(albedoTex, albedo, matKey, albedo)$>; - albedo *= _color; + albedo *= _color.rgb; float roughness = getMaterialRoughness(mat); <$evalMaterialRoughness(roughnessTex, roughness, matKey, roughness)$>; diff --git a/libraries/render-utils/src/model_translucent_normal_map.slv b/libraries/render-utils/src/model_translucent_normal_map.slv index 257711ac24..299e1f53e1 100644 --- a/libraries/render-utils/src/model_translucent_normal_map.slv +++ b/libraries/render-utils/src/model_translucent_normal_map.slv @@ -21,22 +21,20 @@ <@include render-utils/ShaderConstants.h@> -layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) out vec3 _tangentWS; -layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; void main(void) { - _color = color_sRGBToLinear(inColor.xyz); - _alpha = inColor.w; + _color.rgb = color_sRGBToLinear(inColor.rgb); + _color.a = inColor.a; TexMapArray texMapArray = getTexMapArray(); - <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord0)$> - <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord1)$> + <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord01.xy)$> + <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord01.zw)$> // standard transform TransformCamera cam = getTransformCamera(); diff --git a/libraries/render-utils/src/model_translucent_normal_map_fade.slf b/libraries/render-utils/src/model_translucent_normal_map_fade.slf index d17c5105b1..992993edb3 100644 --- a/libraries/render-utils/src/model_translucent_normal_map_fade.slf +++ b/libraries/render-utils/src/model_translucent_normal_map_fade.slf @@ -32,13 +32,13 @@ <@include render-utils/ShaderConstants.h@> -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) in vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) in float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; layout(location=0) out vec4 _fragColor; @@ -55,13 +55,13 @@ void main(void) { <$fetchMaterialTexturesCoord0(matKey, _texCoord0, albedoTex, roughnessTex, normalTex, _SCRIBE_NULL, emissiveTex)$> <$fetchMaterialTexturesCoord1(matKey, _texCoord1, occlusionTex)$> - float opacity = getMaterialOpacity(mat) * _alpha; + float opacity = getMaterialOpacity(mat) * _color.a; <$evalMaterialOpacity(albedoTex.a, opacity, matKey, opacity)$>; <$discardTransparent(opacity)$>; vec3 albedo = getMaterialAlbedo(mat); <$evalMaterialAlbedo(albedoTex, albedo, matKey, albedo)$>; - albedo *= _color; + albedo *= _color.rgb; float roughness = getMaterialRoughness(mat); <$evalMaterialRoughness(roughnessTex, roughness, matKey, roughness)$>; diff --git a/libraries/render-utils/src/model_translucent_unlit.slf b/libraries/render-utils/src/model_translucent_unlit.slf index eef3190d2b..8f823e010a 100644 --- a/libraries/render-utils/src/model_translucent_unlit.slf +++ b/libraries/render-utils/src/model_translucent_unlit.slf @@ -20,9 +20,10 @@ <@include render-utils/ShaderConstants.h@> -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) in float _alpha; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=0) out vec4 _fragColor; @@ -31,13 +32,13 @@ void main(void) { BITFIELD matKey = getMaterialKey(mat); <$fetchMaterialTexturesCoord0(matKey, _texCoord0, albedoTex)$> - float opacity = getMaterialOpacity(mat) * _alpha; + float opacity = getMaterialOpacity(mat) * _color.a; <$evalMaterialOpacity(albedoTex.a, opacity, matKey, opacity)$>; <$discardTransparent(opacity)$>; vec3 albedo = getMaterialAlbedo(mat); <$evalMaterialAlbedo(albedoTex, albedo, matKey, albedo)$>; - albedo *= _color; + albedo *= _color.rgb; _fragColor = vec4(albedo * isUnlitEnabled(), opacity); } diff --git a/libraries/render-utils/src/model_translucent_unlit_fade.slf b/libraries/render-utils/src/model_translucent_unlit_fade.slf index 4efdd7f4e5..2c72780976 100644 --- a/libraries/render-utils/src/model_translucent_unlit_fade.slf +++ b/libraries/render-utils/src/model_translucent_unlit_fade.slf @@ -23,9 +23,10 @@ <@include render-utils/ShaderConstants.h@> -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) in float _alpha; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; layout(location=0) out vec4 _fragColor; @@ -41,13 +42,13 @@ void main(void) { BITFIELD matKey = getMaterialKey(mat); <$fetchMaterialTexturesCoord0(matKey, _texCoord0, albedoTex)$> - float opacity = getMaterialOpacity(mat) * _alpha; + float opacity = getMaterialOpacity(mat) * _color.a; <$evalMaterialOpacity(albedoTex.a, opacity, matKey, opacity)$>; <$discardTransparent(opacity)$>; vec3 albedo = getMaterialAlbedo(mat); <$evalMaterialAlbedo(albedoTex, albedo, matKey, albedo)$>; - albedo *= _color; + albedo *= _color.rgb; albedo += fadeEmissive; _fragColor = vec4(albedo * isUnlitEnabled(), opacity); } diff --git a/libraries/render-utils/src/model_unlit.slf b/libraries/render-utils/src/model_unlit.slf index e920b3eb67..0e93022b83 100644 --- a/libraries/render-utils/src/model_unlit.slf +++ b/libraries/render-utils/src/model_unlit.slf @@ -20,10 +20,11 @@ <$declareMaterialTextures(ALBEDO)$> -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) in float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; void main(void) { @@ -37,7 +38,7 @@ void main(void) { vec3 albedo = getMaterialAlbedo(mat); <$evalMaterialAlbedo(albedoTex, albedo, matKey, albedo)$>; - albedo *= _color; + albedo *= _color.rgb; packDeferredFragmentUnlit( normalize(_normalWS), diff --git a/libraries/render-utils/src/model_unlit_fade.slf b/libraries/render-utils/src/model_unlit_fade.slf index 30d023da88..1172bd5556 100644 --- a/libraries/render-utils/src/model_unlit_fade.slf +++ b/libraries/render-utils/src/model_unlit_fade.slf @@ -24,10 +24,11 @@ <$declareMaterialTextures(ALBEDO)$> layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) in vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) in float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; void main(void) { vec3 fadeEmissive; @@ -46,7 +47,7 @@ void main(void) { vec3 albedo = getMaterialAlbedo(mat); <$evalMaterialAlbedo(albedoTex, albedo, matKey, albedo)$>; - albedo *= _color; + albedo *= _color.rgb; albedo += fadeEmissive; packDeferredFragmentUnlit( normalize(_normalWS), diff --git a/libraries/render-utils/src/render-utils/ShaderConstants.h b/libraries/render-utils/src/render-utils/ShaderConstants.h index 443e75159d..afb195c240 100644 --- a/libraries/render-utils/src/render-utils/ShaderConstants.h +++ b/libraries/render-utils/src/render-utils/ShaderConstants.h @@ -14,27 +14,28 @@ #ifndef RENDER_UTILS_SHADER_CONSTANTS_H #define RENDER_UTILS_SHADER_CONSTANTS_H -#define RENDER_UTILS_ATTR_TEXCOORD0 0 -#define RENDER_UTILS_ATTR_TEXCOORD1 1 -#define RENDER_UTILS_ATTR_COLOR 2 -#define RENDER_UTILS_ATTR_ALPHA 3 +#define RENDER_UTILS_ATTR_TEXCOORD01 0 +#define RENDER_UTILS_ATTR_COLOR 1 // World space -#define RENDER_UTILS_ATTR_POSITION_WS 4 -#define RENDER_UTILS_ATTR_NORMAL_WS 5 -#define RENDER_UTILS_ATTR_TANGENT_WS 6 +#define RENDER_UTILS_ATTR_POSITION_WS 2 +#define RENDER_UTILS_ATTR_NORMAL_WS 3 +#define RENDER_UTILS_ATTR_TANGENT_WS 4 // Model space -#define RENDER_UTILS_ATTR_POSITION_MS 7 -#define RENDER_UTILS_ATTR_NORMAL_MS 8 +#define RENDER_UTILS_ATTR_POSITION_MS 5 +#define RENDER_UTILS_ATTR_NORMAL_MS 6 // Eye space -#define RENDER_UTILS_ATTR_POSITION_ES 9 +#define RENDER_UTILS_ATTR_POSITION_ES 7 + +// don't conflict with GPU_ATTR_V2F_STEREO_SIDE in the GPU shader constants +#define RENDER_UTILS_ATTR_DO_NOT_USE 8 // Fade -#define RENDER_UTILS_ATTR_FADE1 10 -#define RENDER_UTILS_ATTR_FADE2 11 -#define RENDER_UTILS_ATTR_FADE3 12 +#define RENDER_UTILS_ATTR_FADE1 9 +#define RENDER_UTILS_ATTR_FADE2 10 +#define RENDER_UTILS_ATTR_FADE3 11 #define RENDER_UTILS_BUFFER_DEFERRED_FRAME_TRANSFORM 0 diff --git a/libraries/render-utils/src/sdf_text3D.slf b/libraries/render-utils/src/sdf_text3D.slf index b4be4d1d02..999fb9e1a9 100644 --- a/libraries/render-utils/src/sdf_text3D.slf +++ b/libraries/render-utils/src/sdf_text3D.slf @@ -19,7 +19,9 @@ layout(location=RENDER_UTILS_UNIFORM_TEXT_COLOR) uniform vec4 Color; // the interpolated normal layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; #define TAA_TEXTURE_LOD_BIAS -3.0 diff --git a/libraries/render-utils/src/sdf_text3D.slv b/libraries/render-utils/src/sdf_text3D.slv index fa7ee6d409..04ee44510a 100644 --- a/libraries/render-utils/src/sdf_text3D.slv +++ b/libraries/render-utils/src/sdf_text3D.slv @@ -18,10 +18,10 @@ // the interpolated normal layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; void main() { - _texCoord0 = inTexCoord0.xy; + _texCoord01.xy = inTexCoord0.xy; // standard transform TransformCamera cam = getTransformCamera(); diff --git a/libraries/render-utils/src/sdf_text3D_transparent.slf b/libraries/render-utils/src/sdf_text3D_transparent.slf index 8e8a6db504..fbf4c4c372 100644 --- a/libraries/render-utils/src/sdf_text3D_transparent.slf +++ b/libraries/render-utils/src/sdf_text3D_transparent.slf @@ -19,7 +19,9 @@ layout(location=RENDER_UTILS_UNIFORM_TEXT_COLOR) uniform vec4 Color; // the interpolated normal layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; const float gamma = 2.2; const float smoothing = 32.0; diff --git a/libraries/render-utils/src/simple.slf b/libraries/render-utils/src/simple.slf index ace0afc60d..a699a10cad 100644 --- a/libraries/render-utils/src/simple.slf +++ b/libraries/render-utils/src/simple.slf @@ -20,7 +20,9 @@ layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_NORMAL_MS) in vec3 _normalMS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_POSITION_MS) in vec4 _positionMS; layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; diff --git a/libraries/render-utils/src/simple.slv b/libraries/render-utils/src/simple.slv index f4bd6795e3..0dd4e55f26 100644 --- a/libraries/render-utils/src/simple.slv +++ b/libraries/render-utils/src/simple.slv @@ -23,13 +23,13 @@ layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_NORMAL_MS) out vec3 _normalMS; layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_POSITION_MS) out vec4 _positionMS; layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; void main(void) { _color = color_sRGBAToLinear(inColor); - _texCoord0 = inTexCoord0.st; + _texCoord01.xy = inTexCoord0.st; _positionMS = inPosition; _normalMS = inNormal.xyz; diff --git a/libraries/render-utils/src/simple_fade.slf b/libraries/render-utils/src/simple_fade.slf index c07a608a99..00d81cadc9 100644 --- a/libraries/render-utils/src/simple_fade.slf +++ b/libraries/render-utils/src/simple_fade.slf @@ -23,7 +23,9 @@ layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_NORMAL_MS) in vec3 _normalMS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_POSITION_MS) in vec4 _positionMS; layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; diff --git a/libraries/render-utils/src/simple_fade.slv b/libraries/render-utils/src/simple_fade.slv index 24aada33b9..0bbd8eac39 100644 --- a/libraries/render-utils/src/simple_fade.slv +++ b/libraries/render-utils/src/simple_fade.slv @@ -26,14 +26,14 @@ layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_NORMAL_MS) out vec3 _normalMS; layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_POSITION_MS) out vec4 _positionMS; layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; void main(void) { _color = color_sRGBAToLinear(inColor); - _texCoord0 = inTexCoord0.st; + _texCoord01.xy = inTexCoord0.st; _positionMS = inPosition; _normalMS = inNormal.xyz; diff --git a/libraries/render-utils/src/simple_opaque_web_browser.slf b/libraries/render-utils/src/simple_opaque_web_browser.slf index 3b77fbf431..27a0781eef 100644 --- a/libraries/render-utils/src/simple_opaque_web_browser.slf +++ b/libraries/render-utils/src/simple_opaque_web_browser.slf @@ -23,7 +23,9 @@ layout(binding=0) uniform sampler2D originalTexture; // the interpolated normal layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; void main(void) { vec4 texel = texture(originalTexture, _texCoord0.st); diff --git a/libraries/render-utils/src/simple_textured.slf b/libraries/render-utils/src/simple_textured.slf index c123a9671f..f1a60bdc5a 100644 --- a/libraries/render-utils/src/simple_textured.slf +++ b/libraries/render-utils/src/simple_textured.slf @@ -22,7 +22,9 @@ layout(binding=0) uniform sampler2D originalTexture; // the interpolated normal layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; void main(void) { vec4 texel = texture(originalTexture, _texCoord0); diff --git a/libraries/render-utils/src/simple_textured_fade.slf b/libraries/render-utils/src/simple_textured_fade.slf index 850282d40f..a1476939d1 100644 --- a/libraries/render-utils/src/simple_textured_fade.slf +++ b/libraries/render-utils/src/simple_textured_fade.slf @@ -25,7 +25,9 @@ layout(binding=0) uniform sampler2D originalTexture; // the interpolated normal layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; // Declare after all samplers to prevent sampler location mix up with originalTexture diff --git a/libraries/render-utils/src/simple_textured_unlit.slf b/libraries/render-utils/src/simple_textured_unlit.slf index 78ef85ee21..fcdf118732 100644 --- a/libraries/render-utils/src/simple_textured_unlit.slf +++ b/libraries/render-utils/src/simple_textured_unlit.slf @@ -23,7 +23,9 @@ layout(binding=0) uniform sampler2D originalTexture; // the interpolated normal layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; void main(void) { vec4 texel = texture(originalTexture, _texCoord0.st); diff --git a/libraries/render-utils/src/simple_textured_unlit_fade.slf b/libraries/render-utils/src/simple_textured_unlit_fade.slf index c5882c2173..2007f0f684 100644 --- a/libraries/render-utils/src/simple_textured_unlit_fade.slf +++ b/libraries/render-utils/src/simple_textured_unlit_fade.slf @@ -25,7 +25,9 @@ layout(binding=0) uniform sampler2D originalTexture; // the interpolated normal layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; // Declare after all samplers to prevent sampler location mix up with originalTexture diff --git a/libraries/render-utils/src/simple_transparent.slf b/libraries/render-utils/src/simple_transparent.slf index b52c2a613e..d2ba332566 100644 --- a/libraries/render-utils/src/simple_transparent.slf +++ b/libraries/render-utils/src/simple_transparent.slf @@ -20,7 +20,9 @@ layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_NORMAL_MS) in vec3 _normalMS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_POSITION_MS) in vec4 _positionMS; layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; diff --git a/libraries/render-utils/src/simple_transparent_textured.slf b/libraries/render-utils/src/simple_transparent_textured.slf index b7396c3d37..ffd715215a 100644 --- a/libraries/render-utils/src/simple_transparent_textured.slf +++ b/libraries/render-utils/src/simple_transparent_textured.slf @@ -22,7 +22,9 @@ layout(location=0) uniform sampler2D originalTexture; // the interpolated normal layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; void main(void) { vec4 texel = texture(originalTexture, _texCoord0); diff --git a/libraries/render-utils/src/simple_transparent_textured_fade.slf b/libraries/render-utils/src/simple_transparent_textured_fade.slf index 92c6fde0bd..8e530f41aa 100644 --- a/libraries/render-utils/src/simple_transparent_textured_fade.slf +++ b/libraries/render-utils/src/simple_transparent_textured_fade.slf @@ -31,7 +31,9 @@ layout(binding=0) uniform sampler2D originalTexture; layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; // Declare after all samplers to prevent sampler location mix up with originalTexture diff --git a/libraries/render-utils/src/simple_transparent_textured_unlit.slf b/libraries/render-utils/src/simple_transparent_textured_unlit.slf index a3e7c65cd1..d05ca02560 100644 --- a/libraries/render-utils/src/simple_transparent_textured_unlit.slf +++ b/libraries/render-utils/src/simple_transparent_textured_unlit.slf @@ -20,7 +20,9 @@ layout(binding=0) uniform sampler2D originalTexture; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=0) out vec4 _fragColor0; diff --git a/libraries/render-utils/src/simple_transparent_textured_unlit_fade.slf b/libraries/render-utils/src/simple_transparent_textured_unlit_fade.slf index 508ea9a68b..53006b508d 100644 --- a/libraries/render-utils/src/simple_transparent_textured_unlit_fade.slf +++ b/libraries/render-utils/src/simple_transparent_textured_unlit_fade.slf @@ -22,7 +22,9 @@ layout(binding=0) uniform sampler2D originalTexture; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; layout(location=0) out vec4 _fragColor0; diff --git a/libraries/render-utils/src/simple_transparent_web_browser.slf b/libraries/render-utils/src/simple_transparent_web_browser.slf index 3f05a8a480..156339b702 100644 --- a/libraries/render-utils/src/simple_transparent_web_browser.slf +++ b/libraries/render-utils/src/simple_transparent_web_browser.slf @@ -23,7 +23,9 @@ layout(binding=0) uniform sampler2D originalTexture; // the interpolated normal layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) in vec2 _texCoord0; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; +vec2 _texCoord0 = _texCoord01.xy; +vec2 _texCoord1 = _texCoord01.zw; void main(void) { vec4 texel = texture(originalTexture, _texCoord0.st); diff --git a/libraries/render-utils/src/skin_model.slv b/libraries/render-utils/src/skin_model.slv index fb2f8a8e34..d44ca0ae3f 100644 --- a/libraries/render-utils/src/skin_model.slv +++ b/libraries/render-utils/src/skin_model.slv @@ -26,11 +26,9 @@ <@include render-utils/ShaderConstants.h@> layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; void main(void) { vec4 position = vec4(0.0, 0.0, 0.0, 0.0); @@ -39,12 +37,12 @@ void main(void) { skinPositionNormal(inSkinClusterIndex, inSkinClusterWeight, inPosition, inNormal.xyz, position, interpolatedNormal); // pass along the color - _color = color_sRGBToLinear(inColor.rgb); - _alpha = inColor.a; + _color.rgb = color_sRGBToLinear(inColor.rgb); + _color.a = inColor.a; TexMapArray texMapArray = getTexMapArray(); - <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord0)$> - <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord1)$> + <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord01.xy)$> + <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord01.zw)$> // standard transform TransformCamera cam = getTransformCamera(); diff --git a/libraries/render-utils/src/skin_model_dq.slv b/libraries/render-utils/src/skin_model_dq.slv index db062087be..ff73c7a398 100644 --- a/libraries/render-utils/src/skin_model_dq.slv +++ b/libraries/render-utils/src/skin_model_dq.slv @@ -26,11 +26,9 @@ <@include render-utils/ShaderConstants.h@> layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; void main(void) { vec4 position = vec4(0.0, 0.0, 0.0, 0.0); @@ -39,12 +37,12 @@ void main(void) { skinPositionNormal(inSkinClusterIndex, inSkinClusterWeight, inPosition, inNormal.xyz, position, interpolatedNormal); // pass along the color - _color = color_sRGBToLinear(inColor.rgb); - _alpha = inColor.a; + _color.rgb = color_sRGBToLinear(inColor.rgb); + _color.a = inColor.a; TexMapArray texMapArray = getTexMapArray(); - <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord0)$> - <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord1)$> + <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord01.xy)$> + <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord01.zw)$> // standard transform TransformCamera cam = getTransformCamera(); diff --git a/libraries/render-utils/src/skin_model_fade.slv b/libraries/render-utils/src/skin_model_fade.slv index 30b3122334..1689476d38 100644 --- a/libraries/render-utils/src/skin_model_fade.slv +++ b/libraries/render-utils/src/skin_model_fade.slv @@ -26,11 +26,9 @@ <@include render-utils/ShaderConstants.h@> layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; void main(void) { @@ -40,12 +38,12 @@ void main(void) { skinPositionNormal(inSkinClusterIndex, inSkinClusterWeight, inPosition, inNormal.xyz, position, interpolatedNormal); // pass along the color - _color = color_sRGBToLinear(inColor.rgb); - _alpha = inColor.a; + _color.rgb = color_sRGBToLinear(inColor.rgb); + _color.a = inColor.a; TexMapArray texMapArray = getTexMapArray(); - <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord0)$> - <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord1)$> + <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord01.xy)$> + <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord01.zw)$> // standard transform TransformCamera cam = getTransformCamera(); diff --git a/libraries/render-utils/src/skin_model_fade_dq.slv b/libraries/render-utils/src/skin_model_fade_dq.slv index fb23e283bc..6e64305de7 100644 --- a/libraries/render-utils/src/skin_model_fade_dq.slv +++ b/libraries/render-utils/src/skin_model_fade_dq.slv @@ -26,11 +26,9 @@ <@include render-utils/ShaderConstants.h@> layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; -layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; void main(void) { @@ -40,12 +38,12 @@ void main(void) { skinPositionNormal(inSkinClusterIndex, inSkinClusterWeight, inPosition, inNormal.xyz, position, interpolatedNormal); // pass along the color - _color = color_sRGBToLinear(inColor.rgb); - _alpha = inColor.a; + _color.rgb = color_sRGBToLinear(inColor.rgb); + _color.a = inColor.a; TexMapArray texMapArray = getTexMapArray(); - <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord0)$> - <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord1)$> + <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord01.xy)$> + <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord01.zw)$> // standard transform TransformCamera cam = getTransformCamera(); diff --git a/libraries/render-utils/src/skin_model_normal_map.slv b/libraries/render-utils/src/skin_model_normal_map.slv index 288e338b10..f67220c6bd 100644 --- a/libraries/render-utils/src/skin_model_normal_map.slv +++ b/libraries/render-utils/src/skin_model_normal_map.slv @@ -26,12 +26,10 @@ <@include render-utils/ShaderConstants.h@> layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) out vec3 _tangentWS; -layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; void main(void) { vec4 position = vec4(0.0, 0.0, 0.0, 0.0); @@ -41,12 +39,12 @@ void main(void) { skinPositionNormalTangent(inSkinClusterIndex, inSkinClusterWeight, inPosition, inNormal.xyz, inTangent.xyz, position, interpolatedNormal.xyz, interpolatedTangent.xyz); // pass along the color - _color = color_sRGBToLinear(inColor.rgb); - _alpha = inColor.a; + _color.rgb = color_sRGBToLinear(inColor.rgb); + _color.a = inColor.a; TexMapArray texMapArray = getTexMapArray(); - <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord0)$> - <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord1)$> + <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord01.xy)$> + <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord01.zw)$> interpolatedNormal = vec4(normalize(interpolatedNormal.xyz), 0.0); interpolatedTangent = vec4(normalize(interpolatedTangent.xyz), 0.0); diff --git a/libraries/render-utils/src/skin_model_normal_map_dq.slv b/libraries/render-utils/src/skin_model_normal_map_dq.slv index 90e85f8a92..b5ffbdc49d 100644 --- a/libraries/render-utils/src/skin_model_normal_map_dq.slv +++ b/libraries/render-utils/src/skin_model_normal_map_dq.slv @@ -25,12 +25,10 @@ <$declareMaterialTexMapArrayBuffer()$> layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) out vec3 _tangentWS; -layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; void main(void) { vec4 position = vec4(0.0, 0.0, 0.0, 0.0); @@ -40,12 +38,12 @@ void main(void) { skinPositionNormalTangent(inSkinClusterIndex, inSkinClusterWeight, inPosition, inNormal.xyz, inTangent.xyz, position, interpolatedNormal.xyz, interpolatedTangent.xyz); // pass along the color - _color = color_sRGBToLinear(inColor.rgb); - _alpha = inColor.a; + _color.rgb = color_sRGBToLinear(inColor.rgb); + _color.a = inColor.a; TexMapArray texMapArray = getTexMapArray(); - <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord0)$> - <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord1)$> + <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord01.xy)$> + <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord01.zw)$> interpolatedNormal = vec4(normalize(interpolatedNormal.xyz), 0.0); interpolatedTangent = vec4(normalize(interpolatedTangent.xyz), 0.0); diff --git a/libraries/render-utils/src/skin_model_normal_map_fade.slv b/libraries/render-utils/src/skin_model_normal_map_fade.slv index 393a756e7e..5759416d44 100644 --- a/libraries/render-utils/src/skin_model_normal_map_fade.slv +++ b/libraries/render-utils/src/skin_model_normal_map_fade.slv @@ -26,12 +26,10 @@ <@include render-utils/ShaderConstants.h@> layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) out vec3 _tangentWS; -layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; void main(void) { @@ -42,12 +40,12 @@ void main(void) { skinPositionNormalTangent(inSkinClusterIndex, inSkinClusterWeight, inPosition, inNormal.xyz, inTangent.xyz, position, interpolatedNormal.xyz, interpolatedTangent.xyz); // pass along the color - _color = color_sRGBToLinear(inColor.rgb); - _alpha = inColor.a; + _color.rgb = color_sRGBToLinear(inColor.rgb); + _color.a = inColor.a; TexMapArray texMapArray = getTexMapArray(); - <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord0)$> - <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord1)$> + <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord01.xy)$> + <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord01.zw)$> interpolatedNormal = vec4(normalize(interpolatedNormal.xyz), 0.0); interpolatedTangent = vec4(normalize(interpolatedTangent.xyz), 0.0); diff --git a/libraries/render-utils/src/skin_model_normal_map_fade_dq.slv b/libraries/render-utils/src/skin_model_normal_map_fade_dq.slv index 862c14297f..e48bf47758 100644 --- a/libraries/render-utils/src/skin_model_normal_map_fade_dq.slv +++ b/libraries/render-utils/src/skin_model_normal_map_fade_dq.slv @@ -26,12 +26,10 @@ <@include render-utils/ShaderConstants.h@> layout(location=RENDER_UTILS_ATTR_POSITION_ES) out vec4 _positionES; -layout(location=RENDER_UTILS_ATTR_TEXCOORD0) out vec2 _texCoord0; -layout(location=RENDER_UTILS_ATTR_TEXCOORD1) out vec2 _texCoord1; +layout(location=RENDER_UTILS_ATTR_TEXCOORD01) out vec4 _texCoord01; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) out vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) out vec3 _tangentWS; -layout(location=RENDER_UTILS_ATTR_COLOR) out vec3 _color; -layout(location=RENDER_UTILS_ATTR_ALPHA) out float _alpha; +layout(location=RENDER_UTILS_ATTR_COLOR) out vec4 _color; layout(location=RENDER_UTILS_ATTR_POSITION_WS) out vec4 _positionWS; void main(void) { @@ -42,12 +40,12 @@ void main(void) { skinPositionNormalTangent(inSkinClusterIndex, inSkinClusterWeight, inPosition, inNormal.xyz, inTangent.xyz, position, interpolatedNormal.xyz, interpolatedTangent.xyz); // pass along the color - _color = color_sRGBToLinear(inColor.rgb); - _alpha = inColor.a; + _color.rgb = color_sRGBToLinear(inColor.rgb); + _color.a = inColor.a; TexMapArray texMapArray = getTexMapArray(); - <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord0)$> - <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord1)$> + <$evalTexMapArrayTexcoord0(texMapArray, inTexCoord0, _texCoord01.xy)$> + <$evalTexMapArrayTexcoord1(texMapArray, inTexCoord0, _texCoord01.zw)$> interpolatedNormal = vec4(normalize(interpolatedNormal.xyz), 0.0); interpolatedTangent = vec4(normalize(interpolatedTangent.xyz), 0.0); diff --git a/libraries/shaders/CMakeLists.txt b/libraries/shaders/CMakeLists.txt index d27dacc769..4f6db48c08 100644 --- a/libraries/shaders/CMakeLists.txt +++ b/libraries/shaders/CMakeLists.txt @@ -189,5 +189,5 @@ foreach(COMPILED_SHADER ${COMPILED_SHADERS}) set_property(TARGET ${TARGET_NAME} APPEND PROPERTY AUTOGEN_TARGET_DEPENDS "${COMPILED_SHADER}") endforeach() -link_hifi_libraries(shared) +link_hifi_libraries(shared gl) diff --git a/libraries/shaders/src/shaders/Shaders.cpp b/libraries/shaders/src/shaders/Shaders.cpp index 50a7d38a69..ac4810a896 100644 --- a/libraries/shaders/src/shaders/Shaders.cpp +++ b/libraries/shaders/src/shaders/Shaders.cpp @@ -17,6 +17,19 @@ #include #include #include +#include + +#include + +static bool cleanShaders() { +#if defined(Q_OS_MAC) + static const bool CLEAN_SHADERS = true; +#else + static const bool CLEAN_SHADERS = ::gl::disableGl45(); + +#endif + return CLEAN_SHADERS; +} // Can't use the Q_INIT_RESOURCE macro inside a namespace on Mac, // so this is done out of line @@ -74,14 +87,14 @@ void cleanShaderSource(std::string& shaderSource) { std::string loadShaderSource(uint32_t shaderId) { initShaders(); auto shaderStr = loadResource(std::string(":/shaders/") + std::to_string(shaderId)); -#if defined(Q_OS_MAC) - // OSX only supports OpenGL 4.1 without ARB_shading_language_420pack or - // ARB_explicit_uniform_location or basically anything useful that's - // been released in the last 8 fucking years, so in that case we need to - // strip out all explicit locations and do a bunch of background magic to - // make the system seem like it is using the explicit locations - cleanShaderSource(shaderStr); -#endif + if (cleanShaders()) { + // OSX only supports OpenGL 4.1 without ARB_shading_language_420pack or + // ARB_explicit_uniform_location or basically anything useful that's + // been released in the last 8 fucking years, so in that case we need to + // strip out all explicit locations and do a bunch of background magic to + // make the system seem like it is using the explicit locations + cleanShaderSource(shaderStr); + } return shaderStr; } diff --git a/libraries/ui/src/ui/OffscreenQmlSurface.cpp b/libraries/ui/src/ui/OffscreenQmlSurface.cpp index 48e778c063..b242d90d0e 100644 --- a/libraries/ui/src/ui/OffscreenQmlSurface.cpp +++ b/libraries/ui/src/ui/OffscreenQmlSurface.cpp @@ -426,11 +426,17 @@ PointerEvent::EventType OffscreenQmlSurface::choosePointerEventType(QEvent::Type } void OffscreenQmlSurface::hoverBeginEvent(const PointerEvent& event, class QTouchDevice& device) { +#if defined(DISABLE_QML) + return; +#endif handlePointerEvent(event, device); _activeTouchPoints[event.getID()].hovering = true; } void OffscreenQmlSurface::hoverEndEvent(const PointerEvent& event, class QTouchDevice& device) { +#if defined(DISABLE_QML) + return; +#endif _activeTouchPoints[event.getID()].hovering = false; // Send a fake mouse move event if // - the event told us to @@ -444,6 +450,10 @@ void OffscreenQmlSurface::hoverEndEvent(const PointerEvent& event, class QTouchD } bool OffscreenQmlSurface::handlePointerEvent(const PointerEvent& event, class QTouchDevice& device, bool release) { +#if defined(DISABLE_QML) + return false; +#endif + // Ignore mouse interaction if we're paused if (!getRootItem() || isPaused()) { return false; diff --git a/tests-manual/render-utils/src/main.cpp b/tests-manual/render-utils/src/main.cpp index b5bc5daebb..63f56e77ed 100644 --- a/tests-manual/render-utils/src/main.cpp +++ b/tests-manual/render-utils/src/main.cpp @@ -94,16 +94,9 @@ public: QTestWindow() { setSurfaceType(QSurface::OpenGLSurface); - QSurfaceFormat format; - // Qt Quick may need a depth and stencil buffer. Always make sure these are available. - format.setDepthBufferSize(16); - format.setStencilBufferSize(8); - setGLFormatVersion(format); - format.setProfile(QSurfaceFormat::OpenGLContextProfile::CoreProfile); + QSurfaceFormat format = getDefaultOpenGLSurfaceFormat(); format.setOption(QSurfaceFormat::DebugContext); - setFormat(format); - _context.setFormat(format); _context.create(); diff --git a/tests/shaders/src/ShaderTests.cpp b/tests/shaders/src/ShaderTests.cpp index dffd69054d..f7d8222de1 100644 --- a/tests/shaders/src/ShaderTests.cpp +++ b/tests/shaders/src/ShaderTests.cpp @@ -47,15 +47,34 @@ void ShaderTests::cleanupTestCase() { qDebug() << "Done"; } -template -QStringList toStringList(const C& c, F f) { +template +QStringList toQStringList(const C& c) { QStringList result; for (const auto& v : c) { - result << f(v); + result << v.c_str(); } return result; } +template +std::unordered_set toStringSet(const C& c, F f) { + std::unordered_set result; + for (const auto& v : c) { + result.insert(f(v)); + } + return result; +} + +template +bool isSubset(const C& parent, const C& child) { + for (const auto& v : child) { + if (0 == parent.count(v)) { + return false; + } + } + return true; +} + gpu::Shader::ReflectionMap mergeReflection(const std::initializer_list& list) { gpu::Shader::ReflectionMap result; std::unordered_map> usedLocationsByType; @@ -87,6 +106,77 @@ gpu::Shader::ReflectionMap mergeReflection(const std::initializer_list +std::unordered_map invertMap(const std::unordered_map& map) { + std::unordered_map result; + for (const auto& entry : map) { + result[entry.second] = entry.first; + } + return result; +} + +static void verifyBindings(const gpu::Shader::Source& source) { + const auto reflection = source.getReflection(); + for (const auto& entry : reflection) { + const auto& map = entry.second; + const auto reverseMap = invertMap(map); + if (map.size() != reverseMap.size()) { + QFAIL("Bindings are not unique"); + } + } + +} + + +static void verifyInterface(const gpu::Shader::Source& vertexSource, const gpu::Shader::Source& fragmentSource) { + if (0 == fragmentSource.getReflection().count(gpu::Shader::BindingType::INPUT)) { + return; + } + auto fragIn = fragmentSource.getReflection().at(gpu::Shader::BindingType::INPUT); + if (0 == vertexSource.getReflection().count(gpu::Shader::BindingType::OUTPUT)) { + qDebug() << "No vertex output for fragment input"; + //QFAIL("No vertex output for fragment input"); + return; + } + auto vout = vertexSource.getReflection().at(gpu::Shader::BindingType::OUTPUT); + auto vrev = invertMap(vout); + static const std::string IN_STEREO_SIDE_STRING = "_inStereoSide"; + for (const auto entry : fragIn) { + const auto& name = entry.first; + // The presence of "_inStereoSide" in fragment shaders is a bug due to the way we do reflection + // and use preprocessor macros in the shaders + if (name == IN_STEREO_SIDE_STRING) { + continue; + } + if (0 == vout.count(name)) { + qDebug() << "Vertex output missing"; + //QFAIL("Vertex output missing"); + continue; + } + const auto& inLocation = entry.second; + const auto& outLocation = vout.at(name); + if (inLocation != outLocation) { + qDebug() << "Mismatch in vertex / fragment interface"; + //QFAIL("Mismatch in vertex / fragment interface"); + continue; + } + } +} + +template +bool compareBindings(const C& actual, const gpu::Shader::LocationMap& expected) { + if (actual.size() != expected.size()) { + auto actualNames = toStringSet(actual, [](const auto& v) { return v.name; }); + auto expectedNames = toStringSet(expected, [](const auto& v) { return v.first; }); + if (!isSubset(expectedNames, actualNames)) { + qDebug() << "Found" << toQStringList(actualNames); + qDebug() << "Expected" << toQStringList(expectedNames); + return false; + } + } + return true; +} + void ShaderTests::testShaderLoad() { std::set usedShaders; uint32_t maxShader = 0; @@ -97,16 +187,17 @@ void ShaderTests::testShaderLoad() { ++index; uint32_t vertexId = shader::getVertexId(programId); - //QVERIFY(0 != vertexId); uint32_t fragmentId = shader::getFragmentId(programId); - QVERIFY(0 != fragmentId); usedShaders.insert(vertexId); usedShaders.insert(fragmentId); maxShader = std::max(maxShader, std::max(fragmentId, vertexId)); auto vertexSource = gpu::Shader::getShaderSource(vertexId); QVERIFY(!vertexSource.getCode().empty()); + verifyBindings(vertexSource); auto fragmentSource = gpu::Shader::getShaderSource(fragmentId); QVERIFY(!fragmentSource.getCode().empty()); + verifyBindings(fragmentSource); + verifyInterface(vertexSource, fragmentSource); auto expectedBindings = mergeReflection({ vertexSource, fragmentSource }); @@ -124,16 +215,11 @@ void ShaderTests::testShaderLoad() { // Uniforms { - -#ifdef Q_OS_MAC - const auto& uniformRemap = shaderObject.uniformRemap; -#endif auto uniforms = gl::Uniform::load(program); + const auto& uniformRemap = shaderObject.uniformRemap; auto expectedUniforms = expectedBindings[gpu::Shader::BindingType::UNIFORM]; - if (uniforms.size() != expectedUniforms.size()) { - qDebug() << "Found" << toStringList(uniforms, [](const auto& v) { return v.name.c_str(); }); - qDebug() << "Expected" << toStringList(expectedUniforms, [](const auto& v) { return v.first.c_str(); }); - qDebug() << "Uniforms size mismatch"; + if (!compareBindings(uniforms, expectedUniforms)) { + qDebug() << "Uniforms mismatch"; } for (const auto& uniform : uniforms) { if (0 != expectedUniforms.count(uniform.name)) { @@ -152,10 +238,8 @@ void ShaderTests::testShaderLoad() { { const auto textures = gl::Uniform::loadTextures(program); const auto expectedTextures = expectedBindings[gpu::Shader::BindingType::TEXTURE]; - if (textures.size() != expectedTextures.size()) { - qDebug() << "Found" << toStringList(textures, [](const auto& v) { return v.name.c_str(); }); - qDebug() << "Expected" << toStringList(expectedTextures, [](const auto& v) { return v.first.c_str(); }); - qDebug() << "Uniforms size mismatch"; + if (!compareBindings(textures, expectedTextures)) { + qDebug() << "Textures mismatch"; } for (const auto& texture : textures) { if (0 != expectedTextures.count(texture.name)) { @@ -172,10 +256,8 @@ void ShaderTests::testShaderLoad() { { auto ubos = gl::UniformBlock::load(program); auto expectedUbos = expectedBindings[gpu::Shader::BindingType::UNIFORM_BUFFER]; - if (ubos.size() != expectedUbos.size()) { - qDebug() << "Found" << toStringList(ubos, [](const auto& v) { return v.name.c_str(); }); - qDebug() << "Expected" << toStringList(expectedUbos, [](const auto& v) { return v.first.c_str(); }); - qDebug() << "UBOs size mismatch"; + if (!compareBindings(ubos, expectedUbos)) { + qDebug() << "UBOs mismatch"; } for (const auto& ubo : ubos) { if (0 != expectedUbos.count(ubo.name)) { diff --git a/tools/shreflect/src/main.cpp b/tools/shreflect/src/main.cpp index b95b36fd94..e13f937102 100644 --- a/tools/shreflect/src/main.cpp +++ b/tools/shreflect/src/main.cpp @@ -130,6 +130,7 @@ json reflectShader(const std::string& shaderPath) { json inputs; json outputs; json textures; + json textureTypes; json uniforms; json storageBuffers; json uniformBuffers; @@ -148,8 +149,12 @@ json reflectShader(const std::string& shaderPath) { if (m[DECL_SIMPLE].matched) { auto name = m[SIMPLE_NAME].str(); auto type = m[SIMPLE_TYPE].str(); - auto& map = 0 == type.find("sampler") ? textures : uniforms; + bool isTexture = 0 == type.find("sampler"); + auto& map = isTexture ? textures : uniforms; map[name] = binding; + if (isTexture) { + textureTypes[name] = type; + } } else if (m[DECL_STRUCT].matched) { auto name = m[STRUCT_NAME].str(); auto type = m[STRUCT_TYPE].str(); @@ -173,6 +178,9 @@ json reflectShader(const std::string& shaderPath) { if (!textures.empty()) { result["textures"] = textures; } + if (!textureTypes.empty()) { + result["texturesTypes"] = textureTypes; + } if (!uniforms.empty()) { result["uniforms"] = uniforms; } From 9bebd1e6232e1b8bdcf7b32356c394fb4d429039 Mon Sep 17 00:00:00 2001 From: Dante Ruiz Date: Fri, 3 Aug 2018 18:11:55 -0700 Subject: [PATCH 30/37] making changes --- .../qml/hifi/tablet/ControllerSettings.qml | 2 +- interface/src/ui/PreferencesDialog.cpp | 38 +------------------ 2 files changed, 2 insertions(+), 38 deletions(-) diff --git a/interface/resources/qml/hifi/tablet/ControllerSettings.qml b/interface/resources/qml/hifi/tablet/ControllerSettings.qml index 0a45feb61f..135c1379e2 100644 --- a/interface/resources/qml/hifi/tablet/ControllerSettings.qml +++ b/interface/resources/qml/hifi/tablet/ControllerSettings.qml @@ -299,7 +299,7 @@ Item { anchors.fill: stackView id: controllerPrefereneces objectName: "TabletControllerPreferences" - showCategories: [( (HMD.active) ? "VR Movement" : "Movement"), "Game Controller", "Sixense Controllers", "Perception Neuron", "Leap Motion"] + showCategories: ["VR Movement", "Game Controller", "Sixense Controllers", "Perception Neuron", "Leap Motion"] categoryProperties: { "VR Movement" : { "User real-world height (meters)" : { "anchors.right" : "undefined" }, diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp index 50a4d17cae..682dad74e8 100644 --- a/interface/src/ui/PreferencesDialog.cpp +++ b/interface/src/ui/PreferencesDialog.cpp @@ -266,42 +266,6 @@ void setupPreferences() { preferences->addPreference(new SliderPreference(FACE_TRACKING, "Eye Deflection", getter, setter)); } - static const QString MOVEMENT{ "Movement" }; - { - - static const QString movementsControlChannel = QStringLiteral("Hifi-Advanced-Movement-Disabler"); - auto getter = [=]()->bool { return myAvatar->useAdvancedMovementControls(); }; - auto setter = [=](bool value) { myAvatar->setUseAdvancedMovementControls(value); }; - preferences->addPreference(new CheckPreference(MOVEMENT, - QStringLiteral("Advanced movement for hand controllers"), - getter, setter)); - } - { - auto getter = [=]()->int { return myAvatar->getSnapTurn() ? 0 : 1; }; - auto setter = [=](int value) { myAvatar->setSnapTurn(value == 0); }; - auto preference = new RadioButtonsPreference(MOVEMENT, "Snap turn / Smooth turn", getter, setter); - QStringList items; - items << "Snap turn" << "Smooth turn"; - preference->setItems(items); - preferences->addPreference(preference); - } - { - auto getter = [=]()->float { return myAvatar->getUserHeight(); }; - auto setter = [=](float value) { myAvatar->setUserHeight(value); }; - auto preference = new SpinnerPreference(MOVEMENT, "User real-world height (meters)", getter, setter); - preference->setMin(1.0f); - preference->setMax(2.2f); - preference->setDecimals(3); - preference->setStep(0.001f); - preferences->addPreference(preference); - } - { - auto preference = new ButtonPreference(MOVEMENT, "RESET SENSORS", [] { - qApp->resetSensors(); - }); - preferences->addPreference(preference); - } - static const QString VR_MOVEMENT{ "VR Movement" }; { @@ -315,7 +279,7 @@ void setupPreferences() { { auto getter = [=]()->bool { return myAvatar->getFlyingHMDPref(); }; auto setter = [=](bool value) { myAvatar->setFlyingHMDPref(value); }; - preferences->addPreference(new CheckPreference(VR_MOVEMENT, "Flying & jumping", getter, setter)); + preferences->addPreference(new CheckPreference(VR_MOVEMENT, "Flying & jumping (HMD)", getter, setter)); } { auto getter = [=]()->int { return myAvatar->getSnapTurn() ? 0 : 1; }; From e6fb2a9e15a4454aaf9716d0918a1a3207e9858d Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Fri, 3 Aug 2018 21:57:53 -0700 Subject: [PATCH 31/37] Add scribe source files to project --- cmake/macros/AutoScribeShader.cmake | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/cmake/macros/AutoScribeShader.cmake b/cmake/macros/AutoScribeShader.cmake index 03eaa2842f..fec51fefc7 100755 --- a/cmake/macros/AutoScribeShader.cmake +++ b/cmake/macros/AutoScribeShader.cmake @@ -200,14 +200,17 @@ macro(AUTOSCRIBE_SHADER_FINISH) endforeach() if (DEFINED SHADER_HEADERS) - source_group("Shaders/${SHADER_LIB}/Headers" FILES ${SHADER_HEADERS}) + list(REMOVE_DUPLICATES SHADER_HEADERS) + source_group("${SHADER_LIB}/Headers" FILES ${SHADER_HEADERS}) list(APPEND ALL_SHADER_HEADERS ${SHADER_HEADERS}) + list(APPEND ALL_SCRIBE_SHADERS ${SHADER_HEADERS}) endif() string(CONCAT SHADER_ENUMS "${SHADER_ENUMS}" "namespace ${SHADER_NAMESPACE} {\n") if (DEFINED VERTEX_SHADERS) list(REMOVE_DUPLICATES VERTEX_SHADERS) - source_group("Shaders/${SHADER_LIB}/Vertex" FILES ${VERTEX_SHADERS}) + source_group("${SHADER_LIB}/Vertex" FILES ${VERTEX_SHADERS}) + list(APPEND ALL_SCRIBE_SHADERS ${VERTEX_SHADERS}) string(CONCAT SHADER_ENUMS "${SHADER_ENUMS}" "namespace vertex { enum {\n") foreach(SHADER ${VERTEX_SHADERS}) process_shader_file() @@ -217,7 +220,8 @@ macro(AUTOSCRIBE_SHADER_FINISH) if (DEFINED FRAGMENT_SHADERS) list(REMOVE_DUPLICATES FRAGMENT_SHADERS) - source_group("Shaders/${SHADER_LIB}/Fragment" FILES ${FRAGMENT_SHADERS}) + source_group("${SHADER_LIB}/Fragment" FILES ${FRAGMENT_SHADERS}) + list(APPEND ALL_SCRIBE_SHADERS ${FRAGMENT_SHADERS}) string(CONCAT SHADER_ENUMS "${SHADER_ENUMS}" "namespace fragment { enum {\n") foreach(SHADER ${FRAGMENT_SHADERS}) process_shader_file() @@ -266,8 +270,10 @@ macro(AUTOSCRIBE_SHADER_FINISH) endforeach() # Custom targets required to force generation of the shaders via scribe + add_custom_target(scribe_shaders SOURCES ${ALL_SCRIBE_SHADERS}) add_custom_target(compiled_shaders SOURCES ${COMPILED_SHADERS}) add_custom_target(reflected_shaders SOURCES ${COMPILED_SHADER_REFLECTIONS}) + set_target_properties(scribe_shaders PROPERTIES FOLDER "Shaders") set_target_properties(compiled_shaders PROPERTIES FOLDER "Shaders") set_target_properties(reflected_shaders PROPERTIES FOLDER "Shaders") From 2121e201d56a31183e42ca679b1ff61c613f7f0c Mon Sep 17 00:00:00 2001 From: Ken Cooke Date: Sat, 4 Aug 2018 20:09:27 -0700 Subject: [PATCH 32/37] fix assert when azimuth is negative subnormal --- libraries/audio/src/AudioHRTF.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/libraries/audio/src/AudioHRTF.cpp b/libraries/audio/src/AudioHRTF.cpp index c0751c6a20..7349a8ac41 100644 --- a/libraries/audio/src/AudioHRTF.cpp +++ b/libraries/audio/src/AudioHRTF.cpp @@ -919,6 +919,9 @@ static void azimuthToIndex(float azimuth, int& index0, int& index1, float& frac) index1 = index0 + 1; frac = azimuth - (float)index0; + if (index0 >= HRTF_AZIMUTHS) { + index0 -= HRTF_AZIMUTHS; + } if (index1 >= HRTF_AZIMUTHS) { index1 -= HRTF_AZIMUTHS; } From 496724f0db5a5c668afc7f924cbfe430a50de631 Mon Sep 17 00:00:00 2001 From: Ken Cooke Date: Sat, 4 Aug 2018 20:15:04 -0700 Subject: [PATCH 33/37] formatting cleanup --- libraries/audio/src/AudioHRTF.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/audio/src/AudioHRTF.cpp b/libraries/audio/src/AudioHRTF.cpp index 7349a8ac41..23adcde0c5 100644 --- a/libraries/audio/src/AudioHRTF.cpp +++ b/libraries/audio/src/AudioHRTF.cpp @@ -840,7 +840,7 @@ static void nearFieldGainCorrection(float azimuth, float distance, float& gainL, // normalized distance factor = [0,1] as distance = [HRTF_NEARFIELD_MAX,HRTF_HEAD_RADIUS] assert(distance < HRTF_NEARFIELD_MAX); assert(distance > HRTF_HEAD_RADIUS); - float d = (HRTF_NEARFIELD_MAX - distance) * ( 1.0f / (HRTF_NEARFIELD_MAX - HRTF_HEAD_RADIUS)); + float d = (HRTF_NEARFIELD_MAX - distance) * (1.0f / (HRTF_NEARFIELD_MAX - HRTF_HEAD_RADIUS)); // angle of incidence at each ear float angleL = azimuth + HALFPI; From a0ef0c0b137ed94e516d9469e73b5a044ab70026 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Mon, 6 Aug 2018 10:31:14 -0700 Subject: [PATCH 34/37] Fix procedurals --- libraries/procedural/src/procedural/Procedural.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/libraries/procedural/src/procedural/Procedural.cpp b/libraries/procedural/src/procedural/Procedural.cpp index 09e30eab2e..79c0b31dff 100644 --- a/libraries/procedural/src/procedural/Procedural.cpp +++ b/libraries/procedural/src/procedural/Procedural.cpp @@ -119,6 +119,11 @@ void Procedural::setProceduralData(const ProceduralData& proceduralData) { _dirty = true; _enabled = false; + if (proceduralData.version != _data.version ) { + _data.version = proceduralData.version; + _shaderDirty = true; + } + if (proceduralData.uniforms != _data.uniforms) { _data.uniforms = proceduralData.uniforms; _uniformsDirty = true; From 2cd01ad1899c5f483fe391331e0d2fbebb92a719 Mon Sep 17 00:00:00 2001 From: "Anthony J. Thibault" Date: Mon, 6 Aug 2018 11:15:43 -0700 Subject: [PATCH 35/37] Added readme and size field to avatar data packet dissector --- tools/dissectors/3-hf-avatar.lua | 13 +++++++++++++ tools/dissectors/README.md | 14 ++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 tools/dissectors/README.md diff --git a/tools/dissectors/3-hf-avatar.lua b/tools/dissectors/3-hf-avatar.lua index af648ed5b9..0fa551c6f8 100644 --- a/tools/dissectors/3-hf-avatar.lua +++ b/tools/dissectors/3-hf-avatar.lua @@ -19,6 +19,8 @@ local f_avatar_data_valid_rotations = ProtoField.string("hf_avatar.avatar_data_v local f_avatar_data_valid_translations = ProtoField.string("hf_avatar.avatar_data_valid_translations", "Valid Translations") local f_avatar_data_default_rotations = ProtoField.string("hf_avatar.avatar_data_default_rotations", "Valid Default") local f_avatar_data_default_translations = ProtoField.string("hf_avatar.avatar_data_default_translations", "Valid Default") +local f_avatar_data_sizes = ProtoField.string("hf_avatar.avatar_sizes", "Sizes") + p_hf_avatar.fields = { f_avatar_id, f_avatar_data_parent_id @@ -110,6 +112,9 @@ function add_avatar_data_subtrees(avatar_data) if avatar_data["default_translations"] then avatar_subtree:add(f_avatar_data_default_translations, avatar_data["default_translations"]) end + if avatar_data["sizes"] then + avatar_subtree:add(f_avatar_data_sizes, avatar_data["sizes"]) + end end function decode_vec3(buf) @@ -154,6 +159,8 @@ function decode_avatar_data_packet(buf) local i = 0 local result = {} + result["sizes"] = "" + -- uint16 has_flags local has_flags = buf(i, 2):le_uint() i = i + 2 @@ -258,6 +265,8 @@ function decode_avatar_data_packet(buf) if has_joint_data then + local joint_poses_start = i + local num_joints = buf(i, 1):uint() i = i + 1 local num_validity_bytes = math.ceil(num_joints / 8) @@ -279,6 +288,8 @@ function decode_avatar_data_packet(buf) -- TODO: skip hand controller data i = i + 24 + result["sizes"] = result["sizes"] .. " Poses: " .. (i - joint_poses_start) + end if has_joint_default_pose_flags then @@ -295,5 +306,7 @@ function decode_avatar_data_packet(buf) result["default_translations"] = "Default Translations: " .. string.format("(%d/%d) {", #indices, num_joints) .. table.concat(indices, ", ") .. "}" end + result["sizes"] = result["sizes"] .. " Total: " .. i + return result end diff --git a/tools/dissectors/README.md b/tools/dissectors/README.md new file mode 100644 index 0000000000..1e618a7b4c --- /dev/null +++ b/tools/dissectors/README.md @@ -0,0 +1,14 @@ +High Fidelity Wireshark Plugins +--------------------------------- + +Install wireshark 2.4.6 or higher. + +Copy these lua files into c:\Users\username\AppData\Roaming\Wireshark\Plugins + +After a capture any detected High Fidelity Packets should be easily identifiable by one of the following protocols + +* HF-AUDIO - Streaming audio packets +* HF-AVATAR - Streaming avatar mixer packets +* HF-ENTITY - Entity server traffic +* HF-DOMAIN - Domain server traffic +* HFUDT - All other UDP traffic From 993e1e1c4d67c07c5c3120666fd298ad5599e326 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Mon, 6 Aug 2018 14:35:11 -0700 Subject: [PATCH 36/37] Use GLES compatible context for shader tests --- tests/shaders/src/ShaderTests.cpp | 36 +++++++++++++++++++++++++------ tests/shaders/src/ShaderTests.h | 4 +++- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/tests/shaders/src/ShaderTests.cpp b/tests/shaders/src/ShaderTests.cpp index f7d8222de1..4c6b8fc38c 100644 --- a/tests/shaders/src/ShaderTests.cpp +++ b/tests/shaders/src/ShaderTests.cpp @@ -32,10 +32,13 @@ QTEST_MAIN(ShaderTests) +#pragma optimize("", off) void ShaderTests::initTestCase() { + _window = new QWindow(); + _context = new ::gl::Context(_window); getDefaultOpenGLSurfaceFormat(); - _canvas.create(); - if (!_canvas.makeCurrent()) { + _context->create(); + if (!_context->makeCurrent()) { qFatal("Unable to make test GL context current"); } gl::initModuleGl(); @@ -181,9 +184,19 @@ void ShaderTests::testShaderLoad() { std::set usedShaders; uint32_t maxShader = 0; try { + +#if 1 + uint32_t testPrograms[] = { + shader::render_utils::program::parabola, + shader::INVALID_PROGRAM, + }; +#else + const auto& testPrograms = shader::all_programs; +#endif + size_t index = 0; - while (shader::INVALID_PROGRAM != shader::all_programs[index]) { - auto programId = shader::all_programs[index]; + while (shader::INVALID_PROGRAM != testPrograms[index]) { + auto programId = testPrograms[index]; ++index; uint32_t vertexId = shader::getVertexId(programId); @@ -216,6 +229,12 @@ void ShaderTests::testShaderLoad() { // Uniforms { auto uniforms = gl::Uniform::load(program); + for (const auto& uniform : uniforms) { + GLint offset, size; + glGetActiveUniformsiv(program, 1, (GLuint*)&uniform.index, GL_UNIFORM_OFFSET, &offset); + glGetActiveUniformsiv(program, 1, (GLuint*)&uniform.index, GL_UNIFORM_SIZE, &size); + qDebug() << uniform.name.c_str() << " size " << size << "offset" << offset; + } const auto& uniformRemap = shaderObject.uniformRemap; auto expectedUniforms = expectedBindings[gpu::Shader::BindingType::UNIFORM]; if (!compareBindings(uniforms, expectedUniforms)) { @@ -224,11 +243,9 @@ void ShaderTests::testShaderLoad() { for (const auto& uniform : uniforms) { if (0 != expectedUniforms.count(uniform.name)) { auto expectedLocation = expectedUniforms[uniform.name]; -#ifdef Q_OS_MAC if (0 != uniformRemap.count(expectedLocation)) { expectedLocation = uniformRemap.at(expectedLocation); } -#endif QVERIFY(expectedLocation == uniform.binding); } } @@ -236,7 +253,12 @@ void ShaderTests::testShaderLoad() { // Textures { - const auto textures = gl::Uniform::loadTextures(program); + auto textures = gl::Uniform::loadTextures(program); + auto expiredBegin = std::remove_if(textures.begin(), textures.end(), [&](const gl::Uniform& uniform) -> bool { + return uniform.name == "transformObjectBuffer"; + }); + textures.erase(expiredBegin, textures.end()); + const auto expectedTextures = expectedBindings[gpu::Shader::BindingType::TEXTURE]; if (!compareBindings(textures, expectedTextures)) { qDebug() << "Textures mismatch"; diff --git a/tests/shaders/src/ShaderTests.h b/tests/shaders/src/ShaderTests.h index 2b731899cc..d109341c1f 100644 --- a/tests/shaders/src/ShaderTests.h +++ b/tests/shaders/src/ShaderTests.h @@ -12,6 +12,7 @@ #include #include #include +#include class ShaderTests : public QObject { Q_OBJECT @@ -22,7 +23,8 @@ private slots: void testShaderLoad(); private: - OffscreenGLCanvas _canvas; + QWindow* _window{ nullptr }; + gl::Context* _context{ nullptr }; gpu::ContextPointer _gpuContext; }; From dcdc3a323c4701495dc8e774b7372b020dfcc746 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Mon, 6 Aug 2018 14:35:36 -0700 Subject: [PATCH 37/37] Use defines for packed textures to satisfy both GLES and GL 4.1 --- libraries/render-utils/src/directional_ambient_light.slf | 4 ++-- .../render-utils/src/directional_ambient_light_shadow.slf | 4 ++-- libraries/render-utils/src/directional_skybox_light.slf | 4 ++-- .../render-utils/src/directional_skybox_light_shadow.slf | 4 ++-- libraries/render-utils/src/forward_model.slf | 4 ++-- libraries/render-utils/src/forward_model_normal_map.slf | 4 ++-- libraries/render-utils/src/forward_model_translucent.slf | 4 ++-- libraries/render-utils/src/forward_model_unlit.slf | 4 ++-- libraries/render-utils/src/forward_simple.slf | 4 ++-- libraries/render-utils/src/forward_simple_textured.slf | 4 ++-- .../render-utils/src/forward_simple_textured_transparent.slf | 4 ++-- libraries/render-utils/src/forward_simple_textured_unlit.slf | 4 ++-- libraries/render-utils/src/forward_simple_transparent.slf | 4 ++-- libraries/render-utils/src/hmd_ui.slf | 4 ++-- libraries/render-utils/src/local_lights_drawOutline.slf | 4 ++-- libraries/render-utils/src/local_lights_shading.slf | 4 ++-- libraries/render-utils/src/model.slf | 4 ++-- libraries/render-utils/src/model_fade.slf | 4 ++-- libraries/render-utils/src/model_lightmap.slf | 4 ++-- libraries/render-utils/src/model_lightmap_fade.slf | 4 ++-- libraries/render-utils/src/model_lightmap_normal_map.slf | 4 ++-- libraries/render-utils/src/model_lightmap_normal_map_fade.slf | 4 ++-- libraries/render-utils/src/model_normal_map.slf | 4 ++-- libraries/render-utils/src/model_normal_map_fade.slf | 4 ++-- libraries/render-utils/src/model_translucent.slf | 4 ++-- libraries/render-utils/src/model_translucent_fade.slf | 4 ++-- libraries/render-utils/src/model_translucent_normal_map.slf | 4 ++-- .../render-utils/src/model_translucent_normal_map_fade.slf | 4 ++-- libraries/render-utils/src/model_translucent_unlit.slf | 4 ++-- libraries/render-utils/src/model_translucent_unlit_fade.slf | 4 ++-- libraries/render-utils/src/model_unlit.slf | 4 ++-- libraries/render-utils/src/model_unlit_fade.slf | 4 ++-- libraries/render-utils/src/parabola.slv | 2 +- libraries/render-utils/src/sdf_text3D.slf | 4 ++-- libraries/render-utils/src/sdf_text3D_transparent.slf | 4 ++-- libraries/render-utils/src/simple.slf | 4 ++-- libraries/render-utils/src/simple_fade.slf | 4 ++-- libraries/render-utils/src/simple_opaque_web_browser.slf | 4 ++-- libraries/render-utils/src/simple_textured.slf | 4 ++-- libraries/render-utils/src/simple_textured_fade.slf | 4 ++-- libraries/render-utils/src/simple_textured_unlit.slf | 4 ++-- libraries/render-utils/src/simple_textured_unlit_fade.slf | 4 ++-- libraries/render-utils/src/simple_transparent.slf | 4 ++-- libraries/render-utils/src/simple_transparent_textured.slf | 4 ++-- .../render-utils/src/simple_transparent_textured_fade.slf | 4 ++-- .../render-utils/src/simple_transparent_textured_unlit.slf | 4 ++-- .../src/simple_transparent_textured_unlit_fade.slf | 4 ++-- libraries/render-utils/src/simple_transparent_web_browser.slf | 4 ++-- 48 files changed, 95 insertions(+), 95 deletions(-) diff --git a/libraries/render-utils/src/directional_ambient_light.slf b/libraries/render-utils/src/directional_ambient_light.slf index 3105b76bde..15d00f713e 100644 --- a/libraries/render-utils/src/directional_ambient_light.slf +++ b/libraries/render-utils/src/directional_ambient_light.slf @@ -23,8 +23,8 @@ <$declareEvalAmbientSphereGlobalColor(supportScattering)$> layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=0) out vec4 _fragColor; void main(void) { diff --git a/libraries/render-utils/src/directional_ambient_light_shadow.slf b/libraries/render-utils/src/directional_ambient_light_shadow.slf index 88c0188048..d6cdf78f19 100644 --- a/libraries/render-utils/src/directional_ambient_light_shadow.slf +++ b/libraries/render-utils/src/directional_ambient_light_shadow.slf @@ -21,8 +21,8 @@ <$declareEvalAmbientSphereGlobalColor(isScattering)$> layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=0) out vec4 _fragColor; void main(void) { diff --git a/libraries/render-utils/src/directional_skybox_light.slf b/libraries/render-utils/src/directional_skybox_light.slf index 56a7cd1883..b27d759dd4 100644 --- a/libraries/render-utils/src/directional_skybox_light.slf +++ b/libraries/render-utils/src/directional_skybox_light.slf @@ -20,8 +20,8 @@ <$declareEvalSkyboxGlobalColor(isScattering)$> layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=0) out vec4 _fragColor; void main(void) { diff --git a/libraries/render-utils/src/directional_skybox_light_shadow.slf b/libraries/render-utils/src/directional_skybox_light_shadow.slf index 6eaa989c6b..292f7348e3 100644 --- a/libraries/render-utils/src/directional_skybox_light_shadow.slf +++ b/libraries/render-utils/src/directional_skybox_light_shadow.slf @@ -21,8 +21,8 @@ <$declareEvalSkyboxGlobalColor(isScattering)$> layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=0) out vec4 _fragColor; void main(void) { diff --git a/libraries/render-utils/src/forward_model.slf b/libraries/render-utils/src/forward_model.slf index 82d776602f..f77ab358f2 100644 --- a/libraries/render-utils/src/forward_model.slf +++ b/libraries/render-utils/src/forward_model.slf @@ -27,8 +27,8 @@ layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; diff --git a/libraries/render-utils/src/forward_model_normal_map.slf b/libraries/render-utils/src/forward_model_normal_map.slf index 21ed0b9359..73fae33fb0 100644 --- a/libraries/render-utils/src/forward_model_normal_map.slf +++ b/libraries/render-utils/src/forward_model_normal_map.slf @@ -25,8 +25,8 @@ layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; diff --git a/libraries/render-utils/src/forward_model_translucent.slf b/libraries/render-utils/src/forward_model_translucent.slf index 74d200542f..d247b589c7 100644 --- a/libraries/render-utils/src/forward_model_translucent.slf +++ b/libraries/render-utils/src/forward_model_translucent.slf @@ -24,8 +24,8 @@ <$declareMaterialTextures(ALBEDO, ROUGHNESS, _SCRIBE_NULL, METALLIC, EMISSIVE, OCCLUSION)$> layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; diff --git a/libraries/render-utils/src/forward_model_unlit.slf b/libraries/render-utils/src/forward_model_unlit.slf index daad2ee6b9..19b40d884c 100644 --- a/libraries/render-utils/src/forward_model_unlit.slf +++ b/libraries/render-utils/src/forward_model_unlit.slf @@ -20,8 +20,8 @@ <$declareMaterialTextures(ALBEDO)$> layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=0) out vec4 _fragColor0; diff --git a/libraries/render-utils/src/forward_simple.slf b/libraries/render-utils/src/forward_simple.slf index 09365635cf..2c1be14080 100644 --- a/libraries/render-utils/src/forward_simple.slf +++ b/libraries/render-utils/src/forward_simple.slf @@ -22,8 +22,8 @@ layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_NORMAL_MS) in vec3 _normalMS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_POSITION_MS) in vec4 _positionMS; layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; diff --git a/libraries/render-utils/src/forward_simple_textured.slf b/libraries/render-utils/src/forward_simple_textured.slf index 532d12dd17..8570ae6183 100644 --- a/libraries/render-utils/src/forward_simple_textured.slf +++ b/libraries/render-utils/src/forward_simple_textured.slf @@ -28,8 +28,8 @@ layout(binding=0) uniform sampler2D originalTexture; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=0) out vec4 _fragColor0; diff --git a/libraries/render-utils/src/forward_simple_textured_transparent.slf b/libraries/render-utils/src/forward_simple_textured_transparent.slf index 98dc0bb368..11c44c18a2 100644 --- a/libraries/render-utils/src/forward_simple_textured_transparent.slf +++ b/libraries/render-utils/src/forward_simple_textured_transparent.slf @@ -28,8 +28,8 @@ layout(binding=0) uniform sampler2D originalTexture; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=0) out vec4 _fragColor0; diff --git a/libraries/render-utils/src/forward_simple_textured_unlit.slf b/libraries/render-utils/src/forward_simple_textured_unlit.slf index 7d3bf5912a..8ca46da499 100644 --- a/libraries/render-utils/src/forward_simple_textured_unlit.slf +++ b/libraries/render-utils/src/forward_simple_textured_unlit.slf @@ -24,8 +24,8 @@ layout(binding=0) uniform sampler2D originalTexture; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw void main(void) { vec4 texel = texture(originalTexture, _texCoord0.st); diff --git a/libraries/render-utils/src/forward_simple_transparent.slf b/libraries/render-utils/src/forward_simple_transparent.slf index a47d5963a2..f8390d6253 100644 --- a/libraries/render-utils/src/forward_simple_transparent.slf +++ b/libraries/render-utils/src/forward_simple_transparent.slf @@ -21,8 +21,8 @@ layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_NORMAL_MS) in vec3 _normalMS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_POSITION_MS) in vec4 _positionMS; layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; diff --git a/libraries/render-utils/src/hmd_ui.slf b/libraries/render-utils/src/hmd_ui.slf index b8bca889bf..eebeb2e060 100644 --- a/libraries/render-utils/src/hmd_ui.slf +++ b/libraries/render-utils/src/hmd_ui.slf @@ -24,8 +24,8 @@ layout(std140, binding=0) uniform hudBuffer { }; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=0) out vec4 fragColor0; diff --git a/libraries/render-utils/src/local_lights_drawOutline.slf b/libraries/render-utils/src/local_lights_drawOutline.slf index ff6476e21c..fc1d416f96 100644 --- a/libraries/render-utils/src/local_lights_drawOutline.slf +++ b/libraries/render-utils/src/local_lights_drawOutline.slf @@ -34,8 +34,8 @@ layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=0) out vec4 _fragColor; void main(void) { diff --git a/libraries/render-utils/src/local_lights_shading.slf b/libraries/render-utils/src/local_lights_shading.slf index 14cecd1815..538bdacc99 100644 --- a/libraries/render-utils/src/local_lights_shading.slf +++ b/libraries/render-utils/src/local_lights_shading.slf @@ -22,8 +22,8 @@ <@include render-utils/ShaderConstants.h@> layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=0) out vec4 _fragColor; void main(void) { diff --git a/libraries/render-utils/src/model.slf b/libraries/render-utils/src/model.slf index 70b71e0d22..2c42ed6083 100644 --- a/libraries/render-utils/src/model.slf +++ b/libraries/render-utils/src/model.slf @@ -20,8 +20,8 @@ <$declareMaterialTextures(ALBEDO, ROUGHNESS, _SCRIBE_NULL, METALLIC, EMISSIVE, OCCLUSION, SCATTERING)$> layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; diff --git a/libraries/render-utils/src/model_fade.slf b/libraries/render-utils/src/model_fade.slf index 23c629ddb0..b5a2c8d3ef 100644 --- a/libraries/render-utils/src/model_fade.slf +++ b/libraries/render-utils/src/model_fade.slf @@ -26,8 +26,8 @@ layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; diff --git a/libraries/render-utils/src/model_lightmap.slf b/libraries/render-utils/src/model_lightmap.slf index 34da0a8a05..efc36cc14a 100644 --- a/libraries/render-utils/src/model_lightmap.slf +++ b/libraries/render-utils/src/model_lightmap.slf @@ -22,8 +22,8 @@ layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; diff --git a/libraries/render-utils/src/model_lightmap_fade.slf b/libraries/render-utils/src/model_lightmap_fade.slf index 6f6dd9c413..4cbf3dcdea 100644 --- a/libraries/render-utils/src/model_lightmap_fade.slf +++ b/libraries/render-utils/src/model_lightmap_fade.slf @@ -26,8 +26,8 @@ <@include render-utils/ShaderConstants.h@> layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; diff --git a/libraries/render-utils/src/model_lightmap_normal_map.slf b/libraries/render-utils/src/model_lightmap_normal_map.slf index 362c331f63..ebafc6dfe2 100644 --- a/libraries/render-utils/src/model_lightmap_normal_map.slf +++ b/libraries/render-utils/src/model_lightmap_normal_map.slf @@ -22,8 +22,8 @@ layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; diff --git a/libraries/render-utils/src/model_lightmap_normal_map_fade.slf b/libraries/render-utils/src/model_lightmap_normal_map_fade.slf index bbeade488e..a9bac0e051 100644 --- a/libraries/render-utils/src/model_lightmap_normal_map_fade.slf +++ b/libraries/render-utils/src/model_lightmap_normal_map_fade.slf @@ -27,8 +27,8 @@ layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; diff --git a/libraries/render-utils/src/model_normal_map.slf b/libraries/render-utils/src/model_normal_map.slf index 4e89dfb3e8..5f30830511 100644 --- a/libraries/render-utils/src/model_normal_map.slf +++ b/libraries/render-utils/src/model_normal_map.slf @@ -21,8 +21,8 @@ layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; diff --git a/libraries/render-utils/src/model_normal_map_fade.slf b/libraries/render-utils/src/model_normal_map_fade.slf index 16b8138efe..499f376efa 100644 --- a/libraries/render-utils/src/model_normal_map_fade.slf +++ b/libraries/render-utils/src/model_normal_map_fade.slf @@ -25,8 +25,8 @@ layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; diff --git a/libraries/render-utils/src/model_translucent.slf b/libraries/render-utils/src/model_translucent.slf index 7fe81ab992..564150cebd 100644 --- a/libraries/render-utils/src/model_translucent.slf +++ b/libraries/render-utils/src/model_translucent.slf @@ -27,8 +27,8 @@ <$declareMaterialTextures(ALBEDO, ROUGHNESS, _SCRIBE_NULL, _SCRIBE_NULL, EMISSIVE, OCCLUSION)$> layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; diff --git a/libraries/render-utils/src/model_translucent_fade.slf b/libraries/render-utils/src/model_translucent_fade.slf index b9df51fcb9..3cebc59ea7 100644 --- a/libraries/render-utils/src/model_translucent_fade.slf +++ b/libraries/render-utils/src/model_translucent_fade.slf @@ -25,8 +25,8 @@ <@include render-utils/ShaderConstants.h@> layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; diff --git a/libraries/render-utils/src/model_translucent_normal_map.slf b/libraries/render-utils/src/model_translucent_normal_map.slf index c023f78e25..36ea50c321 100644 --- a/libraries/render-utils/src/model_translucent_normal_map.slf +++ b/libraries/render-utils/src/model_translucent_normal_map.slf @@ -29,8 +29,8 @@ <@include render-utils/ShaderConstants.h@> layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; diff --git a/libraries/render-utils/src/model_translucent_normal_map_fade.slf b/libraries/render-utils/src/model_translucent_normal_map_fade.slf index 992993edb3..24922c4e43 100644 --- a/libraries/render-utils/src/model_translucent_normal_map_fade.slf +++ b/libraries/render-utils/src/model_translucent_normal_map_fade.slf @@ -33,8 +33,8 @@ <@include render-utils/ShaderConstants.h@> layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TANGENT_WS) in vec3 _tangentWS; diff --git a/libraries/render-utils/src/model_translucent_unlit.slf b/libraries/render-utils/src/model_translucent_unlit.slf index 8f823e010a..87a712b239 100644 --- a/libraries/render-utils/src/model_translucent_unlit.slf +++ b/libraries/render-utils/src/model_translucent_unlit.slf @@ -21,8 +21,8 @@ <@include render-utils/ShaderConstants.h@> layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=0) out vec4 _fragColor; diff --git a/libraries/render-utils/src/model_translucent_unlit_fade.slf b/libraries/render-utils/src/model_translucent_unlit_fade.slf index 2c72780976..74dee12ec8 100644 --- a/libraries/render-utils/src/model_translucent_unlit_fade.slf +++ b/libraries/render-utils/src/model_translucent_unlit_fade.slf @@ -24,8 +24,8 @@ <@include render-utils/ShaderConstants.h@> layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; diff --git a/libraries/render-utils/src/model_unlit.slf b/libraries/render-utils/src/model_unlit.slf index 0e93022b83..b14a807eb5 100644 --- a/libraries/render-utils/src/model_unlit.slf +++ b/libraries/render-utils/src/model_unlit.slf @@ -21,8 +21,8 @@ <$declareMaterialTextures(ALBEDO)$> layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; diff --git a/libraries/render-utils/src/model_unlit_fade.slf b/libraries/render-utils/src/model_unlit_fade.slf index 1172bd5556..cb5c72bdf2 100644 --- a/libraries/render-utils/src/model_unlit_fade.slf +++ b/libraries/render-utils/src/model_unlit_fade.slf @@ -25,8 +25,8 @@ layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; diff --git a/libraries/render-utils/src/parabola.slv b/libraries/render-utils/src/parabola.slv index 46d6924191..50b5999450 100644 --- a/libraries/render-utils/src/parabola.slv +++ b/libraries/render-utils/src/parabola.slv @@ -27,7 +27,7 @@ layout(location=0) out vec4 _color; void main(void) { _color = color; - float t = parabolicDistance * (floor(gl_VertexID / 2) / float(numSections)); + float t = parabolicDistance * (float(gl_VertexID / 2) / float(numSections)); vec4 pos = vec4(velocity * t + 0.5 * acceleration * t * t, 1); const float EPSILON = 0.00001; diff --git a/libraries/render-utils/src/sdf_text3D.slf b/libraries/render-utils/src/sdf_text3D.slf index 999fb9e1a9..2fbaa03900 100644 --- a/libraries/render-utils/src/sdf_text3D.slf +++ b/libraries/render-utils/src/sdf_text3D.slf @@ -20,8 +20,8 @@ layout(location=RENDER_UTILS_UNIFORM_TEXT_COLOR) uniform vec4 Color; // the interpolated normal layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw #define TAA_TEXTURE_LOD_BIAS -3.0 diff --git a/libraries/render-utils/src/sdf_text3D_transparent.slf b/libraries/render-utils/src/sdf_text3D_transparent.slf index fbf4c4c372..218236c26b 100644 --- a/libraries/render-utils/src/sdf_text3D_transparent.slf +++ b/libraries/render-utils/src/sdf_text3D_transparent.slf @@ -20,8 +20,8 @@ layout(location=RENDER_UTILS_UNIFORM_TEXT_COLOR) uniform vec4 Color; // the interpolated normal layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw const float gamma = 2.2; const float smoothing = 32.0; diff --git a/libraries/render-utils/src/simple.slf b/libraries/render-utils/src/simple.slf index a699a10cad..04ffade2fa 100644 --- a/libraries/render-utils/src/simple.slf +++ b/libraries/render-utils/src/simple.slf @@ -21,8 +21,8 @@ layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_NORMAL_MS) in vec3 _normalMS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_POSITION_MS) in vec4 _positionMS; layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; diff --git a/libraries/render-utils/src/simple_fade.slf b/libraries/render-utils/src/simple_fade.slf index 00d81cadc9..e9f94c29bc 100644 --- a/libraries/render-utils/src/simple_fade.slf +++ b/libraries/render-utils/src/simple_fade.slf @@ -24,8 +24,8 @@ layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_NORMAL_MS) in vec3 _normalMS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_POSITION_MS) in vec4 _positionMS; layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; diff --git a/libraries/render-utils/src/simple_opaque_web_browser.slf b/libraries/render-utils/src/simple_opaque_web_browser.slf index 27a0781eef..cf4828d3b3 100644 --- a/libraries/render-utils/src/simple_opaque_web_browser.slf +++ b/libraries/render-utils/src/simple_opaque_web_browser.slf @@ -24,8 +24,8 @@ layout(binding=0) uniform sampler2D originalTexture; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw void main(void) { vec4 texel = texture(originalTexture, _texCoord0.st); diff --git a/libraries/render-utils/src/simple_textured.slf b/libraries/render-utils/src/simple_textured.slf index f1a60bdc5a..7676844084 100644 --- a/libraries/render-utils/src/simple_textured.slf +++ b/libraries/render-utils/src/simple_textured.slf @@ -23,8 +23,8 @@ layout(binding=0) uniform sampler2D originalTexture; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw void main(void) { vec4 texel = texture(originalTexture, _texCoord0); diff --git a/libraries/render-utils/src/simple_textured_fade.slf b/libraries/render-utils/src/simple_textured_fade.slf index a1476939d1..600f19be0f 100644 --- a/libraries/render-utils/src/simple_textured_fade.slf +++ b/libraries/render-utils/src/simple_textured_fade.slf @@ -26,8 +26,8 @@ layout(binding=0) uniform sampler2D originalTexture; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; // Declare after all samplers to prevent sampler location mix up with originalTexture diff --git a/libraries/render-utils/src/simple_textured_unlit.slf b/libraries/render-utils/src/simple_textured_unlit.slf index fcdf118732..e3d9b9daf6 100644 --- a/libraries/render-utils/src/simple_textured_unlit.slf +++ b/libraries/render-utils/src/simple_textured_unlit.slf @@ -24,8 +24,8 @@ layout(binding=0) uniform sampler2D originalTexture; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw void main(void) { vec4 texel = texture(originalTexture, _texCoord0.st); diff --git a/libraries/render-utils/src/simple_textured_unlit_fade.slf b/libraries/render-utils/src/simple_textured_unlit_fade.slf index 2007f0f684..bffadbe819 100644 --- a/libraries/render-utils/src/simple_textured_unlit_fade.slf +++ b/libraries/render-utils/src/simple_textured_unlit_fade.slf @@ -26,8 +26,8 @@ layout(binding=0) uniform sampler2D originalTexture; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; // Declare after all samplers to prevent sampler location mix up with originalTexture diff --git a/libraries/render-utils/src/simple_transparent.slf b/libraries/render-utils/src/simple_transparent.slf index d2ba332566..f81c06390c 100644 --- a/libraries/render-utils/src/simple_transparent.slf +++ b/libraries/render-utils/src/simple_transparent.slf @@ -21,8 +21,8 @@ layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_NORMAL_MS) in vec3 _normalMS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_POSITION_MS) in vec4 _positionMS; layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; diff --git a/libraries/render-utils/src/simple_transparent_textured.slf b/libraries/render-utils/src/simple_transparent_textured.slf index ffd715215a..0e6198de68 100644 --- a/libraries/render-utils/src/simple_transparent_textured.slf +++ b/libraries/render-utils/src/simple_transparent_textured.slf @@ -23,8 +23,8 @@ layout(location=0) uniform sampler2D originalTexture; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw void main(void) { vec4 texel = texture(originalTexture, _texCoord0); diff --git a/libraries/render-utils/src/simple_transparent_textured_fade.slf b/libraries/render-utils/src/simple_transparent_textured_fade.slf index 8e530f41aa..44a3fe2e01 100644 --- a/libraries/render-utils/src/simple_transparent_textured_fade.slf +++ b/libraries/render-utils/src/simple_transparent_textured_fade.slf @@ -32,8 +32,8 @@ layout(location=RENDER_UTILS_ATTR_POSITION_ES) in vec4 _positionES; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; // Declare after all samplers to prevent sampler location mix up with originalTexture diff --git a/libraries/render-utils/src/simple_transparent_textured_unlit.slf b/libraries/render-utils/src/simple_transparent_textured_unlit.slf index d05ca02560..9d43e41c2f 100644 --- a/libraries/render-utils/src/simple_transparent_textured_unlit.slf +++ b/libraries/render-utils/src/simple_transparent_textured_unlit.slf @@ -21,8 +21,8 @@ layout(binding=0) uniform sampler2D originalTexture; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=0) out vec4 _fragColor0; diff --git a/libraries/render-utils/src/simple_transparent_textured_unlit_fade.slf b/libraries/render-utils/src/simple_transparent_textured_unlit_fade.slf index 53006b508d..43c28c41c3 100644 --- a/libraries/render-utils/src/simple_transparent_textured_unlit_fade.slf +++ b/libraries/render-utils/src/simple_transparent_textured_unlit_fade.slf @@ -23,8 +23,8 @@ layout(binding=0) uniform sampler2D originalTexture; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw layout(location=RENDER_UTILS_ATTR_POSITION_WS) in vec4 _positionWS; layout(location=0) out vec4 _fragColor0; diff --git a/libraries/render-utils/src/simple_transparent_web_browser.slf b/libraries/render-utils/src/simple_transparent_web_browser.slf index 156339b702..df92d238bf 100644 --- a/libraries/render-utils/src/simple_transparent_web_browser.slf +++ b/libraries/render-utils/src/simple_transparent_web_browser.slf @@ -24,8 +24,8 @@ layout(binding=0) uniform sampler2D originalTexture; layout(location=RENDER_UTILS_ATTR_NORMAL_WS) in vec3 _normalWS; layout(location=RENDER_UTILS_ATTR_COLOR) in vec4 _color; layout(location=RENDER_UTILS_ATTR_TEXCOORD01) in vec4 _texCoord01; -vec2 _texCoord0 = _texCoord01.xy; -vec2 _texCoord1 = _texCoord01.zw; +#define _texCoord0 _texCoord01.xy +#define _texCoord1 _texCoord01.zw void main(void) { vec4 texel = texture(originalTexture, _texCoord0.st);