-- **************************************************
-- Provide Moho with the name of this script object
-- **************************************************

ScriptName = "MR_Overlay"

-- **************************************************
-- General information about this script
-- **************************************************

MR_Overlay = {}

function MR_Overlay:Name()
	return self:Localize('UILabel')
end

function MR_Overlay:Version()
	return '1.0'
end

function MR_Overlay:UILabel()
	return self:Localize('UILabel')
end

function MR_Overlay:Creator()
	return 'Eugene Babich'
end

function MR_Overlay:Description()
	return self:Localize('Description')
end


-- **************************************************
-- Is Relevant / Is Enabled
-- **************************************************

function MR_Overlay:IsRelevant(moho)
	return true
end

function MR_Overlay:IsEnabled(moho)
	return true
end

-- **************************************************
-- Recurring Values
-- **************************************************

MR_Overlay.opacityValue = 50
MR_Overlay.strokeWidth = 6
MR_Overlay.selectNewOverlayLayer = false
MR_Overlay.replaceOverlayLayer = true
MR_Overlay.recolorStroke = false
MR_Overlay.strokesOnly = false
MR_Overlay.changeStrokeWidth = false
MR_Overlay.strokeColorR = 225
MR_Overlay.strokeColorG = 30
MR_Overlay.strokeColorB = 30
MR_Overlay.strokeColorA = 255
MR_Overlay.layerSuffix = '_Overlay'
MR_Overlay.doNotRender = true
MR_Overlay.selectedPoints = false
MR_Overlay.delete = false
MR_Overlay.hideOverlay = false
MR_Overlay.showOverlay = false
MR_Overlay.deleteOverlay = false
MR_Overlay.convertOverlay = false
MR_Overlay.overlayLayer = nil
MR_Overlay.flipOverlay = false
MR_Overlay.selectionCenter = true
MR_Overlay.layerOriginCenter = false
MR_Overlay.customCenter = false
MR_Overlay.pickCustomCenter = false
MR_Overlay.customCenterValueX = 0
MR_Overlay.customCenterValueY = 0
MR_Overlay.createOverlayFromFrame = false
MR_Overlay.frameVal1 = 1
MR_Overlay.frameVal2 = 200
MR_Overlay.frameVal3 = 400
MR_Overlay.useFrame1 = true
MR_Overlay.useFrame2 = false
MR_Overlay.useFrame3 = false
MR_Overlay.layersToOverlay = {}
MR_Overlay.secondarySelection = {}
MR_Overlay.autoSelectPoints = false
MR_Overlay.createOverlay = true
MR_Overlay.onlyOverlaySelected = false
MR_Overlay.mirrorFlip = false
MR_Overlay.useShapeForPivot = false

-- **************************************************
-- Prefs
-- **************************************************

function MR_Overlay:LoadPrefs(prefs)
	self.opacityValue = prefs:GetInt("MR_Overlay.opacityValue", 50)
	self.strokeWidth = prefs:GetInt("MR_Overlay.strokeWidth", 6)
	self.doNotRender = prefs:GetBool("MR_Overlay.doNotRender", false)
    self.selectNewOverlayLayer = prefs:GetBool("MR_Overlay.selectNewOverlayLayer", false)
    self.replaceOverlayLayer = prefs:GetBool("MR_Overlay.replaceOverlayLayer", false)
    self.recolorStroke = prefs:GetBool("MR_Overlay.recolorStroke", false)
    self.strokesOnly = prefs:GetBool("MR_Overlay.strokesOnly", false)
    self.changeStrokeWidth = prefs:GetBool("MR_Overlay.changeStrokeWidth", false)
	self.strokeColorR = prefs:GetInt("MR_Overlay.strokeColorR", 225)
	self.strokeColorG = prefs:GetInt("MR_Overlay.strokeColorG", 30)
	self.strokeColorB = prefs:GetInt("MR_Overlay.strokeColorB", 30)
	self.strokeColorA = prefs:GetInt("MR_Overlay.strokeColorA", 255)
	self.hideOverlay = prefs:GetBool("MR_Overlay.hideOverlay", false)
    self.showOverlay = prefs:GetBool("MR_Overlay.showOverlay", false)
    self.deleteOverlay = prefs:GetBool("MR_Overlay.deleteOverlay", false)
    self.convertOverlay = prefs:GetBool("MR_Overlay.convertOverlay", false)
    self.flipOverlay = prefs:GetBool("MR_Overlay.flipOverlay", false)
    self.layerOriginCenter = prefs:GetBool("MR_Overlay.layerOriginCenter", true)
    self.selectionCenter = prefs:GetBool("MR_Overlay.selectionCenter", true)
    self.customCenter = prefs:GetBool("MR_Overlay.customCenter", false)
    self.pickCustomCenter = prefs:GetBool("MR_Overlay.pickCustomCenter", false)
    self.customCenterValueX = prefs:GetFloat("MR_Overlay.customCenterValueX", 0)
    self.customCenterValueY = prefs:GetFloat("MR_Overlay.customCenterValueY", 0)
	self.createOverlayFromFrame = prefs:GetBool("MR_Overlay.createOverlayFromFrame", false)
	self.frameVal1 = prefs:GetInt("MR_Overlay.frameVal1", 1)
	self.frameVal2 = prefs:GetInt("MR_Overlay.frameVal2", 200)
	self.frameVal3 = prefs:GetInt("MR_Overlay.frameVal3", 400)
	self.useFrame1 = prefs:GetBool("MR_Overlay.useFrame1", true)
	self.useFrame2 = prefs:GetBool("MR_Overlay.useFrame2", false)
	self.useFrame3 = prefs:GetBool("MR_Overlay.useFrame3", false)
	self.autoSelectPoints = prefs:GetBool("MR_Overlay.autoSelectPoints", false)
	self.createOverlay = prefs:GetBool("MR_Overlay.createOverlay", true)
	self.mirrorFlip = prefs:GetBool("MR_Overlay.mirrorFlip", false)
	self.useShapeForPivot = prefs:GetBool("MR_Overlay.useShapeForPivot", false)
end

function MR_Overlay:SavePrefs(prefs)
	prefs:SetInt("MR_Overlay.opacityValue", self.opacityValue)
	prefs:SetInt("MR_Overlay.strokeWidth", self.strokeWidth)
	prefs:SetBool("MR_Overlay.doNotRender", self.doNotRender)
    prefs:SetBool("MR_Overlay.selectNewOverlayLayer", self.selectNewOverlayLayer)
    prefs:SetBool("MR_Overlay.replaceOverlayLayer", self.replaceOverlayLayer)
    prefs:SetBool("MR_Overlay.recolorStroke", self.recolorStroke)
    prefs:SetBool("MR_Overlay.strokesOnly", self.strokesOnly)
    prefs:SetBool("MR_Overlay.changeStrokeWidth", self.changeStrokeWidth)
	prefs:SetInt("MR_Overlay.strokeColorR", self.strokeColorR)
	prefs:SetInt("MR_Overlay.strokeColorG", self.strokeColorG)
	prefs:SetInt("MR_Overlay.strokeColorB", self.strokeColorB)
	prefs:SetInt("MR_Overlay.strokeColorA", self.strokeColorA)
	prefs:SetBool("MR_Overlay.hideOverlay", self.hideOverlay)
    prefs:SetBool("MR_Overlay.showOverlay", self.showOverlay)
    prefs:SetBool("MR_Overlay.deleteOverlay", self.deleteOverlay)
    prefs:SetBool("MR_Overlay.convertOverlay", self.convertOverlay)
    prefs:SetBool("MR_Overlay.flipOverlay", self.flipOverlay)
    prefs:SetBool("MR_Overlay.layerOriginCenter", self.layerOriginCenter)
    prefs:SetBool("MR_Overlay.customCenter", self.customCenter)
    prefs:SetBool("MR_Overlay.pickCustomCenter", self.pickCustomCenter)
    prefs:SetFloat("MR_Overlay.customCenterValueX", self.customCenterValueX)
    prefs:SetFloat("MR_Overlay.customCenterValueY", self.customCenterValueY)
	prefs:SetBool("MR_Overlay.createOverlayFromFrame", self.createOverlayFromFrame)
	prefs:SetInt("MR_Overlay.frameVal1", self.frameVal1)
	prefs:SetInt("MR_Overlay.frameVal2", self.frameVal2)
	prefs:SetInt("MR_Overlay.frameVal3", self.frameVal3)
	prefs:SetBool("MR_Overlay.useFrame1", self.useFrame1)
	prefs:SetBool("MR_Overlay.useFrame2", self.useFrame2)
	prefs:SetBool("MR_Overlay.useFrame3", self.useFrame3)
	prefs:SetBool("MR_Overlay.autoSelectPoints", self.autoSelectPoints)
	prefs:SetBool("MR_Overlay.createOverlay", self.createOverlay)
	prefs:SetBool("MR_Overlay.mirrorFlip", self.mirrorFlip)
	prefs:SetBool("MR_Overlay.useShapeForPivot", self.useShapeForPivot)
