import poser, os.path
scene=poser.Scene()
class TextureReferences:
	def PrintTextureReferences(self):
		for s in self.GetTextureReferences():
			print s
	def GetTextureReferences(self):
		references=[]
		for act in scene.Actors():
			try:
				materials = act.Materials()
				if materials:
					for mat in materials:
						shdrTree = mat.ShaderTree(); 
						if shdrTree!=None:
							for node in shdrTree.Nodes():
								for input in node.Inputs():
									if input.InNode():
										self.GetTextureReferencesPerNode(input.InNode(), references)
			except:
				pass
		return references
	def GetTextureReferencesPerNode(self, node, references):
		if node!=None:
			for input in node.Inputs():
				if input.InternalName() == "Image_Source":
					texture = input.Value()
					if not texture in references: references.append(texture)
				self.GetTextureReferencesPerNode(input.InNode(), references)
	def PrintWrongTextureReferences(self):
		for s in self.GetWrongTextureReferences():
			print s
	def GetWrongTextureReferences(self):
		l=[]
		for s in self.GetTextureReferences():
			if not os.path.isfile(s):
				l.append(s)
		return l

	def ResolveReferences(self):
		if (self.GetWrongTextureReferences()):
			if float(poser.Version())>=7.0: scene.ResolvePendingTextures()
			else:
				actual=[scene.OutputRes(), scene.RenderBumpMaps(), scene.RenderTextureMaps(), scene.RenderCastShadows(), scene.CurrentRenderEngine()]
				render=[(1,1), 0, 1, 0, poser.kRenderEngineCodePOSER4]
				if poser.DialogSimple.YesNo("Not all texture references are currently correct, so they should be fixed before exporting to Lux!\nRendering the current scene at minimum size may fix the references. Click yes, if this should be done automatically."):
					self.SetRenderData(render)
					scene.Render()
					self.SetRenderData(actual)
	def SetRenderData(self, data):
		scene.SetOutputRes(data[0][0], data[0][1])
		scene.SetRenderBumpMaps(data[1])
		scene.SetRenderTextureMaps(data[2])
		scene.SetRenderCastShadows(data[3])
		scene.SetCurrentRenderEngine(data[4])


# test code
print 'all texture references:'
TextureReferences().PrintTextureReferences()
print 'wrong references:'
TextureReferences().PrintWrongTextureReferences()
TextureReferences().ResolveReferences()
print 'wrong after resolving tried:'
TextureReferences().PrintWrongTextureReferences()

