TikZ: strange behaviour of cycle / coordinate / pic name in TikZ pics

You can replace

\path[draw,fill=yellow] (a) -- (b) -- (c) -- (d) -- cycle;

by

\path[draw,fill=yellow] (a.center) -- (b.center) -- (c.center) -- (d.center) -- cycle;

Reason

When you try to name the pic (picname), TikZ will name the coordinate (cooname) in the pic by (picnamecorname). This is quite convenient because you can refer to the same coordinate in the different pic.

When TikZ wants to construct the path, it will test whether the given input is a node. If it is a node, it will break the path into pieces so that the path will not overlap the node. On the other hand, if it is a coordinate, it will continue the path

This test is done by

\expandafter\ifx\csname pgf@sh@ns@#2\endcsname\tikz@coordinate@text

where #2 is corname and \tikz@coordinate@text is the string coordinate. This test will fail because \pgf@sh@ns@corname is undefined. Remember that the coordinate is named picnamecorname, so the correct one is \pgf@sh@ns@picnamecorname.

The final result is that the path is broken into pieces and cannot be filled.

However if you execute the unnamed version first, TikZ will draw the expected picture and it will be protocoled. Therefore the drawing will remain the same.

This is probably related to http://tex.stackexchange.com/questions/75146/draw-a-path-between-many-nodes-using-foreach

The most simple solution I've come up with, is this:

\documentclass{article}
\usepackage{tikz}
\begin{document}

\tikzset{
  mypic/.pic = {
    code = {
      \coordinate (a1) at (0,0);
      \coordinate (c1) at (1,1);
      \path[draw,fill=yellow] (a1) rectangle (c1);
    }
  }
}

try 1:        \tikz \pic (k)     {mypic};
try 2:        \tikz \pic[name=l] {mypic};
without name: \tikz \pic         {mypic};
try 3:        \tikz \pic (m)     {mypic};

\end{document}

Where instead of defining all 4 coordinates, just define those coords that form the rectangle.

The major problem with this solution is that is only works with rectangles. If you want to draw more specific figures, you should have use other shapes from the shapes module.


Related to the problem you're facing: in page 218 of the manual (version 3.0.1a), it says that even though you don't close the figure (by not writing cycle, or not repeating in the last position the first coordinate), its fill color will be drawn anyway.

According to what I've experimented, this must be a problem with how the coordinates are managed to draw lines between their points.