end

function MR_Overlay:ResetPrefs()
	self.opacityValue = 50
	self.strokeWidth = 6
	self.doNotRender = true
    self.selectNewOverlayLayer = false
    self.replaceOverlayLayer = true
    self.recolorStroke = false
    self.strokesOnly = false
    self.changeStrokeWidth = false
	self.strokeColorR = 225
	self.strokeColorG = 30
	self.strokeColorB = 30
	self.strokeColorA = 255
	self.hideOverlay = false
    self.showOverlay = false
    self.deleteOverlay = false
    self.convertOverlay = false
    self.flipOverlay = false
    self.selectionCenter = true
    self.layerOriginCenter = false
    self.customCenter = false
    self.pickCustomCenter = false
    self.customCenterValueX = 0
    self.customCenterValueY = 0
    self.createOverlayFromFrame = false
    self.frameVal1 = 1
    self.frameVal2 = 200
    self.frameVal3 = 400
    self.useFrame1 = true
    self.useFrame2 = false
    self.useFrame3 = false
    self.autoSelectPoints = false
    self.createOverlay = true
    self.mirrorFlip = false
    self.useShapeForPivot = false
end

-- **************************************************
-- MR_OverlayDialog
-- **************************************************

local MR_OverlayDialog = {}

MR_OverlayDialog.UPDATE_DIALOG = MOHO.MSG_BASE
MR_OverlayDialog.UPDATE_DIALOG2 = MOHO.MSG_BASE + 1
MR_OverlayDialog.FRAME1 = MOHO.MSG_BASE + 2
MR_OverlayDialog.FRAME2 = MOHO.MSG_BASE + 3
MR_OverlayDialog.FRAME3 = MOHO.MSG_BASE + 4

function MR_OverlayDialog:new(moho)
	local fileWord = MOHO.Localize("/Menus/File/File=File")
	local d = LM.GUI.SimpleDialog(MR_Overlay:Localize('UILabel'), MR_OverlayDialog)
	local l = d:GetLayout()
	
	l:PushH()
	
		l:PushV()
			d.createOverlayRadioButton = LM.GUI.RadioButton(MR_Overlay:Localize('Create Overlay'), d.UPDATE_DIALOG2)
			l:AddChild(d.createOverlayRadioButton, LM.GUI.ALIGN_LEFT, 0)
			d.createOverlayRadioButton:SetToolTip(MR_Overlay:Localize('Create Overlay Tooltip'))
			
			d.GetCustomCenterRadioButton = LM.GUI.RadioButton(MR_Overlay:Localize('Get Custom Center'), d.UPDATE_DIALOG2)
			l:AddChild(d.GetCustomCenterRadioButton, LM.GUI.ALIGN_LEFT, 0)
			d.GetCustomCenterRadioButton:SetToolTip(MR_Overlay:Localize('Get Custom Center Tooltip'))
		
			d.hideOverlayRadioButton = LM.GUI.RadioButton(MR_Overlay:Localize('Hide Overlay'), d.UPDATE_DIALOG2)
			l:AddChild(d.hideOverlayRadioButton, LM.GUI.ALIGN_LEFT, 0)
			d.hideOverlayRadioButton:SetToolTip(MR_Overlay:Localize('Hide Overlay Tooltip'))
			
			d.showOverlayRadioButton = LM.GUI.RadioButton(MR_Overlay:Localize('Show Overlay'), d.UPDATE_DIALOG2)
			l:AddChild(d.showOverlayRadioButton, LM.GUI.ALIGN_LEFT, 0)
			d.showOverlayRadioButton:SetToolTip(MR_Overlay:Localize('Show Overlay Tooltip'))

			d.convertOverlayRadioButton = LM.GUI.RadioButton(MR_Overlay:Localize('Convert Overlay'), d.UPDATE_DIALOG2)
			l:AddChild(d.convertOverlayRadioButton, LM.GUI.ALIGN_LEFT, 0)
			d.convertOverlayRadioButton:SetToolTip(MR_Overlay:Localize('Convert Overlay Tooltip'))

			d.deleteOverlayRadioButton = LM.GUI.RadioButton(MR_Overlay:Localize('Delete Overlay'), d.UPDATE_DIALOG2)
			l:AddChild(d.deleteOverlayRadioButton, LM.GUI.ALIGN_LEFT, 0)
			d.deleteOverlayRadioButton:SetToolTip(MR_Overlay:Localize('Delete Overlay Tooltip'))
		l:Pop()
		
		if fileWord == "Файл" then
			l:AddPadding(12)
		else	
			l:AddPadding(58)
		end	
		
		l:AddChild(LM.GUI.Divider(true), LM.GUI.ALIGN_FILL)
		
		l:PushV()
			
			d.replaceOverlayLayerCheckbox = LM.GUI.CheckBox(MR_Overlay:Localize('Update Overlay Layer'), d.UPDATE_DIALOG)
			l:AddChild(d.replaceOverlayLayerCheckbox, LM.GUI.ALIGN_LEFT, 0)
			d.replaceOverlayLayerCheckbox:SetToolTip(MR_Overlay:Localize('Update top overlay Tooltip'))
			
			d.autoSelectPointsCheckbox = LM.GUI.CheckBox(MR_Overlay:Localize('Auto Update Points'), d.UPDATE_DIALOG2)
			l:AddChild(d.autoSelectPointsCheckbox, LM.GUI.ALIGN_LEFT, 0)
			d.autoSelectPointsCheckbox:SetToolTip(MR_Overlay:Localize('Auto Update Points Tooltip'))
			
			d.selectNewOverlayLayerCheckbox = LM.GUI.CheckBox(MR_Overlay:Localize('Select New Overlay Layer'), d.UPDATE_DIALOG)
			l:AddChild(d.selectNewOverlayLayerCheckbox, LM.GUI.ALIGN_LEFT, 0)
			d.selectNewOverlayLayerCheckbox:SetToolTip(MR_Overlay:Localize('Select new overlay Tooltip'))
			
			d.doNotRenderCheckbox = LM.GUI.CheckBox(MR_Overlay:Localize('Do Not Render'), d.UPDATE_DIALOG)
			l:AddChild(d.doNotRenderCheckbox, LM.GUI.ALIGN_LEFT, 0)
			d.doNotRenderCheckbox:SetToolTip(MR_Overlay:Localize('Do Not Render Tooltip'))
			
			d.useShapeForPivotCheckbox = LM.GUI.CheckBox(MR_Overlay:Localize('Use Shapes Center'), d.UPDATE_DIALOG2)
			l:AddChild(d.useShapeForPivotCheckbox, LM.GUI.ALIGN_LEFT, 0)
			d.useShapeForPivotCheckbox:SetToolTip(MR_Overlay:Localize('Use Shapes Center Tooltip'))
			
		l:Pop()
		
	l:Pop()
	
	l:AddChild(LM.GUI.Divider(false), LM.GUI.ALIGN_FILL)
	
	l:PushH()
	
		l:PushV()
			l:PushH()
				l:AddPadding(10)
				
				d.overlayLayerOpacityText = LM.GUI.DynamicText(MR_Overlay:Localize('opacity'), 0)
				l:AddChild(d.overlayLayerOpacityText, LM.GUI.ALIGN_LEFT, 3)
				d.overlayLayerOpacityText:SetToolTip(MR_Overlay:Localize('Opacity Tooltip'))
				
				if fileWord == "Файл" then
					l:AddPadding(7)
				else
					l:AddPadding(-18)
				end
				
				d.opacityValueInput = LM.GUI.TextControl(0, '100', d.UPDATE_DIALOG, LM.GUI.FIELD_INT, MR_Overlay:Localize(' '))
				l:AddChild(d.opacityValueInput, LM.GUI.ALIGN_RIGHT, 0)
				d.opacityValueInput:SetToolTip(MR_Overlay:Localize('Opacity Tooltip'))
			
			l:Pop()
			
			l:PushH()
				
				d.changeStrokeWidthCheckbox = LM.GUI.CheckBox(MR_Overlay:Localize('Change Stroke Width'), d.UPDATE_DIALOG)
				l:AddChild(d.changeStrokeWidthCheckbox, LM.GUI.ALIGN_LEFT, 0)
				d.changeStrokeWidthCheckbox:SetToolTip(MR_Overlay:Localize('Change Stroke Width Toolip'))
				
				d.strokeWidthValueInput = LM.GUI.TextControl(12, '100', d.UPDATE_DIALOG, LM.GUI.FIELD_FLOAT)
				l:AddChild(d.strokeWidthValueInput, LM.GUI.ALIGN_LEFT, 0)
				d.strokeWidthValueInput:SetToolTip(MR_Overlay:Localize('Change Stroke Width Toolip'))
			
			l:Pop()
			
			l:PushH()
				
				d.recolorStrokeCheckbox = LM.GUI.CheckBox(MR_Overlay:Localize('Recolor Stroke'), d.UPDATE_DIALOG)
				l:AddChild(d.recolorStrokeCheckbox, LM.GUI.ALIGN_LEFT, 0)
				d.recolorStrokeCheckbox:SetToolTip(MR_Overlay:Localize('Recolor Stroke Tooltip'))
				
				d.strokeColorSwatch = LM.GUI.ShortColorSwatch(true, d.UPDATE_DIALOG)
				l:AddChild(d.strokeColorSwatch, LM.GUI.ALIGN_LEFT)
				d.strokeColorSwatch:SetToolTip(MR_Overlay:Localize('Recolor Stroke Tooltip'))

			l:Pop()
			
			d.strokesOnlyCheckbox = LM.GUI.CheckBox(MR_Overlay:Localize('Strokes Only'), d.UPDATE_DIALOG)
			l:AddChild(d.strokesOnlyCheckbox, LM.GUI.ALIGN_LEFT, 0)
			d.strokesOnlyCheckbox:SetToolTip(MR_Overlay:Localize('Strokes Only Tooltip'))
		
		l:Pop()
	
	l:AddChild(LM.GUI.Divider(true), LM.GUI.ALIGN_FILL)
	
	l:PushV()
	
		d.flipCheckbox = LM.GUI.CheckBox(MR_Overlay:Localize('Flip'), d.UPDATE_DIALOG)
		l:AddChild(d.flipCheckbox, LM.GUI.ALIGN_LEFT, 0)
		d.flipCheckbox:SetToolTip(MR_Overlay:Localize('Flip Tooltip'))
		
		d.mirrorFlipCheckbox = LM.GUI.CheckBox(MR_Overlay:Localize('Mirror Flip'), d.UPDATE_DIALOG)
		l:AddChild(d.mirrorFlipCheckbox, LM.GUI.ALIGN_LEFT, 0)
		d.mirrorFlipCheckbox:SetToolTip(MR_Overlay:Localize('Mirror Flip Tooltip'))
		
		d.selectionCenterRadioButton = LM.GUI.RadioButton(MR_Overlay:Localize('Selection Center'), d.UPDATE_DIALOG)
		l:AddChild(d.selectionCenterRadioButton, LM.GUI.ALIGN_LEFT, 0)
		d.selectionCenterRadioButton:SetToolTip(MR_Overlay:Localize('Selection Center Tooltip'))
		
		d.layerOriginCenterRadioButton = LM.GUI.RadioButton(MR_Overlay:Localize('Layer Origin'), d.UPDATE_DIALOG)
		l:AddChild(d.layerOriginCenterRadioButton, LM.GUI.ALIGN_LEFT, 0)
		d.layerOriginCenterRadioButton:SetToolTip(MR_Overlay:Localize('Layer Origin Tooltip'))
		
		d.customflipCenterRadioButton = LM.GUI.RadioButton(MR_Overlay:Localize('Custom Center'), d.UPDATE_DIALOG)
		l:AddChild(d.customflipCenterRadioButton, LM.GUI.ALIGN_LEFT, 0)
		d.customflipCenterRadioButton:SetToolTip(MR_Overlay:Localize('Custom Center Tooltip'))
		
		l:Pop()
		
		l:AddChild(LM.GUI.Divider(true), LM.GUI.ALIGN_FILL)
		
		l:PushV()
			d.createOverlayFromFrameCheckbox = LM.GUI.CheckBox(MR_Overlay:Localize('Create Overlay From Frame:'), d.UPDATE_DIALOG)
			l:AddChild(d.createOverlayFromFrameCheckbox, LM.GUI.ALIGN_LEFT, 0)
			d.createOverlayFromFrameCheckbox:SetToolTip(MR_Overlay:Localize('Create Overlay From Frame Tooltip'))
			
			l:PushH()
				d.frame1RadioButton = LM.GUI.RadioButton(MR_Overlay:Localize('Frame'), d.FRAME1)
				l:AddChild(d.frame1RadioButton, LM.GUI.ALIGN_LEFT, 0)

				d.frameText1Input = LM.GUI.TextControl(50, '100', d.UPDATE_DIALOG, LM.GUI.FIELD_INT, MR_Overlay:Localize(' '))
				l:AddChild(d.frameText1Input, LM.GUI.ALIGN_LEFT, 0)
			l:Pop()
		
			l:PushH()
				d.frame2RadioButton = LM.GUI.RadioButton(MR_Overlay:Localize('Frame'), d.FRAME2)
				l:AddChild(d.frame2RadioButton, LM.GUI.ALIGN_LEFT, 0)

				d.frameText2Input = LM.GUI.TextControl(50, '200', d.UPDATE_DIALOG, LM.GUI.FIELD_INT, MR_Overlay:Localize(' '))
				l:AddChild(d.frameText2Input, LM.GUI.ALIGN_LEFT, 0)
			l:Pop()
			
			l:PushH()
				d.frame3RadioButton = LM.GUI.RadioButton(MR_Overlay:Localize('Frame'), d.FRAME3)
				l:AddChild(d.frame3RadioButton, LM.GUI.ALIGN_LEFT, 0)

				d.frameText3Input = LM.GUI.TextControl(50, '400', d.UPDATE_DIALOG, LM.GUI.FIELD_INT, MR_Overlay:Localize(' '))
				l:AddChild(d.frameText3Input, LM.GUI.ALIGN_LEFT, 0)
			l:Pop()
		l:Pop()	
	l:Pop()
	
	l:AddChild(LM.GUI.Divider(false), LM.GUI.ALIGN_FILL)

	return d
