2 // Copyright (c) 2002-2014 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
7 #include "compiler/translator/OutputHLSL.h"
9 #include "common/angleutils.h"
10 #include "common/utilities.h"
11 #include "common/blocklayout.h"
12 #include "compiler/translator/compilerdebug.h"
13 #include "compiler/translator/InfoSink.h"
14 #include "compiler/translator/DetectDiscontinuity.h"
15 #include "compiler/translator/SearchSymbol.h"
16 #include "compiler/translator/UnfoldShortCircuit.h"
17 #include "compiler/translator/FlagStd140Structs.h"
18 #include "compiler/translator/NodeSearch.h"
19 #include "compiler/translator/RewriteElseBlocks.h"
20 #include "compiler/translator/UtilsHLSL.h"
21 #include "compiler/translator/util.h"
22 #include "compiler/translator/UniformHLSL.h"
23 #include "compiler/translator/StructureHLSL.h"
32 static sh::Attribute MakeAttributeFromType(const TType &type, const TString &name)
34 sh::Attribute attributeVar;
35 attributeVar.type = GLVariableType(type);
36 attributeVar.precision = GLVariablePrecision(type);
37 attributeVar.name = name.c_str();
38 attributeVar.arraySize = static_cast<unsigned int>(type.getArraySize());
39 attributeVar.location = type.getLayoutQualifier().location;
44 TString OutputHLSL::TextureFunction::name() const
46 TString name = "gl_texture";
48 if (IsSampler2D(sampler))
52 else if (IsSampler3D(sampler))
56 else if (IsSamplerCube(sampler))
75 case BIAS: break; // Extra parameter makes the signature unique
76 case LOD: name += "Lod"; break;
77 case LOD0: name += "Lod0"; break;
78 case LOD0BIAS: name += "Lod0"; break; // Extra parameter makes the signature unique
79 case SIZE: name += "Size"; break;
80 case FETCH: name += "Fetch"; break;
81 case GRAD: name += "Grad"; break;
82 default: UNREACHABLE();
88 bool OutputHLSL::TextureFunction::operator<(const TextureFunction &rhs) const
90 if (sampler < rhs.sampler) return true;
91 if (sampler > rhs.sampler) return false;
93 if (coords < rhs.coords) return true;
94 if (coords > rhs.coords) return false;
96 if (!proj && rhs.proj) return true;
97 if (proj && !rhs.proj) return false;
99 if (!offset && rhs.offset) return true;
100 if (offset && !rhs.offset) return false;
102 if (method < rhs.method) return true;
103 if (method > rhs.method) return false;
108 OutputHLSL::OutputHLSL(TParseContext &context, const ShBuiltInResources& resources, ShShaderOutput outputType)
109 : TIntermTraverser(true, true, true), mContext(context), mOutputType(outputType)
111 mUnfoldShortCircuit = new UnfoldShortCircuit(context, this);
112 mInsideFunction = false;
114 mUsesFragColor = false;
115 mUsesFragData = false;
116 mUsesDepthRange = false;
117 mUsesFragCoord = false;
118 mUsesPointCoord = false;
119 mUsesFrontFacing = false;
120 mUsesPointSize = false;
121 mUsesFragDepth = false;
130 mUsesFaceforward1 = false;
131 mUsesFaceforward2 = false;
132 mUsesFaceforward3 = false;
133 mUsesFaceforward4 = false;
134 mUsesAtan2_1 = false;
135 mUsesAtan2_2 = false;
136 mUsesAtan2_3 = false;
137 mUsesAtan2_4 = false;
138 mUsesDiscardRewriting = false;
139 mUsesNestedBreak = false;
141 mNumRenderTargets = resources.EXT_draw_buffers ? resources.MaxDrawBuffers : 1;
145 mContainsLoopDiscontinuity = false;
146 mOutputLod0Function = false;
147 mInsideDiscontinuousLoop = false;
148 mNestedLoopDepth = 0;
150 mExcessiveLoopIndex = NULL;
152 mStructureHLSL = new StructureHLSL;
153 mUniformHLSL = new UniformHLSL(mStructureHLSL, mOutputType);
155 if (mOutputType == SH_HLSL9_OUTPUT)
157 if (mContext.shaderType == GL_FRAGMENT_SHADER)
159 // Reserve registers for dx_DepthRange, dx_ViewCoords and dx_DepthFront
160 mUniformHLSL->reserveUniformRegisters(3);
164 // Reserve registers for dx_DepthRange and dx_ViewAdjust
165 mUniformHLSL->reserveUniformRegisters(2);
169 // Reserve registers for the default uniform block and driver constants
170 mUniformHLSL->reserveInterfaceBlockRegisters(2);
173 OutputHLSL::~OutputHLSL()
175 SafeDelete(mUnfoldShortCircuit);
176 SafeDelete(mStructureHLSL);
177 SafeDelete(mUniformHLSL);
180 void OutputHLSL::output()
182 mContainsLoopDiscontinuity = mContext.shaderType == GL_FRAGMENT_SHADER && containsLoopDiscontinuity(mContext.treeRoot);
183 const std::vector<TIntermTyped*> &flaggedStructs = FlagStd140ValueStructs(mContext.treeRoot);
184 makeFlaggedStructMaps(flaggedStructs);
186 // Work around D3D9 bug that would manifest in vertex shaders with selection blocks which
187 // use a vertex attribute as a condition, and some related computation in the else block.
188 if (mOutputType == SH_HLSL9_OUTPUT && mContext.shaderType == GL_VERTEX_SHADER)
190 RewriteElseBlocks(mContext.treeRoot);
193 mContext.treeRoot->traverse(this); // Output the body first to determine what has to go in the header
196 mContext.infoSink().obj << mHeader.c_str();
197 mContext.infoSink().obj << mBody.c_str();
200 void OutputHLSL::makeFlaggedStructMaps(const std::vector<TIntermTyped *> &flaggedStructs)
202 for (unsigned int structIndex = 0; structIndex < flaggedStructs.size(); structIndex++)
204 TIntermTyped *flaggedNode = flaggedStructs[structIndex];
206 // This will mark the necessary block elements as referenced
207 flaggedNode->traverse(this);
208 TString structName(mBody.c_str());
211 mFlaggedStructOriginalNames[flaggedNode] = structName;
213 for (size_t pos = structName.find('.'); pos != std::string::npos; pos = structName.find('.'))
215 structName.erase(pos, 1);
218 mFlaggedStructMappedNames[flaggedNode] = "map" + structName;
222 TInfoSinkBase &OutputHLSL::getBodyStream()
227 const std::vector<sh::Uniform> &OutputHLSL::getUniforms()
229 return mUniformHLSL->getUniforms();
232 const std::vector<sh::InterfaceBlock> &OutputHLSL::getInterfaceBlocks() const
234 return mUniformHLSL->getInterfaceBlocks();
237 const std::vector<sh::Attribute> &OutputHLSL::getOutputVariables() const
239 return mActiveOutputVariables;
242 const std::vector<sh::Attribute> &OutputHLSL::getAttributes() const
244 return mActiveAttributes;
247 const std::vector<sh::Varying> &OutputHLSL::getVaryings() const
249 return mActiveVaryings;
252 const std::map<std::string, unsigned int> &OutputHLSL::getInterfaceBlockRegisterMap() const
254 return mUniformHLSL->getInterfaceBlockRegisterMap();
257 const std::map<std::string, unsigned int> &OutputHLSL::getUniformRegisterMap() const
259 return mUniformHLSL->getUniformRegisterMap();
262 int OutputHLSL::vectorSize(const TType &type) const
264 int elementSize = type.isMatrix() ? type.getCols() : 1;
265 int arraySize = type.isArray() ? type.getArraySize() : 1;
267 return elementSize * arraySize;
270 TString OutputHLSL::structInitializerString(int indent, const TStructure &structure, const TString &rhsStructName)
274 TString preIndentString;
275 TString fullIndentString;
277 for (int spaces = 0; spaces < (indent * 4); spaces++)
279 preIndentString += ' ';
282 for (int spaces = 0; spaces < ((indent+1) * 4); spaces++)
284 fullIndentString += ' ';
287 init += preIndentString + "{\n";
289 const TFieldList &fields = structure.fields();
290 for (unsigned int fieldIndex = 0; fieldIndex < fields.size(); fieldIndex++)
292 const TField &field = *fields[fieldIndex];
293 const TString &fieldName = rhsStructName + "." + Decorate(field.name());
294 const TType &fieldType = *field.type();
296 if (fieldType.getStruct())
298 init += structInitializerString(indent + 1, *fieldType.getStruct(), fieldName);
302 init += fullIndentString + fieldName + ",\n";
306 init += preIndentString + "}" + (indent == 0 ? ";" : ",") + "\n";
311 void OutputHLSL::header()
313 TInfoSinkBase &out = mHeader;
317 TString flaggedStructs;
319 for (std::map<TIntermTyped*, TString>::const_iterator flaggedStructIt = mFlaggedStructMappedNames.begin(); flaggedStructIt != mFlaggedStructMappedNames.end(); flaggedStructIt++)
321 TIntermTyped *structNode = flaggedStructIt->first;
322 const TString &mappedName = flaggedStructIt->second;
323 const TStructure &structure = *structNode->getType().getStruct();
324 const TString &originalName = mFlaggedStructOriginalNames[structNode];
326 flaggedStructs += "static " + Decorate(structure.name()) + " " + mappedName + " =\n";
327 flaggedStructs += structInitializerString(0, structure, originalName);
328 flaggedStructs += "\n";
331 for (ReferencedSymbols::const_iterator varying = mReferencedVaryings.begin(); varying != mReferencedVaryings.end(); varying++)
333 const TType &type = varying->second->getType();
334 const TString &name = varying->second->getSymbol();
336 // Program linking depends on this exact format
337 varyings += "static " + InterpolationString(type.getQualifier()) + " " + TypeString(type) + " " +
338 Decorate(name) + ArrayString(type) + " = " + initializer(type) + ";\n";
340 declareVaryingToList(type, type.getQualifier(), name, mActiveVaryings);
343 for (ReferencedSymbols::const_iterator attribute = mReferencedAttributes.begin(); attribute != mReferencedAttributes.end(); attribute++)
345 const TType &type = attribute->second->getType();
346 const TString &name = attribute->second->getSymbol();
348 attributes += "static " + TypeString(type) + " " + Decorate(name) + ArrayString(type) + " = " + initializer(type) + ";\n";
350 sh::Attribute attributeVar = MakeAttributeFromType(type, name);
351 mActiveAttributes.push_back(attributeVar);
354 out << mStructureHLSL->structsHeader();
356 out << mUniformHLSL->uniformsHeader(mOutputType, mReferencedUniforms);
357 out << mUniformHLSL->interfaceBlocksHeader(mReferencedInterfaceBlocks);
359 if (mUsesDiscardRewriting)
361 out << "#define ANGLE_USES_DISCARD_REWRITING" << "\n";
364 if (mUsesNestedBreak)
366 out << "#define ANGLE_USES_NESTED_BREAK" << "\n";
369 if (mContext.shaderType == GL_FRAGMENT_SHADER)
371 TExtensionBehavior::const_iterator iter = mContext.extensionBehavior().find("GL_EXT_draw_buffers");
372 const bool usingMRTExtension = (iter != mContext.extensionBehavior().end() && (iter->second == EBhEnable || iter->second == EBhRequire));
374 out << "// Varyings\n";
378 if (mContext.getShaderVersion() >= 300)
380 for (ReferencedSymbols::const_iterator outputVariableIt = mReferencedOutputVariables.begin(); outputVariableIt != mReferencedOutputVariables.end(); outputVariableIt++)
382 const TString &variableName = outputVariableIt->first;
383 const TType &variableType = outputVariableIt->second->getType();
385 out << "static " + TypeString(variableType) + " out_" + variableName + ArrayString(variableType) +
386 " = " + initializer(variableType) + ";\n";
388 sh::Attribute outputVar = MakeAttributeFromType(variableType, variableName);
389 mActiveOutputVariables.push_back(outputVar);
394 const unsigned int numColorValues = usingMRTExtension ? mNumRenderTargets : 1;
396 out << "static float4 gl_Color[" << numColorValues << "] =\n"
398 for (unsigned int i = 0; i < numColorValues; i++)
400 out << " float4(0, 0, 0, 0)";
401 if (i + 1 != numColorValues)
413 out << "static float gl_Depth = 0.0;\n";
418 out << "static float4 gl_FragCoord = float4(0, 0, 0, 0);\n";
423 out << "static float2 gl_PointCoord = float2(0.5, 0.5);\n";
426 if (mUsesFrontFacing)
428 out << "static bool gl_FrontFacing = false;\n";
435 out << "struct gl_DepthRangeParameters\n"
444 if (mOutputType == SH_HLSL11_OUTPUT)
446 out << "cbuffer DriverConstants : register(b1)\n"
451 out << " float3 dx_DepthRange : packoffset(c0);\n";
456 out << " float4 dx_ViewCoords : packoffset(c1);\n";
459 if (mUsesFragCoord || mUsesFrontFacing)
461 out << " float3 dx_DepthFront : packoffset(c2);\n";
470 out << "uniform float3 dx_DepthRange : register(c0);";
475 out << "uniform float4 dx_ViewCoords : register(c1);\n";
478 if (mUsesFragCoord || mUsesFrontFacing)
480 out << "uniform float3 dx_DepthFront : register(c2);\n";
488 out << "static gl_DepthRangeParameters gl_DepthRange = {dx_DepthRange.x, dx_DepthRange.y, dx_DepthRange.z};\n"
492 if (!flaggedStructs.empty())
494 out << "// Std140 Structures accessed by value\n";
496 out << flaggedStructs;
500 if (usingMRTExtension && mNumRenderTargets > 1)
502 out << "#define GL_USES_MRT\n";
507 out << "#define GL_USES_FRAG_COLOR\n";
512 out << "#define GL_USES_FRAG_DATA\n";
515 else // Vertex shader
517 out << "// Attributes\n";
520 "static float4 gl_Position = float4(0, 0, 0, 0);\n";
524 out << "static float gl_PointSize = float(1);\n";
534 out << "struct gl_DepthRangeParameters\n"
543 if (mOutputType == SH_HLSL11_OUTPUT)
547 out << "cbuffer DriverConstants : register(b1)\n"
549 " float3 dx_DepthRange : packoffset(c0);\n"
558 out << "uniform float3 dx_DepthRange : register(c0);\n";
561 out << "uniform float4 dx_ViewAdjust : register(c1);\n"
567 out << "static gl_DepthRangeParameters gl_DepthRange = {dx_DepthRange.x, dx_DepthRange.y, dx_DepthRange.z};\n"
571 if (!flaggedStructs.empty())
573 out << "// Std140 Structures accessed by value\n";
575 out << flaggedStructs;
580 for (TextureFunctionSet::const_iterator textureFunction = mUsesTexture.begin(); textureFunction != mUsesTexture.end(); textureFunction++)
583 if (textureFunction->method == TextureFunction::SIZE)
585 switch(textureFunction->sampler)
587 case EbtSampler2D: out << "int2 "; break;
588 case EbtSampler3D: out << "int3 "; break;
589 case EbtSamplerCube: out << "int2 "; break;
590 case EbtSampler2DArray: out << "int3 "; break;
591 case EbtISampler2D: out << "int2 "; break;
592 case EbtISampler3D: out << "int3 "; break;
593 case EbtISamplerCube: out << "int2 "; break;
594 case EbtISampler2DArray: out << "int3 "; break;
595 case EbtUSampler2D: out << "int2 "; break;
596 case EbtUSampler3D: out << "int3 "; break;
597 case EbtUSamplerCube: out << "int2 "; break;
598 case EbtUSampler2DArray: out << "int3 "; break;
599 case EbtSampler2DShadow: out << "int2 "; break;
600 case EbtSamplerCubeShadow: out << "int2 "; break;
601 case EbtSampler2DArrayShadow: out << "int3 "; break;
602 default: UNREACHABLE();
605 else // Sampling function
607 switch(textureFunction->sampler)
609 case EbtSampler2D: out << "float4 "; break;
610 case EbtSampler3D: out << "float4 "; break;
611 case EbtSamplerCube: out << "float4 "; break;
612 case EbtSampler2DArray: out << "float4 "; break;
613 case EbtISampler2D: out << "int4 "; break;
614 case EbtISampler3D: out << "int4 "; break;
615 case EbtISamplerCube: out << "int4 "; break;
616 case EbtISampler2DArray: out << "int4 "; break;
617 case EbtUSampler2D: out << "uint4 "; break;
618 case EbtUSampler3D: out << "uint4 "; break;
619 case EbtUSamplerCube: out << "uint4 "; break;
620 case EbtUSampler2DArray: out << "uint4 "; break;
621 case EbtSampler2DShadow: out << "float "; break;
622 case EbtSamplerCubeShadow: out << "float "; break;
623 case EbtSampler2DArrayShadow: out << "float "; break;
624 default: UNREACHABLE();
629 out << textureFunction->name();
634 if (mOutputType == SH_HLSL9_OUTPUT)
636 switch(textureFunction->sampler)
638 case EbtSampler2D: out << "sampler2D s"; hlslCoords = 2; break;
639 case EbtSamplerCube: out << "samplerCUBE s"; hlslCoords = 3; break;
640 default: UNREACHABLE();
643 switch(textureFunction->method)
645 case TextureFunction::IMPLICIT: break;
646 case TextureFunction::BIAS: hlslCoords = 4; break;
647 case TextureFunction::LOD: hlslCoords = 4; break;
648 case TextureFunction::LOD0: hlslCoords = 4; break;
649 case TextureFunction::LOD0BIAS: hlslCoords = 4; break;
650 default: UNREACHABLE();
653 else if (mOutputType == SH_HLSL11_OUTPUT)
655 switch(textureFunction->sampler)
657 case EbtSampler2D: out << "Texture2D x, SamplerState s"; hlslCoords = 2; break;
658 case EbtSampler3D: out << "Texture3D x, SamplerState s"; hlslCoords = 3; break;
659 case EbtSamplerCube: out << "TextureCube x, SamplerState s"; hlslCoords = 3; break;
660 case EbtSampler2DArray: out << "Texture2DArray x, SamplerState s"; hlslCoords = 3; break;
661 case EbtISampler2D: out << "Texture2D<int4> x, SamplerState s"; hlslCoords = 2; break;
662 case EbtISampler3D: out << "Texture3D<int4> x, SamplerState s"; hlslCoords = 3; break;
663 case EbtISamplerCube: out << "Texture2DArray<int4> x, SamplerState s"; hlslCoords = 3; break;
664 case EbtISampler2DArray: out << "Texture2DArray<int4> x, SamplerState s"; hlslCoords = 3; break;
665 case EbtUSampler2D: out << "Texture2D<uint4> x, SamplerState s"; hlslCoords = 2; break;
666 case EbtUSampler3D: out << "Texture3D<uint4> x, SamplerState s"; hlslCoords = 3; break;
667 case EbtUSamplerCube: out << "Texture2DArray<uint4> x, SamplerState s"; hlslCoords = 3; break;
668 case EbtUSampler2DArray: out << "Texture2DArray<uint4> x, SamplerState s"; hlslCoords = 3; break;
669 case EbtSampler2DShadow: out << "Texture2D x, SamplerComparisonState s"; hlslCoords = 2; break;
670 case EbtSamplerCubeShadow: out << "TextureCube x, SamplerComparisonState s"; hlslCoords = 3; break;
671 case EbtSampler2DArrayShadow: out << "Texture2DArray x, SamplerComparisonState s"; hlslCoords = 3; break;
672 default: UNREACHABLE();
677 if (textureFunction->method == TextureFunction::FETCH) // Integer coordinates
679 switch(textureFunction->coords)
681 case 2: out << ", int2 t"; break;
682 case 3: out << ", int3 t"; break;
683 default: UNREACHABLE();
686 else // Floating-point coordinates (except textureSize)
688 switch(textureFunction->coords)
690 case 1: out << ", int lod"; break; // textureSize()
691 case 2: out << ", float2 t"; break;
692 case 3: out << ", float3 t"; break;
693 case 4: out << ", float4 t"; break;
694 default: UNREACHABLE();
698 if (textureFunction->method == TextureFunction::GRAD)
700 switch(textureFunction->sampler)
705 case EbtSampler2DArray:
706 case EbtISampler2DArray:
707 case EbtUSampler2DArray:
708 case EbtSampler2DShadow:
709 case EbtSampler2DArrayShadow:
710 out << ", float2 ddx, float2 ddy";
716 case EbtISamplerCube:
717 case EbtUSamplerCube:
718 case EbtSamplerCubeShadow:
719 out << ", float3 ddx, float3 ddy";
721 default: UNREACHABLE();
725 switch(textureFunction->method)
727 case TextureFunction::IMPLICIT: break;
728 case TextureFunction::BIAS: break; // Comes after the offset parameter
729 case TextureFunction::LOD: out << ", float lod"; break;
730 case TextureFunction::LOD0: break;
731 case TextureFunction::LOD0BIAS: break; // Comes after the offset parameter
732 case TextureFunction::SIZE: break;
733 case TextureFunction::FETCH: out << ", int mip"; break;
734 case TextureFunction::GRAD: break;
735 default: UNREACHABLE();
738 if (textureFunction->offset)
740 switch(textureFunction->sampler)
742 case EbtSampler2D: out << ", int2 offset"; break;
743 case EbtSampler3D: out << ", int3 offset"; break;
744 case EbtSampler2DArray: out << ", int2 offset"; break;
745 case EbtISampler2D: out << ", int2 offset"; break;
746 case EbtISampler3D: out << ", int3 offset"; break;
747 case EbtISampler2DArray: out << ", int2 offset"; break;
748 case EbtUSampler2D: out << ", int2 offset"; break;
749 case EbtUSampler3D: out << ", int3 offset"; break;
750 case EbtUSampler2DArray: out << ", int2 offset"; break;
751 case EbtSampler2DShadow: out << ", int2 offset"; break;
752 case EbtSampler2DArrayShadow: out << ", int2 offset"; break;
753 default: UNREACHABLE();
757 if (textureFunction->method == TextureFunction::BIAS ||
758 textureFunction->method == TextureFunction::LOD0BIAS)
760 out << ", float bias";
766 if (textureFunction->method == TextureFunction::SIZE)
768 if (IsSampler2D(textureFunction->sampler) || IsSamplerCube(textureFunction->sampler))
770 if (IsSamplerArray(textureFunction->sampler))
772 out << " uint width; uint height; uint layers; uint numberOfLevels;\n"
773 " x.GetDimensions(lod, width, height, layers, numberOfLevels);\n";
777 out << " uint width; uint height; uint numberOfLevels;\n"
778 " x.GetDimensions(lod, width, height, numberOfLevels);\n";
781 else if (IsSampler3D(textureFunction->sampler))
783 out << " uint width; uint height; uint depth; uint numberOfLevels;\n"
784 " x.GetDimensions(lod, width, height, depth, numberOfLevels);\n";
788 switch(textureFunction->sampler)
790 case EbtSampler2D: out << " return int2(width, height);"; break;
791 case EbtSampler3D: out << " return int3(width, height, depth);"; break;
792 case EbtSamplerCube: out << " return int2(width, height);"; break;
793 case EbtSampler2DArray: out << " return int3(width, height, layers);"; break;
794 case EbtISampler2D: out << " return int2(width, height);"; break;
795 case EbtISampler3D: out << " return int3(width, height, depth);"; break;
796 case EbtISamplerCube: out << " return int2(width, height);"; break;
797 case EbtISampler2DArray: out << " return int3(width, height, layers);"; break;
798 case EbtUSampler2D: out << " return int2(width, height);"; break;
799 case EbtUSampler3D: out << " return int3(width, height, depth);"; break;
800 case EbtUSamplerCube: out << " return int2(width, height);"; break;
801 case EbtUSampler2DArray: out << " return int3(width, height, layers);"; break;
802 case EbtSampler2DShadow: out << " return int2(width, height);"; break;
803 case EbtSamplerCubeShadow: out << " return int2(width, height);"; break;
804 case EbtSampler2DArrayShadow: out << " return int3(width, height, layers);"; break;
805 default: UNREACHABLE();
810 if (IsIntegerSampler(textureFunction->sampler) && IsSamplerCube(textureFunction->sampler))
812 out << " float width; float height; float layers; float levels;\n";
814 out << " uint mip = 0;\n";
816 out << " x.GetDimensions(mip, width, height, layers, levels);\n";
818 out << " bool xMajor = abs(t.x) > abs(t.y) && abs(t.x) > abs(t.z);\n";
819 out << " bool yMajor = abs(t.y) > abs(t.z) && abs(t.y) > abs(t.x);\n";
820 out << " bool zMajor = abs(t.z) > abs(t.x) && abs(t.z) > abs(t.y);\n";
821 out << " bool negative = (xMajor && t.x < 0.0f) || (yMajor && t.y < 0.0f) || (zMajor && t.z < 0.0f);\n";
823 // FACE_POSITIVE_X = 000b
824 // FACE_NEGATIVE_X = 001b
825 // FACE_POSITIVE_Y = 010b
826 // FACE_NEGATIVE_Y = 011b
827 // FACE_POSITIVE_Z = 100b
828 // FACE_NEGATIVE_Z = 101b
829 out << " int face = (int)negative + (int)yMajor * 2 + (int)zMajor * 4;\n";
831 out << " float u = xMajor ? -t.z : (yMajor && t.y < 0.0f ? -t.x : t.x);\n";
832 out << " float v = yMajor ? t.z : (negative ? t.y : -t.y);\n";
833 out << " float m = xMajor ? t.x : (yMajor ? t.y : t.z);\n";
835 out << " t.x = (u * 0.5f / m) + 0.5f;\n";
836 out << " t.y = (v * 0.5f / m) + 0.5f;\n";
838 else if (IsIntegerSampler(textureFunction->sampler) &&
839 textureFunction->method != TextureFunction::FETCH)
841 if (IsSampler2D(textureFunction->sampler))
843 if (IsSamplerArray(textureFunction->sampler))
845 out << " float width; float height; float layers; float levels;\n";
847 if (textureFunction->method == TextureFunction::LOD0)
849 out << " uint mip = 0;\n";
851 else if (textureFunction->method == TextureFunction::LOD0BIAS)
853 out << " uint mip = bias;\n";
857 if (textureFunction->method == TextureFunction::IMPLICIT ||
858 textureFunction->method == TextureFunction::BIAS)
860 out << " x.GetDimensions(0, width, height, layers, levels);\n"
861 " float2 tSized = float2(t.x * width, t.y * height);\n"
862 " float dx = length(ddx(tSized));\n"
863 " float dy = length(ddy(tSized));\n"
864 " float lod = log2(max(dx, dy));\n";
866 if (textureFunction->method == TextureFunction::BIAS)
868 out << " lod += bias;\n";
871 else if (textureFunction->method == TextureFunction::GRAD)
873 out << " x.GetDimensions(0, width, height, layers, levels);\n"
874 " float lod = log2(max(length(ddx), length(ddy)));\n";
877 out << " uint mip = uint(min(max(round(lod), 0), levels - 1));\n";
880 out << " x.GetDimensions(mip, width, height, layers, levels);\n";
884 out << " float width; float height; float levels;\n";
886 if (textureFunction->method == TextureFunction::LOD0)
888 out << " uint mip = 0;\n";
890 else if (textureFunction->method == TextureFunction::LOD0BIAS)
892 out << " uint mip = bias;\n";
896 if (textureFunction->method == TextureFunction::IMPLICIT ||
897 textureFunction->method == TextureFunction::BIAS)
899 out << " x.GetDimensions(0, width, height, levels);\n"
900 " float2 tSized = float2(t.x * width, t.y * height);\n"
901 " float dx = length(ddx(tSized));\n"
902 " float dy = length(ddy(tSized));\n"
903 " float lod = log2(max(dx, dy));\n";
905 if (textureFunction->method == TextureFunction::BIAS)
907 out << " lod += bias;\n";
910 else if (textureFunction->method == TextureFunction::LOD)
912 out << " x.GetDimensions(0, width, height, levels);\n";
914 else if (textureFunction->method == TextureFunction::GRAD)
916 out << " x.GetDimensions(0, width, height, levels);\n"
917 " float lod = log2(max(length(ddx), length(ddy)));\n";
920 out << " uint mip = uint(min(max(round(lod), 0), levels - 1));\n";
923 out << " x.GetDimensions(mip, width, height, levels);\n";
926 else if (IsSampler3D(textureFunction->sampler))
928 out << " float width; float height; float depth; float levels;\n";
930 if (textureFunction->method == TextureFunction::LOD0)
932 out << " uint mip = 0;\n";
934 else if (textureFunction->method == TextureFunction::LOD0BIAS)
936 out << " uint mip = bias;\n";
940 if (textureFunction->method == TextureFunction::IMPLICIT ||
941 textureFunction->method == TextureFunction::BIAS)
943 out << " x.GetDimensions(0, width, height, depth, levels);\n"
944 " float3 tSized = float3(t.x * width, t.y * height, t.z * depth);\n"
945 " float dx = length(ddx(tSized));\n"
946 " float dy = length(ddy(tSized));\n"
947 " float lod = log2(max(dx, dy));\n";
949 if (textureFunction->method == TextureFunction::BIAS)
951 out << " lod += bias;\n";
954 else if (textureFunction->method == TextureFunction::GRAD)
956 out << " x.GetDimensions(0, width, height, depth, levels);\n"
957 " float lod = log2(max(length(ddx), length(ddy)));\n";
960 out << " uint mip = uint(min(max(round(lod), 0), levels - 1));\n";
963 out << " x.GetDimensions(mip, width, height, depth, levels);\n";
971 if (mOutputType == SH_HLSL9_OUTPUT)
973 switch(textureFunction->sampler)
975 case EbtSampler2D: out << "tex2D"; break;
976 case EbtSamplerCube: out << "texCUBE"; break;
977 default: UNREACHABLE();
980 switch(textureFunction->method)
982 case TextureFunction::IMPLICIT: out << "(s, "; break;
983 case TextureFunction::BIAS: out << "bias(s, "; break;
984 case TextureFunction::LOD: out << "lod(s, "; break;
985 case TextureFunction::LOD0: out << "lod(s, "; break;
986 case TextureFunction::LOD0BIAS: out << "lod(s, "; break;
987 default: UNREACHABLE();
990 else if (mOutputType == SH_HLSL11_OUTPUT)
992 if (textureFunction->method == TextureFunction::GRAD)
994 if (IsIntegerSampler(textureFunction->sampler))
998 else if (IsShadowSampler(textureFunction->sampler))
1000 out << "x.SampleCmpLevelZero(s, ";
1004 out << "x.SampleGrad(s, ";
1007 else if (IsIntegerSampler(textureFunction->sampler) ||
1008 textureFunction->method == TextureFunction::FETCH)
1012 else if (IsShadowSampler(textureFunction->sampler))
1014 out << "x.SampleCmp(s, ";
1018 switch(textureFunction->method)
1020 case TextureFunction::IMPLICIT: out << "x.Sample(s, "; break;
1021 case TextureFunction::BIAS: out << "x.SampleBias(s, "; break;
1022 case TextureFunction::LOD: out << "x.SampleLevel(s, "; break;
1023 case TextureFunction::LOD0: out << "x.SampleLevel(s, "; break;
1024 case TextureFunction::LOD0BIAS: out << "x.SampleLevel(s, "; break;
1025 default: UNREACHABLE();
1031 // Integer sampling requires integer addresses
1032 TString addressx = "";
1033 TString addressy = "";
1034 TString addressz = "";
1037 if (IsIntegerSampler(textureFunction->sampler) ||
1038 textureFunction->method == TextureFunction::FETCH)
1042 case 2: out << "int3("; break;
1043 case 3: out << "int4("; break;
1044 default: UNREACHABLE();
1047 // Convert from normalized floating-point to integer
1048 if (textureFunction->method != TextureFunction::FETCH)
1050 addressx = "int(floor(width * frac((";
1051 addressy = "int(floor(height * frac((";
1053 if (IsSamplerArray(textureFunction->sampler))
1055 addressz = "int(max(0, min(layers - 1, floor(0.5 + ";
1057 else if (IsSamplerCube(textureFunction->sampler))
1063 addressz = "int(floor(depth * frac((";
1073 case 2: out << "float2("; break;
1074 case 3: out << "float3("; break;
1075 case 4: out << "float4("; break;
1076 default: UNREACHABLE();
1080 TString proj = ""; // Only used for projected textures
1082 if (textureFunction->proj)
1084 switch(textureFunction->coords)
1086 case 3: proj = " / t.z"; break;
1087 case 4: proj = " / t.w"; break;
1088 default: UNREACHABLE();
1092 out << addressx + ("t.x" + proj) + close + ", " + addressy + ("t.y" + proj) + close;
1094 if (mOutputType == SH_HLSL9_OUTPUT)
1096 if (hlslCoords >= 3)
1098 if (textureFunction->coords < 3)
1104 out << ", t.z" + proj;
1108 if (hlslCoords == 4)
1110 switch(textureFunction->method)
1112 case TextureFunction::BIAS: out << ", bias"; break;
1113 case TextureFunction::LOD: out << ", lod"; break;
1114 case TextureFunction::LOD0: out << ", 0"; break;
1115 case TextureFunction::LOD0BIAS: out << ", bias"; break;
1116 default: UNREACHABLE();
1122 else if (mOutputType == SH_HLSL11_OUTPUT)
1124 if (hlslCoords >= 3)
1126 if (IsIntegerSampler(textureFunction->sampler) && IsSamplerCube(textureFunction->sampler))
1132 out << ", " + addressz + ("t.z" + proj) + close;
1136 if (textureFunction->method == TextureFunction::GRAD)
1138 if (IsIntegerSampler(textureFunction->sampler))
1142 else if (IsShadowSampler(textureFunction->sampler))
1145 switch(textureFunction->coords)
1147 case 3: out << "), t.z"; break;
1148 case 4: out << "), t.w"; break;
1149 default: UNREACHABLE();
1154 out << "), ddx, ddy";
1157 else if (IsIntegerSampler(textureFunction->sampler) ||
1158 textureFunction->method == TextureFunction::FETCH)
1162 else if (IsShadowSampler(textureFunction->sampler))
1165 switch(textureFunction->coords)
1167 case 3: out << "), t.z"; break;
1168 case 4: out << "), t.w"; break;
1169 default: UNREACHABLE();
1174 switch(textureFunction->method)
1176 case TextureFunction::IMPLICIT: out << ")"; break;
1177 case TextureFunction::BIAS: out << "), bias"; break;
1178 case TextureFunction::LOD: out << "), lod"; break;
1179 case TextureFunction::LOD0: out << "), 0"; break;
1180 case TextureFunction::LOD0BIAS: out << "), bias"; break;
1181 default: UNREACHABLE();
1185 if (textureFunction->offset)
1202 out << "#define GL_USES_FRAG_COORD\n";
1205 if (mUsesPointCoord)
1207 out << "#define GL_USES_POINT_COORD\n";
1210 if (mUsesFrontFacing)
1212 out << "#define GL_USES_FRONT_FACING\n";
1217 out << "#define GL_USES_POINT_SIZE\n";
1222 out << "#define GL_USES_FRAG_DEPTH\n";
1225 if (mUsesDepthRange)
1227 out << "#define GL_USES_DEPTH_RANGE\n";
1232 out << "bool xor(bool p, bool q)\n"
1234 " return (p || q) && !(p && q);\n"
1241 out << "float mod(float x, float y)\n"
1243 " return x - y * floor(x / y);\n"
1250 out << "float2 mod(float2 x, float2 y)\n"
1252 " return x - y * floor(x / y);\n"
1259 out << "float2 mod(float2 x, float y)\n"
1261 " return x - y * floor(x / y);\n"
1268 out << "float3 mod(float3 x, float3 y)\n"
1270 " return x - y * floor(x / y);\n"
1277 out << "float3 mod(float3 x, float y)\n"
1279 " return x - y * floor(x / y);\n"
1286 out << "float4 mod(float4 x, float4 y)\n"
1288 " return x - y * floor(x / y);\n"
1295 out << "float4 mod(float4 x, float y)\n"
1297 " return x - y * floor(x / y);\n"
1302 if (mUsesFaceforward1)
1304 out << "float faceforward(float N, float I, float Nref)\n"
1306 " if(dot(Nref, I) >= 0)\n"
1318 if (mUsesFaceforward2)
1320 out << "float2 faceforward(float2 N, float2 I, float2 Nref)\n"
1322 " if(dot(Nref, I) >= 0)\n"
1334 if (mUsesFaceforward3)
1336 out << "float3 faceforward(float3 N, float3 I, float3 Nref)\n"
1338 " if(dot(Nref, I) >= 0)\n"
1350 if (mUsesFaceforward4)
1352 out << "float4 faceforward(float4 N, float4 I, float4 Nref)\n"
1354 " if(dot(Nref, I) >= 0)\n"
1368 out << "float atanyx(float y, float x)\n"
1370 " if(x == 0 && y == 0) x = 1;\n" // Avoid producing a NaN
1371 " return atan2(y, x);\n"
1377 out << "float2 atanyx(float2 y, float2 x)\n"
1379 " if(x[0] == 0 && y[0] == 0) x[0] = 1;\n"
1380 " if(x[1] == 0 && y[1] == 0) x[1] = 1;\n"
1381 " return float2(atan2(y[0], x[0]), atan2(y[1], x[1]));\n"
1387 out << "float3 atanyx(float3 y, float3 x)\n"
1389 " if(x[0] == 0 && y[0] == 0) x[0] = 1;\n"
1390 " if(x[1] == 0 && y[1] == 0) x[1] = 1;\n"
1391 " if(x[2] == 0 && y[2] == 0) x[2] = 1;\n"
1392 " return float3(atan2(y[0], x[0]), atan2(y[1], x[1]), atan2(y[2], x[2]));\n"
1398 out << "float4 atanyx(float4 y, float4 x)\n"
1400 " if(x[0] == 0 && y[0] == 0) x[0] = 1;\n"
1401 " if(x[1] == 0 && y[1] == 0) x[1] = 1;\n"
1402 " if(x[2] == 0 && y[2] == 0) x[2] = 1;\n"
1403 " if(x[3] == 0 && y[3] == 0) x[3] = 1;\n"
1404 " return float4(atan2(y[0], x[0]), atan2(y[1], x[1]), atan2(y[2], x[2]), atan2(y[3], x[3]));\n"
1409 void OutputHLSL::visitSymbol(TIntermSymbol *node)
1411 TInfoSinkBase &out = mBody;
1413 // Handle accessing std140 structs by value
1414 if (mFlaggedStructMappedNames.count(node) > 0)
1416 out << mFlaggedStructMappedNames[node];
1420 TString name = node->getSymbol();
1422 if (name == "gl_DepthRange")
1424 mUsesDepthRange = true;
1429 TQualifier qualifier = node->getQualifier();
1431 if (qualifier == EvqUniform)
1433 const TType& nodeType = node->getType();
1434 const TInterfaceBlock* interfaceBlock = nodeType.getInterfaceBlock();
1438 mReferencedInterfaceBlocks[interfaceBlock->name()] = node;
1442 mReferencedUniforms[name] = node;
1445 out << DecorateUniform(name, nodeType);
1447 else if (qualifier == EvqAttribute || qualifier == EvqVertexIn)
1449 mReferencedAttributes[name] = node;
1450 out << Decorate(name);
1452 else if (IsVarying(qualifier))
1454 mReferencedVaryings[name] = node;
1455 out << Decorate(name);
1457 else if (qualifier == EvqFragmentOut)
1459 mReferencedOutputVariables[name] = node;
1460 out << "out_" << name;
1462 else if (qualifier == EvqFragColor)
1464 out << "gl_Color[0]";
1465 mUsesFragColor = true;
1467 else if (qualifier == EvqFragData)
1470 mUsesFragData = true;
1472 else if (qualifier == EvqFragCoord)
1474 mUsesFragCoord = true;
1477 else if (qualifier == EvqPointCoord)
1479 mUsesPointCoord = true;
1482 else if (qualifier == EvqFrontFacing)
1484 mUsesFrontFacing = true;
1487 else if (qualifier == EvqPointSize)
1489 mUsesPointSize = true;
1492 else if (name == "gl_FragDepthEXT")
1494 mUsesFragDepth = true;
1497 else if (qualifier == EvqInternal)
1503 out << Decorate(name);
1508 void OutputHLSL::visitRaw(TIntermRaw *node)
1510 mBody << node->getRawText();
1513 bool OutputHLSL::visitBinary(Visit visit, TIntermBinary *node)
1515 TInfoSinkBase &out = mBody;
1517 // Handle accessing std140 structs by value
1518 if (mFlaggedStructMappedNames.count(node) > 0)
1520 out << mFlaggedStructMappedNames[node];
1524 switch (node->getOp())
1526 case EOpAssign: outputTriplet(visit, "(", " = ", ")"); break;
1528 if (visit == PreVisit)
1530 // GLSL allows to write things like "float x = x;" where a new variable x is defined
1531 // and the value of an existing variable x is assigned. HLSL uses C semantics (the
1532 // new variable is created before the assignment is evaluated), so we need to convert
1533 // this to "float t = x, x = t;".
1535 TIntermSymbol *symbolNode = node->getLeft()->getAsSymbolNode();
1536 TIntermTyped *expression = node->getRight();
1538 sh::SearchSymbol searchSymbol(symbolNode->getSymbol());
1539 expression->traverse(&searchSymbol);
1540 bool sameSymbol = searchSymbol.foundMatch();
1544 // Type already printed
1545 out << "t" + str(mUniqueIndex) + " = ";
1546 expression->traverse(this);
1548 symbolNode->traverse(this);
1549 out << " = t" + str(mUniqueIndex);
1555 else if (visit == InVisit)
1560 case EOpAddAssign: outputTriplet(visit, "(", " += ", ")"); break;
1561 case EOpSubAssign: outputTriplet(visit, "(", " -= ", ")"); break;
1562 case EOpMulAssign: outputTriplet(visit, "(", " *= ", ")"); break;
1563 case EOpVectorTimesScalarAssign: outputTriplet(visit, "(", " *= ", ")"); break;
1564 case EOpMatrixTimesScalarAssign: outputTriplet(visit, "(", " *= ", ")"); break;
1565 case EOpVectorTimesMatrixAssign:
1566 if (visit == PreVisit)
1570 else if (visit == InVisit)
1573 node->getLeft()->traverse(this);
1574 out << ", transpose(";
1581 case EOpMatrixTimesMatrixAssign:
1582 if (visit == PreVisit)
1586 else if (visit == InVisit)
1589 node->getLeft()->traverse(this);
1597 case EOpDivAssign: outputTriplet(visit, "(", " /= ", ")"); break;
1598 case EOpIndexDirect:
1600 const TType& leftType = node->getLeft()->getType();
1601 if (leftType.isInterfaceBlock())
1603 if (visit == PreVisit)
1605 TInterfaceBlock* interfaceBlock = leftType.getInterfaceBlock();
1606 const int arrayIndex = node->getRight()->getAsConstantUnion()->getIConst(0);
1607 mReferencedInterfaceBlocks[interfaceBlock->instanceName()] = node->getLeft()->getAsSymbolNode();
1608 out << mUniformHLSL->interfaceBlockInstanceString(*interfaceBlock, arrayIndex);
1614 outputTriplet(visit, "", "[", "]");
1618 case EOpIndexIndirect:
1619 // We do not currently support indirect references to interface blocks
1620 ASSERT(node->getLeft()->getBasicType() != EbtInterfaceBlock);
1621 outputTriplet(visit, "", "[", "]");
1623 case EOpIndexDirectStruct:
1624 if (visit == InVisit)
1626 const TStructure* structure = node->getLeft()->getType().getStruct();
1627 const TIntermConstantUnion* index = node->getRight()->getAsConstantUnion();
1628 const TField* field = structure->fields()[index->getIConst(0)];
1629 out << "." + DecorateField(field->name(), *structure);
1634 case EOpIndexDirectInterfaceBlock:
1635 if (visit == InVisit)
1637 const TInterfaceBlock* interfaceBlock = node->getLeft()->getType().getInterfaceBlock();
1638 const TIntermConstantUnion* index = node->getRight()->getAsConstantUnion();
1639 const TField* field = interfaceBlock->fields()[index->getIConst(0)];
1640 out << "." + Decorate(field->name());
1645 case EOpVectorSwizzle:
1646 if (visit == InVisit)
1650 TIntermAggregate *swizzle = node->getRight()->getAsAggregate();
1654 TIntermSequence *sequence = swizzle->getSequence();
1656 for (TIntermSequence::iterator sit = sequence->begin(); sit != sequence->end(); sit++)
1658 TIntermConstantUnion *element = (*sit)->getAsConstantUnion();
1662 int i = element->getIConst(0);
1666 case 0: out << "x"; break;
1667 case 1: out << "y"; break;
1668 case 2: out << "z"; break;
1669 case 3: out << "w"; break;
1670 default: UNREACHABLE();
1678 return false; // Fully processed
1681 case EOpAdd: outputTriplet(visit, "(", " + ", ")"); break;
1682 case EOpSub: outputTriplet(visit, "(", " - ", ")"); break;
1683 case EOpMul: outputTriplet(visit, "(", " * ", ")"); break;
1684 case EOpDiv: outputTriplet(visit, "(", " / ", ")"); break;
1687 if (node->getLeft()->isScalar())
1689 if (node->getOp() == EOpEqual)
1691 outputTriplet(visit, "(", " == ", ")");
1695 outputTriplet(visit, "(", " != ", ")");
1698 else if (node->getLeft()->getBasicType() == EbtStruct)
1700 if (node->getOp() == EOpEqual)
1709 const TStructure &structure = *node->getLeft()->getType().getStruct();
1710 const TFieldList &fields = structure.fields();
1712 for (size_t i = 0; i < fields.size(); i++)
1714 const TField *field = fields[i];
1716 node->getLeft()->traverse(this);
1717 out << "." + DecorateField(field->name(), structure) + " == ";
1718 node->getRight()->traverse(this);
1719 out << "." + DecorateField(field->name(), structure);
1721 if (i < fields.size() - 1)
1733 ASSERT(node->getLeft()->isMatrix() || node->getLeft()->isVector());
1735 if (node->getOp() == EOpEqual)
1737 outputTriplet(visit, "all(", " == ", ")");
1741 outputTriplet(visit, "!all(", " == ", ")");
1745 case EOpLessThan: outputTriplet(visit, "(", " < ", ")"); break;
1746 case EOpGreaterThan: outputTriplet(visit, "(", " > ", ")"); break;
1747 case EOpLessThanEqual: outputTriplet(visit, "(", " <= ", ")"); break;
1748 case EOpGreaterThanEqual: outputTriplet(visit, "(", " >= ", ")"); break;
1749 case EOpVectorTimesScalar: outputTriplet(visit, "(", " * ", ")"); break;
1750 case EOpMatrixTimesScalar: outputTriplet(visit, "(", " * ", ")"); break;
1751 case EOpVectorTimesMatrix: outputTriplet(visit, "mul(", ", transpose(", "))"); break;
1752 case EOpMatrixTimesVector: outputTriplet(visit, "mul(transpose(", "), ", ")"); break;
1753 case EOpMatrixTimesMatrix: outputTriplet(visit, "transpose(mul(transpose(", "), transpose(", ")))"); break;
1755 if (node->getRight()->hasSideEffects())
1757 out << "s" << mUnfoldShortCircuit->getNextTemporaryIndex();
1762 outputTriplet(visit, "(", " || ", ")");
1767 outputTriplet(visit, "xor(", ", ", ")");
1770 if (node->getRight()->hasSideEffects())
1772 out << "s" << mUnfoldShortCircuit->getNextTemporaryIndex();
1777 outputTriplet(visit, "(", " && ", ")");
1780 default: UNREACHABLE();
1786 bool OutputHLSL::visitUnary(Visit visit, TIntermUnary *node)
1788 switch (node->getOp())
1790 case EOpNegative: outputTriplet(visit, "(-", "", ")"); break;
1791 case EOpVectorLogicalNot: outputTriplet(visit, "(!", "", ")"); break;
1792 case EOpLogicalNot: outputTriplet(visit, "(!", "", ")"); break;
1793 case EOpPostIncrement: outputTriplet(visit, "(", "", "++)"); break;
1794 case EOpPostDecrement: outputTriplet(visit, "(", "", "--)"); break;
1795 case EOpPreIncrement: outputTriplet(visit, "(++", "", ")"); break;
1796 case EOpPreDecrement: outputTriplet(visit, "(--", "", ")"); break;
1797 case EOpRadians: outputTriplet(visit, "radians(", "", ")"); break;
1798 case EOpDegrees: outputTriplet(visit, "degrees(", "", ")"); break;
1799 case EOpSin: outputTriplet(visit, "sin(", "", ")"); break;
1800 case EOpCos: outputTriplet(visit, "cos(", "", ")"); break;
1801 case EOpTan: outputTriplet(visit, "tan(", "", ")"); break;
1802 case EOpAsin: outputTriplet(visit, "asin(", "", ")"); break;
1803 case EOpAcos: outputTriplet(visit, "acos(", "", ")"); break;
1804 case EOpAtan: outputTriplet(visit, "atan(", "", ")"); break;
1805 case EOpExp: outputTriplet(visit, "exp(", "", ")"); break;
1806 case EOpLog: outputTriplet(visit, "log(", "", ")"); break;
1807 case EOpExp2: outputTriplet(visit, "exp2(", "", ")"); break;
1808 case EOpLog2: outputTriplet(visit, "log2(", "", ")"); break;
1809 case EOpSqrt: outputTriplet(visit, "sqrt(", "", ")"); break;
1810 case EOpInverseSqrt: outputTriplet(visit, "rsqrt(", "", ")"); break;
1811 case EOpAbs: outputTriplet(visit, "abs(", "", ")"); break;
1812 case EOpSign: outputTriplet(visit, "sign(", "", ")"); break;
1813 case EOpFloor: outputTriplet(visit, "floor(", "", ")"); break;
1814 case EOpCeil: outputTriplet(visit, "ceil(", "", ")"); break;
1815 case EOpFract: outputTriplet(visit, "frac(", "", ")"); break;
1816 case EOpLength: outputTriplet(visit, "length(", "", ")"); break;
1817 case EOpNormalize: outputTriplet(visit, "normalize(", "", ")"); break;
1819 if(mInsideDiscontinuousLoop || mOutputLod0Function)
1821 outputTriplet(visit, "(", "", ", 0.0)");
1825 outputTriplet(visit, "ddx(", "", ")");
1829 if(mInsideDiscontinuousLoop || mOutputLod0Function)
1831 outputTriplet(visit, "(", "", ", 0.0)");
1835 outputTriplet(visit, "ddy(", "", ")");
1839 if(mInsideDiscontinuousLoop || mOutputLod0Function)
1841 outputTriplet(visit, "(", "", ", 0.0)");
1845 outputTriplet(visit, "fwidth(", "", ")");
1848 case EOpAny: outputTriplet(visit, "any(", "", ")"); break;
1849 case EOpAll: outputTriplet(visit, "all(", "", ")"); break;
1850 default: UNREACHABLE();
1856 bool OutputHLSL::visitAggregate(Visit visit, TIntermAggregate *node)
1858 TInfoSinkBase &out = mBody;
1860 switch (node->getOp())
1864 if (mInsideFunction)
1866 outputLineDirective(node->getLine().first_line);
1870 for (TIntermSequence::iterator sit = node->getSequence()->begin(); sit != node->getSequence()->end(); sit++)
1872 outputLineDirective((*sit)->getLine().first_line);
1874 traverseStatements(*sit);
1879 if (mInsideFunction)
1881 outputLineDirective(node->getLine().last_line);
1887 case EOpDeclaration:
1888 if (visit == PreVisit)
1890 TIntermSequence *sequence = node->getSequence();
1891 TIntermTyped *variable = (*sequence)[0]->getAsTyped();
1893 if (variable && (variable->getQualifier() == EvqTemporary || variable->getQualifier() == EvqGlobal))
1895 TStructure *structure = variable->getType().getStruct();
1899 mStructureHLSL->addConstructor(variable->getType(), StructNameString(*structure), NULL);
1902 if (!variable->getAsSymbolNode() || variable->getAsSymbolNode()->getSymbol() != "") // Variable declaration
1904 if (!mInsideFunction)
1909 out << TypeString(variable->getType()) + " ";
1911 for (TIntermSequence::iterator sit = sequence->begin(); sit != sequence->end(); sit++)
1913 TIntermSymbol *symbol = (*sit)->getAsSymbolNode();
1917 symbol->traverse(this);
1918 out << ArrayString(symbol->getType());
1919 out << " = " + initializer(symbol->getType());
1923 (*sit)->traverse(this);
1926 if (*sit != sequence->back())
1932 else if (variable->getAsSymbolNode() && variable->getAsSymbolNode()->getSymbol() == "") // Type (struct) declaration
1934 // Already added to constructor map
1938 else if (variable && IsVaryingOut(variable->getQualifier()))
1940 // Skip translation of invariant declarations
1941 if (variable->getBasicType() == EbtInvariant)
1946 for (TIntermSequence::iterator sit = sequence->begin(); sit != sequence->end(); sit++)
1948 TIntermSymbol *symbol = (*sit)->getAsSymbolNode();
1952 // Vertex (output) varyings which are declared but not written to should still be declared to allow successful linking
1953 mReferencedVaryings[symbol->getSymbol()] = symbol;
1957 (*sit)->traverse(this);
1964 else if (visit == InVisit)
1970 if (visit == PreVisit)
1972 out << TypeString(node->getType()) << " " << Decorate(node->getName()) << (mOutputLod0Function ? "Lod0(" : "(");
1974 TIntermSequence *arguments = node->getSequence();
1976 for (unsigned int i = 0; i < arguments->size(); i++)
1978 TIntermSymbol *symbol = (*arguments)[i]->getAsSymbolNode();
1982 out << argumentString(symbol);
1984 if (i < arguments->size() - 1)
1994 // Also prototype the Lod0 variant if needed
1995 if (mContainsLoopDiscontinuity && !mOutputLod0Function)
1997 mOutputLod0Function = true;
1998 node->traverse(this);
1999 mOutputLod0Function = false;
2005 case EOpComma: outputTriplet(visit, "(", ", ", ")"); break;
2008 TString name = TFunction::unmangleName(node->getName());
2010 out << TypeString(node->getType()) << " ";
2018 out << Decorate(name) << (mOutputLod0Function ? "Lod0(" : "(");
2021 TIntermSequence *sequence = node->getSequence();
2022 TIntermSequence *arguments = (*sequence)[0]->getAsAggregate()->getSequence();
2024 for (unsigned int i = 0; i < arguments->size(); i++)
2026 TIntermSymbol *symbol = (*arguments)[i]->getAsSymbolNode();
2030 TStructure *structure = symbol->getType().getStruct();
2034 mStructureHLSL->addConstructor(symbol->getType(), StructNameString(*structure), NULL);
2037 out << argumentString(symbol);
2039 if (i < arguments->size() - 1)
2050 if (sequence->size() > 1)
2052 mInsideFunction = true;
2053 (*sequence)[1]->traverse(this);
2054 mInsideFunction = false;
2059 if (mContainsLoopDiscontinuity && !mOutputLod0Function)
2063 mOutputLod0Function = true;
2064 node->traverse(this);
2065 mOutputLod0Function = false;
2072 case EOpFunctionCall:
2074 TString name = TFunction::unmangleName(node->getName());
2075 bool lod0 = mInsideDiscontinuousLoop || mOutputLod0Function;
2076 TIntermSequence *arguments = node->getSequence();
2078 if (node->isUserDefined())
2080 out << Decorate(name) << (lod0 ? "Lod0(" : "(");
2084 TBasicType samplerType = (*arguments)[0]->getAsTyped()->getType().getBasicType();
2086 TextureFunction textureFunction;
2087 textureFunction.sampler = samplerType;
2088 textureFunction.coords = (*arguments)[1]->getAsTyped()->getNominalSize();
2089 textureFunction.method = TextureFunction::IMPLICIT;
2090 textureFunction.proj = false;
2091 textureFunction.offset = false;
2093 if (name == "texture2D" || name == "textureCube" || name == "texture")
2095 textureFunction.method = TextureFunction::IMPLICIT;
2097 else if (name == "texture2DProj" || name == "textureProj")
2099 textureFunction.method = TextureFunction::IMPLICIT;
2100 textureFunction.proj = true;
2102 else if (name == "texture2DLod" || name == "textureCubeLod" || name == "textureLod" ||
2103 name == "texture2DLodEXT" || name == "textureCubeLodEXT")
2105 textureFunction.method = TextureFunction::LOD;
2107 else if (name == "texture2DProjLod" || name == "textureProjLod" || name == "texture2DProjLodEXT")
2109 textureFunction.method = TextureFunction::LOD;
2110 textureFunction.proj = true;
2112 else if (name == "textureSize")
2114 textureFunction.method = TextureFunction::SIZE;
2116 else if (name == "textureOffset")
2118 textureFunction.method = TextureFunction::IMPLICIT;
2119 textureFunction.offset = true;
2121 else if (name == "textureProjOffset")
2123 textureFunction.method = TextureFunction::IMPLICIT;
2124 textureFunction.offset = true;
2125 textureFunction.proj = true;
2127 else if (name == "textureLodOffset")
2129 textureFunction.method = TextureFunction::LOD;
2130 textureFunction.offset = true;
2132 else if (name == "textureProjLodOffset")
2134 textureFunction.method = TextureFunction::LOD;
2135 textureFunction.proj = true;
2136 textureFunction.offset = true;
2138 else if (name == "texelFetch")
2140 textureFunction.method = TextureFunction::FETCH;
2142 else if (name == "texelFetchOffset")
2144 textureFunction.method = TextureFunction::FETCH;
2145 textureFunction.offset = true;
2147 else if (name == "textureGrad" || name == "texture2DGradEXT")
2149 textureFunction.method = TextureFunction::GRAD;
2151 else if (name == "textureGradOffset")
2153 textureFunction.method = TextureFunction::GRAD;
2154 textureFunction.offset = true;
2156 else if (name == "textureProjGrad" || name == "texture2DProjGradEXT" || name == "textureCubeGradEXT")
2158 textureFunction.method = TextureFunction::GRAD;
2159 textureFunction.proj = true;
2161 else if (name == "textureProjGradOffset")
2163 textureFunction.method = TextureFunction::GRAD;
2164 textureFunction.proj = true;
2165 textureFunction.offset = true;
2169 if (textureFunction.method == TextureFunction::IMPLICIT) // Could require lod 0 or have a bias argument
2171 unsigned int mandatoryArgumentCount = 2; // All functions have sampler and coordinate arguments
2173 if (textureFunction.offset)
2175 mandatoryArgumentCount++;
2178 bool bias = (arguments->size() > mandatoryArgumentCount); // Bias argument is optional
2180 if (lod0 || mContext.shaderType == GL_VERTEX_SHADER)
2184 textureFunction.method = TextureFunction::LOD0BIAS;
2188 textureFunction.method = TextureFunction::LOD0;
2193 textureFunction.method = TextureFunction::BIAS;
2197 mUsesTexture.insert(textureFunction);
2199 out << textureFunction.name();
2202 for (TIntermSequence::iterator arg = arguments->begin(); arg != arguments->end(); arg++)
2204 if (mOutputType == SH_HLSL11_OUTPUT && IsSampler((*arg)->getAsTyped()->getBasicType()))
2207 (*arg)->traverse(this);
2208 out << ", sampler_";
2211 (*arg)->traverse(this);
2213 if (arg < arguments->end() - 1)
2224 case EOpParameters: outputTriplet(visit, "(", ", ", ")\n{\n"); break;
2225 case EOpConstructFloat: outputConstructor(visit, node->getType(), "vec1", node->getSequence()); break;
2226 case EOpConstructVec2: outputConstructor(visit, node->getType(), "vec2", node->getSequence()); break;
2227 case EOpConstructVec3: outputConstructor(visit, node->getType(), "vec3", node->getSequence()); break;
2228 case EOpConstructVec4: outputConstructor(visit, node->getType(), "vec4", node->getSequence()); break;
2229 case EOpConstructBool: outputConstructor(visit, node->getType(), "bvec1", node->getSequence()); break;
2230 case EOpConstructBVec2: outputConstructor(visit, node->getType(), "bvec2", node->getSequence()); break;
2231 case EOpConstructBVec3: outputConstructor(visit, node->getType(), "bvec3", node->getSequence()); break;
2232 case EOpConstructBVec4: outputConstructor(visit, node->getType(), "bvec4", node->getSequence()); break;
2233 case EOpConstructInt: outputConstructor(visit, node->getType(), "ivec1", node->getSequence()); break;
2234 case EOpConstructIVec2: outputConstructor(visit, node->getType(), "ivec2", node->getSequence()); break;
2235 case EOpConstructIVec3: outputConstructor(visit, node->getType(), "ivec3", node->getSequence()); break;
2236 case EOpConstructIVec4: outputConstructor(visit, node->getType(), "ivec4", node->getSequence()); break;
2237 case EOpConstructUInt: outputConstructor(visit, node->getType(), "uvec1", node->getSequence()); break;
2238 case EOpConstructUVec2: outputConstructor(visit, node->getType(), "uvec2", node->getSequence()); break;
2239 case EOpConstructUVec3: outputConstructor(visit, node->getType(), "uvec3", node->getSequence()); break;
2240 case EOpConstructUVec4: outputConstructor(visit, node->getType(), "uvec4", node->getSequence()); break;
2241 case EOpConstructMat2: outputConstructor(visit, node->getType(), "mat2", node->getSequence()); break;
2242 case EOpConstructMat3: outputConstructor(visit, node->getType(), "mat3", node->getSequence()); break;
2243 case EOpConstructMat4: outputConstructor(visit, node->getType(), "mat4", node->getSequence()); break;
2244 case EOpConstructStruct:
2246 const TString &structName = StructNameString(*node->getType().getStruct());
2247 mStructureHLSL->addConstructor(node->getType(), structName, node->getSequence());
2248 outputTriplet(visit, structName + "_ctor(", ", ", ")");
2251 case EOpLessThan: outputTriplet(visit, "(", " < ", ")"); break;
2252 case EOpGreaterThan: outputTriplet(visit, "(", " > ", ")"); break;
2253 case EOpLessThanEqual: outputTriplet(visit, "(", " <= ", ")"); break;
2254 case EOpGreaterThanEqual: outputTriplet(visit, "(", " >= ", ")"); break;
2255 case EOpVectorEqual: outputTriplet(visit, "(", " == ", ")"); break;
2256 case EOpVectorNotEqual: outputTriplet(visit, "(", " != ", ")"); break;
2259 // We need to look at the number of components in both arguments
2260 const int modValue = (*node->getSequence())[0]->getAsTyped()->getNominalSize() * 10 +
2261 (*node->getSequence())[1]->getAsTyped()->getNominalSize();
2264 case 11: mUsesMod1 = true; break;
2265 case 22: mUsesMod2v = true; break;
2266 case 21: mUsesMod2f = true; break;
2267 case 33: mUsesMod3v = true; break;
2268 case 31: mUsesMod3f = true; break;
2269 case 44: mUsesMod4v = true; break;
2270 case 41: mUsesMod4f = true; break;
2271 default: UNREACHABLE();
2274 outputTriplet(visit, "mod(", ", ", ")");
2277 case EOpPow: outputTriplet(visit, "pow(", ", ", ")"); break;
2279 ASSERT(node->getSequence()->size() == 2); // atan(x) is a unary operator
2280 switch ((*node->getSequence())[0]->getAsTyped()->getNominalSize())
2282 case 1: mUsesAtan2_1 = true; break;
2283 case 2: mUsesAtan2_2 = true; break;
2284 case 3: mUsesAtan2_3 = true; break;
2285 case 4: mUsesAtan2_4 = true; break;
2286 default: UNREACHABLE();
2288 outputTriplet(visit, "atanyx(", ", ", ")");
2290 case EOpMin: outputTriplet(visit, "min(", ", ", ")"); break;
2291 case EOpMax: outputTriplet(visit, "max(", ", ", ")"); break;
2292 case EOpClamp: outputTriplet(visit, "clamp(", ", ", ")"); break;
2293 case EOpMix: outputTriplet(visit, "lerp(", ", ", ")"); break;
2294 case EOpStep: outputTriplet(visit, "step(", ", ", ")"); break;
2295 case EOpSmoothStep: outputTriplet(visit, "smoothstep(", ", ", ")"); break;
2296 case EOpDistance: outputTriplet(visit, "distance(", ", ", ")"); break;
2297 case EOpDot: outputTriplet(visit, "dot(", ", ", ")"); break;
2298 case EOpCross: outputTriplet(visit, "cross(", ", ", ")"); break;
2299 case EOpFaceForward:
2301 switch ((*node->getSequence())[0]->getAsTyped()->getNominalSize()) // Number of components in the first argument
2303 case 1: mUsesFaceforward1 = true; break;
2304 case 2: mUsesFaceforward2 = true; break;
2305 case 3: mUsesFaceforward3 = true; break;
2306 case 4: mUsesFaceforward4 = true; break;
2307 default: UNREACHABLE();
2310 outputTriplet(visit, "faceforward(", ", ", ")");
2313 case EOpReflect: outputTriplet(visit, "reflect(", ", ", ")"); break;
2314 case EOpRefract: outputTriplet(visit, "refract(", ", ", ")"); break;
2315 case EOpMul: outputTriplet(visit, "(", " * ", ")"); break;
2316 default: UNREACHABLE();
2322 bool OutputHLSL::visitSelection(Visit visit, TIntermSelection *node)
2324 TInfoSinkBase &out = mBody;
2326 if (node->usesTernaryOperator())
2328 out << "s" << mUnfoldShortCircuit->getNextTemporaryIndex();
2330 else // if/else statement
2332 mUnfoldShortCircuit->traverse(node->getCondition());
2336 node->getCondition()->traverse(this);
2340 outputLineDirective(node->getLine().first_line);
2343 bool discard = false;
2345 if (node->getTrueBlock())
2347 traverseStatements(node->getTrueBlock());
2349 // Detect true discard
2350 discard = (discard || FindDiscard::search(node->getTrueBlock()));
2353 outputLineDirective(node->getLine().first_line);
2356 if (node->getFalseBlock())
2360 outputLineDirective(node->getFalseBlock()->getLine().first_line);
2363 outputLineDirective(node->getFalseBlock()->getLine().first_line);
2364 traverseStatements(node->getFalseBlock());
2366 outputLineDirective(node->getFalseBlock()->getLine().first_line);
2369 // Detect false discard
2370 discard = (discard || FindDiscard::search(node->getFalseBlock()));
2373 // ANGLE issue 486: Detect problematic conditional discard
2374 if (discard && FindSideEffectRewriting::search(node))
2376 mUsesDiscardRewriting = true;
2383 void OutputHLSL::visitConstantUnion(TIntermConstantUnion *node)
2385 writeConstantUnion(node->getType(), node->getUnionArrayPointer());
2388 bool OutputHLSL::visitLoop(Visit visit, TIntermLoop *node)
2392 bool wasDiscontinuous = mInsideDiscontinuousLoop;
2394 if (mContainsLoopDiscontinuity && !mInsideDiscontinuousLoop)
2396 mInsideDiscontinuousLoop = containsLoopDiscontinuity(node);
2399 if (mOutputType == SH_HLSL9_OUTPUT)
2401 if (handleExcessiveLoop(node))
2403 mInsideDiscontinuousLoop = wasDiscontinuous;
2410 TInfoSinkBase &out = mBody;
2412 if (node->getType() == ELoopDoWhile)
2416 outputLineDirective(node->getLine().first_line);
2423 if (node->getInit())
2425 node->getInit()->traverse(this);
2430 if (node->getCondition())
2432 node->getCondition()->traverse(this);
2437 if (node->getExpression())
2439 node->getExpression()->traverse(this);
2444 outputLineDirective(node->getLine().first_line);
2448 if (node->getBody())
2450 traverseStatements(node->getBody());
2453 outputLineDirective(node->getLine().first_line);
2456 if (node->getType() == ELoopDoWhile)
2458 outputLineDirective(node->getCondition()->getLine().first_line);
2461 node->getCondition()->traverse(this);
2468 mInsideDiscontinuousLoop = wasDiscontinuous;
2474 bool OutputHLSL::visitBranch(Visit visit, TIntermBranch *node)
2476 TInfoSinkBase &out = mBody;
2478 switch (node->getFlowOp())
2481 outputTriplet(visit, "discard;\n", "", "");
2484 if (visit == PreVisit)
2486 if (mNestedLoopDepth > 1)
2488 mUsesNestedBreak = true;
2491 if (mExcessiveLoopIndex)
2494 mExcessiveLoopIndex->traverse(this);
2495 out << " = true; break;}\n";
2503 case EOpContinue: outputTriplet(visit, "continue;\n", "", ""); break;
2505 if (visit == PreVisit)
2507 if (node->getExpression())
2516 else if (visit == PostVisit)
2518 if (node->getExpression())
2524 default: UNREACHABLE();
2530 void OutputHLSL::traverseStatements(TIntermNode *node)
2532 if (isSingleStatement(node))
2534 mUnfoldShortCircuit->traverse(node);
2537 node->traverse(this);
2540 bool OutputHLSL::isSingleStatement(TIntermNode *node)
2542 TIntermAggregate *aggregate = node->getAsAggregate();
2546 if (aggregate->getOp() == EOpSequence)
2552 for (TIntermSequence::iterator sit = aggregate->getSequence()->begin(); sit != aggregate->getSequence()->end(); sit++)
2554 if (!isSingleStatement(*sit))
2567 // Handle loops with more than 254 iterations (unsupported by D3D9) by splitting them
2568 // (The D3D documentation says 255 iterations, but the compiler complains at anything more than 254).
2569 bool OutputHLSL::handleExcessiveLoop(TIntermLoop *node)
2571 const int MAX_LOOP_ITERATIONS = 254;
2572 TInfoSinkBase &out = mBody;
2574 // Parse loops of the form:
2575 // for(int index = initial; index [comparator] limit; index += increment)
2576 TIntermSymbol *index = NULL;
2577 TOperator comparator = EOpNull;
2582 // Parse index name and intial value
2583 if (node->getInit())
2585 TIntermAggregate *init = node->getInit()->getAsAggregate();
2589 TIntermSequence *sequence = init->getSequence();
2590 TIntermTyped *variable = (*sequence)[0]->getAsTyped();
2592 if (variable && variable->getQualifier() == EvqTemporary)
2594 TIntermBinary *assign = variable->getAsBinaryNode();
2596 if (assign->getOp() == EOpInitialize)
2598 TIntermSymbol *symbol = assign->getLeft()->getAsSymbolNode();
2599 TIntermConstantUnion *constant = assign->getRight()->getAsConstantUnion();
2601 if (symbol && constant)
2603 if (constant->getBasicType() == EbtInt && constant->isScalar())
2606 initial = constant->getIConst(0);
2614 // Parse comparator and limit value
2615 if (index != NULL && node->getCondition())
2617 TIntermBinary *test = node->getCondition()->getAsBinaryNode();
2619 if (test && test->getLeft()->getAsSymbolNode()->getId() == index->getId())
2621 TIntermConstantUnion *constant = test->getRight()->getAsConstantUnion();
2625 if (constant->getBasicType() == EbtInt && constant->isScalar())
2627 comparator = test->getOp();
2628 limit = constant->getIConst(0);
2635 if (index != NULL && comparator != EOpNull && node->getExpression())
2637 TIntermBinary *binaryTerminal = node->getExpression()->getAsBinaryNode();
2638 TIntermUnary *unaryTerminal = node->getExpression()->getAsUnaryNode();
2642 TOperator op = binaryTerminal->getOp();
2643 TIntermConstantUnion *constant = binaryTerminal->getRight()->getAsConstantUnion();
2647 if (constant->getBasicType() == EbtInt && constant->isScalar())
2649 int value = constant->getIConst(0);
2653 case EOpAddAssign: increment = value; break;
2654 case EOpSubAssign: increment = -value; break;
2655 default: UNIMPLEMENTED();
2660 else if (unaryTerminal)
2662 TOperator op = unaryTerminal->getOp();
2666 case EOpPostIncrement: increment = 1; break;
2667 case EOpPostDecrement: increment = -1; break;
2668 case EOpPreIncrement: increment = 1; break;
2669 case EOpPreDecrement: increment = -1; break;
2670 default: UNIMPLEMENTED();
2675 if (index != NULL && comparator != EOpNull && increment != 0)
2677 if (comparator == EOpLessThanEqual)
2679 comparator = EOpLessThan;
2683 if (comparator == EOpLessThan)
2685 int iterations = (limit - initial) / increment;
2687 if (iterations <= MAX_LOOP_ITERATIONS)
2689 return false; // Not an excessive loop
2692 TIntermSymbol *restoreIndex = mExcessiveLoopIndex;
2693 mExcessiveLoopIndex = index;
2696 index->traverse(this);
2699 index->traverse(this);
2700 out << " = false;\n";
2702 bool firstLoopFragment = true;
2704 while (iterations > 0)
2706 int clampedLimit = initial + increment * std::min(MAX_LOOP_ITERATIONS, iterations);
2708 if (!firstLoopFragment)
2710 out << "if (!Break";
2711 index->traverse(this);
2715 if (iterations <= MAX_LOOP_ITERATIONS) // Last loop fragment
2717 mExcessiveLoopIndex = NULL; // Stops setting the Break flag
2720 // for(int index = initial; index < clampedLimit; index += increment)
2723 index->traverse(this);
2728 index->traverse(this);
2730 out << clampedLimit;
2733 index->traverse(this);
2738 outputLineDirective(node->getLine().first_line);
2741 if (node->getBody())
2743 node->getBody()->traverse(this);
2746 outputLineDirective(node->getLine().first_line);
2749 if (!firstLoopFragment)
2754 firstLoopFragment = false;
2756 initial += MAX_LOOP_ITERATIONS * increment;
2757 iterations -= MAX_LOOP_ITERATIONS;
2762 mExcessiveLoopIndex = restoreIndex;
2766 else UNIMPLEMENTED();
2769 return false; // Not handled as an excessive loop
2772 void OutputHLSL::outputTriplet(Visit visit, const TString &preString, const TString &inString, const TString &postString)
2774 TInfoSinkBase &out = mBody;
2776 if (visit == PreVisit)
2780 else if (visit == InVisit)
2784 else if (visit == PostVisit)
2790 void OutputHLSL::outputLineDirective(int line)
2792 if ((mContext.compileOptions & SH_LINE_DIRECTIVES) && (line > 0))
2795 mBody << "#line " << line;
2797 if (mContext.sourcePath)
2799 mBody << " \"" << mContext.sourcePath << "\"";
2806 TString OutputHLSL::argumentString(const TIntermSymbol *symbol)
2808 TQualifier qualifier = symbol->getQualifier();
2809 const TType &type = symbol->getType();
2810 TString name = symbol->getSymbol();
2812 if (name.empty()) // HLSL demands named arguments, also for prototypes
2814 name = "x" + str(mUniqueIndex++);
2818 name = Decorate(name);
2821 if (mOutputType == SH_HLSL11_OUTPUT && IsSampler(type.getBasicType()))
2823 return QualifierString(qualifier) + " " + TextureString(type) + " texture_" + name + ArrayString(type) + ", " +
2824 QualifierString(qualifier) + " " + SamplerString(type) + " sampler_" + name + ArrayString(type);
2827 return QualifierString(qualifier) + " " + TypeString(type) + " " + name + ArrayString(type);
2830 TString OutputHLSL::initializer(const TType &type)
2834 size_t size = type.getObjectSize();
2835 for (size_t component = 0; component < size; component++)
2839 if (component + 1 < size)
2845 return "{" + string + "}";
2848 void OutputHLSL::outputConstructor(Visit visit, const TType &type, const TString &name, const TIntermSequence *parameters)
2850 TInfoSinkBase &out = mBody;
2852 if (visit == PreVisit)
2854 mStructureHLSL->addConstructor(type, name, parameters);
2858 else if (visit == InVisit)
2862 else if (visit == PostVisit)
2868 const ConstantUnion *OutputHLSL::writeConstantUnion(const TType &type, const ConstantUnion *constUnion)
2870 TInfoSinkBase &out = mBody;
2872 const TStructure* structure = type.getStruct();
2875 out << StructNameString(*structure) + "_ctor(";
2877 const TFieldList& fields = structure->fields();
2879 for (size_t i = 0; i < fields.size(); i++)
2881 const TType *fieldType = fields[i]->type();
2882 constUnion = writeConstantUnion(*fieldType, constUnion);
2884 if (i != fields.size() - 1)
2894 size_t size = type.getObjectSize();
2895 bool writeType = size > 1;
2899 out << TypeString(type) << "(";
2902 for (size_t i = 0; i < size; i++, constUnion++)
2904 switch (constUnion->getType())
2906 case EbtFloat: out << std::min(FLT_MAX, std::max(-FLT_MAX, constUnion->getFConst())); break;
2907 case EbtInt: out << constUnion->getIConst(); break;
2908 case EbtUInt: out << constUnion->getUConst(); break;
2909 case EbtBool: out << constUnion->getBConst(); break;
2910 default: UNREACHABLE();
2928 class DeclareVaryingTraverser : public GetVariableTraverser<Varying>
2931 DeclareVaryingTraverser(std::vector<Varying> *output,
2932 InterpolationType interpolation)
2933 : GetVariableTraverser(output),
2934 mInterpolation(interpolation)
2938 void visitVariable(Varying *varying)
2940 varying->interpolation = mInterpolation;
2943 InterpolationType mInterpolation;
2946 void OutputHLSL::declareVaryingToList(const TType &type, TQualifier baseTypeQualifier,
2947 const TString &name, std::vector<Varying> &fieldsOut)
2949 DeclareVaryingTraverser traverser(&fieldsOut, GetInterpolationType(baseTypeQualifier));
2950 traverser.traverse(type, name);