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"
28 TString OutputHLSL::TextureFunction::name() const
30 TString name = "gl_texture";
32 if (IsSampler2D(sampler))
36 else if (IsSampler3D(sampler))
40 else if (IsSamplerCube(sampler))
59 case BIAS: break; // Extra parameter makes the signature unique
60 case LOD: name += "Lod"; break;
61 case LOD0: name += "Lod0"; break;
62 case LOD0BIAS: name += "Lod0"; break; // Extra parameter makes the signature unique
63 case SIZE: name += "Size"; break;
64 case FETCH: name += "Fetch"; break;
65 case GRAD: name += "Grad"; break;
66 default: UNREACHABLE();
72 const char *RegisterPrefix(const TType &type)
74 if (IsSampler(type.getBasicType()))
84 bool OutputHLSL::TextureFunction::operator<(const TextureFunction &rhs) const
86 if (sampler < rhs.sampler) return true;
87 if (sampler > rhs.sampler) return false;
89 if (coords < rhs.coords) return true;
90 if (coords > rhs.coords) return false;
92 if (!proj && rhs.proj) return true;
93 if (proj && !rhs.proj) return false;
95 if (!offset && rhs.offset) return true;
96 if (offset && !rhs.offset) return false;
98 if (method < rhs.method) return true;
99 if (method > rhs.method) return false;
104 OutputHLSL::OutputHLSL(TParseContext &context, const ShBuiltInResources& resources, ShShaderOutput outputType)
105 : TIntermTraverser(true, true, true), mContext(context), mOutputType(outputType)
107 mUnfoldShortCircuit = new UnfoldShortCircuit(context, this);
108 mInsideFunction = false;
110 mUsesFragColor = false;
111 mUsesFragData = false;
112 mUsesDepthRange = false;
113 mUsesFragCoord = false;
114 mUsesPointCoord = false;
115 mUsesFrontFacing = false;
116 mUsesPointSize = false;
117 mUsesFragDepth = false;
126 mUsesFaceforward1 = false;
127 mUsesFaceforward2 = false;
128 mUsesFaceforward3 = false;
129 mUsesFaceforward4 = false;
130 mUsesAtan2_1 = false;
131 mUsesAtan2_2 = false;
132 mUsesAtan2_3 = false;
133 mUsesAtan2_4 = false;
134 mUsesDiscardRewriting = false;
135 mUsesNestedBreak = false;
137 mNumRenderTargets = resources.EXT_draw_buffers ? resources.MaxDrawBuffers : 1;
141 mContainsLoopDiscontinuity = false;
142 mOutputLod0Function = false;
143 mInsideDiscontinuousLoop = false;
144 mNestedLoopDepth = 0;
146 mExcessiveLoopIndex = NULL;
148 if (mOutputType == SH_HLSL9_OUTPUT)
150 if (mContext.shaderType == SH_FRAGMENT_SHADER)
152 mUniformRegister = 3; // Reserve registers for dx_DepthRange, dx_ViewCoords and dx_DepthFront
156 mUniformRegister = 2; // Reserve registers for dx_DepthRange and dx_ViewAdjust
161 mUniformRegister = 0;
164 mSamplerRegister = 0;
165 mInterfaceBlockRegister = 2; // Reserve registers for the default uniform block and driver constants
169 OutputHLSL::~OutputHLSL()
171 delete mUnfoldShortCircuit;
174 void OutputHLSL::output()
176 mContainsLoopDiscontinuity = mContext.shaderType == SH_FRAGMENT_SHADER && containsLoopDiscontinuity(mContext.treeRoot);
177 const std::vector<TIntermTyped*> &flaggedStructs = FlagStd140ValueStructs(mContext.treeRoot);
178 makeFlaggedStructMaps(flaggedStructs);
180 // Work around D3D9 bug that would manifest in vertex shaders with selection blocks which
181 // use a vertex attribute as a condition, and some related computation in the else block.
182 if (mOutputType == SH_HLSL9_OUTPUT && mContext.shaderType == SH_VERTEX_SHADER)
184 RewriteElseBlocks(mContext.treeRoot);
187 mContext.treeRoot->traverse(this); // Output the body first to determine what has to go in the header
190 mContext.infoSink().obj << mHeader.c_str();
191 mContext.infoSink().obj << mBody.c_str();
194 void OutputHLSL::makeFlaggedStructMaps(const std::vector<TIntermTyped *> &flaggedStructs)
196 for (unsigned int structIndex = 0; structIndex < flaggedStructs.size(); structIndex++)
198 TIntermTyped *flaggedNode = flaggedStructs[structIndex];
200 // This will mark the necessary block elements as referenced
201 flaggedNode->traverse(this);
202 TString structName(mBody.c_str());
205 mFlaggedStructOriginalNames[flaggedNode] = structName;
207 for (size_t pos = structName.find('.'); pos != std::string::npos; pos = structName.find('.'))
209 structName.erase(pos, 1);
212 mFlaggedStructMappedNames[flaggedNode] = "map" + structName;
216 TInfoSinkBase &OutputHLSL::getBodyStream()
221 const std::vector<gl::Uniform> &OutputHLSL::getUniforms()
223 return mActiveUniforms;
226 const std::vector<gl::InterfaceBlock> &OutputHLSL::getInterfaceBlocks() const
228 return mActiveInterfaceBlocks;
231 const std::vector<gl::Attribute> &OutputHLSL::getOutputVariables() const
233 return mActiveOutputVariables;
236 const std::vector<gl::Attribute> &OutputHLSL::getAttributes() const
238 return mActiveAttributes;
241 const std::vector<gl::Varying> &OutputHLSL::getVaryings() const
243 return mActiveVaryings;
246 int OutputHLSL::vectorSize(const TType &type) const
248 int elementSize = type.isMatrix() ? type.getCols() : 1;
249 int arraySize = type.isArray() ? type.getArraySize() : 1;
251 return elementSize * arraySize;
254 TString OutputHLSL::interfaceBlockFieldString(const TInterfaceBlock &interfaceBlock, const TField &field)
256 if (interfaceBlock.hasInstanceName())
258 return interfaceBlock.name() + "." + field.name();
266 TString OutputHLSL::decoratePrivate(const TString &privateText)
268 return "dx_" + privateText;
271 TString OutputHLSL::interfaceBlockStructNameString(const TInterfaceBlock &interfaceBlock)
273 return decoratePrivate(interfaceBlock.name()) + "_type";
276 TString OutputHLSL::interfaceBlockInstanceString(const TInterfaceBlock& interfaceBlock, unsigned int arrayIndex)
278 if (!interfaceBlock.hasInstanceName())
282 else if (interfaceBlock.isArray())
284 return decoratePrivate(interfaceBlock.instanceName()) + "_" + str(arrayIndex);
288 return decorate(interfaceBlock.instanceName());
292 TString OutputHLSL::interfaceBlockFieldTypeString(const TField &field, TLayoutBlockStorage blockStorage)
294 const TType &fieldType = *field.type();
295 const TLayoutMatrixPacking matrixPacking = fieldType.getLayoutQualifier().matrixPacking;
296 ASSERT(matrixPacking != EmpUnspecified);
298 if (fieldType.isMatrix())
300 // Use HLSL row-major packing for GLSL column-major matrices
301 const TString &matrixPackString = (matrixPacking == EmpRowMajor ? "column_major" : "row_major");
302 return matrixPackString + " " + typeString(fieldType);
304 else if (fieldType.getStruct())
306 // Use HLSL row-major packing for GLSL column-major matrices
307 return structureTypeName(*fieldType.getStruct(), matrixPacking == EmpColumnMajor, blockStorage == EbsStd140);
311 return typeString(fieldType);
315 TString OutputHLSL::interfaceBlockFieldString(const TInterfaceBlock &interfaceBlock, TLayoutBlockStorage blockStorage)
319 int elementIndex = 0;
321 for (unsigned int typeIndex = 0; typeIndex < interfaceBlock.fields().size(); typeIndex++)
323 const TField &field = *interfaceBlock.fields()[typeIndex];
324 const TType &fieldType = *field.type();
326 if (blockStorage == EbsStd140)
328 // 2 and 3 component vector types in some cases need pre-padding
329 hlsl += std140PrePaddingString(fieldType, &elementIndex);
332 hlsl += " " + interfaceBlockFieldTypeString(field, blockStorage) +
333 " " + decorate(field.name()) + arrayString(fieldType) + ";\n";
335 // must pad out after matrices and arrays, where HLSL usually allows itself room to pack stuff
336 if (blockStorage == EbsStd140)
338 const bool useHLSLRowMajorPacking = (fieldType.getLayoutQualifier().matrixPacking == EmpColumnMajor);
339 hlsl += std140PostPaddingString(fieldType, useHLSLRowMajorPacking);
346 TString OutputHLSL::interfaceBlockStructString(const TInterfaceBlock &interfaceBlock)
348 const TLayoutBlockStorage blockStorage = interfaceBlock.blockStorage();
350 return "struct " + interfaceBlockStructNameString(interfaceBlock) + "\n"
352 interfaceBlockFieldString(interfaceBlock, blockStorage) +
356 TString OutputHLSL::interfaceBlockString(const TInterfaceBlock &interfaceBlock, unsigned int registerIndex, unsigned int arrayIndex)
358 const TString &arrayIndexString = (arrayIndex != GL_INVALID_INDEX ? decorate(str(arrayIndex)) : "");
359 const TString &blockName = interfaceBlock.name() + arrayIndexString;
362 hlsl += "cbuffer " + blockName + " : register(b" + str(registerIndex) + ")\n"
365 if (interfaceBlock.hasInstanceName())
367 hlsl += " " + interfaceBlockStructNameString(interfaceBlock) + " " + interfaceBlockInstanceString(interfaceBlock, arrayIndex) + ";\n";
371 const TLayoutBlockStorage blockStorage = interfaceBlock.blockStorage();
372 hlsl += interfaceBlockFieldString(interfaceBlock, blockStorage);
380 TString OutputHLSL::std140PrePaddingString(const TType &type, int *elementIndex)
382 if (type.getBasicType() == EbtStruct || type.isMatrix() || type.isArray())
384 // no padding needed, HLSL will align the field to a new register
389 const GLenum glType = glVariableType(type);
390 const int numComponents = gl::UniformComponentCount(glType);
392 if (numComponents >= 4)
394 // no padding needed, HLSL will align the field to a new register
399 if (*elementIndex + numComponents > 4)
401 // no padding needed, HLSL will align the field to a new register
402 *elementIndex = numComponents;
408 const int alignment = numComponents == 3 ? 4 : numComponents;
409 const int paddingOffset = (*elementIndex % alignment);
411 if (paddingOffset != 0)
413 // padding is neccessary
414 for (int paddingIndex = paddingOffset; paddingIndex < alignment; paddingIndex++)
416 padding += " float pad_" + str(mPaddingCounter++) + ";\n";
419 *elementIndex += (alignment - paddingOffset);
422 *elementIndex += numComponents;
428 TString OutputHLSL::std140PostPaddingString(const TType &type, bool useHLSLRowMajorPacking)
430 if (!type.isMatrix() && !type.isArray() && type.getBasicType() != EbtStruct)
435 int numComponents = 0;
439 // This method can also be called from structureString, which does not use layout qualifiers.
440 // Thus, use the method parameter for determining the matrix packing.
442 // Note HLSL row major packing corresponds to GL API column-major, and vice-versa, since we
443 // wish to always transpose GL matrices to play well with HLSL's matrix array indexing.
445 const bool isRowMajorMatrix = !useHLSLRowMajorPacking;
446 const GLenum glType = glVariableType(type);
447 numComponents = gl::MatrixComponentCount(glType, isRowMajorMatrix);
449 else if (type.getStruct())
451 const TString &structName = structureTypeName(*type.getStruct(), useHLSLRowMajorPacking, true);
452 numComponents = mStd140StructElementIndexes[structName];
454 if (numComponents == 0)
461 const GLenum glType = glVariableType(type);
462 numComponents = gl::UniformComponentCount(glType);
466 for (int paddingOffset = numComponents; paddingOffset < 4; paddingOffset++)
468 padding += " float pad_" + str(mPaddingCounter++) + ";\n";
473 // Use the same layout for packed and shared
474 void setBlockLayout(gl::InterfaceBlock *interfaceBlock, gl::BlockLayoutType newLayout)
476 interfaceBlock->layout = newLayout;
477 interfaceBlock->blockInfo.clear();
481 case gl::BLOCKLAYOUT_SHARED:
482 case gl::BLOCKLAYOUT_PACKED:
484 gl::HLSLBlockEncoder hlslEncoder(&interfaceBlock->blockInfo, gl::HLSLBlockEncoder::ENCODE_PACKED);
485 hlslEncoder.encodeInterfaceBlockFields(interfaceBlock->fields);
486 interfaceBlock->dataSize = hlslEncoder.getBlockSize();
490 case gl::BLOCKLAYOUT_STANDARD:
492 gl::Std140BlockEncoder stdEncoder(&interfaceBlock->blockInfo);
493 stdEncoder.encodeInterfaceBlockFields(interfaceBlock->fields);
494 interfaceBlock->dataSize = stdEncoder.getBlockSize();
504 gl::BlockLayoutType convertBlockLayoutType(TLayoutBlockStorage blockStorage)
506 switch (blockStorage)
508 case EbsPacked: return gl::BLOCKLAYOUT_PACKED;
509 case EbsShared: return gl::BLOCKLAYOUT_SHARED;
510 case EbsStd140: return gl::BLOCKLAYOUT_STANDARD;
511 default: UNREACHABLE(); return gl::BLOCKLAYOUT_SHARED;
515 TString OutputHLSL::structInitializerString(int indent, const TStructure &structure, const TString &rhsStructName)
519 TString preIndentString;
520 TString fullIndentString;
522 for (int spaces = 0; spaces < (indent * 4); spaces++)
524 preIndentString += ' ';
527 for (int spaces = 0; spaces < ((indent+1) * 4); spaces++)
529 fullIndentString += ' ';
532 init += preIndentString + "{\n";
534 const TFieldList &fields = structure.fields();
535 for (unsigned int fieldIndex = 0; fieldIndex < fields.size(); fieldIndex++)
537 const TField &field = *fields[fieldIndex];
538 const TString &fieldName = rhsStructName + "." + decorate(field.name());
539 const TType &fieldType = *field.type();
541 if (fieldType.getStruct())
543 init += structInitializerString(indent + 1, *fieldType.getStruct(), fieldName);
547 init += fullIndentString + fieldName + ",\n";
551 init += preIndentString + "}" + (indent == 0 ? ";" : ",") + "\n";
556 void OutputHLSL::header()
558 TInfoSinkBase &out = mHeader;
561 TString interfaceBlocks;
564 TString flaggedStructs;
566 for (ReferencedSymbols::const_iterator uniformIt = mReferencedUniforms.begin(); uniformIt != mReferencedUniforms.end(); uniformIt++)
568 const TIntermSymbol &uniform = *uniformIt->second;
569 const TType &type = uniform.getType();
570 const TString &name = uniform.getSymbol();
572 int registerIndex = declareUniformAndAssignRegister(type, name);
574 if (mOutputType == SH_HLSL11_OUTPUT && IsSampler(type.getBasicType())) // Also declare the texture
576 uniforms += "uniform " + samplerString(type) + " sampler_" + decorateUniform(name, type) + arrayString(type) +
577 " : register(s" + str(registerIndex) + ");\n";
579 uniforms += "uniform " + textureString(type) + " texture_" + decorateUniform(name, type) + arrayString(type) +
580 " : register(t" + str(registerIndex) + ");\n";
584 const TStructure *structure = type.getStruct();
585 // If this is a nameless struct, we need to use its full definition, rather than its (empty) name.
586 // TypeString() will invoke defineNameless in this case, but layout qualifiers, if relevant, will not
587 // be taken into account.
588 const TString &typeName = ((structure && !structure->name().empty()) ?
589 structureTypeName(*structure, false, false) : typeString(type));
591 const TString ®isterString = TString("register(") + RegisterPrefix(type) + str(registerIndex) + ")";
593 uniforms += "uniform " + typeName + " " + decorateUniform(name, type) + arrayString(type) + " : " + registerString + ";\n";
597 for (ReferencedSymbols::const_iterator interfaceBlockIt = mReferencedInterfaceBlocks.begin(); interfaceBlockIt != mReferencedInterfaceBlocks.end(); interfaceBlockIt++)
599 const TType &nodeType = interfaceBlockIt->second->getType();
600 const TInterfaceBlock &interfaceBlock = *nodeType.getInterfaceBlock();
601 const TFieldList &fieldList = interfaceBlock.fields();
603 unsigned int arraySize = static_cast<unsigned int>(interfaceBlock.arraySize());
604 gl::InterfaceBlock activeBlock(interfaceBlock.name().c_str(), arraySize, mInterfaceBlockRegister);
605 for (unsigned int typeIndex = 0; typeIndex < fieldList.size(); typeIndex++)
607 const TField &field = *fieldList[typeIndex];
608 const TString &fullUniformName = interfaceBlockFieldString(interfaceBlock, field);
609 declareInterfaceBlockField(*field.type(), fullUniformName, activeBlock.fields);
612 mInterfaceBlockRegister += std::max(1u, arraySize);
614 gl::BlockLayoutType blockLayoutType = convertBlockLayoutType(interfaceBlock.blockStorage());
615 setBlockLayout(&activeBlock, blockLayoutType);
617 if (interfaceBlock.matrixPacking() == EmpRowMajor)
619 activeBlock.isRowMajorLayout = true;
622 mActiveInterfaceBlocks.push_back(activeBlock);
624 if (interfaceBlock.hasInstanceName())
626 interfaceBlocks += interfaceBlockStructString(interfaceBlock);
631 for (unsigned int arrayIndex = 0; arrayIndex < arraySize; arrayIndex++)
633 interfaceBlocks += interfaceBlockString(interfaceBlock, activeBlock.registerIndex + arrayIndex, arrayIndex);
638 interfaceBlocks += interfaceBlockString(interfaceBlock, activeBlock.registerIndex, GL_INVALID_INDEX);
642 for (std::map<TIntermTyped*, TString>::const_iterator flaggedStructIt = mFlaggedStructMappedNames.begin(); flaggedStructIt != mFlaggedStructMappedNames.end(); flaggedStructIt++)
644 TIntermTyped *structNode = flaggedStructIt->first;
645 const TString &mappedName = flaggedStructIt->second;
646 const TStructure &structure = *structNode->getType().getStruct();
647 const TString &originalName = mFlaggedStructOriginalNames[structNode];
649 flaggedStructs += "static " + decorate(structure.name()) + " " + mappedName + " =\n";
650 flaggedStructs += structInitializerString(0, structure, originalName);
651 flaggedStructs += "\n";
654 for (ReferencedSymbols::const_iterator varying = mReferencedVaryings.begin(); varying != mReferencedVaryings.end(); varying++)
656 const TType &type = varying->second->getType();
657 const TString &name = varying->second->getSymbol();
659 // Program linking depends on this exact format
660 varyings += "static " + interpolationString(type.getQualifier()) + " " + typeString(type) + " " +
661 decorate(name) + arrayString(type) + " = " + initializer(type) + ";\n";
663 declareVaryingToList(type, type.getQualifier(), name, mActiveVaryings);
666 for (ReferencedSymbols::const_iterator attribute = mReferencedAttributes.begin(); attribute != mReferencedAttributes.end(); attribute++)
668 const TType &type = attribute->second->getType();
669 const TString &name = attribute->second->getSymbol();
671 attributes += "static " + typeString(type) + " " + decorate(name) + arrayString(type) + " = " + initializer(type) + ";\n";
673 gl::Attribute attributeVar(glVariableType(type), glVariablePrecision(type), name.c_str(),
674 (unsigned int)type.getArraySize(), type.getLayoutQualifier().location);
675 mActiveAttributes.push_back(attributeVar);
678 for (StructDeclarations::iterator structDeclaration = mStructDeclarations.begin(); structDeclaration != mStructDeclarations.end(); structDeclaration++)
680 out << *structDeclaration;
683 for (Constructors::iterator constructor = mConstructors.begin(); constructor != mConstructors.end(); constructor++)
688 if (mUsesDiscardRewriting)
690 out << "#define ANGLE_USES_DISCARD_REWRITING" << "\n";
693 if (mUsesNestedBreak)
695 out << "#define ANGLE_USES_NESTED_BREAK" << "\n";
698 if (mContext.shaderType == SH_FRAGMENT_SHADER)
700 TExtensionBehavior::const_iterator iter = mContext.extensionBehavior().find("GL_EXT_draw_buffers");
701 const bool usingMRTExtension = (iter != mContext.extensionBehavior().end() && (iter->second == EBhEnable || iter->second == EBhRequire));
703 out << "// Varyings\n";
707 if (mContext.getShaderVersion() >= 300)
709 for (ReferencedSymbols::const_iterator outputVariableIt = mReferencedOutputVariables.begin(); outputVariableIt != mReferencedOutputVariables.end(); outputVariableIt++)
711 const TString &variableName = outputVariableIt->first;
712 const TType &variableType = outputVariableIt->second->getType();
713 const TLayoutQualifier &layoutQualifier = variableType.getLayoutQualifier();
715 out << "static " + typeString(variableType) + " out_" + variableName + arrayString(variableType) +
716 " = " + initializer(variableType) + ";\n";
718 gl::Attribute outputVar(glVariableType(variableType), glVariablePrecision(variableType), variableName.c_str(),
719 (unsigned int)variableType.getArraySize(), layoutQualifier.location);
720 mActiveOutputVariables.push_back(outputVar);
725 const unsigned int numColorValues = usingMRTExtension ? mNumRenderTargets : 1;
727 out << "static float4 gl_Color[" << numColorValues << "] =\n"
729 for (unsigned int i = 0; i < numColorValues; i++)
731 out << " float4(0, 0, 0, 0)";
732 if (i + 1 != numColorValues)
744 out << "static float gl_Depth = 0.0;\n";
749 out << "static float4 gl_FragCoord = float4(0, 0, 0, 0);\n";
754 out << "static float2 gl_PointCoord = float2(0.5, 0.5);\n";
757 if (mUsesFrontFacing)
759 out << "static bool gl_FrontFacing = false;\n";
766 out << "struct gl_DepthRangeParameters\n"
775 if (mOutputType == SH_HLSL11_OUTPUT)
777 out << "cbuffer DriverConstants : register(b1)\n"
782 out << " float3 dx_DepthRange : packoffset(c0);\n";
787 out << " float4 dx_ViewCoords : packoffset(c1);\n";
790 if (mUsesFragCoord || mUsesFrontFacing)
792 out << " float3 dx_DepthFront : packoffset(c2);\n";
801 out << "uniform float3 dx_DepthRange : register(c0);";
806 out << "uniform float4 dx_ViewCoords : register(c1);\n";
809 if (mUsesFragCoord || mUsesFrontFacing)
811 out << "uniform float3 dx_DepthFront : register(c2);\n";
819 out << "static gl_DepthRangeParameters gl_DepthRange = {dx_DepthRange.x, dx_DepthRange.y, dx_DepthRange.z};\n"
826 if (!interfaceBlocks.empty())
828 out << interfaceBlocks;
831 if (!flaggedStructs.empty())
833 out << "// Std140 Structures accessed by value\n";
835 out << flaggedStructs;
840 if (usingMRTExtension && mNumRenderTargets > 1)
842 out << "#define GL_USES_MRT\n";
847 out << "#define GL_USES_FRAG_COLOR\n";
852 out << "#define GL_USES_FRAG_DATA\n";
855 else // Vertex shader
857 out << "// Attributes\n";
860 "static float4 gl_Position = float4(0, 0, 0, 0);\n";
864 out << "static float gl_PointSize = float(1);\n";
874 out << "struct gl_DepthRangeParameters\n"
883 if (mOutputType == SH_HLSL11_OUTPUT)
887 out << "cbuffer DriverConstants : register(b1)\n"
889 " float3 dx_DepthRange : packoffset(c0);\n"
898 out << "uniform float3 dx_DepthRange : register(c0);\n";
901 out << "uniform float4 dx_ViewAdjust : register(c1);\n"
907 out << "static gl_DepthRangeParameters gl_DepthRange = {dx_DepthRange.x, dx_DepthRange.y, dx_DepthRange.z};\n"
914 if (!interfaceBlocks.empty())
916 out << interfaceBlocks;
919 if (!flaggedStructs.empty())
921 out << "// Std140 Structures accessed by value\n";
923 out << flaggedStructs;
929 for (TextureFunctionSet::const_iterator textureFunction = mUsesTexture.begin(); textureFunction != mUsesTexture.end(); textureFunction++)
932 if (textureFunction->method == TextureFunction::SIZE)
934 switch(textureFunction->sampler)
936 case EbtSampler2D: out << "int2 "; break;
937 case EbtSampler3D: out << "int3 "; break;
938 case EbtSamplerCube: out << "int2 "; break;
939 case EbtSampler2DArray: out << "int3 "; break;
940 case EbtISampler2D: out << "int2 "; break;
941 case EbtISampler3D: out << "int3 "; break;
942 case EbtISamplerCube: out << "int2 "; break;
943 case EbtISampler2DArray: out << "int3 "; break;
944 case EbtUSampler2D: out << "int2 "; break;
945 case EbtUSampler3D: out << "int3 "; break;
946 case EbtUSamplerCube: out << "int2 "; break;
947 case EbtUSampler2DArray: out << "int3 "; break;
948 case EbtSampler2DShadow: out << "int2 "; break;
949 case EbtSamplerCubeShadow: out << "int2 "; break;
950 case EbtSampler2DArrayShadow: out << "int3 "; break;
951 default: UNREACHABLE();
954 else // Sampling function
956 switch(textureFunction->sampler)
958 case EbtSampler2D: out << "float4 "; break;
959 case EbtSampler3D: out << "float4 "; break;
960 case EbtSamplerCube: out << "float4 "; break;
961 case EbtSampler2DArray: out << "float4 "; break;
962 case EbtISampler2D: out << "int4 "; break;
963 case EbtISampler3D: out << "int4 "; break;
964 case EbtISamplerCube: out << "int4 "; break;
965 case EbtISampler2DArray: out << "int4 "; break;
966 case EbtUSampler2D: out << "uint4 "; break;
967 case EbtUSampler3D: out << "uint4 "; break;
968 case EbtUSamplerCube: out << "uint4 "; break;
969 case EbtUSampler2DArray: out << "uint4 "; break;
970 case EbtSampler2DShadow: out << "float "; break;
971 case EbtSamplerCubeShadow: out << "float "; break;
972 case EbtSampler2DArrayShadow: out << "float "; break;
973 default: UNREACHABLE();
978 out << textureFunction->name();
983 if (mOutputType == SH_HLSL9_OUTPUT)
985 switch(textureFunction->sampler)
987 case EbtSampler2D: out << "sampler2D s"; hlslCoords = 2; break;
988 case EbtSamplerCube: out << "samplerCUBE s"; hlslCoords = 3; break;
989 default: UNREACHABLE();
992 switch(textureFunction->method)
994 case TextureFunction::IMPLICIT: break;
995 case TextureFunction::BIAS: hlslCoords = 4; break;
996 case TextureFunction::LOD: hlslCoords = 4; break;
997 case TextureFunction::LOD0: hlslCoords = 4; break;
998 case TextureFunction::LOD0BIAS: hlslCoords = 4; break;
999 default: UNREACHABLE();
1002 else if (mOutputType == SH_HLSL11_OUTPUT)
1004 switch(textureFunction->sampler)
1006 case EbtSampler2D: out << "Texture2D x, SamplerState s"; hlslCoords = 2; break;
1007 case EbtSampler3D: out << "Texture3D x, SamplerState s"; hlslCoords = 3; break;
1008 case EbtSamplerCube: out << "TextureCube x, SamplerState s"; hlslCoords = 3; break;
1009 case EbtSampler2DArray: out << "Texture2DArray x, SamplerState s"; hlslCoords = 3; break;
1010 case EbtISampler2D: out << "Texture2D<int4> x, SamplerState s"; hlslCoords = 2; break;
1011 case EbtISampler3D: out << "Texture3D<int4> x, SamplerState s"; hlslCoords = 3; break;
1012 case EbtISamplerCube: out << "Texture2DArray<int4> x, SamplerState s"; hlslCoords = 3; break;
1013 case EbtISampler2DArray: out << "Texture2DArray<int4> x, SamplerState s"; hlslCoords = 3; break;
1014 case EbtUSampler2D: out << "Texture2D<uint4> x, SamplerState s"; hlslCoords = 2; break;
1015 case EbtUSampler3D: out << "Texture3D<uint4> x, SamplerState s"; hlslCoords = 3; break;
1016 case EbtUSamplerCube: out << "Texture2DArray<uint4> x, SamplerState s"; hlslCoords = 3; break;
1017 case EbtUSampler2DArray: out << "Texture2DArray<uint4> x, SamplerState s"; hlslCoords = 3; break;
1018 case EbtSampler2DShadow: out << "Texture2D x, SamplerComparisonState s"; hlslCoords = 2; break;
1019 case EbtSamplerCubeShadow: out << "TextureCube x, SamplerComparisonState s"; hlslCoords = 3; break;
1020 case EbtSampler2DArrayShadow: out << "Texture2DArray x, SamplerComparisonState s"; hlslCoords = 3; break;
1021 default: UNREACHABLE();
1026 if (textureFunction->method == TextureFunction::FETCH) // Integer coordinates
1028 switch(textureFunction->coords)
1030 case 2: out << ", int2 t"; break;
1031 case 3: out << ", int3 t"; break;
1032 default: UNREACHABLE();
1035 else // Floating-point coordinates (except textureSize)
1037 switch(textureFunction->coords)
1039 case 1: out << ", int lod"; break; // textureSize()
1040 case 2: out << ", float2 t"; break;
1041 case 3: out << ", float3 t"; break;
1042 case 4: out << ", float4 t"; break;
1043 default: UNREACHABLE();
1047 if (textureFunction->method == TextureFunction::GRAD)
1049 switch(textureFunction->sampler)
1054 case EbtSampler2DArray:
1055 case EbtISampler2DArray:
1056 case EbtUSampler2DArray:
1057 case EbtSampler2DShadow:
1058 case EbtSampler2DArrayShadow:
1059 out << ", float2 ddx, float2 ddy";
1064 case EbtSamplerCube:
1065 case EbtISamplerCube:
1066 case EbtUSamplerCube:
1067 case EbtSamplerCubeShadow:
1068 out << ", float3 ddx, float3 ddy";
1070 default: UNREACHABLE();
1074 switch(textureFunction->method)
1076 case TextureFunction::IMPLICIT: break;
1077 case TextureFunction::BIAS: break; // Comes after the offset parameter
1078 case TextureFunction::LOD: out << ", float lod"; break;
1079 case TextureFunction::LOD0: break;
1080 case TextureFunction::LOD0BIAS: break; // Comes after the offset parameter
1081 case TextureFunction::SIZE: break;
1082 case TextureFunction::FETCH: out << ", int mip"; break;
1083 case TextureFunction::GRAD: break;
1084 default: UNREACHABLE();
1087 if (textureFunction->offset)
1089 switch(textureFunction->sampler)
1091 case EbtSampler2D: out << ", int2 offset"; break;
1092 case EbtSampler3D: out << ", int3 offset"; break;
1093 case EbtSampler2DArray: out << ", int2 offset"; break;
1094 case EbtISampler2D: out << ", int2 offset"; break;
1095 case EbtISampler3D: out << ", int3 offset"; break;
1096 case EbtISampler2DArray: out << ", int2 offset"; break;
1097 case EbtUSampler2D: out << ", int2 offset"; break;
1098 case EbtUSampler3D: out << ", int3 offset"; break;
1099 case EbtUSampler2DArray: out << ", int2 offset"; break;
1100 case EbtSampler2DShadow: out << ", int2 offset"; break;
1101 case EbtSampler2DArrayShadow: out << ", int2 offset"; break;
1102 default: UNREACHABLE();
1106 if (textureFunction->method == TextureFunction::BIAS ||
1107 textureFunction->method == TextureFunction::LOD0BIAS)
1109 out << ", float bias";
1115 if (textureFunction->method == TextureFunction::SIZE)
1117 if (IsSampler2D(textureFunction->sampler) || IsSamplerCube(textureFunction->sampler))
1119 if (IsSamplerArray(textureFunction->sampler))
1121 out << " uint width; uint height; uint layers; uint numberOfLevels;\n"
1122 " x.GetDimensions(lod, width, height, layers, numberOfLevels);\n";
1126 out << " uint width; uint height; uint numberOfLevels;\n"
1127 " x.GetDimensions(lod, width, height, numberOfLevels);\n";
1130 else if (IsSampler3D(textureFunction->sampler))
1132 out << " uint width; uint height; uint depth; uint numberOfLevels;\n"
1133 " x.GetDimensions(lod, width, height, depth, numberOfLevels);\n";
1137 switch(textureFunction->sampler)
1139 case EbtSampler2D: out << " return int2(width, height);"; break;
1140 case EbtSampler3D: out << " return int3(width, height, depth);"; break;
1141 case EbtSamplerCube: out << " return int2(width, height);"; break;
1142 case EbtSampler2DArray: out << " return int3(width, height, layers);"; break;
1143 case EbtISampler2D: out << " return int2(width, height);"; break;
1144 case EbtISampler3D: out << " return int3(width, height, depth);"; break;
1145 case EbtISamplerCube: out << " return int2(width, height);"; break;
1146 case EbtISampler2DArray: out << " return int3(width, height, layers);"; break;
1147 case EbtUSampler2D: out << " return int2(width, height);"; break;
1148 case EbtUSampler3D: out << " return int3(width, height, depth);"; break;
1149 case EbtUSamplerCube: out << " return int2(width, height);"; break;
1150 case EbtUSampler2DArray: out << " return int3(width, height, layers);"; break;
1151 case EbtSampler2DShadow: out << " return int2(width, height);"; break;
1152 case EbtSamplerCubeShadow: out << " return int2(width, height);"; break;
1153 case EbtSampler2DArrayShadow: out << " return int3(width, height, layers);"; break;
1154 default: UNREACHABLE();
1159 if (IsIntegerSampler(textureFunction->sampler) && IsSamplerCube(textureFunction->sampler))
1161 out << " float width; float height; float layers; float levels;\n";
1163 out << " uint mip = 0;\n";
1165 out << " x.GetDimensions(mip, width, height, layers, levels);\n";
1167 out << " bool xMajor = abs(t.x) > abs(t.y) && abs(t.x) > abs(t.z);\n";
1168 out << " bool yMajor = abs(t.y) > abs(t.z) && abs(t.y) > abs(t.x);\n";
1169 out << " bool zMajor = abs(t.z) > abs(t.x) && abs(t.z) > abs(t.y);\n";
1170 out << " bool negative = (xMajor && t.x < 0.0f) || (yMajor && t.y < 0.0f) || (zMajor && t.z < 0.0f);\n";
1172 // FACE_POSITIVE_X = 000b
1173 // FACE_NEGATIVE_X = 001b
1174 // FACE_POSITIVE_Y = 010b
1175 // FACE_NEGATIVE_Y = 011b
1176 // FACE_POSITIVE_Z = 100b
1177 // FACE_NEGATIVE_Z = 101b
1178 out << " int face = (int)negative + (int)yMajor * 2 + (int)zMajor * 4;\n";
1180 out << " float u = xMajor ? -t.z : (yMajor && t.y < 0.0f ? -t.x : t.x);\n";
1181 out << " float v = yMajor ? t.z : (negative ? t.y : -t.y);\n";
1182 out << " float m = xMajor ? t.x : (yMajor ? t.y : t.z);\n";
1184 out << " t.x = (u * 0.5f / m) + 0.5f;\n";
1185 out << " t.y = (v * 0.5f / m) + 0.5f;\n";
1187 else if (IsIntegerSampler(textureFunction->sampler) &&
1188 textureFunction->method != TextureFunction::FETCH)
1190 if (IsSampler2D(textureFunction->sampler))
1192 if (IsSamplerArray(textureFunction->sampler))
1194 out << " float width; float height; float layers; float levels;\n";
1196 if (textureFunction->method == TextureFunction::LOD0)
1198 out << " uint mip = 0;\n";
1200 else if (textureFunction->method == TextureFunction::LOD0BIAS)
1202 out << " uint mip = bias;\n";
1206 if (textureFunction->method == TextureFunction::IMPLICIT ||
1207 textureFunction->method == TextureFunction::BIAS)
1209 out << " x.GetDimensions(0, width, height, layers, levels);\n"
1210 " float2 tSized = float2(t.x * width, t.y * height);\n"
1211 " float dx = length(ddx(tSized));\n"
1212 " float dy = length(ddy(tSized));\n"
1213 " float lod = log2(max(dx, dy));\n";
1215 if (textureFunction->method == TextureFunction::BIAS)
1217 out << " lod += bias;\n";
1220 else if (textureFunction->method == TextureFunction::GRAD)
1222 out << " x.GetDimensions(0, width, height, layers, levels);\n"
1223 " float lod = log2(max(length(ddx), length(ddy)));\n";
1226 out << " uint mip = uint(min(max(round(lod), 0), levels - 1));\n";
1229 out << " x.GetDimensions(mip, width, height, layers, levels);\n";
1233 out << " float width; float height; float levels;\n";
1235 if (textureFunction->method == TextureFunction::LOD0)
1237 out << " uint mip = 0;\n";
1239 else if (textureFunction->method == TextureFunction::LOD0BIAS)
1241 out << " uint mip = bias;\n";
1245 if (textureFunction->method == TextureFunction::IMPLICIT ||
1246 textureFunction->method == TextureFunction::BIAS)
1248 out << " x.GetDimensions(0, width, height, levels);\n"
1249 " float2 tSized = float2(t.x * width, t.y * height);\n"
1250 " float dx = length(ddx(tSized));\n"
1251 " float dy = length(ddy(tSized));\n"
1252 " float lod = log2(max(dx, dy));\n";
1254 if (textureFunction->method == TextureFunction::BIAS)
1256 out << " lod += bias;\n";
1259 else if (textureFunction->method == TextureFunction::LOD)
1261 out << " x.GetDimensions(0, width, height, levels);\n";
1263 else if (textureFunction->method == TextureFunction::GRAD)
1265 out << " x.GetDimensions(0, width, height, levels);\n"
1266 " float lod = log2(max(length(ddx), length(ddy)));\n";
1269 out << " uint mip = uint(min(max(round(lod), 0), levels - 1));\n";
1272 out << " x.GetDimensions(mip, width, height, levels);\n";
1275 else if (IsSampler3D(textureFunction->sampler))
1277 out << " float width; float height; float depth; float levels;\n";
1279 if (textureFunction->method == TextureFunction::LOD0)
1281 out << " uint mip = 0;\n";
1283 else if (textureFunction->method == TextureFunction::LOD0BIAS)
1285 out << " uint mip = bias;\n";
1289 if (textureFunction->method == TextureFunction::IMPLICIT ||
1290 textureFunction->method == TextureFunction::BIAS)
1292 out << " x.GetDimensions(0, width, height, depth, levels);\n"
1293 " float3 tSized = float3(t.x * width, t.y * height, t.z * depth);\n"
1294 " float dx = length(ddx(tSized));\n"
1295 " float dy = length(ddy(tSized));\n"
1296 " float lod = log2(max(dx, dy));\n";
1298 if (textureFunction->method == TextureFunction::BIAS)
1300 out << " lod += bias;\n";
1303 else if (textureFunction->method == TextureFunction::GRAD)
1305 out << " x.GetDimensions(0, width, height, depth, levels);\n"
1306 " float lod = log2(max(length(ddx), length(ddy)));\n";
1309 out << " uint mip = uint(min(max(round(lod), 0), levels - 1));\n";
1312 out << " x.GetDimensions(mip, width, height, depth, levels);\n";
1320 if (mOutputType == SH_HLSL9_OUTPUT)
1322 switch(textureFunction->sampler)
1324 case EbtSampler2D: out << "tex2D"; break;
1325 case EbtSamplerCube: out << "texCUBE"; break;
1326 default: UNREACHABLE();
1329 switch(textureFunction->method)
1331 case TextureFunction::IMPLICIT: out << "(s, "; break;
1332 case TextureFunction::BIAS: out << "bias(s, "; break;
1333 case TextureFunction::LOD: out << "lod(s, "; break;
1334 case TextureFunction::LOD0: out << "lod(s, "; break;
1335 case TextureFunction::LOD0BIAS: out << "lod(s, "; break;
1336 default: UNREACHABLE();
1339 else if (mOutputType == SH_HLSL11_OUTPUT)
1341 if (textureFunction->method == TextureFunction::GRAD)
1343 if (IsIntegerSampler(textureFunction->sampler))
1347 else if (IsShadowSampler(textureFunction->sampler))
1349 out << "x.SampleCmpLevelZero(s, ";
1353 out << "x.SampleGrad(s, ";
1356 else if (IsIntegerSampler(textureFunction->sampler) ||
1357 textureFunction->method == TextureFunction::FETCH)
1361 else if (IsShadowSampler(textureFunction->sampler))
1363 out << "x.SampleCmp(s, ";
1367 switch(textureFunction->method)
1369 case TextureFunction::IMPLICIT: out << "x.Sample(s, "; break;
1370 case TextureFunction::BIAS: out << "x.SampleBias(s, "; break;
1371 case TextureFunction::LOD: out << "x.SampleLevel(s, "; break;
1372 case TextureFunction::LOD0: out << "x.SampleLevel(s, "; break;
1373 case TextureFunction::LOD0BIAS: out << "x.SampleLevel(s, "; break;
1374 default: UNREACHABLE();
1380 // Integer sampling requires integer addresses
1381 TString addressx = "";
1382 TString addressy = "";
1383 TString addressz = "";
1386 if (IsIntegerSampler(textureFunction->sampler) ||
1387 textureFunction->method == TextureFunction::FETCH)
1391 case 2: out << "int3("; break;
1392 case 3: out << "int4("; break;
1393 default: UNREACHABLE();
1396 // Convert from normalized floating-point to integer
1397 if (textureFunction->method != TextureFunction::FETCH)
1399 addressx = "int(floor(width * frac((";
1400 addressy = "int(floor(height * frac((";
1402 if (IsSamplerArray(textureFunction->sampler))
1404 addressz = "int(max(0, min(layers - 1, floor(0.5 + ";
1406 else if (IsSamplerCube(textureFunction->sampler))
1412 addressz = "int(floor(depth * frac((";
1422 case 2: out << "float2("; break;
1423 case 3: out << "float3("; break;
1424 case 4: out << "float4("; break;
1425 default: UNREACHABLE();
1429 TString proj = ""; // Only used for projected textures
1431 if (textureFunction->proj)
1433 switch(textureFunction->coords)
1435 case 3: proj = " / t.z"; break;
1436 case 4: proj = " / t.w"; break;
1437 default: UNREACHABLE();
1441 out << addressx + ("t.x" + proj) + close + ", " + addressy + ("t.y" + proj) + close;
1443 if (mOutputType == SH_HLSL9_OUTPUT)
1445 if (hlslCoords >= 3)
1447 if (textureFunction->coords < 3)
1453 out << ", t.z" + proj;
1457 if (hlslCoords == 4)
1459 switch(textureFunction->method)
1461 case TextureFunction::BIAS: out << ", bias"; break;
1462 case TextureFunction::LOD: out << ", lod"; break;
1463 case TextureFunction::LOD0: out << ", 0"; break;
1464 case TextureFunction::LOD0BIAS: out << ", bias"; break;
1465 default: UNREACHABLE();
1471 else if (mOutputType == SH_HLSL11_OUTPUT)
1473 if (hlslCoords >= 3)
1475 if (IsIntegerSampler(textureFunction->sampler) && IsSamplerCube(textureFunction->sampler))
1481 out << ", " + addressz + ("t.z" + proj) + close;
1485 if (textureFunction->method == TextureFunction::GRAD)
1487 if (IsIntegerSampler(textureFunction->sampler))
1491 else if (IsShadowSampler(textureFunction->sampler))
1494 switch(textureFunction->coords)
1496 case 3: out << "), t.z"; break;
1497 case 4: out << "), t.w"; break;
1498 default: UNREACHABLE();
1503 out << "), ddx, ddy";
1506 else if (IsIntegerSampler(textureFunction->sampler) ||
1507 textureFunction->method == TextureFunction::FETCH)
1511 else if (IsShadowSampler(textureFunction->sampler))
1514 switch(textureFunction->coords)
1516 case 3: out << "), t.z"; break;
1517 case 4: out << "), t.w"; break;
1518 default: UNREACHABLE();
1523 switch(textureFunction->method)
1525 case TextureFunction::IMPLICIT: out << ")"; break;
1526 case TextureFunction::BIAS: out << "), bias"; break;
1527 case TextureFunction::LOD: out << "), lod"; break;
1528 case TextureFunction::LOD0: out << "), 0"; break;
1529 case TextureFunction::LOD0BIAS: out << "), bias"; break;
1530 default: UNREACHABLE();
1534 if (textureFunction->offset)
1551 out << "#define GL_USES_FRAG_COORD\n";
1554 if (mUsesPointCoord)
1556 out << "#define GL_USES_POINT_COORD\n";
1559 if (mUsesFrontFacing)
1561 out << "#define GL_USES_FRONT_FACING\n";
1566 out << "#define GL_USES_POINT_SIZE\n";
1571 out << "#define GL_USES_FRAG_DEPTH\n";
1574 if (mUsesDepthRange)
1576 out << "#define GL_USES_DEPTH_RANGE\n";
1581 out << "bool xor(bool p, bool q)\n"
1583 " return (p || q) && !(p && q);\n"
1590 out << "float mod(float x, float y)\n"
1592 " return x - y * floor(x / y);\n"
1599 out << "float2 mod(float2 x, float2 y)\n"
1601 " return x - y * floor(x / y);\n"
1608 out << "float2 mod(float2 x, float y)\n"
1610 " return x - y * floor(x / y);\n"
1617 out << "float3 mod(float3 x, float3 y)\n"
1619 " return x - y * floor(x / y);\n"
1626 out << "float3 mod(float3 x, float y)\n"
1628 " return x - y * floor(x / y);\n"
1635 out << "float4 mod(float4 x, float4 y)\n"
1637 " return x - y * floor(x / y);\n"
1644 out << "float4 mod(float4 x, float y)\n"
1646 " return x - y * floor(x / y);\n"
1651 if (mUsesFaceforward1)
1653 out << "float faceforward(float N, float I, float Nref)\n"
1655 " if(dot(Nref, I) >= 0)\n"
1667 if (mUsesFaceforward2)
1669 out << "float2 faceforward(float2 N, float2 I, float2 Nref)\n"
1671 " if(dot(Nref, I) >= 0)\n"
1683 if (mUsesFaceforward3)
1685 out << "float3 faceforward(float3 N, float3 I, float3 Nref)\n"
1687 " if(dot(Nref, I) >= 0)\n"
1699 if (mUsesFaceforward4)
1701 out << "float4 faceforward(float4 N, float4 I, float4 Nref)\n"
1703 " if(dot(Nref, I) >= 0)\n"
1717 out << "float atanyx(float y, float x)\n"
1719 " if(x == 0 && y == 0) x = 1;\n" // Avoid producing a NaN
1720 " return atan2(y, x);\n"
1726 out << "float2 atanyx(float2 y, float2 x)\n"
1728 " if(x[0] == 0 && y[0] == 0) x[0] = 1;\n"
1729 " if(x[1] == 0 && y[1] == 0) x[1] = 1;\n"
1730 " return float2(atan2(y[0], x[0]), atan2(y[1], x[1]));\n"
1736 out << "float3 atanyx(float3 y, float3 x)\n"
1738 " if(x[0] == 0 && y[0] == 0) x[0] = 1;\n"
1739 " if(x[1] == 0 && y[1] == 0) x[1] = 1;\n"
1740 " if(x[2] == 0 && y[2] == 0) x[2] = 1;\n"
1741 " return float3(atan2(y[0], x[0]), atan2(y[1], x[1]), atan2(y[2], x[2]));\n"
1747 out << "float4 atanyx(float4 y, float4 x)\n"
1749 " if(x[0] == 0 && y[0] == 0) x[0] = 1;\n"
1750 " if(x[1] == 0 && y[1] == 0) x[1] = 1;\n"
1751 " if(x[2] == 0 && y[2] == 0) x[2] = 1;\n"
1752 " if(x[3] == 0 && y[3] == 0) x[3] = 1;\n"
1753 " return float4(atan2(y[0], x[0]), atan2(y[1], x[1]), atan2(y[2], x[2]), atan2(y[3], x[3]));\n"
1758 void OutputHLSL::visitSymbol(TIntermSymbol *node)
1760 TInfoSinkBase &out = mBody;
1762 // Handle accessing std140 structs by value
1763 if (mFlaggedStructMappedNames.count(node) > 0)
1765 out << mFlaggedStructMappedNames[node];
1769 TString name = node->getSymbol();
1771 if (name == "gl_DepthRange")
1773 mUsesDepthRange = true;
1778 TQualifier qualifier = node->getQualifier();
1780 if (qualifier == EvqUniform)
1782 const TType& nodeType = node->getType();
1783 const TInterfaceBlock* interfaceBlock = nodeType.getInterfaceBlock();
1787 mReferencedInterfaceBlocks[interfaceBlock->name()] = node;
1791 mReferencedUniforms[name] = node;
1794 out << decorateUniform(name, nodeType);
1796 else if (qualifier == EvqAttribute || qualifier == EvqVertexIn)
1798 mReferencedAttributes[name] = node;
1799 out << decorate(name);
1801 else if (isVarying(qualifier))
1803 mReferencedVaryings[name] = node;
1804 out << decorate(name);
1806 else if (qualifier == EvqFragmentOut)
1808 mReferencedOutputVariables[name] = node;
1809 out << "out_" << name;
1811 else if (qualifier == EvqFragColor)
1813 out << "gl_Color[0]";
1814 mUsesFragColor = true;
1816 else if (qualifier == EvqFragData)
1819 mUsesFragData = true;
1821 else if (qualifier == EvqFragCoord)
1823 mUsesFragCoord = true;
1826 else if (qualifier == EvqPointCoord)
1828 mUsesPointCoord = true;
1831 else if (qualifier == EvqFrontFacing)
1833 mUsesFrontFacing = true;
1836 else if (qualifier == EvqPointSize)
1838 mUsesPointSize = true;
1841 else if (name == "gl_FragDepthEXT")
1843 mUsesFragDepth = true;
1846 else if (qualifier == EvqInternal)
1852 out << decorate(name);
1857 void OutputHLSL::visitRaw(TIntermRaw *node)
1859 mBody << node->getRawText();
1862 bool OutputHLSL::visitBinary(Visit visit, TIntermBinary *node)
1864 TInfoSinkBase &out = mBody;
1866 // Handle accessing std140 structs by value
1867 if (mFlaggedStructMappedNames.count(node) > 0)
1869 out << mFlaggedStructMappedNames[node];
1873 switch (node->getOp())
1875 case EOpAssign: outputTriplet(visit, "(", " = ", ")"); break;
1877 if (visit == PreVisit)
1879 // GLSL allows to write things like "float x = x;" where a new variable x is defined
1880 // and the value of an existing variable x is assigned. HLSL uses C semantics (the
1881 // new variable is created before the assignment is evaluated), so we need to convert
1882 // this to "float t = x, x = t;".
1884 TIntermSymbol *symbolNode = node->getLeft()->getAsSymbolNode();
1885 TIntermTyped *expression = node->getRight();
1887 sh::SearchSymbol searchSymbol(symbolNode->getSymbol());
1888 expression->traverse(&searchSymbol);
1889 bool sameSymbol = searchSymbol.foundMatch();
1893 // Type already printed
1894 out << "t" + str(mUniqueIndex) + " = ";
1895 expression->traverse(this);
1897 symbolNode->traverse(this);
1898 out << " = t" + str(mUniqueIndex);
1904 else if (visit == InVisit)
1909 case EOpAddAssign: outputTriplet(visit, "(", " += ", ")"); break;
1910 case EOpSubAssign: outputTriplet(visit, "(", " -= ", ")"); break;
1911 case EOpMulAssign: outputTriplet(visit, "(", " *= ", ")"); break;
1912 case EOpVectorTimesScalarAssign: outputTriplet(visit, "(", " *= ", ")"); break;
1913 case EOpMatrixTimesScalarAssign: outputTriplet(visit, "(", " *= ", ")"); break;
1914 case EOpVectorTimesMatrixAssign:
1915 if (visit == PreVisit)
1919 else if (visit == InVisit)
1922 node->getLeft()->traverse(this);
1923 out << ", transpose(";
1930 case EOpMatrixTimesMatrixAssign:
1931 if (visit == PreVisit)
1935 else if (visit == InVisit)
1938 node->getLeft()->traverse(this);
1946 case EOpDivAssign: outputTriplet(visit, "(", " /= ", ")"); break;
1947 case EOpIndexDirect:
1949 const TType& leftType = node->getLeft()->getType();
1950 if (leftType.isInterfaceBlock())
1952 if (visit == PreVisit)
1954 TInterfaceBlock* interfaceBlock = leftType.getInterfaceBlock();
1955 const int arrayIndex = node->getRight()->getAsConstantUnion()->getIConst(0);
1957 mReferencedInterfaceBlocks[interfaceBlock->instanceName()] = node->getLeft()->getAsSymbolNode();
1958 out << interfaceBlockInstanceString(*interfaceBlock, arrayIndex);
1965 outputTriplet(visit, "", "[", "]");
1969 case EOpIndexIndirect:
1970 // We do not currently support indirect references to interface blocks
1971 ASSERT(node->getLeft()->getBasicType() != EbtInterfaceBlock);
1972 outputTriplet(visit, "", "[", "]");
1974 case EOpIndexDirectStruct:
1975 if (visit == InVisit)
1977 const TStructure* structure = node->getLeft()->getType().getStruct();
1978 const TIntermConstantUnion* index = node->getRight()->getAsConstantUnion();
1979 const TField* field = structure->fields()[index->getIConst(0)];
1980 out << "." + decorateField(field->name(), *structure);
1985 case EOpIndexDirectInterfaceBlock:
1986 if (visit == InVisit)
1988 const TInterfaceBlock* interfaceBlock = node->getLeft()->getType().getInterfaceBlock();
1989 const TIntermConstantUnion* index = node->getRight()->getAsConstantUnion();
1990 const TField* field = interfaceBlock->fields()[index->getIConst(0)];
1991 out << "." + decorate(field->name());
1996 case EOpVectorSwizzle:
1997 if (visit == InVisit)
2001 TIntermAggregate *swizzle = node->getRight()->getAsAggregate();
2005 TIntermSequence &sequence = swizzle->getSequence();
2007 for (TIntermSequence::iterator sit = sequence.begin(); sit != sequence.end(); sit++)
2009 TIntermConstantUnion *element = (*sit)->getAsConstantUnion();
2013 int i = element->getIConst(0);
2017 case 0: out << "x"; break;
2018 case 1: out << "y"; break;
2019 case 2: out << "z"; break;
2020 case 3: out << "w"; break;
2021 default: UNREACHABLE();
2029 return false; // Fully processed
2032 case EOpAdd: outputTriplet(visit, "(", " + ", ")"); break;
2033 case EOpSub: outputTriplet(visit, "(", " - ", ")"); break;
2034 case EOpMul: outputTriplet(visit, "(", " * ", ")"); break;
2035 case EOpDiv: outputTriplet(visit, "(", " / ", ")"); break;
2038 if (node->getLeft()->isScalar())
2040 if (node->getOp() == EOpEqual)
2042 outputTriplet(visit, "(", " == ", ")");
2046 outputTriplet(visit, "(", " != ", ")");
2049 else if (node->getLeft()->getBasicType() == EbtStruct)
2051 if (node->getOp() == EOpEqual)
2060 const TStructure &structure = *node->getLeft()->getType().getStruct();
2061 const TFieldList &fields = structure.fields();
2063 for (size_t i = 0; i < fields.size(); i++)
2065 const TField *field = fields[i];
2067 node->getLeft()->traverse(this);
2068 out << "." + decorateField(field->name(), structure) + " == ";
2069 node->getRight()->traverse(this);
2070 out << "." + decorateField(field->name(), structure);
2072 if (i < fields.size() - 1)
2084 ASSERT(node->getLeft()->isMatrix() || node->getLeft()->isVector());
2086 if (node->getOp() == EOpEqual)
2088 outputTriplet(visit, "all(", " == ", ")");
2092 outputTriplet(visit, "!all(", " == ", ")");
2096 case EOpLessThan: outputTriplet(visit, "(", " < ", ")"); break;
2097 case EOpGreaterThan: outputTriplet(visit, "(", " > ", ")"); break;
2098 case EOpLessThanEqual: outputTriplet(visit, "(", " <= ", ")"); break;
2099 case EOpGreaterThanEqual: outputTriplet(visit, "(", " >= ", ")"); break;
2100 case EOpVectorTimesScalar: outputTriplet(visit, "(", " * ", ")"); break;
2101 case EOpMatrixTimesScalar: outputTriplet(visit, "(", " * ", ")"); break;
2102 case EOpVectorTimesMatrix: outputTriplet(visit, "mul(", ", transpose(", "))"); break;
2103 case EOpMatrixTimesVector: outputTriplet(visit, "mul(transpose(", "), ", ")"); break;
2104 case EOpMatrixTimesMatrix: outputTriplet(visit, "transpose(mul(transpose(", "), transpose(", ")))"); break;
2106 if (node->getRight()->hasSideEffects())
2108 out << "s" << mUnfoldShortCircuit->getNextTemporaryIndex();
2113 outputTriplet(visit, "(", " || ", ")");
2118 outputTriplet(visit, "xor(", ", ", ")");
2121 if (node->getRight()->hasSideEffects())
2123 out << "s" << mUnfoldShortCircuit->getNextTemporaryIndex();
2128 outputTriplet(visit, "(", " && ", ")");
2131 default: UNREACHABLE();
2137 bool OutputHLSL::visitUnary(Visit visit, TIntermUnary *node)
2139 switch (node->getOp())
2141 case EOpNegative: outputTriplet(visit, "(-", "", ")"); break;
2142 case EOpVectorLogicalNot: outputTriplet(visit, "(!", "", ")"); break;
2143 case EOpLogicalNot: outputTriplet(visit, "(!", "", ")"); break;
2144 case EOpPostIncrement: outputTriplet(visit, "(", "", "++)"); break;
2145 case EOpPostDecrement: outputTriplet(visit, "(", "", "--)"); break;
2146 case EOpPreIncrement: outputTriplet(visit, "(++", "", ")"); break;
2147 case EOpPreDecrement: outputTriplet(visit, "(--", "", ")"); break;
2148 case EOpConvIntToBool:
2149 case EOpConvUIntToBool:
2150 case EOpConvFloatToBool:
2151 switch (node->getOperand()->getType().getNominalSize())
2153 case 1: outputTriplet(visit, "bool(", "", ")"); break;
2154 case 2: outputTriplet(visit, "bool2(", "", ")"); break;
2155 case 3: outputTriplet(visit, "bool3(", "", ")"); break;
2156 case 4: outputTriplet(visit, "bool4(", "", ")"); break;
2157 default: UNREACHABLE();
2160 case EOpConvBoolToFloat:
2161 case EOpConvIntToFloat:
2162 case EOpConvUIntToFloat:
2163 switch (node->getOperand()->getType().getNominalSize())
2165 case 1: outputTriplet(visit, "float(", "", ")"); break;
2166 case 2: outputTriplet(visit, "float2(", "", ")"); break;
2167 case 3: outputTriplet(visit, "float3(", "", ")"); break;
2168 case 4: outputTriplet(visit, "float4(", "", ")"); break;
2169 default: UNREACHABLE();
2172 case EOpConvFloatToInt:
2173 case EOpConvBoolToInt:
2174 case EOpConvUIntToInt:
2175 switch (node->getOperand()->getType().getNominalSize())
2177 case 1: outputTriplet(visit, "int(", "", ")"); break;
2178 case 2: outputTriplet(visit, "int2(", "", ")"); break;
2179 case 3: outputTriplet(visit, "int3(", "", ")"); break;
2180 case 4: outputTriplet(visit, "int4(", "", ")"); break;
2181 default: UNREACHABLE();
2184 case EOpConvFloatToUInt:
2185 case EOpConvBoolToUInt:
2186 case EOpConvIntToUInt:
2187 switch (node->getOperand()->getType().getNominalSize())
2189 case 1: outputTriplet(visit, "uint(", "", ")"); break;
2190 case 2: outputTriplet(visit, "uint2(", "", ")"); break;
2191 case 3: outputTriplet(visit, "uint3(", "", ")"); break;
2192 case 4: outputTriplet(visit, "uint4(", "", ")"); break;
2193 default: UNREACHABLE();
2196 case EOpRadians: outputTriplet(visit, "radians(", "", ")"); break;
2197 case EOpDegrees: outputTriplet(visit, "degrees(", "", ")"); break;
2198 case EOpSin: outputTriplet(visit, "sin(", "", ")"); break;
2199 case EOpCos: outputTriplet(visit, "cos(", "", ")"); break;
2200 case EOpTan: outputTriplet(visit, "tan(", "", ")"); break;
2201 case EOpAsin: outputTriplet(visit, "asin(", "", ")"); break;
2202 case EOpAcos: outputTriplet(visit, "acos(", "", ")"); break;
2203 case EOpAtan: outputTriplet(visit, "atan(", "", ")"); break;
2204 case EOpExp: outputTriplet(visit, "exp(", "", ")"); break;
2205 case EOpLog: outputTriplet(visit, "log(", "", ")"); break;
2206 case EOpExp2: outputTriplet(visit, "exp2(", "", ")"); break;
2207 case EOpLog2: outputTriplet(visit, "log2(", "", ")"); break;
2208 case EOpSqrt: outputTriplet(visit, "sqrt(", "", ")"); break;
2209 case EOpInverseSqrt: outputTriplet(visit, "rsqrt(", "", ")"); break;
2210 case EOpAbs: outputTriplet(visit, "abs(", "", ")"); break;
2211 case EOpSign: outputTriplet(visit, "sign(", "", ")"); break;
2212 case EOpFloor: outputTriplet(visit, "floor(", "", ")"); break;
2213 case EOpCeil: outputTriplet(visit, "ceil(", "", ")"); break;
2214 case EOpFract: outputTriplet(visit, "frac(", "", ")"); break;
2215 case EOpLength: outputTriplet(visit, "length(", "", ")"); break;
2216 case EOpNormalize: outputTriplet(visit, "normalize(", "", ")"); break;
2218 if(mInsideDiscontinuousLoop || mOutputLod0Function)
2220 outputTriplet(visit, "(", "", ", 0.0)");
2224 outputTriplet(visit, "ddx(", "", ")");
2228 if(mInsideDiscontinuousLoop || mOutputLod0Function)
2230 outputTriplet(visit, "(", "", ", 0.0)");
2234 outputTriplet(visit, "ddy(", "", ")");
2238 if(mInsideDiscontinuousLoop || mOutputLod0Function)
2240 outputTriplet(visit, "(", "", ", 0.0)");
2244 outputTriplet(visit, "fwidth(", "", ")");
2247 case EOpAny: outputTriplet(visit, "any(", "", ")"); break;
2248 case EOpAll: outputTriplet(visit, "all(", "", ")"); break;
2249 default: UNREACHABLE();
2255 bool OutputHLSL::visitAggregate(Visit visit, TIntermAggregate *node)
2257 TInfoSinkBase &out = mBody;
2259 switch (node->getOp())
2263 if (mInsideFunction)
2265 outputLineDirective(node->getLine().first_line);
2269 for (TIntermSequence::iterator sit = node->getSequence().begin(); sit != node->getSequence().end(); sit++)
2271 outputLineDirective((*sit)->getLine().first_line);
2273 traverseStatements(*sit);
2278 if (mInsideFunction)
2280 outputLineDirective(node->getLine().last_line);
2286 case EOpDeclaration:
2287 if (visit == PreVisit)
2289 TIntermSequence &sequence = node->getSequence();
2290 TIntermTyped *variable = sequence[0]->getAsTyped();
2292 if (variable && (variable->getQualifier() == EvqTemporary || variable->getQualifier() == EvqGlobal))
2294 if (variable->getType().getStruct())
2296 addConstructor(variable->getType(), structNameString(*variable->getType().getStruct()), NULL);
2299 if (!variable->getAsSymbolNode() || variable->getAsSymbolNode()->getSymbol() != "") // Variable declaration
2301 if (!mInsideFunction)
2306 out << typeString(variable->getType()) + " ";
2308 for (TIntermSequence::iterator sit = sequence.begin(); sit != sequence.end(); sit++)
2310 TIntermSymbol *symbol = (*sit)->getAsSymbolNode();
2314 symbol->traverse(this);
2315 out << arrayString(symbol->getType());
2316 out << " = " + initializer(symbol->getType());
2320 (*sit)->traverse(this);
2323 if (*sit != sequence.back())
2329 else if (variable->getAsSymbolNode() && variable->getAsSymbolNode()->getSymbol() == "") // Type (struct) declaration
2331 // Already added to constructor map
2335 else if (variable && isVaryingOut(variable->getQualifier()))
2337 for (TIntermSequence::iterator sit = sequence.begin(); sit != sequence.end(); sit++)
2339 TIntermSymbol *symbol = (*sit)->getAsSymbolNode();
2343 // Vertex (output) varyings which are declared but not written to should still be declared to allow successful linking
2344 mReferencedVaryings[symbol->getSymbol()] = symbol;
2348 (*sit)->traverse(this);
2355 else if (visit == InVisit)
2361 if (visit == PreVisit)
2363 out << typeString(node->getType()) << " " << decorate(node->getName()) << (mOutputLod0Function ? "Lod0(" : "(");
2365 TIntermSequence &arguments = node->getSequence();
2367 for (unsigned int i = 0; i < arguments.size(); i++)
2369 TIntermSymbol *symbol = arguments[i]->getAsSymbolNode();
2373 out << argumentString(symbol);
2375 if (i < arguments.size() - 1)
2385 // Also prototype the Lod0 variant if needed
2386 if (mContainsLoopDiscontinuity && !mOutputLod0Function)
2388 mOutputLod0Function = true;
2389 node->traverse(this);
2390 mOutputLod0Function = false;
2396 case EOpComma: outputTriplet(visit, "(", ", ", ")"); break;
2399 TString name = TFunction::unmangleName(node->getName());
2401 out << typeString(node->getType()) << " ";
2409 out << decorate(name) << (mOutputLod0Function ? "Lod0(" : "(");
2412 TIntermSequence &sequence = node->getSequence();
2413 TIntermSequence &arguments = sequence[0]->getAsAggregate()->getSequence();
2415 for (unsigned int i = 0; i < arguments.size(); i++)
2417 TIntermSymbol *symbol = arguments[i]->getAsSymbolNode();
2421 if (symbol->getType().getStruct())
2423 addConstructor(symbol->getType(), structNameString(*symbol->getType().getStruct()), NULL);
2426 out << argumentString(symbol);
2428 if (i < arguments.size() - 1)
2439 if (sequence.size() > 1)
2441 mInsideFunction = true;
2442 sequence[1]->traverse(this);
2443 mInsideFunction = false;
2448 if (mContainsLoopDiscontinuity && !mOutputLod0Function)
2452 mOutputLod0Function = true;
2453 node->traverse(this);
2454 mOutputLod0Function = false;
2461 case EOpFunctionCall:
2463 TString name = TFunction::unmangleName(node->getName());
2464 bool lod0 = mInsideDiscontinuousLoop || mOutputLod0Function;
2465 TIntermSequence &arguments = node->getSequence();
2467 if (node->isUserDefined())
2469 out << decorate(name) << (lod0 ? "Lod0(" : "(");
2473 TBasicType samplerType = arguments[0]->getAsTyped()->getType().getBasicType();
2475 TextureFunction textureFunction;
2476 textureFunction.sampler = samplerType;
2477 textureFunction.coords = arguments[1]->getAsTyped()->getNominalSize();
2478 textureFunction.method = TextureFunction::IMPLICIT;
2479 textureFunction.proj = false;
2480 textureFunction.offset = false;
2482 if (name == "texture2D" || name == "textureCube" || name == "texture")
2484 textureFunction.method = TextureFunction::IMPLICIT;
2486 else if (name == "texture2DProj" || name == "textureProj")
2488 textureFunction.method = TextureFunction::IMPLICIT;
2489 textureFunction.proj = true;
2491 else if (name == "texture2DLod" || name == "textureCubeLod" || name == "textureLod" ||
2492 name == "texture2DLodEXT" || name == "textureCubeLodEXT")
2494 textureFunction.method = TextureFunction::LOD;
2496 else if (name == "texture2DProjLod" || name == "textureProjLod" || name == "texture2DProjLodEXT")
2498 textureFunction.method = TextureFunction::LOD;
2499 textureFunction.proj = true;
2501 else if (name == "textureSize")
2503 textureFunction.method = TextureFunction::SIZE;
2505 else if (name == "textureOffset")
2507 textureFunction.method = TextureFunction::IMPLICIT;
2508 textureFunction.offset = true;
2510 else if (name == "textureProjOffset")
2512 textureFunction.method = TextureFunction::IMPLICIT;
2513 textureFunction.offset = true;
2514 textureFunction.proj = true;
2516 else if (name == "textureLodOffset")
2518 textureFunction.method = TextureFunction::LOD;
2519 textureFunction.offset = true;
2521 else if (name == "textureProjLodOffset")
2523 textureFunction.method = TextureFunction::LOD;
2524 textureFunction.proj = true;
2525 textureFunction.offset = true;
2527 else if (name == "texelFetch")
2529 textureFunction.method = TextureFunction::FETCH;
2531 else if (name == "texelFetchOffset")
2533 textureFunction.method = TextureFunction::FETCH;
2534 textureFunction.offset = true;
2536 else if (name == "textureGrad" || name == "texture2DGradEXT")
2538 textureFunction.method = TextureFunction::GRAD;
2540 else if (name == "textureGradOffset")
2542 textureFunction.method = TextureFunction::GRAD;
2543 textureFunction.offset = true;
2545 else if (name == "textureProjGrad" || name == "texture2DProjGradEXT" || name == "textureCubeGradEXT")
2547 textureFunction.method = TextureFunction::GRAD;
2548 textureFunction.proj = true;
2550 else if (name == "textureProjGradOffset")
2552 textureFunction.method = TextureFunction::GRAD;
2553 textureFunction.proj = true;
2554 textureFunction.offset = true;
2558 if (textureFunction.method == TextureFunction::IMPLICIT) // Could require lod 0 or have a bias argument
2560 unsigned int mandatoryArgumentCount = 2; // All functions have sampler and coordinate arguments
2562 if (textureFunction.offset)
2564 mandatoryArgumentCount++;
2567 bool bias = (arguments.size() > mandatoryArgumentCount); // Bias argument is optional
2569 if (lod0 || mContext.shaderType == SH_VERTEX_SHADER)
2573 textureFunction.method = TextureFunction::LOD0BIAS;
2577 textureFunction.method = TextureFunction::LOD0;
2582 textureFunction.method = TextureFunction::BIAS;
2586 mUsesTexture.insert(textureFunction);
2588 out << textureFunction.name();
2591 for (TIntermSequence::iterator arg = arguments.begin(); arg != arguments.end(); arg++)
2593 if (mOutputType == SH_HLSL11_OUTPUT && IsSampler((*arg)->getAsTyped()->getBasicType()))
2596 (*arg)->traverse(this);
2597 out << ", sampler_";
2600 (*arg)->traverse(this);
2602 if (arg < arguments.end() - 1)
2613 case EOpParameters: outputTriplet(visit, "(", ", ", ")\n{\n"); break;
2614 case EOpConstructFloat:
2615 addConstructor(node->getType(), "vec1", &node->getSequence());
2616 outputTriplet(visit, "vec1(", "", ")");
2618 case EOpConstructVec2:
2619 addConstructor(node->getType(), "vec2", &node->getSequence());
2620 outputTriplet(visit, "vec2(", ", ", ")");
2622 case EOpConstructVec3:
2623 addConstructor(node->getType(), "vec3", &node->getSequence());
2624 outputTriplet(visit, "vec3(", ", ", ")");
2626 case EOpConstructVec4:
2627 addConstructor(node->getType(), "vec4", &node->getSequence());
2628 outputTriplet(visit, "vec4(", ", ", ")");
2630 case EOpConstructBool:
2631 addConstructor(node->getType(), "bvec1", &node->getSequence());
2632 outputTriplet(visit, "bvec1(", "", ")");
2634 case EOpConstructBVec2:
2635 addConstructor(node->getType(), "bvec2", &node->getSequence());
2636 outputTriplet(visit, "bvec2(", ", ", ")");
2638 case EOpConstructBVec3:
2639 addConstructor(node->getType(), "bvec3", &node->getSequence());
2640 outputTriplet(visit, "bvec3(", ", ", ")");
2642 case EOpConstructBVec4:
2643 addConstructor(node->getType(), "bvec4", &node->getSequence());
2644 outputTriplet(visit, "bvec4(", ", ", ")");
2646 case EOpConstructInt:
2647 addConstructor(node->getType(), "ivec1", &node->getSequence());
2648 outputTriplet(visit, "ivec1(", "", ")");
2650 case EOpConstructIVec2:
2651 addConstructor(node->getType(), "ivec2", &node->getSequence());
2652 outputTriplet(visit, "ivec2(", ", ", ")");
2654 case EOpConstructIVec3:
2655 addConstructor(node->getType(), "ivec3", &node->getSequence());
2656 outputTriplet(visit, "ivec3(", ", ", ")");
2658 case EOpConstructIVec4:
2659 addConstructor(node->getType(), "ivec4", &node->getSequence());
2660 outputTriplet(visit, "ivec4(", ", ", ")");
2662 case EOpConstructUInt:
2663 addConstructor(node->getType(), "uvec1", &node->getSequence());
2664 outputTriplet(visit, "uvec1(", "", ")");
2666 case EOpConstructUVec2:
2667 addConstructor(node->getType(), "uvec2", &node->getSequence());
2668 outputTriplet(visit, "uvec2(", ", ", ")");
2670 case EOpConstructUVec3:
2671 addConstructor(node->getType(), "uvec3", &node->getSequence());
2672 outputTriplet(visit, "uvec3(", ", ", ")");
2674 case EOpConstructUVec4:
2675 addConstructor(node->getType(), "uvec4", &node->getSequence());
2676 outputTriplet(visit, "uvec4(", ", ", ")");
2678 case EOpConstructMat2:
2679 addConstructor(node->getType(), "mat2", &node->getSequence());
2680 outputTriplet(visit, "mat2(", ", ", ")");
2682 case EOpConstructMat3:
2683 addConstructor(node->getType(), "mat3", &node->getSequence());
2684 outputTriplet(visit, "mat3(", ", ", ")");
2686 case EOpConstructMat4:
2687 addConstructor(node->getType(), "mat4", &node->getSequence());
2688 outputTriplet(visit, "mat4(", ", ", ")");
2690 case EOpConstructStruct:
2692 const TString &structName = structNameString(*node->getType().getStruct());
2693 addConstructor(node->getType(), structName, &node->getSequence());
2694 outputTriplet(visit, structName + "_ctor(", ", ", ")");
2697 case EOpLessThan: outputTriplet(visit, "(", " < ", ")"); break;
2698 case EOpGreaterThan: outputTriplet(visit, "(", " > ", ")"); break;
2699 case EOpLessThanEqual: outputTriplet(visit, "(", " <= ", ")"); break;
2700 case EOpGreaterThanEqual: outputTriplet(visit, "(", " >= ", ")"); break;
2701 case EOpVectorEqual: outputTriplet(visit, "(", " == ", ")"); break;
2702 case EOpVectorNotEqual: outputTriplet(visit, "(", " != ", ")"); break;
2705 // We need to look at the number of components in both arguments
2706 const int modValue = node->getSequence()[0]->getAsTyped()->getNominalSize() * 10
2707 + node->getSequence()[1]->getAsTyped()->getNominalSize();
2710 case 11: mUsesMod1 = true; break;
2711 case 22: mUsesMod2v = true; break;
2712 case 21: mUsesMod2f = true; break;
2713 case 33: mUsesMod3v = true; break;
2714 case 31: mUsesMod3f = true; break;
2715 case 44: mUsesMod4v = true; break;
2716 case 41: mUsesMod4f = true; break;
2717 default: UNREACHABLE();
2720 outputTriplet(visit, "mod(", ", ", ")");
2723 case EOpPow: outputTriplet(visit, "pow(", ", ", ")"); break;
2725 ASSERT(node->getSequence().size() == 2); // atan(x) is a unary operator
2726 switch (node->getSequence()[0]->getAsTyped()->getNominalSize())
2728 case 1: mUsesAtan2_1 = true; break;
2729 case 2: mUsesAtan2_2 = true; break;
2730 case 3: mUsesAtan2_3 = true; break;
2731 case 4: mUsesAtan2_4 = true; break;
2732 default: UNREACHABLE();
2734 outputTriplet(visit, "atanyx(", ", ", ")");
2736 case EOpMin: outputTriplet(visit, "min(", ", ", ")"); break;
2737 case EOpMax: outputTriplet(visit, "max(", ", ", ")"); break;
2738 case EOpClamp: outputTriplet(visit, "clamp(", ", ", ")"); break;
2739 case EOpMix: outputTriplet(visit, "lerp(", ", ", ")"); break;
2740 case EOpStep: outputTriplet(visit, "step(", ", ", ")"); break;
2741 case EOpSmoothStep: outputTriplet(visit, "smoothstep(", ", ", ")"); break;
2742 case EOpDistance: outputTriplet(visit, "distance(", ", ", ")"); break;
2743 case EOpDot: outputTriplet(visit, "dot(", ", ", ")"); break;
2744 case EOpCross: outputTriplet(visit, "cross(", ", ", ")"); break;
2745 case EOpFaceForward:
2747 switch (node->getSequence()[0]->getAsTyped()->getNominalSize()) // Number of components in the first argument
2749 case 1: mUsesFaceforward1 = true; break;
2750 case 2: mUsesFaceforward2 = true; break;
2751 case 3: mUsesFaceforward3 = true; break;
2752 case 4: mUsesFaceforward4 = true; break;
2753 default: UNREACHABLE();
2756 outputTriplet(visit, "faceforward(", ", ", ")");
2759 case EOpReflect: outputTriplet(visit, "reflect(", ", ", ")"); break;
2760 case EOpRefract: outputTriplet(visit, "refract(", ", ", ")"); break;
2761 case EOpMul: outputTriplet(visit, "(", " * ", ")"); break;
2762 default: UNREACHABLE();
2768 bool OutputHLSL::visitSelection(Visit visit, TIntermSelection *node)
2770 TInfoSinkBase &out = mBody;
2772 if (node->usesTernaryOperator())
2774 out << "s" << mUnfoldShortCircuit->getNextTemporaryIndex();
2776 else // if/else statement
2778 mUnfoldShortCircuit->traverse(node->getCondition());
2782 node->getCondition()->traverse(this);
2786 outputLineDirective(node->getLine().first_line);
2789 bool discard = false;
2791 if (node->getTrueBlock())
2793 traverseStatements(node->getTrueBlock());
2795 // Detect true discard
2796 discard = (discard || FindDiscard::search(node->getTrueBlock()));
2799 outputLineDirective(node->getLine().first_line);
2802 if (node->getFalseBlock())
2806 outputLineDirective(node->getFalseBlock()->getLine().first_line);
2809 outputLineDirective(node->getFalseBlock()->getLine().first_line);
2810 traverseStatements(node->getFalseBlock());
2812 outputLineDirective(node->getFalseBlock()->getLine().first_line);
2815 // Detect false discard
2816 discard = (discard || FindDiscard::search(node->getFalseBlock()));
2819 // ANGLE issue 486: Detect problematic conditional discard
2820 if (discard && FindSideEffectRewriting::search(node))
2822 mUsesDiscardRewriting = true;
2829 void OutputHLSL::visitConstantUnion(TIntermConstantUnion *node)
2831 writeConstantUnion(node->getType(), node->getUnionArrayPointer());
2834 bool OutputHLSL::visitLoop(Visit visit, TIntermLoop *node)
2838 bool wasDiscontinuous = mInsideDiscontinuousLoop;
2840 if (mContainsLoopDiscontinuity && !mInsideDiscontinuousLoop)
2842 mInsideDiscontinuousLoop = containsLoopDiscontinuity(node);
2845 if (mOutputType == SH_HLSL9_OUTPUT)
2847 if (handleExcessiveLoop(node))
2849 mInsideDiscontinuousLoop = wasDiscontinuous;
2856 TInfoSinkBase &out = mBody;
2858 if (node->getType() == ELoopDoWhile)
2862 outputLineDirective(node->getLine().first_line);
2869 if (node->getInit())
2871 node->getInit()->traverse(this);
2876 if (node->getCondition())
2878 node->getCondition()->traverse(this);
2883 if (node->getExpression())
2885 node->getExpression()->traverse(this);
2890 outputLineDirective(node->getLine().first_line);
2894 if (node->getBody())
2896 traverseStatements(node->getBody());
2899 outputLineDirective(node->getLine().first_line);
2902 if (node->getType() == ELoopDoWhile)
2904 outputLineDirective(node->getCondition()->getLine().first_line);
2907 node->getCondition()->traverse(this);
2914 mInsideDiscontinuousLoop = wasDiscontinuous;
2920 bool OutputHLSL::visitBranch(Visit visit, TIntermBranch *node)
2922 TInfoSinkBase &out = mBody;
2924 switch (node->getFlowOp())
2927 outputTriplet(visit, "discard;\n", "", "");
2930 if (visit == PreVisit)
2932 if (mNestedLoopDepth > 1)
2934 mUsesNestedBreak = true;
2937 if (mExcessiveLoopIndex)
2940 mExcessiveLoopIndex->traverse(this);
2941 out << " = true; break;}\n";
2949 case EOpContinue: outputTriplet(visit, "continue;\n", "", ""); break;
2951 if (visit == PreVisit)
2953 if (node->getExpression())
2962 else if (visit == PostVisit)
2964 if (node->getExpression())
2970 default: UNREACHABLE();
2976 void OutputHLSL::traverseStatements(TIntermNode *node)
2978 if (isSingleStatement(node))
2980 mUnfoldShortCircuit->traverse(node);
2983 node->traverse(this);
2986 bool OutputHLSL::isSingleStatement(TIntermNode *node)
2988 TIntermAggregate *aggregate = node->getAsAggregate();
2992 if (aggregate->getOp() == EOpSequence)
2998 for (TIntermSequence::iterator sit = aggregate->getSequence().begin(); sit != aggregate->getSequence().end(); sit++)
3000 if (!isSingleStatement(*sit))
3013 // Handle loops with more than 254 iterations (unsupported by D3D9) by splitting them
3014 // (The D3D documentation says 255 iterations, but the compiler complains at anything more than 254).
3015 bool OutputHLSL::handleExcessiveLoop(TIntermLoop *node)
3017 const int MAX_LOOP_ITERATIONS = 254;
3018 TInfoSinkBase &out = mBody;
3020 // Parse loops of the form:
3021 // for(int index = initial; index [comparator] limit; index += increment)
3022 TIntermSymbol *index = NULL;
3023 TOperator comparator = EOpNull;
3028 // Parse index name and intial value
3029 if (node->getInit())
3031 TIntermAggregate *init = node->getInit()->getAsAggregate();
3035 TIntermSequence &sequence = init->getSequence();
3036 TIntermTyped *variable = sequence[0]->getAsTyped();
3038 if (variable && variable->getQualifier() == EvqTemporary)
3040 TIntermBinary *assign = variable->getAsBinaryNode();
3042 if (assign->getOp() == EOpInitialize)
3044 TIntermSymbol *symbol = assign->getLeft()->getAsSymbolNode();
3045 TIntermConstantUnion *constant = assign->getRight()->getAsConstantUnion();
3047 if (symbol && constant)
3049 if (constant->getBasicType() == EbtInt && constant->isScalar())
3052 initial = constant->getIConst(0);
3060 // Parse comparator and limit value
3061 if (index != NULL && node->getCondition())
3063 TIntermBinary *test = node->getCondition()->getAsBinaryNode();
3065 if (test && test->getLeft()->getAsSymbolNode()->getId() == index->getId())
3067 TIntermConstantUnion *constant = test->getRight()->getAsConstantUnion();
3071 if (constant->getBasicType() == EbtInt && constant->isScalar())
3073 comparator = test->getOp();
3074 limit = constant->getIConst(0);
3081 if (index != NULL && comparator != EOpNull && node->getExpression())
3083 TIntermBinary *binaryTerminal = node->getExpression()->getAsBinaryNode();
3084 TIntermUnary *unaryTerminal = node->getExpression()->getAsUnaryNode();
3088 TOperator op = binaryTerminal->getOp();
3089 TIntermConstantUnion *constant = binaryTerminal->getRight()->getAsConstantUnion();
3093 if (constant->getBasicType() == EbtInt && constant->isScalar())
3095 int value = constant->getIConst(0);
3099 case EOpAddAssign: increment = value; break;
3100 case EOpSubAssign: increment = -value; break;
3101 default: UNIMPLEMENTED();
3106 else if (unaryTerminal)
3108 TOperator op = unaryTerminal->getOp();
3112 case EOpPostIncrement: increment = 1; break;
3113 case EOpPostDecrement: increment = -1; break;
3114 case EOpPreIncrement: increment = 1; break;
3115 case EOpPreDecrement: increment = -1; break;
3116 default: UNIMPLEMENTED();
3121 if (index != NULL && comparator != EOpNull && increment != 0)
3123 if (comparator == EOpLessThanEqual)
3125 comparator = EOpLessThan;
3129 if (comparator == EOpLessThan)
3131 int iterations = (limit - initial) / increment;
3133 if (iterations <= MAX_LOOP_ITERATIONS)
3135 return false; // Not an excessive loop
3138 TIntermSymbol *restoreIndex = mExcessiveLoopIndex;
3139 mExcessiveLoopIndex = index;
3142 index->traverse(this);
3145 index->traverse(this);
3146 out << " = false;\n";
3148 bool firstLoopFragment = true;
3150 while (iterations > 0)
3152 int clampedLimit = initial + increment * std::min(MAX_LOOP_ITERATIONS, iterations);
3154 if (!firstLoopFragment)
3156 out << "if (!Break";
3157 index->traverse(this);
3161 if (iterations <= MAX_LOOP_ITERATIONS) // Last loop fragment
3163 mExcessiveLoopIndex = NULL; // Stops setting the Break flag
3166 // for(int index = initial; index < clampedLimit; index += increment)
3169 index->traverse(this);
3174 index->traverse(this);
3176 out << clampedLimit;
3179 index->traverse(this);
3184 outputLineDirective(node->getLine().first_line);
3187 if (node->getBody())
3189 node->getBody()->traverse(this);
3192 outputLineDirective(node->getLine().first_line);
3195 if (!firstLoopFragment)
3200 firstLoopFragment = false;
3202 initial += MAX_LOOP_ITERATIONS * increment;
3203 iterations -= MAX_LOOP_ITERATIONS;
3208 mExcessiveLoopIndex = restoreIndex;
3212 else UNIMPLEMENTED();
3215 return false; // Not handled as an excessive loop
3218 void OutputHLSL::outputTriplet(Visit visit, const TString &preString, const TString &inString, const TString &postString)
3220 TInfoSinkBase &out = mBody;
3222 if (visit == PreVisit)
3226 else if (visit == InVisit)
3230 else if (visit == PostVisit)
3236 void OutputHLSL::outputLineDirective(int line)
3238 if ((mContext.compileOptions & SH_LINE_DIRECTIVES) && (line > 0))
3241 mBody << "#line " << line;
3243 if (mContext.sourcePath)
3245 mBody << " \"" << mContext.sourcePath << "\"";
3252 TString OutputHLSL::argumentString(const TIntermSymbol *symbol)
3254 TQualifier qualifier = symbol->getQualifier();
3255 const TType &type = symbol->getType();
3256 TString name = symbol->getSymbol();
3258 if (name.empty()) // HLSL demands named arguments, also for prototypes
3260 name = "x" + str(mUniqueIndex++);
3264 name = decorate(name);
3267 if (mOutputType == SH_HLSL11_OUTPUT && IsSampler(type.getBasicType()))
3269 return qualifierString(qualifier) + " " + textureString(type) + " texture_" + name + arrayString(type) + ", " +
3270 qualifierString(qualifier) + " " + samplerString(type) + " sampler_" + name + arrayString(type);
3273 return qualifierString(qualifier) + " " + typeString(type) + " " + name + arrayString(type);
3276 TString OutputHLSL::interpolationString(TQualifier qualifier)
3280 case EvqVaryingIn: return "";
3281 case EvqFragmentIn: return "";
3282 case EvqInvariantVaryingIn: return "";
3283 case EvqSmoothIn: return "linear";
3284 case EvqFlatIn: return "nointerpolation";
3285 case EvqCentroidIn: return "centroid";
3286 case EvqVaryingOut: return "";
3287 case EvqVertexOut: return "";
3288 case EvqInvariantVaryingOut: return "";
3289 case EvqSmoothOut: return "linear";
3290 case EvqFlatOut: return "nointerpolation";
3291 case EvqCentroidOut: return "centroid";
3292 default: UNREACHABLE();
3298 TString OutputHLSL::qualifierString(TQualifier qualifier)
3302 case EvqIn: return "in";
3303 case EvqOut: return "inout"; // 'out' results in an HLSL error if not all fields are written, for GLSL it's undefined
3304 case EvqInOut: return "inout";
3305 case EvqConstReadOnly: return "const";
3306 default: UNREACHABLE();
3312 TString OutputHLSL::typeString(const TType &type)
3314 const TStructure* structure = type.getStruct();
3317 const TString& typeName = structure->name();
3320 return structNameString(*type.getStruct());
3322 else // Nameless structure, define in place
3324 return structureString(*structure, false, false);
3327 else if (type.isMatrix())
3329 int cols = type.getCols();
3330 int rows = type.getRows();
3331 return "float" + str(cols) + "x" + str(rows);
3335 switch (type.getBasicType())
3338 switch (type.getNominalSize())
3340 case 1: return "float";
3341 case 2: return "float2";
3342 case 3: return "float3";
3343 case 4: return "float4";
3346 switch (type.getNominalSize())
3348 case 1: return "int";
3349 case 2: return "int2";
3350 case 3: return "int3";
3351 case 4: return "int4";
3354 switch (type.getNominalSize())
3356 case 1: return "uint";
3357 case 2: return "uint2";
3358 case 3: return "uint3";
3359 case 4: return "uint4";
3362 switch (type.getNominalSize())
3364 case 1: return "bool";
3365 case 2: return "bool2";
3366 case 3: return "bool3";
3367 case 4: return "bool4";
3374 case EbtSampler2DArray:
3375 case EbtISampler2DArray:
3376 case EbtUSampler2DArray:
3378 case EbtSamplerCube:
3379 case EbtISamplerCube:
3380 case EbtUSamplerCube:
3381 return "samplerCUBE";
3382 case EbtSamplerExternalOES:
3390 return "<unknown type>";
3393 TString OutputHLSL::textureString(const TType &type)
3395 switch (type.getBasicType())
3397 case EbtSampler2D: return "Texture2D";
3398 case EbtSamplerCube: return "TextureCube";
3399 case EbtSamplerExternalOES: return "Texture2D";
3400 case EbtSampler2DArray: return "Texture2DArray";
3401 case EbtSampler3D: return "Texture3D";
3402 case EbtISampler2D: return "Texture2D<int4>";
3403 case EbtISampler3D: return "Texture3D<int4>";
3404 case EbtISamplerCube: return "Texture2DArray<int4>";
3405 case EbtISampler2DArray: return "Texture2DArray<int4>";
3406 case EbtUSampler2D: return "Texture2D<uint4>";
3407 case EbtUSampler3D: return "Texture3D<uint4>";
3408 case EbtUSamplerCube: return "Texture2DArray<uint4>";
3409 case EbtUSampler2DArray: return "Texture2DArray<uint4>";
3410 case EbtSampler2DShadow: return "Texture2D";
3411 case EbtSamplerCubeShadow: return "TextureCube";
3412 case EbtSampler2DArrayShadow: return "Texture2DArray";
3413 default: UNREACHABLE();
3416 return "<unknown texture type>";
3419 TString OutputHLSL::samplerString(const TType &type)
3421 if (IsShadowSampler(type.getBasicType()))
3423 return "SamplerComparisonState";
3427 return "SamplerState";
3431 TString OutputHLSL::arrayString(const TType &type)
3433 if (!type.isArray())
3438 return "[" + str(type.getArraySize()) + "]";
3441 TString OutputHLSL::initializer(const TType &type)
3445 size_t size = type.getObjectSize();
3446 for (size_t component = 0; component < size; component++)
3450 if (component + 1 < size)
3456 return "{" + string + "}";
3459 TString OutputHLSL::structureString(const TStructure &structure, bool useHLSLRowMajorPacking, bool useStd140Packing)
3461 const TFieldList &fields = structure.fields();
3462 const bool isNameless = (structure.name() == "");
3463 const TString &structName = structureTypeName(structure, useHLSLRowMajorPacking, useStd140Packing);
3464 const TString declareString = (isNameless ? "struct" : "struct " + structName);
3467 string += declareString + "\n"
3470 int elementIndex = 0;
3472 for (unsigned int i = 0; i < fields.size(); i++)
3474 const TField &field = *fields[i];
3475 const TType &fieldType = *field.type();
3476 const TStructure *fieldStruct = fieldType.getStruct();
3477 const TString &fieldTypeString = fieldStruct ? structureTypeName(*fieldStruct, useHLSLRowMajorPacking, useStd140Packing) : typeString(fieldType);
3479 if (useStd140Packing)
3481 string += std140PrePaddingString(*field.type(), &elementIndex);
3484 string += " " + fieldTypeString + " " + decorateField(field.name(), structure) + arrayString(fieldType) + ";\n";
3486 if (useStd140Packing)
3488 string += std140PostPaddingString(*field.type(), useHLSLRowMajorPacking);
3492 // Nameless structs do not finish with a semicolon and newline, to leave room for an instance variable
3493 string += (isNameless ? "} " : "};\n");
3495 // Add remaining element index to the global map, for use with nested structs in standard layouts
3496 if (useStd140Packing)
3498 mStd140StructElementIndexes[structName] = elementIndex;
3504 TString OutputHLSL::structureTypeName(const TStructure &structure, bool useHLSLRowMajorPacking, bool useStd140Packing)
3506 if (structure.name() == "")
3511 TString prefix = "";
3513 // Structs packed with row-major matrices in HLSL are prefixed with "rm"
3514 // GLSL column-major maps to HLSL row-major, and the converse is true
3516 if (useStd140Packing)
3521 if (useHLSLRowMajorPacking)
3523 if (prefix != "") prefix += "_";
3527 return prefix + structNameString(structure);
3530 void OutputHLSL::addConstructor(const TType &type, const TString &name, const TIntermSequence *parameters)
3534 return; // Nameless structures don't have constructors
3537 if (type.getStruct() && mStructNames.find(name) != mStructNames.end())
3539 return; // Already added
3542 TType ctorType = type;
3543 ctorType.clearArrayness();
3544 ctorType.setPrecision(EbpHigh);
3545 ctorType.setQualifier(EvqTemporary);
3547 typedef std::vector<TType> ParameterArray;
3548 ParameterArray ctorParameters;
3550 const TStructure* structure = type.getStruct();
3553 mStructNames.insert(name);
3555 const TString &structString = structureString(*structure, false, false);
3557 if (std::find(mStructDeclarations.begin(), mStructDeclarations.end(), structString) == mStructDeclarations.end())
3559 // Add row-major packed struct for interface blocks
3560 TString rowMajorString = "#pragma pack_matrix(row_major)\n" +
3561 structureString(*structure, true, false) +
3562 "#pragma pack_matrix(column_major)\n";
3564 TString std140String = structureString(*structure, false, true);
3565 TString std140RowMajorString = "#pragma pack_matrix(row_major)\n" +
3566 structureString(*structure, true, true) +
3567 "#pragma pack_matrix(column_major)\n";
3569 mStructDeclarations.push_back(structString);
3570 mStructDeclarations.push_back(rowMajorString);
3571 mStructDeclarations.push_back(std140String);
3572 mStructDeclarations.push_back(std140RowMajorString);
3575 const TFieldList &fields = structure->fields();
3576 for (unsigned int i = 0; i < fields.size(); i++)
3578 ctorParameters.push_back(*fields[i]->type());
3581 else if (parameters)
3583 for (TIntermSequence::const_iterator parameter = parameters->begin(); parameter != parameters->end(); parameter++)
3585 ctorParameters.push_back((*parameter)->getAsTyped()->getType());
3590 TString constructor;
3592 if (ctorType.getStruct())
3594 constructor += name + " " + name + "_ctor(";
3596 else // Built-in type
3598 constructor += typeString(ctorType) + " " + name + "(";
3601 for (unsigned int parameter = 0; parameter < ctorParameters.size(); parameter++)
3603 const TType &type = ctorParameters[parameter];
3605 constructor += typeString(type) + " x" + str(parameter) + arrayString(type);
3607 if (parameter < ctorParameters.size() - 1)
3609 constructor += ", ";
3613 constructor += ")\n"
3616 if (ctorType.getStruct())
3618 constructor += " " + name + " structure = {";
3622 constructor += " return " + typeString(ctorType) + "(";
3625 if (ctorType.isMatrix() && ctorParameters.size() == 1)
3627 int rows = ctorType.getRows();
3628 int cols = ctorType.getCols();
3629 const TType ¶meter = ctorParameters[0];
3631 if (parameter.isScalar())
3633 for (int row = 0; row < rows; row++)
3635 for (int col = 0; col < cols; col++)
3637 constructor += TString((row == col) ? "x0" : "0.0");
3639 if (row < rows - 1 || col < cols - 1)
3641 constructor += ", ";
3646 else if (parameter.isMatrix())
3648 for (int row = 0; row < rows; row++)
3650 for (int col = 0; col < cols; col++)
3652 if (row < parameter.getRows() && col < parameter.getCols())
3654 constructor += TString("x0") + "[" + str(row) + "]" + "[" + str(col) + "]";
3658 constructor += TString((row == col) ? "1.0" : "0.0");
3661 if (row < rows - 1 || col < cols - 1)
3663 constructor += ", ";
3672 size_t remainingComponents = ctorType.getObjectSize();
3673 size_t parameterIndex = 0;
3675 while (remainingComponents > 0)
3677 const TType ¶meter = ctorParameters[parameterIndex];
3678 const size_t parameterSize = parameter.getObjectSize();
3679 bool moreParameters = parameterIndex + 1 < ctorParameters.size();
3681 constructor += "x" + str(parameterIndex);
3683 if (parameter.isScalar())
3685 remainingComponents -= parameter.getObjectSize();
3687 else if (parameter.isVector())
3689 if (remainingComponents == parameterSize || moreParameters)
3691 ASSERT(parameterSize <= remainingComponents);
3692 remainingComponents -= parameterSize;
3694 else if (remainingComponents < static_cast<size_t>(parameter.getNominalSize()))
3696 switch (remainingComponents)
3698 case 1: constructor += ".x"; break;
3699 case 2: constructor += ".xy"; break;
3700 case 3: constructor += ".xyz"; break;
3701 case 4: constructor += ".xyzw"; break;
3702 default: UNREACHABLE();
3705 remainingComponents = 0;
3709 else if (parameter.isMatrix() || parameter.getStruct())
3711 ASSERT(remainingComponents == parameterSize || moreParameters);
3712 ASSERT(parameterSize <= remainingComponents);
3714 remainingComponents -= parameterSize;
3723 if (remainingComponents)
3725 constructor += ", ";
3730 if (ctorType.getStruct())
3732 constructor += "};\n"
3733 " return structure;\n"
3738 constructor += ");\n"
3742 mConstructors.insert(constructor);
3745 const ConstantUnion *OutputHLSL::writeConstantUnion(const TType &type, const ConstantUnion *constUnion)
3747 TInfoSinkBase &out = mBody;
3749 const TStructure* structure = type.getStruct();
3752 out << structNameString(*structure) + "_ctor(";
3754 const TFieldList& fields = structure->fields();
3756 for (size_t i = 0; i < fields.size(); i++)
3758 const TType *fieldType = fields[i]->type();
3760 constUnion = writeConstantUnion(*fieldType, constUnion);
3762 if (i != fields.size() - 1)
3772 size_t size = type.getObjectSize();
3773 bool writeType = size > 1;
3777 out << typeString(type) << "(";
3780 for (size_t i = 0; i < size; i++, constUnion++)
3782 switch (constUnion->getType())
3784 case EbtFloat: out << std::min(FLT_MAX, std::max(-FLT_MAX, constUnion->getFConst())); break;
3785 case EbtInt: out << constUnion->getIConst(); break;
3786 case EbtUInt: out << constUnion->getUConst(); break;
3787 case EbtBool: out << constUnion->getBConst(); break;
3788 default: UNREACHABLE();
3806 TString OutputHLSL::structNameString(const TStructure &structure)
3808 if (structure.name().empty())
3813 return "ss_" + str(structure.uniqueId()) + structure.name();
3816 TString OutputHLSL::decorate(const TString &string)
3818 if (string.compare(0, 3, "gl_") != 0 && string.compare(0, 3, "dx_") != 0)
3820 return "_" + string;
3826 TString OutputHLSL::decorateUniform(const TString &string, const TType &type)
3828 if (type.getBasicType() == EbtSamplerExternalOES)
3830 return "ex_" + string;
3833 return decorate(string);
3836 TString OutputHLSL::decorateField(const TString &string, const TStructure &structure)
3838 if (structure.name().compare(0, 3, "gl_") != 0)
3840 return decorate(string);
3846 void OutputHLSL::declareInterfaceBlockField(const TType &type, const TString &name, std::vector<gl::InterfaceBlockField>& output)
3848 const TStructure *structure = type.getStruct();
3852 const bool isRowMajorMatrix = (type.isMatrix() && type.getLayoutQualifier().matrixPacking == EmpRowMajor);
3853 gl::InterfaceBlockField field(glVariableType(type), glVariablePrecision(type), name.c_str(),
3854 (unsigned int)type.getArraySize(), isRowMajorMatrix);
3855 output.push_back(field);
3859 gl::InterfaceBlockField structField(GL_STRUCT_ANGLEX, GL_NONE, name.c_str(), (unsigned int)type.getArraySize(), false);
3861 const TFieldList &fields = structure->fields();
3863 for (size_t fieldIndex = 0; fieldIndex < fields.size(); fieldIndex++)
3865 TField *field = fields[fieldIndex];
3866 TType *fieldType = field->type();
3868 // make sure to copy matrix packing information
3869 fieldType->setLayoutQualifier(type.getLayoutQualifier());
3871 declareInterfaceBlockField(*fieldType, field->name(), structField.fields);
3874 output.push_back(structField);
3878 gl::Uniform OutputHLSL::declareUniformToList(const TType &type, const TString &name, int registerIndex, std::vector<gl::Uniform>& output)
3880 const TStructure *structure = type.getStruct();
3884 gl::Uniform uniform(glVariableType(type), glVariablePrecision(type), name.c_str(),
3885 (unsigned int)type.getArraySize(), (unsigned int)registerIndex, 0);
3886 output.push_back(uniform);
3892 gl::Uniform structUniform(GL_STRUCT_ANGLEX, GL_NONE, name.c_str(), (unsigned int)type.getArraySize(),
3893 (unsigned int)registerIndex, GL_INVALID_INDEX);
3895 const TFieldList &fields = structure->fields();
3897 for (size_t fieldIndex = 0; fieldIndex < fields.size(); fieldIndex++)
3899 TField *field = fields[fieldIndex];
3900 TType *fieldType = field->type();
3902 declareUniformToList(*fieldType, field->name(), GL_INVALID_INDEX, structUniform.fields);
3905 // assign register offset information -- this will override the information in any sub-structures.
3906 HLSLVariableGetRegisterInfo(registerIndex, &structUniform, mOutputType);
3908 output.push_back(structUniform);
3910 return structUniform;
3914 gl::InterpolationType getInterpolationType(TQualifier qualifier)
3920 return gl::INTERPOLATION_FLAT;
3928 return gl::INTERPOLATION_SMOOTH;
3931 case EvqCentroidOut:
3932 return gl::INTERPOLATION_CENTROID;
3934 default: UNREACHABLE();
3935 return gl::INTERPOLATION_SMOOTH;
3939 void OutputHLSL::declareVaryingToList(const TType &type, TQualifier baseTypeQualifier, const TString &name, std::vector<gl::Varying>& fieldsOut)
3941 const TStructure *structure = type.getStruct();
3943 gl::InterpolationType interpolation = getInterpolationType(baseTypeQualifier);
3946 gl::Varying varying(glVariableType(type), glVariablePrecision(type), name.c_str(), (unsigned int)type.getArraySize(), interpolation);
3947 fieldsOut.push_back(varying);
3951 gl::Varying structVarying(GL_STRUCT_ANGLEX, GL_NONE, name.c_str(), (unsigned int)type.getArraySize(), interpolation);
3952 const TFieldList &fields = structure->fields();
3954 structVarying.structName = structure->name().c_str();
3956 for (size_t fieldIndex = 0; fieldIndex < fields.size(); fieldIndex++)
3958 const TField &field = *fields[fieldIndex];
3959 declareVaryingToList(*field.type(), baseTypeQualifier, field.name(), structVarying.fields);
3962 fieldsOut.push_back(structVarying);
3966 int OutputHLSL::declareUniformAndAssignRegister(const TType &type, const TString &name)
3968 int registerIndex = (IsSampler(type.getBasicType()) ? mSamplerRegister : mUniformRegister);
3970 const gl::Uniform &uniform = declareUniformToList(type, name, registerIndex, mActiveUniforms);
3972 if (IsSampler(type.getBasicType()))
3974 mSamplerRegister += gl::HLSLVariableRegisterCount(uniform, mOutputType);
3978 mUniformRegister += gl::HLSLVariableRegisterCount(uniform, mOutputType);
3981 return registerIndex;
3984 GLenum OutputHLSL::glVariableType(const TType &type)
3986 if (type.getBasicType() == EbtFloat)
3988 if (type.isScalar())
3992 else if (type.isVector())
3994 switch(type.getNominalSize())
3996 case 2: return GL_FLOAT_VEC2;
3997 case 3: return GL_FLOAT_VEC3;
3998 case 4: return GL_FLOAT_VEC4;
3999 default: UNREACHABLE();
4002 else if (type.isMatrix())
4004 switch (type.getCols())
4007 switch(type.getRows())
4009 case 2: return GL_FLOAT_MAT2;
4010 case 3: return GL_FLOAT_MAT2x3;
4011 case 4: return GL_FLOAT_MAT2x4;
4012 default: UNREACHABLE();
4016 switch(type.getRows())
4018 case 2: return GL_FLOAT_MAT3x2;
4019 case 3: return GL_FLOAT_MAT3;
4020 case 4: return GL_FLOAT_MAT3x4;
4021 default: UNREACHABLE();
4025 switch(type.getRows())
4027 case 2: return GL_FLOAT_MAT4x2;
4028 case 3: return GL_FLOAT_MAT4x3;
4029 case 4: return GL_FLOAT_MAT4;
4030 default: UNREACHABLE();
4033 default: UNREACHABLE();
4038 else if (type.getBasicType() == EbtInt)
4040 if (type.isScalar())
4044 else if (type.isVector())
4046 switch(type.getNominalSize())
4048 case 2: return GL_INT_VEC2;
4049 case 3: return GL_INT_VEC3;
4050 case 4: return GL_INT_VEC4;
4051 default: UNREACHABLE();
4056 else if (type.getBasicType() == EbtUInt)
4058 if (type.isScalar())
4060 return GL_UNSIGNED_INT;
4062 else if (type.isVector())
4064 switch(type.getNominalSize())
4066 case 2: return GL_UNSIGNED_INT_VEC2;
4067 case 3: return GL_UNSIGNED_INT_VEC3;
4068 case 4: return GL_UNSIGNED_INT_VEC4;
4069 default: UNREACHABLE();
4074 else if (type.getBasicType() == EbtBool)
4076 if (type.isScalar())
4080 else if (type.isVector())
4082 switch(type.getNominalSize())
4084 case 2: return GL_BOOL_VEC2;
4085 case 3: return GL_BOOL_VEC3;
4086 case 4: return GL_BOOL_VEC4;
4087 default: UNREACHABLE();
4093 switch(type.getBasicType())
4095 case EbtSampler2D: return GL_SAMPLER_2D;
4096 case EbtSampler3D: return GL_SAMPLER_3D;
4097 case EbtSamplerCube: return GL_SAMPLER_CUBE;
4098 case EbtSampler2DArray: return GL_SAMPLER_2D_ARRAY;
4099 case EbtISampler2D: return GL_INT_SAMPLER_2D;
4100 case EbtISampler3D: return GL_INT_SAMPLER_3D;
4101 case EbtISamplerCube: return GL_INT_SAMPLER_CUBE;
4102 case EbtISampler2DArray: return GL_INT_SAMPLER_2D_ARRAY;
4103 case EbtUSampler2D: return GL_UNSIGNED_INT_SAMPLER_2D;
4104 case EbtUSampler3D: return GL_UNSIGNED_INT_SAMPLER_3D;
4105 case EbtUSamplerCube: return GL_UNSIGNED_INT_SAMPLER_CUBE;
4106 case EbtUSampler2DArray: return GL_UNSIGNED_INT_SAMPLER_2D_ARRAY;
4107 case EbtSampler2DShadow: return GL_SAMPLER_2D_SHADOW;
4108 case EbtSamplerCubeShadow: return GL_SAMPLER_CUBE_SHADOW;
4109 case EbtSampler2DArrayShadow: return GL_SAMPLER_2D_ARRAY_SHADOW;
4110 default: UNREACHABLE();
4116 GLenum OutputHLSL::glVariablePrecision(const TType &type)
4118 if (type.getBasicType() == EbtFloat)
4120 switch (type.getPrecision())
4122 case EbpHigh: return GL_HIGH_FLOAT;
4123 case EbpMedium: return GL_MEDIUM_FLOAT;
4124 case EbpLow: return GL_LOW_FLOAT;
4126 // Should be defined as the default precision by the parser
4127 default: UNREACHABLE();
4130 else if (type.getBasicType() == EbtInt || type.getBasicType() == EbtUInt)
4132 switch (type.getPrecision())
4134 case EbpHigh: return GL_HIGH_INT;
4135 case EbpMedium: return GL_MEDIUM_INT;
4136 case EbpLow: return GL_LOW_INT;
4138 // Should be defined as the default precision by the parser
4139 default: UNREACHABLE();
4143 // Other types (boolean, sampler) don't have a precision
4147 bool OutputHLSL::isVaryingOut(TQualifier qualifier)
4152 case EvqInvariantVaryingOut:
4155 case EvqCentroidOut:
4165 bool OutputHLSL::isVaryingIn(TQualifier qualifier)
4170 case EvqInvariantVaryingIn:
4183 bool OutputHLSL::isVarying(TQualifier qualifier)
4185 return isVaryingIn(qualifier) || isVaryingOut(qualifier);