end

function MR_OverlayDialog:UpdateWidgets(moho)
	self.opacityValueInput:SetValue(MR_Overlay.opacityValue)
	self.strokeWidthValueInput:SetValue(MR_Overlay.strokeWidth)
	self.doNotRenderCheckbox:SetValue(MR_Overlay.doNotRender)
	self.selectNewOverlayLayerCheckbox:SetValue(MR_Overlay.selectNewOverlayLayer)
	self.replaceOverlayLayerCheckbox:SetValue(MR_Overlay.replaceOverlayLayer)
	self.recolorStrokeCheckbox:SetValue(MR_Overlay.recolorStroke)
	self.strokesOnlyCheckbox:SetValue(MR_Overlay.strokesOnly)
	self.changeStrokeWidthCheckbox:SetValue(MR_Overlay.changeStrokeWidth)
	
	self.strokeWidthValueInput:Enable(self.changeStrokeWidthCheckbox:Value())
	self.strokeColorSwatch:Enable(self.recolorStrokeCheckbox:Value())
	
	local strokeColor = LM.rgb_color:new_local()
	strokeColor.r = MR_Overlay.strokeColorR
	strokeColor.g = MR_Overlay.strokeColorG
	strokeColor.b = MR_Overlay.strokeColorB
	strokeColor.a = MR_Overlay.strokeColorA
	
	self.strokeColorSwatch:SetValue(strokeColor)
	
	self.flipCheckbox:SetValue(MR_Overlay.flipOverlay)
	self.mirrorFlipCheckbox:SetValue(MR_Overlay.mirrorFlip)
	self.mirrorFlipCheckbox:Enable(MR_Overlay.flipOverlay)
	self.selectionCenterRadioButton:SetValue(MR_Overlay.selectionCenter)
	self.layerOriginCenterRadioButton:SetValue(MR_Overlay.layerOriginCenter)
	self.customflipCenterRadioButton:SetValue(MR_Overlay.customCenter)
	self.selectionCenterRadioButton:Enable(MR_Overlay.flipOverlay)
	self.layerOriginCenterRadioButton:Enable(MR_Overlay.flipOverlay)
	self.customflipCenterRadioButton:Enable(MR_Overlay.flipOverlay)
	self.createOverlayFromFrameCheckbox:SetValue(MR_Overlay.createOverlayFromFrame)
	self.useShapeForPivotCheckbox:SetValue(MR_Overlay.useShapeForPivot)
	
	if MR_Overlay.onlyOverlaySelected then
		self.createOverlayRadioButton:Enable(false)
	else
		self.createOverlayRadioButton:Enable(true)
	end	
	
	self.frame1RadioButton:SetValue(MR_Overlay.useFrame1)
	self.frame2RadioButton:SetValue(MR_Overlay.useFrame2)
	self.frame3RadioButton:SetValue(MR_Overlay.useFrame3)
	
	if MR_Overlay.createOverlayFromFrame then
		self.frame1RadioButton:Enable(true)
		self.frame2RadioButton:Enable(true)
		self.frame3RadioButton:Enable(true)
		self.frameText1Input:Enable(true)
		self.frameText2Input:Enable(true)
		self.frameText3Input:Enable(true)
	else
		self.frame1RadioButton:Enable(false)
		self.frame2RadioButton:Enable(false)
		self.frame3RadioButton:Enable(false)
		self.frameText1Input:Enable(false)
		self.frameText2Input:Enable(false)
		self.frameText3Input:Enable(false)
	end
	
	self.frameText1Input:SetValue(MR_Overlay.frameVal1)
	self.frameText2Input:SetValue(MR_Overlay.frameVal2)
	self.frameText3Input:SetValue(MR_Overlay.frameVal3)
	self.autoSelectPointsCheckbox:SetValue(MR_Overlay.autoSelectPoints)
	self.createOverlayRadioButton:SetValue(MR_Overlay.createOverlay)
	self.hideOverlayRadioButton:SetValue(MR_Overlay.hideOverlay)
	self.showOverlayRadioButton:SetValue(MR_Overlay.showOverlay)
	self.deleteOverlayRadioButton:SetValue(MR_Overlay.deleteOverlay)
	self.convertOverlayRadioButton:SetValue(MR_Overlay.convertOverlay)
	self.GetCustomCenterRadioButton:SetValue(MR_Overlay.pickCustomCenter)

	if MR_Overlay.hideOverlay and not MR_Overlay.overlayLayer then
		MR_Overlay.hideOverlay = false
		self.hideOverlayRadioButton:SetValue(false)
		self.createOverlayRadioButton:SetValue(true)
		MR_Overlay.createOverlay = true
	elseif MR_Overlay.showOverlay and not MR_Overlay.overlayLayer then
		MR_Overlay.showOverlay = false
		self.showOverlayRadioButton:SetValue(false)
		self.createOverlayRadioButton:SetValue(true)
		MR_Overlay.createOverlay = true
	elseif MR_Overlay.deleteOverlay and not MR_Overlay.overlayLayer then
		MR_Overlay.deleteOverlay = false
		self.deleteOverlayRadioButton:SetValue(false)
		self.createOverlayRadioButton:SetValue(true)
		MR_Overlay.createOverlay = true
	elseif MR_Overlay.convertOverlay and not MR_Overlay.overlayLayer then
		MR_Overlay.convertOverlay = false
		self.convertOverlayRadioButton:SetValue(false)
		self.createOverlayRadioButton:SetValue(true)
		MR_Overlay.createOverlay = true
	end	
	
	self.useShapeForPivotCheckbox:Enable(MR_Overlay.autoSelectPoints)
	self.autoSelectPointsCheckbox:Enable(true)
	
	if not MR_Overlay.createOverlay then
		self.opacityValueInput:Enable(false)
		self.strokeWidthValueInput:Enable(false)
		self.doNotRenderCheckbox:Enable(false)
		self.selectNewOverlayLayerCheckbox:Enable(false)
		self.replaceOverlayLayerCheckbox:Enable(false)
		self.recolorStrokeCheckbox:Enable(false)
		self.strokesOnlyCheckbox:Enable(false)
		self.changeStrokeWidthCheckbox:Enable(false)
		self.flipCheckbox:Enable(false)
		self.selectionCenterRadioButton:Enable(false)
		self.layerOriginCenterRadioButton:Enable(false)
		self.customflipCenterRadioButton:Enable(false)
		self.createOverlayFromFrameCheckbox:Enable(false)
		self.frame1RadioButton:Enable(false)
		self.frame2RadioButton:Enable(false)
		self.frame3RadioButton:Enable(false)
		self.frameText1Input:Enable(false)
		self.frameText2Input:Enable(false)
		self.frameText3Input:Enable(false)
		self.strokeColorSwatch:Enable(false)
		self.overlayLayerOpacityText:Enable(false)
		self.mirrorFlipCheckbox:Enable(false)
		self.autoSelectPointsCheckbox:Enable(false)
	end
	
	self.hideOverlayRadioButton:Enable(MR_Overlay.overlayLayer)
	self.showOverlayRadioButton:Enable(MR_Overlay.overlayLayer)
	self.deleteOverlayRadioButton:Enable(MR_Overlay.overlayLayer)
	self.convertOverlayRadioButton:Enable(MR_Overlay.overlayLayer)
	if self.GetCustomCenterRadioButton:Value() then
		self.useShapeForPivotCheckbox:Enable(self.autoSelectPointsCheckbox:Value())
	else
		self.useShapeForPivotCheckbox:Enable(false)
	end
end

function MR_OverlayDialog:OnOK(moho)
	MR_Overlay.opacityValue = LM.Clamp(self.opacityValueInput:IntValue(), 0, 100)
	MR_Overlay.strokeWidth = LM.Clamp(self.strokeWidthValueInput:FloatValue(), 0.25, 256)
	MR_Overlay.doNotRender = self.doNotRenderCheckbox:Value()
	MR_Overlay.selectNewOverlayLayer = self.selectNewOverlayLayerCheckbox:Value()
	MR_Overlay.replaceOverlayLayer = self.replaceOverlayLayerCheckbox:Value()
	MR_Overlay.recolorStroke = self.recolorStrokeCheckbox:Value()
	MR_Overlay.strokesOnly = self.strokesOnlyCheckbox:Value()
	MR_Overlay.changeStrokeWidth = self.changeStrokeWidthCheckbox:Value()
	local colorSwatchValue = self.strokeColorSwatch:Value()
	MR_Overlay.strokeColorR = colorSwatchValue.r
	MR_Overlay.strokeColorG = colorSwatchValue.g
	MR_Overlay.strokeColorB = colorSwatchValue.b
	MR_Overlay.strokeColorA = colorSwatchValue.a
	MR_Overlay.flipOverlay = self.flipCheckbox:Value()
	MR_Overlay.mirrorFlip = self.mirrorFlipCheckbox:Value()
	MR_Overlay.selectionCenter = self.selectionCenterRadioButton:Value()
	MR_Overlay.layerOriginCenter = self.layerOriginCenterRadioButton:Value()
	MR_Overlay.customCenter = self.customflipCenterRadioButton:Value()
	
	MR_Overlay.createOverlayFromFrame = self.createOverlayFromFrameCheckbox:Value()
	MR_Overlay.useFrame1 = self.frame1RadioButton:Value()
	MR_Overlay.useFrame2 = self.frame2RadioButton:Value()
	MR_Overlay.useFrame3 = self.frame3RadioButton:Value()
	MR_Overlay.frameVal1 = LM.Clamp(self.frameText1Input:Value(), 0, 10000)
	MR_Overlay.frameVal2 = LM.Clamp(self.frameText2Input:Value(), 0, 10000)
	MR_Overlay.frameVal3 = LM.Clamp(self.frameText3Input:Value(), 0, 10000)
	MR_Overlay.autoSelectPoints = self.autoSelectPointsCheckbox:Value()
	MR_Overlay.createOverlay = self.createOverlayRadioButton:Value()
	MR_Overlay.hideOverlay = self.hideOverlayRadioButton:Value()
	MR_Overlay.showOverlay = self.showOverlayRadioButton:Value()
	MR_Overlay.deleteOverlay = self.deleteOverlayRadioButton:Value()
	MR_Overlay.convertOverlay = self.convertOverlayRadioButton:Value()
	MR_Overlay.pickCustomCenter = self.GetCustomCenterRadioButton:Value()
	MR_Overlay.useShapeForPivot = self.useShapeForPivotCheckbox:Value()
end

function MR_OverlayDialog:HandleMessage(msg)
	if msg == self.UPDATE_DIALOG then
		self.opacityValueInput:SetValue(LM.Clamp(self.opacityValueInput:IntValue(), 0, 100))
		self.strokeWidthValueInput:SetValue(LM.Clamp(self.strokeWidthValueInput:FloatValue(), 0.25, 256))
		
		self.strokeWidthValueInput:Enable(self.changeStrokeWidthCheckbox:Value())
		self.strokeColorSwatch:Enable(self.recolorStrokeCheckbox:Value())
		self.selectionCenterRadioButton:Enable(self.flipCheckbox:Value())
		self.layerOriginCenterRadioButton:Enable(self.flipCheckbox:Value())
		self.customflipCenterRadioButton:Enable(self.flipCheckbox:Value())
		self.frame1RadioButton:Enable(self.createOverlayFromFrameCheckbox:Value())
		self.frame2RadioButton:Enable(self.createOverlayFromFrameCheckbox:Value())
		self.frame3RadioButton:Enable(self.createOverlayFromFrameCheckbox:Value())
		self.frameText1Input:Enable(self.createOverlayFromFrameCheckbox:Value())
		self.frameText2Input:Enable(self.createOverlayFromFrameCheckbox:Value())
		self.frameText3Input:Enable(self.createOverlayFromFrameCheckbox:Value())
		self.frameText1Input:SetValue(LM.Clamp(self.frameText1Input:IntValue(), 0, 10000))
		self.frameText2Input:SetValue(LM.Clamp(self.frameText2Input:IntValue(), 0, 10000))
		self.frameText3Input:SetValue(LM.Clamp(self.frameText3Input:IntValue(), 0, 10000))
		self.mirrorFlipCheckbox:Enable(self.flipCheckbox:Value())
		self.useShapeForPivotCheckbox:Enable(self.autoSelectPointsCheckbox:Value())
		if self.GetCustomCenterRadioButton:Value() then
			self.useShapeForPivotCheckbox:Enable(self.autoSelectPointsCheckbox:Value())
		else
			self.useShapeForPivotCheckbox:Enable(false)
		end
	elseif msg == self.UPDATE_DIALOG2 then
		if self.createOverlayRadioButton:Value() then
			self.opacityValueInput:Enable(true)
			self.strokeWidthValueInput:Enable(self.changeStrokeWidthCheckbox:Value())
			self.doNotRenderCheckbox:Enable(self.createOverlayRadioButton:Value())
			self.selectNewOverlayLayerCheckbox:Enable(self.createOverlayRadioButton:Value())
			self.replaceOverlayLayerCheckbox:Enable(self.createOverlayRadioButton:Value())
			self.recolorStrokeCheckbox:Enable(self.createOverlayRadioButton:Value())
			self.strokesOnlyCheckbox:Enable(true)
			self.changeStrokeWidthCheckbox:Enable(self.createOverlayRadioButton:Value())
			self.flipCheckbox:Enable(true)
			self.selectionCenterRadioButton:Enable(self.flipCheckbox:Value())
			self.layerOriginCenterRadioButton:Enable(self.flipCheckbox:Value())
			self.customflipCenterRadioButton:Enable(self.flipCheckbox:Value())
			self.createOverlayFromFrameCheckbox:Enable(true)
			self.frame1RadioButton:Enable(self.createOverlayFromFrameCheckbox:Value())
			self.frame2RadioButton:Enable(self.createOverlayFromFrameCheckbox:Value())
			self.frame3RadioButton:Enable(self.createOverlayFromFrameCheckbox:Value())
			self.frameText1Input:Enable(self.createOverlayFromFrameCheckbox:Value())
			self.frameText2Input:Enable(self.createOverlayFromFrameCheckbox:Value())
			self.frameText3Input:Enable(self.createOverlayFromFrameCheckbox:Value())
			self.strokeColorSwatch:Enable(self.recolorStrokeCheckbox:Value())
			self.overlayLayerOpacityText:Enable(true)
			self.mirrorFlipCheckbox:Enable(self.flipCheckbox:Value())
			self.autoSelectPointsCheckbox:Enable(true)
		else
			self.opacityValueInput:Enable(false)
			self.strokeWidthValueInput:Enable(false)
			self.doNotRenderCheckbox:Enable(false)
			self.selectNewOverlayLayerCheckbox:Enable(false)
			self.replaceOverlayLayerCheckbox:Enable(false)
			self.recolorStrokeCheckbox:Enable(false)
			self.strokesOnlyCheckbox:Enable(false)
			self.changeStrokeWidthCheckbox:Enable(false)
			self.flipCheckbox:Enable(false)
			self.selectionCenterRadioButton:Enable(false)
			self.layerOriginCenterRadioButton:Enable(false)
			self.customflipCenterRadioButton:Enable(false)
			self.createOverlayFromFrameCheckbox:Enable(false)
			self.frame1RadioButton:Enable(false)
			self.frame2RadioButton:Enable(false)
			self.frame3RadioButton:Enable(false)
			self.frameText1Input:Enable(false)
			self.frameText2Input:Enable(false)
			self.frameText3Input:Enable(false)
			self.strokeColorSwatch:Enable(false)
			self.overlayLayerOpacityText:Enable(false)
			self.mirrorFlipCheckbox:Enable(false)
			self.autoSelectPointsCheckbox:Enable(false)
		end
		if self.GetCustomCenterRadioButton:Value() then
			self.useShapeForPivotCheckbox:Enable(self.autoSelectPointsCheckbox:Value())
		else
			self.useShapeForPivotCheckbox:Enable(false)
		end
	elseif msg == self.FRAME1 then
		self.frame1RadioButton:SetValue(true)
		self.frame2RadioButton:SetValue(false)
		self.frame3RadioButton:SetValue(false)
	elseif msg == self.FRAME2 then
		self.frame1RadioButton:SetValue(false)
		self.frame2RadioButton:SetValue(true)
		self.frame3RadioButton:SetValue(false)
	elseif msg == self.FRAME3 then
		self.frame1RadioButton:SetValue(false)
		self.frame2RadioButton:SetValue(false)
		self.frame3RadioButton:SetValue(true)
	end
end


-- **************************************************
-- The guts of this script
-- **************************************************

function MR_Overlay:Run(moho)
	self.overlayLayer = self:CheckExistOverlayLayer(moho)
	self:ScanLayers(moho, false)
	if self.layersToOverlay[1] == nil and moho.layer == self.overlayLayer then
		self.onlyOverlaySelected = true
		self.createOverlay = false
		self.pickCustomCenter = true
	else
		self.onlyOverlaySelected = false
	end
	
	local dlog = MR_OverlayDialog:new(moho)
	if (dlog:DoModal() == LM.GUI.MSG_CANCEL) then
		return
	end
	
	if self.deleteOverlay and self.overlayLayer then
		self:DeleteOverlayLayer(moho, self.overlayLayer)
	elseif self.hideOverlay and self.overlayLayer then
		self.overlayLayer:SetVisible(false)
	elseif self.showOverlay and self.overlayLayer then
		self.overlayLayer:SetVisible(true)
	elseif self.convertOverlay and self.overlayLayer then
		self:ConvertOverlayLayer(moho, self.overlayLayer)
	elseif self.pickCustomCenter then
		self:PickCustomCenter(moho, moho.layer)
	end	
	
	if not self.createOverlay then
		return
	end
	
	self:ScanLayers(moho, true)
	
	if self.layersToOverlay[1] == nil then
		return
	end
	
	moho.document:PrepUndo(nil)
	moho.document:SetDirty()
	
	local curLayer = moho.layer
	local curFrame = moho.frame
	local curName = moho.layer:Name()
	local curAction = moho.layer:CurrentAction()

	if #self.layersToOverlay > 1 then
		curName = 'Multilayer'
	end
	
	if self.createOverlayFromFrame then
		if self.useFrame1 then
			moho:SetCurFrame(self.frameVal1)
		elseif self.useFrame2 then
			moho:SetCurFrame(self.frameVal2)	
		elseif self.useFrame3 then
			moho:SetCurFrame(self.frameVal3)
		end
	end
	
	local posList = {}
	local curveList = {}
	local skelControl = false
	local skelLayer = curLayer:ControllingBoneLayer()
	local skel = nil
	if skelLayer ~= nil then
		skel = skelLayer:Skeleton()
		skelControl = true
	end
	
	
	for k, id in ipairs(self.layersToOverlay) do
		local layer = moho:LayerAsVector(moho.document:LayerByAbsoluteID(id))
		local layerMesh = layer:Mesh()
		local layerPosList = {}
		if self.autoSelectPoints then
			layerMesh:SelectAll()
		else	
			layerMesh:SelectConnected()
		end
		for i = 0, layerMesh:CountPoints() - 1 do
			local pt = layerMesh:Point(i)
			if (pt.fSelected) then
				local globalPointPos = LM.Vector2:new_local()
				globalPointPos:Set(pt.fPos)
				globalPointPos = self:GetGlobalPointPos(moho, globalPointPos, layer)
				table.insert(layerPosList, globalPointPos)
			end
		end
		table.insert(posList, layerPosList)
	end

	for k, id in ipairs(self.layersToOverlay) do
		local layer = moho:LayerAsVector(moho.document:LayerByAbsoluteID(id))
		local layerMesh = layer:Mesh()
		local layerCurveList = {}
		for i = 0, layerMesh:CountCurves() - 1 do
			local curve = layerMesh:Curve(i)
			local handlePosList = {}
			handlePosList.inV = {}
			handlePosList.outV = {}
			local isCurveSelected = false
			for j = 0, curve:CountPoints() - 1 do
				if curve:Point(j).fSelected then
					isCurveSelected = true
					local handlePosIn =	curve:GetControlHandle(j, moho.layerFrame, true)
					local handlePosOut = curve:GetControlHandle(j, moho.layerFrame, false)
					handlePosIn = self:GetGlobalPointPos(moho, handlePosIn, layer)
					handlePosOut = self:GetGlobalPointPos(moho, handlePosOut, layer)
					table.insert(handlePosList.inV, handlePosIn)
					table.insert(handlePosList.outV, handlePosOut)
				end	
			end
			if isCurveSelected then
				table.insert(layerCurveList, handlePosList)
			end	
		end
		table.insert(curveList, layerCurveList)
	end
	
	if curAction ~= '' then
		moho.document:SetCurrentDocAction(nil)
		moho.layer:ActivateAction(nil)
	end

	local topLayer = moho.document:Layer(moho.document:CountLayers()-1)

	moho:SetSelLayer(topLayer)
	
	local overlayLayer = nil
	
	if self.replaceOverlayLayer then
		local scriptData = topLayer:ScriptData()
		if (scriptData:HasKey("MR Overlay Layer")) then
			local topLayerMesh = moho:LayerAsVector(topLayer):Mesh()
			if topLayerMesh ~= nil then
				topLayerMesh:Clear()
				overlayLayer = topLayer
				overlayLayer:SetVisible(true)
				moho.view:DrawMe()
			end
		else
			if (scriptData:HasKey("MR Guides Layer")) then
				topLayer = moho.document:Layer(moho.document:CountLayers()-2)
				scriptData = topLayer:ScriptData()
				moho:SetSelLayer(topLayer)
				if (scriptData:HasKey("MR Overlay Layer")) then
					local topLayerMesh = moho:LayerAsVector(topLayer):Mesh()
					if topLayerMesh ~= nil then
						topLayerMesh:Clear()
						overlayLayer = topLayer
						overlayLayer:SetVisible(true)
						moho.view:DrawMe()
					end
				else
					overlayLayer = self:CreatNewLayer(moho)
				end	
			else	
				overlayLayer = self:CreatNewLayer(moho)
			end
		end	
	else
		local scriptData = topLayer:ScriptData()
		if (scriptData:HasKey("MR Guides Layer")) then
			topLayer = moho.document:Layer(moho.document:CountLayers()-2)
			scriptData = topLayer:ScriptData()
			moho:SetSelLayer(topLayer)
			overlayLayer = self:CreatNewLayer(moho)
		else	
			overlayLayer = self:CreatNewLayer(moho)
		end
	end

	overlayLayer:SetName(curName.. self.layerSuffix)
	overlayLayer.fAlpha:SetValue(0, self.opacityValue / 100)
	if self.doNotRender then
		overlayLayer:SetEditOnly(true)
	else
		overlayLayer:SetEditOnly(false)
	end
	
	local newMesh = moho:LayerAsVector(overlayLayer):Mesh()
	for k, id in ipairs(self.layersToOverlay) do
		local layer = moho:LayerAsVector(moho.document:LayerByAbsoluteID(id))
		local layerMesh = layer:Mesh()
		moho:SetSelLayer(layer)
		if self.autoSelectPoints then
			layerMesh:SelectAll()
		else
			layerMesh:SelectConnected()
		end

		moho:Copy(layerMesh)
		moho:SetSelLayer(overlayLayer)
		local layerPoints = newMesh:CountPoints()
		local layerCurves = newMesh:CountCurves()

		moho:Paste()

		overlayLayer:ClearAnimation(true)

		for i, a in pairs(posList[k]) do
			local pointID = i-1 + layerPoints
			if pointID <= newMesh:CountPoints() then
				local pt = newMesh:Point(pointID)
				if (pt.fSelected) then
					pt.fAnimPos:SetValue(0, posList[k][i])
				end
			end	
		end
		
		overlayLayer:UpdateCurFrame()
		
		for i, a in pairs(curveList[k]) do
			local curveID = i - 1 + layerCurves
			if curveID <= newMesh:CountCurves() then
				local curve = newMesh:Curve(i - 1 + layerCurves)
				for e, b in pairs(curveList[k][i].inV) do
					local pn = e-1
					curve:SetControlHandle(e -1,curveList[k][i].inV[e] , moho.layerFrame, true)
					curve:SetControlHandle(e-1,curveList[k][i].outV[e] , moho.layerFrame, false)
				end
			end	
		end
		
		local curvature = 0
		local curve = nil
		local ptPos = -1
		local newMeshPoints = newMesh:CountPoints()
		for i = 0, newMeshPoints - 1 do
			local pointID = i + layerPoints
			if pointID <= newMeshPoints - 1 then
				local pt = newMesh:Point(i + layerPoints)
				if pt then
					for j = 0, pt:CountCurves() - 1 do
						curve, ptPos = pt:Curve(j + layerPoints, ptPos)
						curve:SetCurvature(ptPos, curve:GetCurvature(ptPos, moho.layerFrame), 0)
								
						curve:SetWeight(ptPos, curve:GetWeight(ptPos, moho.layerFrame, true), 0, true)
						curve:SetWeight(ptPos, curve:GetWeight(ptPos, moho.layerFrame, false), 0, false)
						
						curve:SetOffset(ptPos, curve:GetOffset(ptPos, moho.layerFrame, true), 0, true)
						curve:SetOffset(ptPos, curve:GetOffset(ptPos, moho.layerFrame, false), 0, false)
					end
				end	
			end	
		end
		
		if self.strokesOnly then
			for i = 0, newMesh:CountShapes() - 1 do
				local shape = newMesh:Shape(i)
				if (shape ~= nil) then
					shape.fHasFill = false
				end
			end
		end
		
		if self.recolorStroke then
			local color = LM.rgb_color:new_local()
			color.r = self.strokeColorR
			color.g = self.strokeColorG
			color.b = self.strokeColorB
			color.a = self.strokeColorA
			if (style ~= nil) then
				style.fLineCol:SetValue(0, color)
			end
			for i = 0, newMesh:CountShapes() - 1 do
				local shape = newMesh:Shape(i)
				if (shape ~= nil) then
					shape.fMyStyle.fLineCol:SetValue(0, color)
				end
			end
		end
		
		if self.changeStrokeWidth then
			local lineWidth = self.strokeWidth
			lineWidth = LM.Clamp(lineWidth, 0.25, 256)
			for i = 0, newMesh:CountShapes() - 1 do
				local shape = newMesh:Shape(i)
				if (shape ~= nil) then
					shape.fMyStyle.fLineWidth = lineWidth / moho.document:Height()
				end
			end
		end

	end
	
	if self.flipOverlay then
		local layerPoints = newMesh:CountPoints()
		local pointsDif = 0
		if self.mirrorFlip then
			pointsDif = layerPoints
			moho:Copy(newMesh)
			moho:Paste()
		end	
		
		local centerVec = LM.Vector2:new_local()
		if self.selectionCenter then
			local minAll = LM.Vector2:new_local()
            local maxAll = LM.Vector2:new_local()
			minAll:Set(1000000, 1000000)
			maxAll:Set(-1000000, -1000000)
			for i = 0, newMesh:CountShapes() - 1 do
				local shape = newMesh:Shape(i)
				local min = LM.Vector2:new_local()
				local max = LM.Vector2:new_local()
                shape:ShapeBounds(min, max, 0)
				if min.x < minAll.x then
					minAll.x = min.x
				end
				if min.y < minAll.y then
					minAll.y = min.y
				end
				if max.x > maxAll.x then
					maxAll.x = max.x
				end
				if max.y > maxAll.y then
					maxAll.y = max.y
				end
			end
			
			local center = LM.Vector2:new_local()
			center:Set(minAll.x + ((maxAll.x - minAll.x) / 2), minAll.y + ((maxAll.y - minAll.y) / 2))
			centerVec:Set(self:GetGlobalPointPos(moho, center, overlayLayer))
		elseif self.layerOriginCenter then
			centerVec:Set(self:GetGlobalPointPos(moho, curLayer:Origin(), curLayer))
		elseif self.customCenter then
			centerVec:Set(self.customCenterValueX, self.customCenterValueY)
		end
		for i = 0 + pointsDif, newMesh:CountPoints() - 1 do
			local pt = newMesh:Point(i)
			local dif = LM.Vector2:new_local()
			local newPos = LM.Vector2:new_local()
			dif:Set(centerVec.x - pt.fAnimPos:GetValue(0).x, 0)
			newPos:Set(centerVec.x + dif.x, pt.fAnimPos:GetValue(0).y)
			pt.fAnimPos:SetValue(0, newPos)
			pt:FlipControlHandles(0)
		end	
	end
	
	overlayLayer:ClearAnimation(true)
	
	self:ReturnToAction(moho, curAction, curLayer, curFrame)
	
	if not self.selectNewOverlayLayer then
		moho:SetSelLayer(curLayer)
		for _, layer in ipairs(self.secondarySelection) do
			layer:SetSecondarySelection(true)
		end
	end
	
	if self.createOverlayFromFrame then
		moho:SetCurFrame(curFrame)
	end	
	
	overlayLayer:UpdateCurFrame()
	curLayer:UpdateCurFrame()
	moho:UpdateUI()
	moho.view:DrawMe()
	moho:UpdateSelectedChannels()
end

function MR_Overlay:CreatNewLayer(moho)
	local overlayLayer = moho:CreateNewLayer(MOHO.LT_VECTOR, false)
	local scriptData = overlayLayer:ScriptData()
	scriptData:Set("MR Overlay Layer", true)
	
	local numVers = {}
	local vers = moho:AppVersion()
	for n in string.gmatch (vers, "%d+") do
		table.insert(numVers, tonumber(n))
	end
	if numVers[1] == 13 and numVers[2] == 5 then
		if numVers[3] ~= nil then
			if numVers[3] >= 2 then
				overlayLayer:SetIgnoredByLayerPicker(true)
			end
		end
	elseif numVers[1] == 13 and numVers[2] > 5 then
		overlayLayer:SetIgnoredByLayerPicker(true)
	elseif numVers[1] > 13 then
		overlayLayer:SetIgnoredByLayerPicker(true)	
	end
	
	return overlayLayer
end

function MR_Overlay:CheckExistOverlayLayer(moho)
	local topLayer = moho.document:Layer(moho.document:CountLayers()-1)
	local overlayLayer = nil
	local scriptData = topLayer:ScriptData()
	if (scriptData:HasKey("MR Overlay Layer")) then
		overlayLayer = moho:LayerAsVector(topLayer)
	elseif (scriptData:HasKey("MR Guides Layer")) then
		topLayer = moho.document:Layer(moho.document:CountLayers()-2)
		scriptData = topLayer:ScriptData()
		if (scriptData:HasKey("MR Overlay Layer")) then
			overlayLayer = moho:LayerAsVector(topLayer)
		end	
	end	
	return overlayLayer
end

function MR_Overlay:ConvertOverlayLayer(moho, overlLayer)
	moho.document:PrepUndo(nil)
	moho.document:SetDirty()
	local scriptData = overlLayer:ScriptData()
	scriptData:Remove("MR Overlay Layer")
	local newName = overlLayer:Name()
	if string.sub(overlLayer:Name(), overlLayer:Name():len() - self.layerSuffix:len() +1) == self.layerSuffix then
		newName = string.sub(overlLayer:Name(), 0,-(self.layerSuffix:len() +1))
		if newName == 'Multilayer' then
			newName = 'Converted Overlay'
		end
		overlLayer:SetName(newName)
	end
	overlLayer:SetVisible(true)
	overlLayer.fAlpha:SetValue(0, 1)
	overlLayer:SetEditOnly(false)
	overlLayer:UpdateCurFrame()
	moho.view:DrawMe()
	moho:UpdateUI()
end

function MR_Overlay:DeleteOverlayLayer(moho, overlLayer)
	local curLayer = moho.layer
	local curAction = moho.layer:CurrentAction()
	local curFrame = moho.frame
	local overlayLayer = overlLayer
	if overlayLayer ~= nil then
		moho.document:PrepUndo(nil)
		moho.document:SetDirty()
		if not self.onlyOverlaySelected then
			local parentGroup = curLayer:Parent()
			moho:DeleteLayer(overlayLayer)
			if curAction ~= '' then
				self:ReturnToAction(moho, curAction, curLayer, curFrame)
			else
				moho:SetSelLayer(curLayer)
			end	
			if curFrame > 0 then
				moho:SetCurFrame(0)
				moho:SetCurFrame(curFrame)
			elseif curFrame == 0 then
				moho:SetCurFrame(1)
				moho:SetCurFrame(curFrame)
			end
			curLayer:UpdateCurFrame()
		else
			local topLayer = moho.document:Layer(moho.document:CountLayers()-2)
			moho:DeleteLayer(overlayLayer)
			moho:SetSelLayer(topLayer)
		end
		moho.view:DrawMe()
		moho:UpdateUI()
		moho:UpdateSelectedChannels()
	end
end

function MR_Overlay:PickCustomCenter(moho, layer)
	local centerPos = LM.Vector2:new_local()
	local centerFound = false
	if moho:LayerAsVector(layer) then
		local mesh = moho:LayerAsVector(layer):Mesh()
		if self.useShapeForPivot and mesh:CountShapes() > 0 then
			local minAll = LM.Vector2:new_local()
            local maxAll = LM.Vector2:new_local()
			minAll:Set(1000000, 1000000)
			maxAll:Set(-1000000, -1000000)
			for i = 0, mesh:CountShapes() - 1 do
				local shape = mesh:Shape(i)
				local min = LM.Vector2:new_local()
				local max = LM.Vector2:new_local()
                shape:ShapeBounds(min, max, 0)
				if min.x < minAll.x then
					minAll.x = min.x
				end
				if min.y < minAll.y then
					minAll.y = min.y
				end
				if max.x > maxAll.x then
					maxAll.x = max.x
				end
				if max.y > maxAll.y then
					maxAll.y = max.y
				end
			end
			centerFound = true
			local center = LM.Vector2:new_local()
			center:Set(minAll.x + ((maxAll.x - minAll.x) / 2), minAll.y + ((maxAll.y - minAll.y) / 2))
			centerPos:Set(self:GetGlobalPointPos(moho, center, layer))
		else
			local selectedPoints = false
			for i = 0, mesh:CountPoints() - 1 do
				local pt = mesh:Point(i)
				if (pt.fSelected) then
					selectedPoints = true
					break
				end
			end
			if selectedPoints then
				centerFound = true
				centerPos:Set(self:GetGlobalPointPos(moho, mesh:SelectedCenter(), layer))
			end
		end	
	end
	
	if not centerFound then
		centerPos:Set(self:GetGlobalPointPos(moho, layer:Origin(), layer))
	end
	
	self.customCenterValueX = centerPos.x
	self.customCenterValueY = centerPos.y
end

function MR_Overlay:GetGlobalPointPos(moho, pointPosition, layer)
	local pointPos = LM.Vector2:new_local()
	pointPos:Set(pointPosition)
	local layerMatrix = LM.Matrix:new_local()
	layer:GetFullTransform(moho.frame, layerMatrix, nil)
	layerMatrix:Transform(pointPos)
	return pointPos
end

function MR_Overlay:ScanLayers(moho, autoSelect)
	self.layersToOverlay = {}
	self.secondarySelection = {}
	for l = 0, moho.document:CountSelectedLayers()-1 do
		local layer = moho.document:GetSelectedLayer(l)
		if layer ~= moho.layer then
			table.insert(self.secondarySelection, layer)
		end
		if moho:LayerAsVector(layer) then
			local mesh = moho:LayerAsVector(layer):Mesh()
			local selectedPoints = false
			if self.autoSelectPoints and autoSelect then
				mesh:SelectAll()
			end
			for i = 0, mesh:CountPoints() - 1 do
				local pt = mesh:Point(i)
				if (pt.fSelected) then
					selectedPoints = true
					break
				end
			end	
			if selectedPoints then
				local isLayerNew = true
				for k, id in ipairs(self.layersToOverlay) do
					if layer == moho.document:LayerByAbsoluteID(id) then
						isLayerNew = false
					end
				end
				if isLayerNew and layer ~= self.overlayLayer then
					table.insert(self.layersToOverlay, moho.document:LayerAbsoluteID(layer))
				end	
			end
		elseif layer:IsGroupType() then
			self:ScanGroup(moho, layer, autoSelect)
		end
	end
	table.sort(self.layersToOverlay)
end

function MR_Overlay:ScanGroup(moho, group, autoSelect)
	local groupLayer = moho:LayerAsGroup(group)
	for i=0, groupLayer:CountLayers()-1 do
		local layer = group:Layer(i)
		if layer:IsGroupType() then
			self:ScanGroup(moho, layer) -- recursion
		elseif moho:LayerAsVector(layer) then
			local mesh = moho:LayerAsVector(layer):Mesh()
			local selectedPoints = false
			if self.autoSelectPoints and autoSelect then
				mesh:SelectAll()
			end
			for i = 0, mesh:CountPoints() - 1 do
				local pt = mesh:Point(i)
				if (pt.fSelected) then
					selectedPoints = true
					break
				end
			end	
			if selectedPoints then
				local isLayerNew = true
				for k, id in ipairs(self.layersToOverlay) do
					if layer == moho.document:LayerByAbsoluteID(id) then
						isLayerNew = false
					end
				end
				if isLayerNew then
					table.insert(self.layersToOverlay, moho.document:LayerAbsoluteID(layer))
				end
			end
		end
	end
end

function MR_Overlay:ReturnToAction(moho, returnAction, returnLayer, frame)
	if returnAction ~= '' then
		local parentGroup = returnLayer:Parent()
		local skelLayer = nil
		
		if returnLayer:LayerType() == 4 and returnLayer:HasAction(returnAction) then
			skelLayer = returnLayer
		elseif parentGroup ~= nil then
			local targetGroup = parentGroup
			repeat
				if targetGroup:LayerType() == 4 then -- LT_BONE
					if targetGroup:HasAction(returnAction) then
						skelLayer = targetGroup
					end	
				end
				targetGroup = targetGroup:Parent()
			until targetGroup == nil
		end	
		moho:SetSelLayer(skelLayer)
		moho.document:SetCurrentDocAction(returnAction)
		skelLayer:ActivateAction(returnAction)
		if skelLayer ~= returnLayer then
			moho:SetSelLayer(returnLayer)
			returnLayer:ActivateAction(returnAction)
		end	
		moho:SetCurFrame(frame)
	end
end

-- **************************************************
-- Localization
-- **************************************************

function MR_Overlay:Localize(text)
	local phrase = {}

	phrase['Description'] = 'Script allows you to create an “overlay” -  a new layer that can be used as a visual reference. The content of the layer is based on the selected points or vector layers. You can choose the color and line width, turn off the fills and mirror the overlay.'
	phrase['UILabel'] = 'Overlay'

	phrase['opacity'] = 'Overlay Layer Opacity:'
	phrase['Opacity Tooltip'] = 'Opacity of the newly created overlay layer. 100 - completely opaque, 0 - completely transparent.'
	phrase['Do Not Render'] = 'Do Not Render Overlay'
	phrase['Do Not Render Tooltip'] = "Check if you don't want the newly created overlay layer to appear in the rendered image."
    phrase['Select New Overlay Layer'] = 'Select New Overlay Layer'
    phrase['Select new overlay Tooltip'] = 'Select new overlay layer and remove selection from the current layer.'
    phrase['Update Overlay Layer'] = 'Update Existing Overlay Layer'
    phrase['Update top overlay Tooltip'] = 'Update the topmost overlay layer, if exists.'
    phrase['Recolor Stroke'] = 'Recolor Stroke:'
    phrase['Recolor Stroke Tooltip'] = 'The color of the strokes in the newly created overlay layer.'
    phrase['Strokes Only'] = 'Strokes Only'
    phrase['Strokes Only Tooltip'] = 'If checked, only strokes will be created, no fills.'
    phrase['Change Stroke Width'] = 'Change Stroke Width:'
    phrase['Change Stroke Width Toolip'] = 'The width of the strokes in the newly created overlay layer.'
	phrase['Hide Overlay'] = 'Hide Overlay'
	phrase['Hide Overlay Tooltip'] = 'Hide the topmost existing overlay layer.'
    phrase['Show Overlay'] = 'Show Overlay'
    phrase['Show Overlay Tooltip'] = 'Show the topmost existing overlay layer.'
    phrase['Delete Overlay'] = 'Delete Overlay'
    phrase['Delete Overlay Tooltip'] = 'Delete the topmost overlay layer.'
	phrase['Convert Overlay'] = 'Convert Overlay'
    phrase['Convert Overlay Tooltip'] = 'Convert existing overlay to a normal layer.'
	phrase['Flip'] = 'Flip Overlay'
	phrase['Flip Tooltip'] = 'These controls are responsible for the pivot position and flip settings.'
	phrase['Selection Center'] = 'Selection Center'
	phrase['Selection Center Tooltip'] = 'Use selection\'s center for flip pivot'
	phrase['Layer Origin'] = 'Layer Origin'
	phrase['Layer Origin Tooltip'] = 'Use layer\'s origin for flip pivot'
	phrase['Custom Center'] = 'Custom Pivot'
	phrase['Custom Center Tooltip'] = 'Use custom pivot for flip'
	phrase['Get Custom Center'] = 'Set Custom Pivot'
	phrase['Get Custom Center Tooltip'] = 'If there are points selected, the pivot will be set to the center of the selection. If no points selected, the pivot will be set to the layer\'s origin.'
	phrase['Create Overlay From Frame:'] = 'Create From Frame:'
	phrase['Create Overlay From Frame Tooltip'] = 'These settings allow you to create the overlay based on a particular frame instead of the current one.'
    phrase['Frame'] = 'Frame:'
    phrase['Auto Update Points'] = 'Auto Select Points'
    phrase['Auto Update Points Tooltip'] = 'Automatically select all points.'
    phrase['Create Overlay'] = 'Create Overlay'
    phrase['Mirror Flip'] = 'Mirror Flip'
    phrase['Mirror Flip Tooltip'] = 'Show original overlay and flipped one.'
    phrase['Create Overlay Tooltip'] = 'Create overlay layer or update existing one.'
    phrase['Use Shapes Center'] = 'Use Shapes Center'
    phrase['Use Shapes Center Tooltip'] = 'When this option turned on, the pivot will be placed to the center of the shapes instead of points center, which may be different.'
    phrase[' '] = ' '

	local fileWord = MOHO.Localize("/Menus/File/File=File")
	if fileWord == "Файл" then
		phrase['Description'] = 'Скрипт позволяет создать слой на базе выделенных точек или векторных слоёв для отображения содержимого поверх всех слоёв как ориентир. Так же скрипт позволяет настраивать цвет и ширину контура оверлея, отключать заливку и отражать оверлей.'
		phrase['UILabel'] = 'Оверлей'

		phrase['opacity'] = 'Прозрачность оверлея:'
		phrase['Opacity Tooltip'] = 'Прозрачность создаваемого оверлея. 100 - полностью непрозрачен, 0 - полностью прозрачен.'
		phrase['Do Not Render'] = 'Не рендерить оверлей'
		phrase['Do Not Render Tooltip'] = "Включите, если вы не хотите, что бы оверлей отображался на рендере."
        phrase['Select New Overlay Layer'] = 'Выделить оверлей'
        phrase['Select new overlay Tooltip'] = 'Перевести выделение на оверлей. Иначе текущий слой останется выделенным.'
        phrase['Update Overlay Layer'] = 'Обновить существущий оверлей'
        phrase['Update top overlay Tooltip'] = 'Обновить верхний оверлей, если он существует.'
		phrase['Recolor Stroke'] = 'Перекрасить контур:'
		phrase['Recolor Stroke Tooltip'] = 'Цвет контура в создаваемом оверлее.'
		phrase['Strokes Only'] = 'Только контур'
		phrase['Strokes Only Tooltip'] = 'Еслои включен, будет создан только контур без заливок.'
		phrase['Change Stroke Width'] = 'Изменить ширину контура:'
		phrase['Change Stroke Width Toolip'] = 'Ширина контура в создаваемом оверлее.'
		phrase['Hide Overlay'] = 'Выключить видимость оверлея'
		phrase['Hide Overlay Tooltip'] = 'Выключить видимость верхнего оверлея.'
		phrase['Show Overlay'] = 'Включить видимость оверлея'
		phrase['Show Overlay Tooltip'] = 'Включить видимость верхнего оверлея.'
		phrase['Delete Overlay'] = 'Удалить оверлей'
		phrase['Delete Overlay Tooltip'] = 'Удалить верхний существующий оверлей.'
		phrase['Convert Overlay'] = 'Конвертировать оверлей'
		phrase['Convert Overlay Tooltip'] = 'Конвертировать оверлей в обычный слой.'
		phrase['Flip'] = 'Отразить оверлей'
		phrase['Flip Tooltip'] = 'Эти опции отвечают за позицию пивота и настройки отзеркаливания оверлея.'
		phrase['Selection Center'] = 'Центр выделения'
		phrase['Selection Center Tooltip'] = 'Использовать центр выделенных точек для пивота.'
		phrase['Layer Origin'] = 'Ориджн слоя'
		phrase['Layer Origin Tooltip'] = 'Использовать ориджин слоя для пивота.'
		phrase['Custom Center'] = 'Настраиваемый пивот'
		phrase['Custom Center Tooltip'] = 'Использовать настраиваемый пивот.'
		phrase['Get Custom Center'] = 'Установить пивот'
		phrase['Get Custom Center Tooltip'] = 'Если выделены точки, пивот будет установлен в выделения. Если точки не выделены, пивот установится в ориджин слоя.'
		phrase['Create Overlay From Frame:'] = 'Создать с кадра:'
		phrase['Create Overlay From Frame Tooltip'] = 'Эти настройки позволяют создавать оверлей базируясь на заданном кадре, а не на текущем.'
		phrase['Frame'] = 'Кадр:'
		phrase['Auto Update Points'] = 'Авто выделение точек'
		phrase['Auto Update Points Tooltip'] = 'Автоматически выделять все точки.'
		phrase['Create Overlay'] = 'Создать оверлей'
		phrase['Create Overlay Tooltip'] = 'Создать слой овелея или обновить существующий.'
		phrase['Mirror Flip'] = 'Отзеркалить'
		phrase['Mirror Flip Tooltip'] = 'Показать оригинальный и отражонный оверлей.'
		phrase['Use Shapes Center'] = 'Использовать центр форм'
		phrase['Use Shapes Center Tooltip'] = 'Когда эта опция включена, пивот будет взят из центра форм вместо центра точек, так как они не всегда совпадают.'
		phrase[' '] = ' '
	end

	return phrase[text]
end

Icon
MR Overlay
Listed

Script type: Button/Menu

Uploaded: Dec 06 2021, 02:59

Script allows you to create an “overlay” - a new layer that can be used as a visual reference.

Installation Options:

This script, and all other scripts on this site are distributed as free software under the GNU General Public License 3.0 or later.
Downloads count: 174